问:
"implements Runnable" vs "extends Thread" in Java
From what time I've spent with threads in Java, I've found these two ways to write threads:

With implements Runnable:

```<code>public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call
</code>```

Or, with extends Thread:

```<code>public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call
</code>```

Is there any significant difference in these two blocks of code?

答:
If you want to separate your concerns like, if you want to create Tasks and it does not matter to you who is the worker working on your task then use Runnable and define your work as a task. Just like when you use executor service, you define tasks in form of Runnable/callable and give them to executor service which will then hold the responsibility of workers.

If you want to create a worker by yourself and assign that worker your task, you want more control over the worker thread then use Thread class.

Body:
From what time I've spent with threads in Java, I've found these two ways to write threads:

With implements Runnable:

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call

Or, with extends Thread:

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call

Is there any significant difference in these two blocks of code?

LastEditorDisplayName: Jon Skeet


来源: stackexchange

问:
How to alert if the expire date is close to now date in tkinter
I make like a shop market in tkinter, I tried to make a function that send me a messagebox.showwarning() If (date_now - 5_days) == expire_date

I tried this code in this question before But doesn't works:

from datetime import datetime, date
datet = '15-12-2015'

ExpirationDate = datetime.strptime(datet,"%d-%m-%Y").date()
now = date.today()
if (now - 5) == ExpirationDate:
    messagebox.showwarning("Expired item", "This item is Expired")
```

答:
You should use the timedelta to define 5 days like:

```<code>from datetime import timedelta

five_days = timedelta(days=5)
</code>```

You should also fix the if statement, testing for exact equality ignores all dates after the expiration. Why not use >=.

ContentLicense: CC BY-SA 4.0

Body:
You should use the timedelta to define 5 days like:

from datetime import timedelta

five_days = timedelta(days=5)

You should also fix the if statement, testing for exact equality ignores all dates after the expiration. Why not use >=.


问:
Python group similar file name from glob list and append
Assume using glob, we read a folder which contains several csv files such as:

```<code>/C/share\AA_12345_1.csv

/C/share\AA_12345_2.csv

/C/share\AA_12345_3.csv

/C/share\BB_13_1.csv

/C/share\BB_13_2.csv
</code>```

The goal is to append the csv files based on the similar filename group, example append

```<code>/C/share\AA_12345_1.csv

...

/C/share\AA_12345_3.csv
</code>```

as one dataframe of /C/share\AA_12345

```<code>/C/share\BB_13_1.csv

/C/share\BB_13_2.csv
</code>```

also as one dataframe of /C/share\BB_13

My current approach is using

```<code>res = [list(i) for j, i in groupby(lof,
          lambda a:a.partition('\.*_\d*_?[0-9]_*(?=_)')[0])]
</code>```

to get group of [[/C/share\AA_12345_1.csv,/C/share\AA_12345_2.csv , /C/share\AA_12345_3.csv ],[/C/share\BB_13_1.csv,/C/share\BB_13_2.csv]]
and then for each group read the csv and append.

However the result is still one biglist [/C/share\AA_12345_1.csv,...,/C/share\BB_13_2.csv]

Any idea/pointer on how to move forward?

Many thanks in advance!

答:
Here's my different approach to get group of similar file:</p>
```<code>key_func = lambda x : re.search(r"\w*\D_\d*",x).group()

res = [list(j) for i, j  in itertools.groupby(d, key_func)] #d contains list of csv files
for i in res:
    print(i)
</code>```

Body:
Assume using glob, we read a folder which contains several csv files such as:

/C/share\AA_12345_1.csv

/C/share\AA_12345_2.csv

/C/share\AA_12345_3.csv

/C/share\BB_13_1.csv

/C/share\BB_13_2.csv

The goal is to append the csv files based on the similar filename group, example append

/C/share\AA_12345_1.csv

...

/C/share\AA_12345_3.csv

as one dataframe of /C/share\AA_12345

/C/share\BB_13_1.csv

/C/share\BB_13_2.csv

also as one dataframe of /C/share\BB_13

My current approach is using

res = [list(i) for j, i in groupby(lof,
          lambda a:a.partition('\.*_\d*_?[0-9]_*(?=_)')[0])]

to get group of [[/C/share\AA_12345_1.csv,/C/share\AA_12345_2.csv , /C/share\AA_12345_3.csv ],[/C/share\BB_13_1.csv,/C/share\BB_13_2.csv]]
and then for each group read the csv and append.

However the result is still one biglist [/C/share\AA_12345_1.csv,...,/C/share\BB_13_2.csv]

Any idea/pointer on how to move forward?

Many thanks in advance!

Body:
Here's my different approach to get group of similar file:

key_func = lambda x : re.search(r"\w*\D_\d*",x).group()

res = [list(j) for i, j  in itertools.groupby(d, key_func)] #d contains list of csv files
for i in res:
    print(i)


问:
Retrieve a data from an ArrayList
I have this variable:

```<code>protected ArrayList<String> list = new ArrayList<String>();
</code>```

The data is in this form:

```<code>data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";
</code>```

I want to retrieve a data value1 from it. How can I do this?

答:
you can just split on whitespace like this:

```<code>String[] result = data.split(" ");
</code>```

your value1 should be third item in this array, so you can access it by calling:

```<code>String value1 = result[2];
</code>```

Or if you wrote this code why the hell would you try to get value from a string where you just put that value yourself. :)

ContentLicense: CC BY-SA 3.0

Title: Retrieve a data from an ArrayList

Body:
I have this variable:

protected ArrayList<String> list = new ArrayList<String>();

The data is in this form:

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";

I want to retrieve a data value1 from it. How can I do this?

Body:
you can just split on whitespace like this:

String[] result = data.split(" ");

your value1 should be third item in this array, so you can access it by calling:

String value1 = result[2];

Or if you wrote this code why the hell would you try to get value from a string where you just put that value yourself. :)


问:
Configure Multiple NAT gateways
I have two public & private subnets across two AZs. I want to create a NAT in both public subnets. How do I route my private route table to use both NATs? Case three in this accepted answer. I know it's possible but I'm unsure on how to implement it. Should the destination cidr_block be the public subnet's cidr block? I also tried 0.0.0.0/0 and errored out.

```<code>resource "aws_route" "r" {
  count                     = length(aws_nat_gateway.this)
  route_table_id            = aws_vpc.vpc.default_route_table_id
  destination_cidr_block    = "aws_subnet.public_subnets.${count.index}.cidr_block"
  nat_gateway_id            = "aws_nat_gateway.this.${count.index}.id"
  depends_on                = [aws_vpc.vpc,aws_subnet.public_subnets,aws_nat_gateway.this]
}
</code>```

When I tried 0.0.0.0/0

error creating Route in Route Table (rtb-059eee10e310ade77) with destination (0.0.0.0/0): RouteAlreadyExists: The route identified by 0.0.0.0/0 already exists.

答:
Short answer: you need to have a separate route table for each private subnet.

Long answer: I would start by defining a map that contains configuration for each availability zone. I avoid count in modern Terraform configs because it's too easy to cause incompatibilities down the road (especially if you're using it to index an array).

```<code>locals {
  subnets = {
    "1a" = { "public_cidr": "172.31.0.0/24", private_cidr: "172.31.1.0/24" }
    "1b" = { "public_cidr": "172.31.2.0/24", private_cidr: "172.31.3.0/24" }
  }
}
</code>```

Now, you can use for_each to create public and private subnets for each of these availability zones:

```<code>resource "aws_subnet" "public" {
  for_each    = local.subnets
  vpc_id      = aws_vpc.example.id
  cidr_block  = each.value["public_cidr"]
  tags = {
    Name      = "public-${each.key}"
  }
}

resource "aws_subnet" "private" {
  for_each    = local.subnets
  vpc_id      = aws_vpc.example.id
  cidr_block  = each.value["private_cidr"]
  tags = {
    Name      = "private-${each.key}"
  }
}
</code>```

You can associate the public subnets with the default route table (which must have a route to the Internet Gateway). Personally, I prefer creating my own public route table, rather than updating the default.

Next, you'll need to create a NAT Gateway in each public subnet:

```<code>resource "aws_nat_gateway" "example" {
  depends_on    = [aws_internet_gateway.example]
  for_each      = local.subnets
  allocation_id = aws_eip.nat_ip[each.key].id
  subnet_id     = aws_subnet.public[each.key].id

  tags = {
    Name        = "nat-${each.key}"
  }
}
</code>```

And now the important part: each private subnet needs its own route table, which references the NAT Gateway specific to its availability zone.

```<code>resource "aws_route_table" "private" {
  for_each          = local.subnets
  vpc_id            = aws_vpc.example.id

  route {
    cidr_block      = "0.0.0.0/0"
    nat_gateway_id  = aws_nat_gateway.example[each.key].id
  }

  tags = {
    Name            = "private-${each.key}"
  }
}

resource "aws_route_table_association" "private" {
  for_each       = local.subnets
  subnet_id      = aws_subnet.private[each.key].id
  route_table_id = aws_route_table.private[each.key].id
}
</code>```

Title: Configure Multiple NAT gateways

Body:
I have two public & private subnets across two AZs. I want to create a NAT in both public subnets. How do I route my private route table to use both NATs? Case three in this accepted answer. I know it's possible but I'm unsure on how to implement it. Should the destination cidr_block be the public subnet's cidr block? I also tried 0.0.0.0/0 and errored out.

resource "aws_route" "r" {
  count                     = length(aws_nat_gateway.this)
  route_table_id            = aws_vpc.vpc.default_route_table_id
  destination_cidr_block    = "aws_subnet.public_subnets.${count.index}.cidr_block"
  nat_gateway_id            = "aws_nat_gateway.this.${count.index}.id"
  depends_on                = [aws_vpc.vpc,aws_subnet.public_subnets,aws_nat_gateway.this]
}

When I tried 0.0.0.0/0

error creating Route in Route Table (rtb-059eee10e310ade77) with destination (0.0.0.0/0): RouteAlreadyExists: The route identified by 0.0.0.0/0 already exists.

Body:
Short answer: you need to have a separate route table for each private subnet.

Long answer: I would start by defining a map that contains configuration for each availability zone. I avoid count in modern Terraform configs because it's too easy to cause incompatibilities down the road (especially if you're using it to index an array).

locals {
  subnets = {
    "1a" = { "public_cidr": "172.31.0.0/24", private_cidr: "172.31.1.0/24" }
    "1b" = { "public_cidr": "172.31.2.0/24", private_cidr: "172.31.3.0/24" }
  }
}

Now, you can use for_each to create public and private subnets for each of these availability zones:

resource "aws_subnet" "public" {
  for_each    = local.subnets
  vpc_id      = aws_vpc.example.id
  cidr_block  = each.value["public_cidr"]
  tags = {
    Name      = "public-${each.key}"
  }
}

resource "aws_subnet" "private" {
  for_each    = local.subnets
  vpc_id      = aws_vpc.example.id
  cidr_block  = each.value["private_cidr"]
  tags = {
    Name      = "private-${each.key}"
  }
}

You can associate the public subnets with the default route table (which must have a route to the Internet Gateway). Personally, I prefer creating my own public route table, rather than updating the default.

Next, you'll need to create a NAT Gateway in each public subnet:

resource "aws_nat_gateway" "example" {
  depends_on    = [aws_internet_gateway.example]
  for_each      = local.subnets
  allocation_id = aws_eip.nat_ip[each.key].id
  subnet_id     = aws_subnet.public[each.key].id

  tags = {
    Name        = "nat-${each.key}"
  }
}

And now the important part: each private subnet needs its own route table, which references the NAT Gateway specific to its availability zone.

resource "aws_route_table" "private" {
  for_each          = local.subnets
  vpc_id            = aws_vpc.example.id

  route {
    cidr_block      = "0.0.0.0/0"
    nat_gateway_id  = aws_nat_gateway.example[each.key].id
  }

  tags = {
    Name            = "private-${each.key}"
  }
}

resource "aws_route_table_association" "private" {
  for_each       = local.subnets
  subnet_id      = aws_subnet.private[each.key].id
  route_table_id = aws_route_table.private[each.key].id
}


问:
undefined is appending in top of documnet
Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I'm seeing undefined in the first line of the document.</p>
```<code>const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype}
                          </li>
                      </ul>
                  </div`);
})```

All I'm trying to do is create a list item, I don't have any console logs in the file or browser.

can someone please help to understand why I'm seeing undefined in the top line?

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)
</code>```

答:
You have 2 problems.

map function returns an array, so instead of an html string, you have an array at the end.

Since you create html variable inside the map function, you don't concatinate anything. Everytime you have a new html variable with no value.

What you want can be done by map function, but reduce function suits better.

```<code>eleOne.innerHTML = letterArry.reduce(
  (previous, current) => previous + makeString(current), ''
);

const makeString = (current) => {
  return `<div class={alphabets}><ul>
    <li id= ${current.id}>${current.name} ${current.soundtype}</li>
  </ul></div>`
}
</code>```

Body:
Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I'm seeing undefined in the first line of the document.

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `

                              ${i.name} ${i.soundtype}

                  </div`);
})```

All I'm trying to do is create a list item, I don't have any console logs in the file or browser.

can someone please help to understand why I'm seeing undefined in the top line?

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)

Body:
You have 2 problems.

map function returns an array, so instead of an html string, you have an array at the end.

Since you create html variable inside the map function, you don't concatinate anything. Everytime you have a new html variable with no value.

What you want can be done by map function, but reduce function suits better.

eleOne.innerHTML = letterArry.reduce(
  (previous, current) => previous + makeString(current), ''
);

const makeString = (current) => {
  return `<div class={alphabets}><ul>
    <li id= ${current.id}>${current.name} ${current.soundtype}</li>
  </ul></div>`
}


问:
How can I sum up the values from a column and then separate them in different columns?
I'm just a beginner with R and I've been having some trouble organising my data set.

I have a particular problem. I'm working with a data set from an agricultural survey. In this data set, subjects (farms) have different plots and in those plots have different crops. Something like this

Subject
CropName
Area

A
Corn
2

A
Carrots
2

A
Avocado
0,5

A
Corn
1

B
Grapes
2

C
Carrots
3

As you can see, not all farms have the same crops and the same crops can be found in different plots of the same farm.

What I want to do is to sum up the values of each crop in a farm and separate them in different columns, to obtain only one observation per farm. Which will make my life easier on the analysis phase.

Something like this:

Subject
Corn
Carrots
Avocado
Grapes

A
3
2
0.5
0

B
0
0
0
2

C
0
3
0
0

I've have not idea how to do it. I'm open to suggestions about how my code should look like.
Thanks a lot!

答:
It looks like you're fairly new to SO; welcome to the community! If you want great answers quickly, it's best to make your question reproducible. This includes sample data like the output from dput(head(dataObject))), what you have tried so far, and any libraries you are using. Check it out: making R reproducible questions.

You can create this table, like so:

```<code>library(tidyverse)

df1 <- data.frame(
  stringsAsFactors = FALSE,
  Subject = c("A", "A", "A", "A", "B", "C"),
  CropName = c("Corn","Carrots",
               "Avocado","Corn","Grapes","Carrots"),
  Area = c("2", "2", "0.5", "1", "2", "3"))

head(df1)
#   Subject CropName Area
# 1       A     Corn    2
# 2       A  Carrots    2
# 3       A  Avocado  0.5
# 4       A     Corn    1
# 5       B   Grapes    2
# 6       C  Carrots    3

df1 %>% mutate(Area = as.numeric(Area)) %>% # change to number
  group_by(CropName, Subject) %>%  # group by what's wanted as names
  summarise(Area = sum(Area)) %>%  # where the values will come from
  spread(CropName, Area, fill = 0) # render the spread, fill with 0
</code>```

The console output will render the following:

```<code># A tibble: 3 × 5
  Subject Avocado Carrots  Corn Grapes
  <chr>     <dbl>   <dbl> <dbl>  <dbl>
1 A           0.5       2     3      0
2 B           0         0     0      2
3 C           0         3     0      0
</code>```

Body:
It looks like you're fairly new to SO; welcome to the community! If you want great answers quickly, it's best to make your question reproducible. This includes sample data like the output from dput(head(dataObject))), what you have tried so far, and any libraries you are using. Check it out: making R reproducible questions.

You can create this table, like so:

library(tidyverse)

df1 <- data.frame(
  stringsAsFactors = FALSE,
  Subject = c("A", "A", "A", "A", "B", "C"),
  CropName = c("Corn","Carrots",
               "Avocado","Corn","Grapes","Carrots"),
  Area = c("2", "2", "0.5", "1", "2", "3"))

head(df1)
#   Subject CropName Area
# 1       A     Corn    2
# 2       A  Carrots    2
# 3       A  Avocado  0.5
# 4       A     Corn    1
# 5       B   Grapes    2
# 6       C  Carrots    3

df1 %>% mutate(Area = as.numeric(Area)) %>% # change to number
  group_by(CropName, Subject) %>%  # group by what's wanted as names
  summarise(Area = sum(Area)) %>%  # where the values will come from
  spread(CropName, Area, fill = 0) # render the spread, fill with 0

The console output will render the following:

# A tibble: 3 × 5
  Subject Avocado Carrots  Corn Grapes
  <chr>     <dbl>   <dbl> <dbl>  <dbl>
1 A           0.5       2     3      0
2 B           0         0     0      2
3 C           0         3     0      0


问:
MongooseError: Query was already executed
I updated Mongoose to the latest version (6.0.1) and now I'm getting this error whenever .findOne() is executed:

MongooseError: Query was already executed: Streams.findOne({ i: 6 })
    at model.Query._wrappedThunk [as _findOne] (C:\Users\honza\ZiggerTestMaster\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
    at C:\Users\honza\ZiggerTestMaster\node_modules\kareem\index.js:370:33
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at listOnTimeout (node:internal/timers:526:9)
    at processTimers (node:internal/timers:500:7) {
  originalStack: 'Error\n' +
    '    at model.Query._wrappedThunk [as _findOne] (C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:25:28)\n' +
    '    at C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\kareem\\index.js:370:33\n' +
    '    at processTicksAndRejections (node:internal/process/task_queues:78:11)\n' +
    '    at runNextTicks (node:internal/process/task_queues:65:3)\n' +
    '    at listOnTimeout (node:internal/timers:526:9)\n' +
    '    at processTimers (node:internal/timers:500:7)'
}
```
<p>My code is as follows:</p>
```var visitorData = Visitor.find({});

app.get("/retrieve", function(req,res){
    visitorData.exec(function (err,data) {
        if (err) {
            throw err;
        }
        res.render("retrieve", { title:"View Visitor Data", records: data});
     });
});
```

It executes properly the first time I open the route but, whenever I refresh it, it throws the above error. Has been happening since Mongoose got the latest version.

答:
Don't use the callback within the findOne, instead
use .then() , after the Query, like so

```<code> Visitor.find({})
.then(function (err, data) {
        if (!err) {
            res.render("retrieve", { title: "View Visitor Data", records: data });
        } else {
            throw err;
        }
    }
</code>```

This should most likely work , otherwise use clone() if necessary , as stated by
Avis

Body:
I updated Mongoose to the latest version (6.0.1) and now I'm getting this error whenever .findOne() is executed:

MongooseError: Query was already executed: Streams.findOne({ i: 6 })
    at model.Query._wrappedThunk [as _findOne] (C:\Users\honza\ZiggerTestMaster\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
    at C:\Users\honza\ZiggerTestMaster\node_modules\kareem\index.js:370:33
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at listOnTimeout (node:internal/timers:526:9)
    at processTimers (node:internal/timers:500:7) {
  originalStack: 'Error\n' +
    '    at model.Query._wrappedThunk [as _findOne] (C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:25:28)\n' +
    '    at C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\kareem\\index.js:370:33\n' +
    '    at processTicksAndRejections (node:internal/process/task_queues:78:11)\n' +
    '    at runNextTicks (node:internal/process/task_queues:65:3)\n' +
    '    at listOnTimeout (node:internal/timers:526:9)\n' +
    '    at processTimers (node:internal/timers:500:7)'
}

My code is as follows:

var visitorData = Visitor.find({});

app.get("/retrieve", function(req,res){
    visitorData.exec(function (err,data) {
        if (err) {
            throw err;
        }
        res.render("retrieve", { title:"View Visitor Data", records: data});
     });
});

It executes properly the first time I open the route but, whenever I refresh it, it throws the above error. Has been happening since Mongoose got the latest version.

Body:
Don't use the callback within the findOne, instead
use .then() , after the Query, like so

 Visitor.find({})
.then(function (err, data) {
        if (!err) {
            res.render("retrieve", { title: "View Visitor Data", records: data });
        } else {
            throw err;
        }
    }

This should most likely work , otherwise use clone() if necessary , as stated by
Avis


问:
issue iterating a python string list
Hello I'm getting an issue while I'm trying to remove every len of string in the list that is mod by 2

def remove_even_length(l):
    for i in l:
        if  len(i) %2==0:
            if i in l:
                l.remove(i)
    return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))
```

what is happening is when it goes inside the list it skips ,[is , question] which both are mod 2 I don't know why it doesn't check the len of these 2 strings.

答:
Might be a problem resulting from the fact that you are iterating over the list while changing it.

Try creating a new list and returning it:

```<code>def remove_even_length(old_list):
    new_list = []
    for i in old_list:
        if len(i) % 2 != 0:
            new_list.append(i)
    return new_list

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = remove_even_length(wordlist)
print(wordlist_without_even)
</code>```

Or just use a List Comprehension:

```<code>wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = list([word for word in wordlist if len(word) % 2 != 0])
print(wordlist_without_even)
</code>```

Title: issue iterating a python string list

Body:
Hello I'm getting an issue while I'm trying to remove every len of string in the list that is mod by 2

def remove_even_length(l):
    for i in l:
        if  len(i) %2==0:
            if i in l:
                l.remove(i)
    return l

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
print(remove_even_length(wordlist))

what is happening is when it goes inside the list it skips ,[is , question] which both are mod 2 I don't know why it doesn't check the len of these 2 strings.

Body:
Might be a problem resulting from the fact that you are iterating over the list while changing it.

Try creating a new list and returning it:

def remove_even_length(old_list):
    new_list = []
    for i in old_list:
        if len(i) % 2 != 0:
            new_list.append(i)
    return new_list

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = remove_even_length(wordlist)
print(wordlist_without_even)

Or just use a List Comprehension:

wordlist = ["be", "is", "not", "or", "question", "the", "to"]
wordlist_without_even = list([word for word in wordlist if len(word) % 2 != 0])
print(wordlist_without_even)


问:
Vuetify navigation drawer keep list item colored on click
I have created a navigation drawer but cannot achieve to keep background on item click.

what i have for now is custom scoped css for the list that looks like.

What i want to achieve is that the background green color remains on click.
and change list item backround according to whereever i click between default background and my style.

For now my code looks like.

```<code><v-navigation-drawer
          v-model="drawer"
          :mini-variant.sync="mini"
          height="100vh"
          permanent
          color="blue-grey darken-4"
        >
          <v-list-item class="px-2">
            <v-list-item-avatar>
              <v-img src="https://randomuser.me/api/portraits/men/85.jpg" />
            </v-list-item-avatar>

            <v-list-item-title class="ListItemClass">
              John Leider
            </v-list-item-title>

            <v-btn
              icon
              @click.stop="mini = !mini"
              color="blue-grey lighten-5"
            >
              <v-icon>mdi-chevron-left</v-icon>
            </v-btn>
          </v-list-item>

          <v-list-item class="mb-1 px-2">
            <v-list-item-icon>
              <v-btn
                icon
                @click.stop="mini = !mini"
                color="blue-grey lighten-5"
              >
                <v-icon>mdi-arrow-expand-horizontal</v-icon>
              </v-btn>
            </v-list-item-icon>
          </v-list-item>
          <div
            id="divider"
            style="background-color:#f5f5f5; height: 2px; width:80%;margin: 0 auto;;"
          />

          <v-list dense>
            <v-list-item
              class="SelectedTile"
              v-for="item in items"
              :key="item.title"
              link
            >
              <v-list-item-icon>
                <v-icon color="blue-grey lighten-5">
                  {{ item.icon }}
                </v-icon>
              </v-list-item-icon>

              <v-list-item-content color="blue-grey lighten-5">
                <v-list-item-title class="ListItemClass">
                  {{ item.title }}
                </v-list-item-title>
              </v-list-item-content>
            </v-list-item>
          </v-list>
        </v-navigation-drawer>
</code>```

And my style

```<code><style scoped>
.ListItemClass {
  color: #f5f5f5;
}
.SelectedTile:hover {
    border-radius: 4px;
    background: #455A64
}
.SelectedTile:active {
    border-radius: 4px;
    background: rgba(10, 204, 117, 0.19)
}
</style>
</code>```

I connot figure out how to do it.

Thanks for the help

答:
If you are creating v-navigation-drawer for the whole app, it would be better if you will change something in your template.

I hope you are using vue-router to navigate between pages.

Your App.vue should look like this:

<template>
  <v-app>
    <v-navigation-drawer
      app
      ...another props
    >
      ...navigation-drawer internal data
    </v-navigation-drawer>

    <v-main>
      <v-container fluid>
        <router-view></router-view>
      </v-container>
    </v-main>
  </v-app>
</template>
```
<p>With a template like this you can use an <code>active-class</code> prop inside your <code>v-list-item</code> component this way:</p>
<pre class="lang-js prettyprint-override"><code>...
<v-list dense>
  <v-list-item
    class="SelectedTile"
    active-class="SelectedTile-active"
    v-for="item in items"
    :key="item.title"
    :to="item.path"
    link
  >
    <v-list-item-icon>
      <v-icon color="blue-grey lighten-5">
        {{ item.icon }}
      </v-icon>
    </v-list-item-icon>

    <v-list-item-content color="blue-grey lighten-5">
      <v-list-item-title class="ListItemClass">
        {{ item.title }}
      </v-list-item-title>
    </v-list-item-content>
  </v-list-item>
</v-list>
...
<script>
export default {
  ...
  data() {
    return {
      ...
      items: [
        { title: "First", icon: "mdi-home", path: "/first" },
        { title: "Second", icon: "mdi-send", path: "/second" },
        { title: "Third", icon: "mdi-lock", path: "/third" },
      ],
    };
  },
};
</script>

<style scoped>
.ListItemClass {
  color: #f5f5f5;
}

.SelectedTile:hover {
    border-radius: 4px;
    background: #455A64
}

.SelectedTile-active {
  border-radius: 4px;
  background: rgba(10, 204, 117, 0.19)
}
</style>
</code>```

Check this demo at CodeSandbox.

If for some reason you cannot use the first method, try this:

To create a group of selectable v-list-item's you can wrap it into v-list-item-group component:

...
<v-list dense>
  <v-list-item-group
    v-model="selectedItem"
    active-class="SelectedTile-active"
    mandatory
  >
    <v-list-item
      class="SelectedTile"
      v-for="item in items"
      :key="item.title"
      link
    >
      <v-list-item-icon>
        <v-icon color="blue-grey lighten-5">
          {{ item.icon }}
        </v-icon>
      </v-list-item-icon>

      <v-list-item-content color="blue-grey lighten-5">
        <v-list-item-title class="ListItemClass">
          {{ item.title }}
        </v-list-item-title>
      </v-list-item-content>
    </v-list-item>
  </v-list-item-group>
</v-list>
...
data: () => ({
  ...
  selectedItem: 0,
})
...

```

But as you can see, if you are using mandatory prop in v-list-item-group component, at least one item should always be selected.

Body:
I have created a navigation drawer but cannot achieve to keep background on item click.

what i have for now is custom scoped css for the list that looks like.

What i want to achieve is that the background green color remains on click.
and change list item backround according to whereever i click between default background and my style.

For now my code looks like.

<v-navigation-drawer
          v-model="drawer"
          :mini-variant.sync="mini"
          height="100vh"
          permanent
          color="blue-grey darken-4"
        >
          <v-list-item class="px-2">
            <v-list-item-avatar>
              <v-img src="https://randomuser.me/api/portraits/men/85.jpg" />
            </v-list-item-avatar>

            <v-list-item-title class="ListItemClass">
              John Leider
            </v-list-item-title>

            <v-btn
              icon
              @click.stop="mini = !mini"
              color="blue-grey lighten-5"
            >
              <v-icon>mdi-chevron-left</v-icon>
            </v-btn>
          </v-list-item>

          <v-list-item class="mb-1 px-2">
            <v-list-item-icon>
              <v-btn
                icon
                @click.stop="mini = !mini"
                color="blue-grey lighten-5"
              >
                <v-icon>mdi-arrow-expand-horizontal</v-icon>
              </v-btn>
            </v-list-item-icon>
          </v-list-item>

          <v-list dense>
            <v-list-item
              class="SelectedTile"
              v-for="item in items"
              :key="item.title"
              link
            >
              <v-list-item-icon>
                <v-icon color="blue-grey lighten-5">
                  {{ item.icon }}
                </v-icon>
              </v-list-item-icon>

              <v-list-item-content color="blue-grey lighten-5">
                <v-list-item-title class="ListItemClass">
                  {{ item.title }}
                </v-list-item-title>
              </v-list-item-content>
            </v-list-item>
          </v-list>
        </v-navigation-drawer>

And my style

I connot figure out how to do it.

Thanks for the help

Body:
If you are creating v-navigation-drawer for the whole app, it would be better if you will change something in your template.

I hope you are using vue-router to navigate between pages.

Your App.vue should look like this:

<template>
  <v-app>
    <v-navigation-drawer
      app
      ...another props
    >
      ...navigation-drawer internal data
    </v-navigation-drawer>

    <v-main>
      <v-container fluid>
        <router-view></router-view>
      </v-container>
    </v-main>
  </v-app>
</template>

With a template like this you can use an active-class prop inside your v-list-item component this way:

...
<v-list dense>
  <v-list-item
    class="SelectedTile"
    active-class="SelectedTile-active"
    v-for="item in items"
    :key="item.title"
    :to="item.path"
    link
  >
    <v-list-item-icon>
      <v-icon color="blue-grey lighten-5">
        {{ item.icon }}
      </v-icon>
    </v-list-item-icon>

    <v-list-item-content color="blue-grey lighten-5">
      <v-list-item-title class="ListItemClass">
        {{ item.title }}
      </v-list-item-title>
    </v-list-item-content>
  </v-list-item>
</v-list>
...
<script>
export default {
  ...
  data() {
    return {
      ...
      items: [
        { title: "First", icon: "mdi-home", path: "/first" },
        { title: "Second", icon: "mdi-send", path: "/second" },
        { title: "Third", icon: "mdi-lock", path: "/third" },
      ],
    };
  },
};
</script>

<style scoped>
.ListItemClass {
  color: #f5f5f5;
}

.SelectedTile:hover {
    border-radius: 4px;
    background: #455A64
}

.SelectedTile-active {
  border-radius: 4px;
  background: rgba(10, 204, 117, 0.19)
}
</style>

Check this demo at CodeSandbox.

If for some reason you cannot use the first method, try this:

To create a group of selectable v-list-item's you can wrap it into v-list-item-group component:

...
<v-list dense>
  <v-list-item-group
    v-model="selectedItem"
    active-class="SelectedTile-active"
    mandatory
  >
    <v-list-item
      class="SelectedTile"
      v-for="item in items"
      :key="item.title"
      link
    >
      <v-list-item-icon>
        <v-icon color="blue-grey lighten-5">
          {{ item.icon }}
        </v-icon>
      </v-list-item-icon>

      <v-list-item-content color="blue-grey lighten-5">
        <v-list-item-title class="ListItemClass">
          {{ item.title }}
        </v-list-item-title>
      </v-list-item-content>
    </v-list-item>
  </v-list-item-group>
</v-list>
...
data: () => ({
  ...
  selectedItem: 0,
})
...
<style scoped>
.ListItemClass {
  color: #f5f5f5;
}

.SelectedTile:hover {
    border-radius: 4px;
    background: #455A64
}

.SelectedTile-active {
  border-radius: 4px;
  background: rgba(10, 204, 117, 0.19)
}
</style>

But as you can see, if you are using mandatory prop in v-list-item-group component, at least one item should always be selected.


答: You're operating on the list as you're iterating through it. Try creating a separate results list, and pushing the values that do/don't fit your criteria to this new list. I think you'll find your results then.</p>

Title: issue iterating a python string list


问:
Convert IEnumerable to IEnumerable<T> when T isn't known until runtime
How can I convert IEnumerable to IEnumerable<T> when T isn't known until runtime?

I have a method that absolutely needs an IEnumerable<T> where T isn't known until runtime and T must be the actual type and not an ancestor type like object.

I'm betting the reflection API allows for something like this but I don't know exactly how.

Update

I can get a type object like this:

```<code>var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
    var type = first.GetType();

}
</code>```

Update2

The "method" I was referring to was actually the Setter of the WPF DataGrid's ItemSource property.
The problem I'm having is that if I don't pass it an IEnumerable<T> the rows generated in the Datagrid are all blank, as if it's method of reflecting over the properties of T is not working and it can't generate columns.

Even using this code has this unwanted effect:

```<code>    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }
</code>```

答:
Here's the code that worked for me:</p>

```<code>    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }
</code>```

Body:
How can I convert IEnumerable to IEnumerable<T> when T isn't known until runtime?

I have a method that absolutely needs an IEnumerable<T> where T isn't known until runtime and T must be the actual type and not an ancestor type like object.

I'm betting the reflection API allows for something like this but I don't know exactly how.

Update

I can get a type object like this:

var first = results.Cast<object>().FirstOrDefault();
if (first != null)
{
    var type = first.GetType();

}

Update2

The "method" I was referring to was actually the Setter of the WPF DataGrid's ItemSource property.
The problem I'm having is that if I don't pass it an IEnumerable<T> the rows generated in the Datagrid are all blank, as if it's method of reflecting over the properties of T is not working and it can't generate columns.

Even using this code has this unwanted effect:

    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }

Body:
Here's the code that worked for me:

    public CollectionResultWindow(IEnumerable results)
    {
        Contract.Requires(results != null, "results is null.");

        InitializeComponent();
        DataContext = this;

        var first = results.Cast<object>().FirstOrDefault();
        if (first != null)
        {
            Type type = first.GetType();
            var castMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(type);
            dynamic genericResults = castMethod.Invoke(null, new[] { results });
            Results = genericResults; // Results is a dependency property that DataGrid.ItemSource is bound to.
        }

    }


问:
Assign function to word in QLabel
I am searching for a solution for the following problem:
I want to assign a function to a certain word inside a QLabel of PyQt5, so that when the word is clicked the function is executed.

```<code>    from PyQt5.QtWidgets import QMainWindow, QLabel, QVBoxLayout, QApplication, QWidget
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = "App"
        self.left = 0
        self.top = 0
        self.width = 700
        self.height = 300
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setWindowTitle('Hauptmenü')

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.vbox = QVBoxLayout()

        self.initUI()

    def initUI(self):
        self.label_text = QLabel(self)
        text = "<a href='#'>Word1</a> and <a href='#'>Word2</a>"
        self.label_text.setText(text)
        self.vbox.addWidget(self.label_text)
        self.central_widget.setLayout(self.vbox)
        self.show()

        self.label_text.linkActivated.connect(self.function1)

    def function1(self):
        print("ja")

    def function2(self):
        pass

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = Window()
    demo.show()

    sys.exit(app.exec_())
</code>```

When clicking on word1 and word2 in the QLabel different functions should be executed. I don't know how to connect the word2 to the second function.

答:
Use html capabilities and style attribute to override default html link. Now when you click on Word1 and Word2, labelClicked function received the anchor as parameter:

```<code>from PyQt5.QtWidgets import QMainWindow, QLabel, QVBoxLayout, QApplication, QWidget
import sys

class Window(QMainWindow):
    def __init__(self):
        ...

    def initUI(self):
        self.label_text = QLabel(self)
        text = 'Here is the text with <a style="text-decoration:none; color:none" href="#word1">Word1</a> and here comes the <a style="text-decoration:none; color:none" href="#word2">Word2</a>'
        self.label_text.setText(text)
        self.label_text.linkActivated.connect(self.labelClicked)
        self.vbox.addWidget(self.label_text)
        self.central_widget.setLayout(self.vbox)
        self.show()

    def labelClicked(self, link):
        print(link)

if __name__ == '__main__':
    ...
</code>```

Title: Assign function to word in QLabel

Body:
I am searching for a solution for the following problem:
I want to assign a function to a certain word inside a QLabel of PyQt5, so that when the word is clicked the function is executed.

    from PyQt5.QtWidgets import QMainWindow, QLabel, QVBoxLayout, QApplication, QWidget
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = "App"
        self.left = 0
        self.top = 0
        self.width = 700
        self.height = 300
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setWindowTitle('Hauptmenü')

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.vbox = QVBoxLayout()

        self.initUI()

    def initUI(self):
        self.label_text = QLabel(self)
        text = "Word1 and Word2"
        self.label_text.setText(text)
        self.vbox.addWidget(self.label_text)
        self.central_widget.setLayout(self.vbox)
        self.show()

        self.label_text.linkActivated.connect(self.function1)

    def function1(self):
        print("ja")

    def function2(self):
        pass

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = Window()
    demo.show()

    sys.exit(app.exec_())

When clicking on word1 and word2 in the QLabel different functions should be executed. I don't know how to connect the word2 to the second function.

Body:
Use html capabilities and style attribute to override default html link. Now when you click on Word1 and Word2, labelClicked function received the anchor as parameter:

from PyQt5.QtWidgets import QMainWindow, QLabel, QVBoxLayout, QApplication, QWidget
import sys

class Window(QMainWindow):
    def __init__(self):
        ...

    def initUI(self):
        self.label_text = QLabel(self)
        text = 'Here is the text with <a style="text-decoration:none; color:none" href="#word1">Word1</a> and here comes the <a style="text-decoration:none; color:none" href="#word2">Word2</a>'
        self.label_text.setText(text)
        self.label_text.linkActivated.connect(self.labelClicked)
        self.vbox.addWidget(self.label_text)
        self.central_widget.setLayout(self.vbox)
        self.show()

    def labelClicked(self, link):
        print(link)

if __name__ == '__main__':
    ...


答:
It happens because you are removing elements while iterating which changes the length of list while looping. You can use the following code to remove the elements based on a condition in one line.</p>
```<code>def remove_even_length(l):
    l1 = [x for x in l if len(x) % 2]

    return l1
</code>```

Title: issue iterating a python string list

Body:
It happens because you are removing elements while iterating which changes the length of list while looping. You can use the following code to remove the elements based on a condition in one line.

def remove_even_length(l):
    l1 = [x for x in l if len(x) % 2]

    return l1


问:
Why does Safari add a margin between my search input and button elements?
I have a search bar that looks like this Search bar.

However, when I view my website in Safari, it looks like this: Broken search bar.

For some reason, there is a gap between my search icon and search input elements. I've tried disabling webkit styles using -webkit-appearance: none;, but it doesn't work. Here is my code:

body {
background-color: #000000
}

header {
  display: flex;
  justify-content: right;
  margin: 1rem;
}

#search {
  font-family: 'Montserrat', sans-serif;
  border: none;
  border-radius: 5px 0 0 5px;
  padding: 13px;
  background-color: rgba(255, 255, 255, 0.5);
  flex: 0.95;
  color: #ffffff;
  font-weight: bold;
}

#search::placeholder {
  color: #ffffff;
}

#search:focus {
  outline: none;
}

.search-container {
  display: flex;
  max-width: 350px;
  min-width: 350px;
}

.search-button {
  border: none;
  cursor: pointer;
  color: var(--dark-bg);
  background-color: #ffffff;
  border-radius: 0 5px 5px 0;
  font-size: 20px;
  padding: 0 13px;
  flex: 0.05;
}

input[type='search']::-ms-clear {
  display: none;
  width: 0;
  height: 0;
}

input[type='search']::-ms-reveal {
  display: none;
  width: 0;
  height: 0;
}

input[type='search']::-webkit-search-decoration,
input[type='search']::-webkit-search-cancel-button,
input[type='search']::-webkit-search-results-button,
input[type='search']::-webkit-search-results-decoration {
  display: none;
}

input[type='search'],
button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
      <div class="search-container">
        <input
          type="search"
          id="search"
          name="search"
          placeholder="City Search"
          autocomplete="off"
        />
        <button type="submit" class="search-button">
          <i class="fa fa-search"></i>
        </button>
      </div>
    </header></code>```

答:
There is some extra margin that creates this gap on Safari.

So, you can add zero margin to #search and .search-button

#search {
  font-family: 'Montserrat', sans-serif;
  border: none;
  border-radius: 5px 0 0 5px;
  padding: 13px;
  background-color: rgba(255, 255, 255, 0.5);
  flex: 0.95;
  color: #ffffff;
  font-weight: bold;
  margin: 0;
}
```
<pre class="lang-css prettyprint-override"><code>.search-button {
  border: none;
  cursor: pointer;
  color: var(--dark-bg);
  background-color: #ffffff;
  border-radius: 0 5px 5px 0;
  font-size: 20px;
  padding: 0 13px;
  flex: 0.05;
  margin: 0;
}
</code>```

Fiddle: https://jsfiddle.net/kongallis/kdezgsw5/1/

Body:
I have a search bar that looks like this Search bar.

However, when I view my website in Safari, it looks like this: Broken search bar.

For some reason, there is a gap between my search icon and search input elements. I've tried disabling webkit styles using -webkit-appearance: none;, but it doesn't work. Here is my code:

body {
background-color: #000000
}

header {
  display: flex;
  justify-content: right;
  margin: 1rem;
}

#search {
  font-family: 'Montserrat', sans-serif;
  border: none;
  border-radius: 5px 0 0 5px;
  padding: 13px;
  background-color: rgba(255, 255, 255, 0.5);
  flex: 0.95;
  color: #ffffff;
  font-weight: bold;
}

#search::placeholder {
  color: #ffffff;
}

#search:focus {
  outline: none;
}

.search-container {
  display: flex;
  max-width: 350px;
  min-width: 350px;
}

.search-button {
  border: none;
  cursor: pointer;
  color: var(--dark-bg);
  background-color: #ffffff;
  border-radius: 0 5px 5px 0;
  font-size: 20px;
  padding: 0 13px;
  flex: 0.05;
}

input[type='search']::-ms-clear {
  display: none;
  width: 0;
  height: 0;
}

input[type='search']::-ms-reveal {
  display: none;
  width: 0;
  height: 0;
}

input[type='search']::-webkit-search-decoration,
input[type='search']::-webkit-search-cancel-button,
input[type='search']::-webkit-search-results-button,
input[type='search']::-webkit-search-results-decoration {
  display: none;
}

input[type='search'],
button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

        <input
          type="search"
          id="search"
          name="search"
          placeholder="City Search"
          autocomplete="off"
        />
        <button type="submit" class="search-button">

        </button>

Body:
There is some extra margin that creates this gap on Safari.

So, you can add zero margin to #search and .search-button

#search {
  font-family: 'Montserrat', sans-serif;
  border: none;
  border-radius: 5px 0 0 5px;
  padding: 13px;
  background-color: rgba(255, 255, 255, 0.5);
  flex: 0.95;
  color: #ffffff;
  font-weight: bold;
  margin: 0;
}

.search-button {
  border: none;
  cursor: pointer;
  color: var(--dark-bg);
  background-color: #ffffff;
  border-radius: 0 5px 5px 0;
  font-size: 20px;
  padding: 0 13px;
  flex: 0.05;
  margin: 0;
}

Fiddle: https://jsfiddle.net/kongallis/kdezgsw5/1/


问:
ASP.Net Core OData - filter by number of nested matching
I have a root Company entity with CompanyType children. I want to filter companies that have all provided types. It's possible to create such filter in pure SQL

```<code>SELECT Companies.Id, Companies.Name
FROM Companies
JOIN (
  SELECT CompanyTypes.CompanyId FROM CompanyTypes
  WHERE CompanyTypes.CompanyTypeId IN (123, 456, 789, 555)
  GROUP BY CompanyId
  HAVING COUNT(*) = 4
) Types ON Companies.ID = Types.CompanyID
</code>```

It's also possible to create such filter using linq to sql

```<code>var typeIds = new[] { 123, 456, 789, 555 };
var companies = await EFContext.Companies.Where(company => company.CompanyTypes.Count(type => typeIds.Contains(type.CompanyTypeId)) == typeIds.Length).ToListAsync();
</code>```

Is there a way to compose such query using odata syntax? I've tried this

```<code>companyTypeIds/any(i: i eq 123) and companyTypeIds/any(i: i eq 456) and companyTypeIds/any(i: i eq 789) and companyTypeIds/any(i: i eq 555)
</code>```

It gives expected result but underlying query is different and it becomes very slow when number of conditions grows. Is there a way to make it more efficient like provided SQL queries? The backend is using ASP.Net Core 6, EF Core 6, ASP.Net Core OData 8 (latest at the moment).

答:
Having the SQL and the LINQ that you want to translate into an OData query makes this a much easier proposition, the WHERE IN () combined with HAVING COUNT(*) = 4 can both be implemented in OData v4.01 and recently that support has been improved

Adding support for $count segment in $filter collections in OData WebAPI

In OData core  v7.9.0 we added improved support for $count segment in $filter collection properties.

```<code>$filter=navProp/$count($filter=prop gt 1) gt 2
$filter=collectionProp/$count($filter=prop gt 1) gt 2
</code>```

For this LINQ:

```<code>var typeIds = new[] { 123, 456, 789, 555 };
var companies = await EFContext.Companies.Where(company =>
company.CompanyTypes.Count(type => typeIds.Contains(type.CompanyTypeId)) ==
typeIds.Length).ToListAsync();
</code>```

The following should work for your query:

~/Companies?$filter=CompanyTypes/$count($filter=CompanyTypeId in (123, 456, 789, 555) eq 4)

Body:
I have a root Company entity with CompanyType children. I want to filter companies that have all provided types. It's possible to create such filter in pure SQL

SELECT Companies.Id, Companies.Name
FROM Companies
JOIN (
  SELECT CompanyTypes.CompanyId FROM CompanyTypes
  WHERE CompanyTypes.CompanyTypeId IN (123, 456, 789, 555)
  GROUP BY CompanyId
  HAVING COUNT(*) = 4
) Types ON Companies.ID = Types.CompanyID

It's also possible to create such filter using linq to sql

var typeIds = new[] { 123, 456, 789, 555 };
var companies = await EFContext.Companies.Where(company => company.CompanyTypes.Count(type => typeIds.Contains(type.CompanyTypeId)) == typeIds.Length).ToListAsync();

Is there a way to compose such query using odata syntax? I've tried this

companyTypeIds/any(i: i eq 123) and companyTypeIds/any(i: i eq 456) and companyTypeIds/any(i: i eq 789) and companyTypeIds/any(i: i eq 555)

It gives expected result but underlying query is different and it becomes very slow when number of conditions grows. Is there a way to make it more efficient like provided SQL queries? The backend is using ASP.Net Core 6, EF Core 6, ASP.Net Core OData 8 (latest at the moment).

Body:
Having the SQL and the LINQ that you want to translate into an OData query makes this a much easier proposition, the WHERE IN () combined with HAVING COUNT(*) = 4 can both be implemented in OData v4.01 and recently that support has been improved

Adding support for $count segment in $filter collections in OData WebAPI

In OData core  v7.9.0 we added improved support for $count segment in $filter collection properties.

$filter=navProp/$count($filter=prop gt 1) gt 2
$filter=collectionProp/$count($filter=prop gt 1) gt 2

For this LINQ:

var typeIds = new[] { 123, 456, 789, 555 };
var companies = await EFContext.Companies.Where(company =>
company.CompanyTypes.Count(type => typeIds.Contains(type.CompanyTypeId)) ==
typeIds.Length).ToListAsync();

The following should work for your query:

~/Companies?$filter=CompanyTypes/$count($filter=CompanyTypeId in (123, 456, 789, 555) eq 4)


问:
'CountVectorizer()' splitting on space instead of on comma
So in my dataframe I have a column 'Actors' that contains multiple 'first_name last name' of actors.

e.g: 'Dennis Christopher,Dennis Quaid,Daniel Stern' as type 'category'

When I use CountVectorizer().fit_transform(df['Actors']) it will sparse the above group as 6 words. I would like the function to not consider the ' '(space) between names but only the ',' so that with the previous example it would be sparse into 3 words.

```<code>vectorizer = CountVectorizer()
Actors_f = vectorizer.fit_transform(df.loc[df['Actors'].notna(), 'Actors'])
</code>```

Is there a way to do that?

答:
Use the below tokenizer to split by comma in your case:

vectorizer = CountVectorizer(tokenizer=lambda x: x.split(','))

Body:
So in my dataframe I have a column 'Actors' that contains multiple 'first_name last name' of actors.

e.g: 'Dennis Christopher,Dennis Quaid,Daniel Stern' as type 'category'

When I use CountVectorizer().fit_transform(df['Actors']) it will sparse the above group as 6 words. I would like the function to not consider the ' '(space) between names but only the ',' so that with the previous example it would be sparse into 3 words.

vectorizer = CountVectorizer()
Actors_f = vectorizer.fit_transform(df.loc[df['Actors'].notna(), 'Actors'])

Is there a way to do that?


问:
Finding json attribute by wildard with jq
I am trying to find a way to extract JSON attributes using wildcard selection with jq. Is there any way to do it? I have the following JSON file.  The fields can be dynamic for each system. I want to map Core with its "input" temperature (tempX_input).

{
  "Core 0": {
    "temp2_input": "52.000",
    "temp2_max": "100.000",
    "temp2_crit": "100.000",
    "temp2_crit_alarm": "0.000"
  },
  "Core 1": {
    "temp3_input": "53.000",
    "temp3_max": "100.000",
    "temp3_crit": "100.000",
    "temp3_crit_alarm": "0.000"
  }
}
```
<p><strong>Result:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
  "Core 0": "52.000",
  "Core 1": "53.000"
}
</code>```

答:
Using regular expression :</p>
```<code>jq 'map_values(
        to_entries[] |
        select(.key |
                test("temp[[:digit:]]+_input")).value
    )' input.json
</code>```

Body:
I am trying to find a way to extract JSON attributes using wildcard selection with jq. Is there any way to do it? I have the following JSON file.  The fields can be dynamic for each system. I want to map Core with its "input" temperature (tempX_input).

{
  "Core 0": {
    "temp2_input": "52.000",
    "temp2_max": "100.000",
    "temp2_crit": "100.000",
    "temp2_crit_alarm": "0.000"
  },
  "Core 1": {
    "temp3_input": "53.000",
    "temp3_max": "100.000",
    "temp3_crit": "100.000",
    "temp3_crit_alarm": "0.000"
  }
}

Result:

{
  "Core 0": "52.000",
  "Core 1": "53.000"
}

Body:
Using regular expression :

jq 'map_values(
        to_entries[] |
        select(.key |
                test("temp[[:digit:]]+_input")).value
    )' input.json


问:
JavaScript: add new property to array elements according to another array
I have two arrays.

When comparing, if arr1 property id matches with arr2 property id, then add new property tag: assign else add tag: ''

I have tried the below code:

```<code>var result = arr1.filter(({ id: id }) =>
  !arr2.some(({ name: name }) => name === id)
);
</code>```

Sample inputs:

```<code>var arr1 = [
  {id:1, name: "ram"},
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]
var arr2 = [
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]
</code>```

Expected Output:

```<code> [
  {id:1, name: "ram", tag:''},
  {id:24, name: "zen", tag: 'yes'},
  {id: 3, name: "sam", tag: 'yes'}
]
</code>```

答:
Create a Set of ids in arr2 using Array#map

Again, using Array#map, iterate over arr1 and set tag using Set#has

const
  arr1 = [ {id:1, name: "ram"}, {id:24, name: "zen"}, {id: 3, name: "sam"} ],
  arr2 = [ {id:24, name: "zen"}, {id: 3, name: "sam"} ];

const arr2IdsSet = new Set( arr2.map(({ id }) => id) );

const res = arr1.map(e => ({ ...e, tag: arr2IdsSet.has(e.id) ? 'yes' : '' }));

console.log(res);```

Body:
I have two arrays.

When comparing, if arr1 property id matches with arr2 property id, then add new property tag: assign else add tag: ''

I have tried the below code:

var result = arr1.filter(({ id: id }) =>
  !arr2.some(({ name: name }) => name === id)
);

Sample inputs:

var arr1 = [
  {id:1, name: "ram"},
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]
var arr2 = [
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]

Expected Output:

 [
  {id:1, name: "ram", tag:''},
  {id:24, name: "zen", tag: 'yes'},
  {id: 3, name: "sam", tag: 'yes'}
]


问:
Limit TextField to x amount of characters using SwiftUI
Using iOS13.2, Swift-5.1.2, Xcode-11.2, I try the following:

I want to use a TextField. The user shall only be able to enter x-amount of characters into the TextField.

My code looks as follows:

```<code>import Combine
import SwiftUI

class Entry: ObservableObject {

  @Published var entry = "" {
    didSet {
        entry = String(entry.prefix(6)) // trying to limit to 6 characters
    }
  }
}
</code>```

And in the above code, there is already the exception line.

I can see that the didSet{...} is wrong (since we end up in an endless loop setting/didSetting again and again)...

What is a better way to limit a TextField to x-amount of characters ?

Here is the rest of the code:

```<code>struct NumberView: View {
    var body: some View {

        Group {
            HStack {
                Spacer()
                NumberIcon(number: 1)
                NumberIcon(number: 2)
                NumberIcon(number: 3)
                NumberIcon(number: 4)
                NumberIcon(number: 5)
                NumberIcon(number: 6)
                Spacer()
            }
         }
    }
}
</code>```

```<code>struct NumberIcon: View {
    @ObservedObject private var entry = Entry()
    var number: Int = 0
    var body: some View {
        TextField(" ", text: $entry.entry, onEditingChanged: { editing in
            print(editing)
            print(self.$entry)
        })
            .padding()
            .foregroundColor(Color.black)
            .background(Color.green)
            .font(.largeTitle)
            .lineLimit(1)
            .cornerRadius(16.0)
            .clipped()
            .keyboardType(.numberPad)
    }
}

struct NumberView_Previews: PreviewProvider {
    static var previews: some View {
        NumberView()
    }
}
</code>```

I know that there are UIKit wrapper possibilities to use the good-old shouldChangeCharactersIn delegate methods form UITextFieldDelegate - but I would like to implement the character limitation purely with SwiftUI (no UIKit code). How can I do that ?

答:
U can use this:</p>
```<code>.onReceive(variable.publisher.collect()) {
        variable = String($0.prefix(4))
}
</code>```

Body:
Using iOS13.2, Swift-5.1.2, Xcode-11.2, I try the following:

I want to use a TextField. The user shall only be able to enter x-amount of characters into the TextField.

My code looks as follows:

import Combine
import SwiftUI

class Entry: ObservableObject {

  @Published var entry = "" {
    didSet {
        entry = String(entry.prefix(6)) // trying to limit to 6 characters
    }
  }
}

And in the above code, there is already the exception line.

I can see that the didSet{...} is wrong (since we end up in an endless loop setting/didSetting again and again)...

What is a better way to limit a TextField to x-amount of characters ?

Here is the rest of the code:

struct NumberView: View {
    var body: some View {

        Group {
            HStack {
                Spacer()
                NumberIcon(number: 1)
                NumberIcon(number: 2)
                NumberIcon(number: 3)
                NumberIcon(number: 4)
                NumberIcon(number: 5)
                NumberIcon(number: 6)
                Spacer()
            }
         }
    }
}

struct NumberIcon: View {
    @ObservedObject private var entry = Entry()
    var number: Int = 0
    var body: some View {
        TextField(" ", text: $entry.entry, onEditingChanged: { editing in
            print(editing)
            print(self.$entry)
        })
            .padding()
            .foregroundColor(Color.black)
            .background(Color.green)
            .font(.largeTitle)
            .lineLimit(1)
            .cornerRadius(16.0)
            .clipped()
            .keyboardType(.numberPad)
    }
}

struct NumberView_Previews: PreviewProvider {
    static var previews: some View {
        NumberView()
    }
}

I know that there are UIKit wrapper possibilities to use the good-old shouldChangeCharactersIn delegate methods form UITextFieldDelegate - but I would like to implement the character limitation purely with SwiftUI (no UIKit code). How can I do that ?

Body:
U can use this:

.onReceive(variable.publisher.collect()) {
        variable = String($0.prefix(4))
}


问:
OpenCV python: ValueError: too many values to unpack , img
I am writing an opencv project which is a fingers distance finder and making an image(its complicated to explain but I try my best.

When i run the script, I get this error

```<code>Traceback (most recent call last):
  File "D:/P4rakash_Python_Projects/Python Projects/adding things/python.py", line 16, in <module>
    hands, img2 = detector.findHands(img)
ValueError: too many values to unpack (expected 2)
[ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

</code>```

I dont understand this error if someone fix this and answer me I can get the hang off it.

this is the full code

```<code>from cv2 import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = HandDetector(detectionCon=0.8)

startDist = None

scale = 0.
cx, cy = 500, 500
while True:
    Success, img = cap.read()
    hands, img = detector.findHands(img)
    img1 = cv2.imread("kisspng-computer-icons-code-coupon-font-computer-coding-5b4cbf4c6bb012.9457556415317563644411.png")

    if len(hands) == 2:
        # print(detector.fingersUp(hands[0]), detector.fingersUp(hands[1]))
        if detector.fingersUp(hands[0]) == [1, 1, 0, 0, 0] and detector.fingersUp(hands[1]) == [1, 1, 0, 0, 0]:
            # print("ZOOMMING GESTUREs")
            lmList1 = hands[0]["lmList"]
            lmList2 = hands[1]["lmList"]

            # Point 8 is teh tip of the finger
            if startDist is None:
                length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)

                startDist = length

            length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)
            scale = int((length - startDist) // 2)
            cx, cy = info[4:]
            # print(scale)
    else:
        startDist = None
    try:
        h1, w1, _ = img1.shape
        newH, newW = ((h1 + scale) // 2) * 2, ((w1 + scale) // 2) * 2
        img1 = cv2.resize(img1, (newW, newH))

        img[cy - newH // 2:cy + newH // 2, cx - newW // 2:cx + newW // 2] = img1

    except:
        pass

    img = cv2.flip(img, 1)
    cv2.imshow("Hollow.os", img)
    cv2.waitKey(1)

</code>```

when I do this code there is a warning coming called Unexpected argument

help is mostly what I want now

答:
That's because findhands returns only 1 value, not 2.

The right syntax would be

```<code>img2 = detector.findHands(img)
</code>```

Body:
I am writing an opencv project which is a fingers distance finder and making an image(its complicated to explain but I try my best.

When i run the script, I get this error

Traceback (most recent call last):
  File "D:/P4rakash_Python_Projects/Python Projects/adding things/python.py", line 16, in <module>
    hands, img2 = detector.findHands(img)
ValueError: too many values to unpack (expected 2)
[ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

I dont understand this error if someone fix this and answer me I can get the hang off it.

this is the full code

from cv2 import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = HandDetector(detectionCon=0.8)

startDist = None

scale = 0.
cx, cy = 500, 500
while True:
    Success, img = cap.read()
    hands, img = detector.findHands(img)
    img1 = cv2.imread("kisspng-computer-icons-code-coupon-font-computer-coding-5b4cbf4c6bb012.9457556415317563644411.png")

    if len(hands) == 2:
        # print(detector.fingersUp(hands[0]), detector.fingersUp(hands[1]))
        if detector.fingersUp(hands[0]) == [1, 1, 0, 0, 0] and detector.fingersUp(hands[1]) == [1, 1, 0, 0, 0]:
            # print("ZOOMMING GESTUREs")
            lmList1 = hands[0]["lmList"]
            lmList2 = hands[1]["lmList"]

            # Point 8 is teh tip of the finger
            if startDist is None:
                length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)

                startDist = length

            length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)
            scale = int((length - startDist) // 2)
            cx, cy = info[4:]
            # print(scale)
    else:
        startDist = None
    try:
        h1, w1, _ = img1.shape
        newH, newW = ((h1 + scale) // 2) * 2, ((w1 + scale) // 2) * 2
        img1 = cv2.resize(img1, (newW, newH))

        img[cy - newH // 2:cy + newH // 2, cx - newW // 2:cx + newW // 2] = img1

    except:
        pass

    img = cv2.flip(img, 1)
    cv2.imshow("Hollow.os", img)
    cv2.waitKey(1)

when I do this code there is a warning coming called Unexpected argument

help is mostly what I want now

Body:
That's because findhands returns only 1 value, not 2.

The right syntax would be

img2 = detector.findHands(img)


问:
Change font size if the text exceeds the boundary of Textblock
I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?</p>

答:
Edit: I should look at the tags before posting. No clue what WPF might have to offer to solve this.

I don't have any proof to back this up, but it seems that (also for variable-width fonts, at least all the ones installed on my machine):

Font size has a linear relationship with the width of a given string

Font size 0 results in a width of 0

This means you could probably use MeasureString once on the largest font size allowed, and then interpolate to find the optimal font size.

There are some "pixel bumps" on that "linear road" though, so you could be a few pixels off - but it's a good alternative from the measure-loops.


问:
Cartesian product of list of templates and list of types to instantiate them with
Not sure if title is descriptive, but what I would like is this:

input:

list of templates(in my case containers) taking 1 (required, can be more optional) type arguments

list of types

output:

"cartesian product" where each template in first set is instantiated with every type in second set.

example:

```<code>template_list<std::vector, std::set> x type_list<int, double> =>
type_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double>>
</code>```

I found this question, but that is about a case when elements of both sets are types.

How to create the Cartesian product of a type list?

I presume that what I want is impossible without macros, but it may be possible that I am missing something.

答:
You could use std::tuples. Especially std::tuple_cat is nice for this.

Example:

#include <iostream>
#include <set>
#include <tuple>
#include <type_traits>
#include <vector>

template <template <class...> class... C>
struct template_list {};

template <template <class...> class C, class... Ts>
auto toc(const std::tuple<Ts...>&) {
    return std::tuple<C<Ts>...>{};
}

template <template <class...> class... C, class... Ts>
auto operator*(template_list<C...>, const std::tuple<Ts...>& tup) {
    return std::tuple_cat(toc<C>(tup)...);
}

int main() {
    template_list<std::vector, std::set> templ;
    std::tuple<int, double, float> typel;

    auto res = templ * typel;

    static_assert(
        std::is_same_v<decltype(res),
                       std::tuple<std::vector<int>, std::vector<double>,
                                  std::vector<float>, std::set<int>,
                                  std::set<double>, std::set<float>>>);
}
```
<p>Demo</p>
<hr />
<p>A similar solution made into a more classical type trait in which <code>res</code> will result in having the same type as above could look like this:</p>
<pre class="lang-cpp prettyprint-override"><code>template <template <class...> class... C>
struct template_list {};

template <class Temps, class Types>
struct cartesian_product {

    template <template <class...> class C, class... Ts>
    static std::tuple<C<Ts>...> toc(const std::tuple<Ts...>&);

    template <template <class...> class... C, class... Ts>
    static auto build(template_list<C...>, const std::tuple<Ts...>& tup)
        -> decltype(std::tuple_cat(std::declval<decltype(toc<C>(tup))>()...));

    using type = decltype(build(std::declval<Temps>(), std::declval<Types>()));
};

template<class Temps, class Types>
using cartesian_product_t = typename cartesian_product<Temps,Types>::type;
</code>```

int main() {
    using templt = template_list<std::vector, std::set>;
    using typelt = std::tuple<int, double, float>;

    cartesian_product_t<templt, typelt> res;
}
```

Body:
Not sure if title is descriptive, but what I would like is this:

input:

list of templates(in my case containers) taking 1 (required, can be more optional) type arguments

list of types

output:

"cartesian product" where each template in first set is instantiated with every type in second set.

example:

template_list<std::vector, std::set> x type_list<int, double> =>
type_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double>>

I found this question, but that is about a case when elements of both sets are types.

How to create the Cartesian product of a type list?

I presume that what I want is impossible without macros, but it may be possible that I am missing something.

Body:
You could use std::tuples. Especially std::tuple_cat is nice for this.

Example:

#include <iostream>
#include <set>
#include <tuple>
#include <type_traits>
#include <vector>

template <template <class...> class... C>
struct template_list {};

template <template <class...> class C, class... Ts>
auto toc(const std::tuple<Ts...>&) {
    return std::tuple<C<Ts>...>{};
}

template <template <class...> class... C, class... Ts>
auto operator*(template_list<C...>, const std::tuple<Ts...>& tup) {
    return std::tuple_cat(toc<C>(tup)...);
}

int main() {
    template_list<std::vector, std::set> templ;
    std::tuple<int, double, float> typel;

    auto res = templ * typel;

    static_assert(
        std::is_same_v<decltype(res),
                       std::tuple<std::vector<int>, std::vector<double>,
                                  std::vector<float>, std::set<int>,
                                  std::set<double>, std::set<float>>>);
}

Demo

A similar solution made into a more classical type trait in which res will result in having the same type as above could look like this:

template <template <class...> class... C>
struct template_list {};

template <class Temps, class Types>
struct cartesian_product {

    template <template <class...> class C, class... Ts>
    static std::tuple<C<Ts>...> toc(const std::tuple<Ts...>&);

    template <template <class...> class... C, class... Ts>
    static auto build(template_list<C...>, const std::tuple<Ts...>& tup)
        -> decltype(std::tuple_cat(std::declval<decltype(toc<C>(tup))>()...));

    using type = decltype(build(std::declval<Temps>(), std::declval<Types>()));
};

template<class Temps, class Types>
using cartesian_product_t = typename cartesian_product<Temps,Types>::type;

int main() {
    using templt = template_list<std::vector, std::set>;
    using typelt = std::tuple<int, double, float>;

    cartesian_product_t<templt, typelt> res;
}


问:
Flutter animate CrossAxisalignment with tween
I'm searching for a solution to implement a change in the CrossAxisAllignment of a Column using and AnimatedBuilder. As the child of the AnimatedBuilder I use a Column in which I change the CrossAxisAlignment to either start or center.

This was my idea to create the Animation with a Tween but I couldn't find a Tween specificaly for the CrossAxisAlignment:

```<code>_positionAnimation =
        AlignmentTween(begin: CrossAxisAlignment.start end: CrossAxisAlignment.center).animate(_positionController);
</code>```

This is my AnimatedBuilder with the Column as a child to change the alignment.

```<code>AnimatedBuilder(
  animation: _positionController,
  builder: (context, child) => Padding(
    padding: const EdgeInsets.all(16.0),
    child: SizedBox(
      width: double.infinity,
      child: Column(
          crossAxisAlignment: _positionAnimation.value,
          children: [
            FadeTransition(
              opacity: _animationController,
              child: Text(
                carouselList[_current].title,
                style: Theme.of(context).textTheme.headline5,
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            FadeTransition(
              opacity: _animationController,
              child: Text(
                carouselList[_current].paragraph,
                style: Theme.of(context).textTheme.bodyText2,
              ),
            )
          ]),
    ),
  ),
),
</code>```

Is there a way to implement the animation of the CrossAxisAlignment with a Tween?

答:
CrossAxisAlignment is an enum, and enums values are very specific! there is no interpolation between them or a lerp method for them or even a probability to implement one sadly.

But if you want to achive like-effect you can do it using a Stack with Align (Alignment can be interpolated) or Positioned.

But if you insist on using a Flex you can compine Flexible or Expanded with an IntTween or StepTween to get the desired effect.

If the new Tween classes are new to you, here is a  useful link for them.

Body:
I'm searching for a solution to implement a change in the CrossAxisAllignment of a Column using and AnimatedBuilder. As the child of the AnimatedBuilder I use a Column in which I change the CrossAxisAlignment to either start or center.

This was my idea to create the Animation with a Tween but I couldn't find a Tween specificaly for the CrossAxisAlignment:

_positionAnimation =
        AlignmentTween(begin: CrossAxisAlignment.start end: CrossAxisAlignment.center).animate(_positionController);

This is my AnimatedBuilder with the Column as a child to change the alignment.

AnimatedBuilder(
  animation: _positionController,
  builder: (context, child) => Padding(
    padding: const EdgeInsets.all(16.0),
    child: SizedBox(
      width: double.infinity,
      child: Column(
          crossAxisAlignment: _positionAnimation.value,
          children: [
            FadeTransition(
              opacity: _animationController,
              child: Text(
                carouselList[_current].title,
                style: Theme.of(context).textTheme.headline5,
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            FadeTransition(
              opacity: _animationController,
              child: Text(
                carouselList[_current].paragraph,
                style: Theme.of(context).textTheme.bodyText2,
              ),
            )
          ]),
    ),
  ),
),

Is there a way to implement the animation of the CrossAxisAlignment with a Tween?


问:
Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary
I have this dictionary below:

```<code>d ={'1':['a','b'], '2':['c','d']}
</code>```

I need to combine the values of it by using for- loop to become as below:

The expected results:

```<code>ac
ad
bc
bd
</code>```

This is my poor try and I couldn't continue, How can I do it?

My try:

```<code>dic = {'1':['a','b'], '2':['c','d']}
for x ,y in dic.values():
    print(x,y)
</code>```

My output:

```<code>a b
c d
</code>```

答:
```<code>my_dict= {'1':['a', 'b'], '2':['c', 'd'}}
my_list= list(my_dict.values())
for i in my_list[0]:
    for j in my_list[1]:
        print(i+j)
</code>```

Body:
I have this dictionary below:

d ={'1':['a','b'], '2':['c','d']}

I need to combine the values of it by using for- loop to become as below:

The expected results:

ac
ad
bc
bd

This is my poor try and I couldn't continue, How can I do it?

My try:

dic = {'1':['a','b'], '2':['c','d']}
for x ,y in dic.values():
    print(x,y)

My output:

a b
c d


问:
ConcurrentDictionary GetOrAdd async
I want to use something like GetOrAdd with a ConcurrentDictionary as a cache to a webservice.  Is there an async version of this dictionary? GetOrAdd will be making a web request using HttpClient, so it would be nice if there was a version of this dictionary where GetOrAdd was async.

To clear up some confusion, the contents of the dictionary will be the response from a call to a webservice.

```<code>ConcurrentDictionary<string, Response> _cache
    = new ConcurrentDictionary<string, Response>();

var response = _cache.GetOrAdd("id",
    (x) => { _httpClient.GetAsync(x).GetAwaiter().GetResponse(); });
</code>```

答:
I solved this years ago before ConcurrentDictionary and the TPL was born. I'm in a café and don't have that original code but it went something like this.

It's not a rigorous answer but may inspire your own solution. The important thing is to return the value that was just added or exists already along with the boolean so you can fork execution.

The design lets you easily fork the race winning logic vs. the losing logic.

```<code>public bool TryAddValue(TKey key, TValue value, out TValue contains)
{
    // guards etc.

    while (true)
    {
        if (this.concurrentDic.TryAdd(key, value))
        {
            contains = value;
            return true;
        }
        else if (this.concurrentDic.TryGetValue(key, out var existing))
        {
            contains = existing;
            return false;
        }
        else
        {
            // Slipped down the rare path. The value was removed between the
            // above checks. I think just keep trying because we must have
            // been really unlucky.

            // Note this spinning will cause adds to execute out of
            // order since a very unlucky add on a fast moving collection
            // could in theory be bumped again and again before getting
            // lucky and getting its value added, or locating existing.

            // A tiny random sleep might work. Experiment under load.
        }
    }
}
</code>```

This could be made into an extension for ConcurrentDictionary or be a method on its own your own cache or something using locks.

Perhaps a GetOrAdd(K,V) could be used with an Object.ReferenceEquals() to check if it was added or not, instead of the spin design.

To be honest, the above code isn't the point of my answer. The power comes in the simple design of the method signature and how it affords the following:

```<code>static readonly ConcurrentDictionary<string, Task<Task<Thing>>> tasks = new();

//

var newTask = new Task<Task<Thing>>(() => GetThingAsync(thingId));

if (this.tasks.TryAddValue(thingId, newTask, out var task))
{
    task.Start();
}

var thingTask = await task;
var thing = await thingTask;
</code>```

It's a little quirky how a Task needs to hold a Task (if your work is async), and there's the allocations of unused Tasks to consider.

I think it's a shame Microsoft didn't ship its thread-safe collection with this method, or extract a "concurrent collection" interface.

My real implementation was a cache with sophisticated expiring inner collections and stuff. I guess you could subclass the .NET Task class and add a CreatedAt property to aid with eviction.

Disclaimer I've not tried this at all, it's off top of head, but I used this sort of design in an ultra-hi thru-put app in 2009.

Title: ConcurrentDictionary GetOrAdd async

Body:
I want to use something like GetOrAdd with a ConcurrentDictionary as a cache to a webservice.  Is there an async version of this dictionary? GetOrAdd will be making a web request using HttpClient, so it would be nice if there was a version of this dictionary where GetOrAdd was async.

To clear up some confusion, the contents of the dictionary will be the response from a call to a webservice.

ConcurrentDictionary<string, Response> _cache
    = new ConcurrentDictionary<string, Response>();

var response = _cache.GetOrAdd("id",
    (x) => { _httpClient.GetAsync(x).GetAwaiter().GetResponse(); });

Body:
I solved this years ago before ConcurrentDictionary and the TPL was born. I'm in a café and don't have that original code but it went something like this.

It's not a rigorous answer but may inspire your own solution. The important thing is to return the value that was just added or exists already along with the boolean so you can fork execution.

The design lets you easily fork the race winning logic vs. the losing logic.

public bool TryAddValue(TKey key, TValue value, out TValue contains)
{
    // guards etc.

    while (true)
    {
        if (this.concurrentDic.TryAdd(key, value))
        {
            contains = value;
            return true;
        }
        else if (this.concurrentDic.TryGetValue(key, out var existing))
        {
            contains = existing;
            return false;
        }
        else
        {
            // Slipped down the rare path. The value was removed between the
            // above checks. I think just keep trying because we must have
            // been really unlucky.

            // Note this spinning will cause adds to execute out of
            // order since a very unlucky add on a fast moving collection
            // could in theory be bumped again and again before getting
            // lucky and getting its value added, or locating existing.

            // A tiny random sleep might work. Experiment under load.
        }
    }
}

This could be made into an extension for ConcurrentDictionary or be a method on its own your own cache or something using locks.

Perhaps a GetOrAdd(K,V) could be used with an Object.ReferenceEquals() to check if it was added or not, instead of the spin design.

To be honest, the above code isn't the point of my answer. The power comes in the simple design of the method signature and how it affords the following:

static readonly ConcurrentDictionary<string, Task<Task<Thing>>> tasks = new();

//

var newTask = new Task<Task<Thing>>(() => GetThingAsync(thingId));

if (this.tasks.TryAddValue(thingId, newTask, out var task))
{
    task.Start();
}

var thingTask = await task;
var thing = await thingTask;

It's a little quirky how a Task needs to hold a Task (if your work is async), and there's the allocations of unused Tasks to consider.

I think it's a shame Microsoft didn't ship its thread-safe collection with this method, or extract a "concurrent collection" interface.

My real implementation was a cache with sophisticated expiring inner collections and stuff. I guess you could subclass the .NET Task class and add a CreatedAt property to aid with eviction.

Disclaimer I've not tried this at all, it's off top of head, but I used this sort of design in an ultra-hi thru-put app in 2009.


问:
How can I detect the encoding/codepage of a text file?
In our application, we receive text files (.txt, .csv, etc.) from diverse sources. When reading, these files sometimes contain garbage, because the files where created in a different/unknown codepage.

Is there a way to (automatically) detect the codepage of a text file?

The detectEncodingFromByteOrderMarks, on the StreamReader constructor, works for UTF8  and other unicode marked files, but I'm looking for a way to detect code pages, like ibm850, windows1252.

Thanks for your answers, this is what I've done.

The files we receive are from end-users, they do not have a clue about codepages. The receivers are also end-users, by now this is what they know about codepages: Codepages exist, and are annoying.

Solution:

Open the received file in Notepad, look at a garbled piece of text. If somebody is called François or something, with your human intelligence you can guess this.

I've created a small app that the user can use to open the file with, and enter a text that user knows it will appear in the file, when the correct codepage is used.

Loop through all codepages, and display the ones that give a solution with the user provided text.

If more as one codepage pops up, ask the user to specify more text.

答: try and install the perl module Text::Unaccent::PurePerl by typing cpanm Text::Unaccent this generates a build.log file that displays as chinese in some applications as english in others cpanm is the initial text a plausible attempt should you be lucky enough to have spaces in the language is to compare the distribution frequency of words via a statistical test</p>

OwnerDisplayName: GvS

LastEditorDisplayName: GvS


问:
MongoDB Aggregation - Field must be a accumulator object in group stage
I am new to mongodb aggregation. Let's say I have this data:

[
{
            "end_year": 2020,
            "intensity": 12,
            "sector": "Information Technology",
            "topic": "robot",
            "insight": "62 market research reports study robotics industry",
            "url": "http://robohub.org/62-market-research-reports-study-robotics-industry/",
            "region": "",
            "start_year": 2016,
            "impact": "",
            "added": "July, 16 2016 02:44:49",
            "published": "July, 11 2016 00:00:00",
            "country": "",
            "relevance": 3,
            "pestle": "Economic",
            "source": "Robothub",
            "title": "Forecasts the industrial robotics market in APAC to grow at a CAGR of 8.7% during the period 2016-2020 in the top 5 segments.",
            "likelihood": 4
        },
        {
            "end_year": "",
            "intensity": 2,
            "sector": "Government",
            "topic": "government",
            "insight": "Oil, Greed, and Grievances in the Middle East and North Africa",
            "url": "https://www.newsecuritybeat.org/2016/07/oil-greed-grievances-middle-east-north-africa/",
            "region": "",
            "start_year": "",
            "impact": "",
            "added": "July, 16 2016 01:12:21",
            "published": "July, 12 2016 00:00:00",
            "country": "",
            "relevance": 1,
            "pestle": "Political",
            "source": "New Security Beat",
            "title": "Countries threatened by larger-scale insurgencies might want to consider giving regional groups some share in central government decision-making.",
            "likelihood": 2
        }
]        ```
</div>
</div>
</p>
<p>This is my query:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// return all the countries associated with a single topic
const data = await  Data.aggregate([
        { $match: {} },
        { $group: { _id: "$topic",country: ["$country"],likelihood: ["$likelihood"],relevance: ["$relevance"],intensity: ["$intensity"] } }
        ])</code>```

I want to return all countries,likelihoods,relevances associated with a single/common topic

I know how to get the first and last ones using $first and $last operators. How do I get all of them in an array?

答:
We can use $push operator to add all of the field values:

const data = await  Data.aggregate([
        { $match: {} },
        { $group: { _id: "$topic",data: { $push: { country: "$country",likelihood: "$likelihood",relevance: "$relevance",intensity: "$intensity"   } } } }
     ])```

Body:
I am new to mongodb aggregation. Let's say I have this data:

[
{
            "end_year": 2020,
            "intensity": 12,
            "sector": "Information Technology",
            "topic": "robot",
            "insight": "62 market research reports study robotics industry",
            "url": "http://robohub.org/62-market-research-reports-study-robotics-industry/",
            "region": "",
            "start_year": 2016,
            "impact": "",
            "added": "July, 16 2016 02:44:49",
            "published": "July, 11 2016 00:00:00",
            "country": "",
            "relevance": 3,
            "pestle": "Economic",
            "source": "Robothub",
            "title": "Forecasts the industrial robotics market in APAC to grow at a CAGR of 8.7% during the period 2016-2020 in the top 5 segments.",
            "likelihood": 4
        },
        {
            "end_year": "",
            "intensity": 2,
            "sector": "Government",
            "topic": "government",
            "insight": "Oil, Greed, and Grievances in the Middle East and North Africa",
            "url": "https://www.newsecuritybeat.org/2016/07/oil-greed-grievances-middle-east-north-africa/",
            "region": "",
            "start_year": "",
            "impact": "",
            "added": "July, 16 2016 01:12:21",
            "published": "July, 12 2016 00:00:00",
            "country": "",
            "relevance": 1,
            "pestle": "Political",
            "source": "New Security Beat",
            "title": "Countries threatened by larger-scale insurgencies might want to consider giving regional groups some share in central government decision-making.",
            "likelihood": 2
        }
]

This is my query:

// return all the countries associated with a single topic
const data = await  Data.aggregate([
        { $match: {} },
        { $group: { _id: "$topic",country: ["$country"],likelihood: ["$likelihood"],relevance: ["$relevance"],intensity: ["$intensity"] } }
        ])

I want to return all countries,likelihoods,relevances associated with a single/common topic

I know how to get the first and last ones using $first and $last operators. How do I get all of them in an array?


问:
TCPDF 1st page Missing on Import Page
When I try to import a pdf from an existing pdf it removes the first page and starts from the second. where am I going wrong</p>
```<code> $pdf = new TcpdfFpdi('P', 'mm', 'A4', true, 'UTF-8', false, true);

 $pdf->SetCreator('TCPDF Name');
 $pdf->SetAuthor('TCPDF Author');
 $pdf->SetTitle('TCPDF title');
 $pdf->SetSubject('TCPDF Tutorial');
 $pdf->SetKeywords('KEYWORDS');

 $pagecount = $pdf->setSourceFile('/** file path**/');

  for ($i=1; $i<=$pagecount; $i++) {

       $tplId = $pdf->importPage($i);
       $pdf->useTemplate($tplId,0,0,'210','297');

        if ($i < $pagecount)
            $pdf->AddPage('P','A4');
         }

  $pdf->Output(public_path('filename'.pdf'), 'F');
</code>```

答:
```<code>    $pdf = new TcpdfFpdi('P', 'mm', 'A4', true, 'UTF-8', false, true);

   $pages = $pdf->setSourceFile($this->file->path());
     for ($i=1; $i<=$pages; $i++)
        {
           $pdf->AddPage();
           $tplIdx = $pdf->importPage($i);
           $pdf->useTemplate($tplIdx, 0, 0, '210','297');
       }
    $pdf->Output(public_path('filename'.pdf'), 'F');
</code>```

Title: TCPDF 1st page Missing on Import Page

Body:
When I try to import a pdf from an existing pdf it removes the first page and starts from the second. where am I going wrong

 $pdf = new TcpdfFpdi('P', 'mm', 'A4', true, 'UTF-8', false, true);

 $pdf->SetCreator('TCPDF Name');
 $pdf->SetAuthor('TCPDF Author');
 $pdf->SetTitle('TCPDF title');
 $pdf->SetSubject('TCPDF Tutorial');
 $pdf->SetKeywords('KEYWORDS');

 $pagecount = $pdf->setSourceFile('/** file path**/');

  for ($i=1; $i<=$pagecount; $i++) {

       $tplId = $pdf->importPage($i);
       $pdf->useTemplate($tplId,0,0,'210','297');

        if ($i < $pagecount)
            $pdf->AddPage('P','A4');
         }

  $pdf->Output(public_path('filename'.pdf'), 'F');