问:
How to patch Dto to Entity?
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

```<code>@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }
</code>```

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

答:
Two possible ways to resolve this problem. You have to either change the service method to accept the dto and not the entity or you have to create a @Component class which implements Converter, override the convert method and do the necessary field changes there and then @Autowire GenericConversionService in your controller and call genericConversionService.convert(userDto, User.class);

The converter should look like this:

```<code>import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class UserDtoToUser implements Converter<UserDto, User> {

    @Override
    public User convert(UserDto source) {
        User user = new User();
        // user.set ..... for all necessary fields
        return user;
    }

}
</code>```

EDIT

In case you want to check the validity of the fields you're receiving you can simply use the following annotations to ensure your data is correct: @NotBlank - this checks if a field is null or an empty string, @NotNull - this checks if a field is null, @NotEmpty - this checks if a field is null or an empty collection. Important to remember - you must add the @Valid annotation before the object you want to validate (side note - in case of nested objects you also need to add it to your object fields) so it looks like this @RequestBody @Valid UserDto userDto,

And then for the dto it should look something like this:

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

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

public class UserDto {
    @NotNull
    private Integer id;

    @NotBlank
    private String username;

    @NotBlank
    private String password;

    @NotEmpty
    private List<String> roles;
}
</code>```

Change to fields to whatever is in your dto of course. Also in case you need to do more validations there are a number of other validation annotations you can add.

Title: How to patch Dto to Entity?

Body:
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

Body:
Two possible ways to resolve this problem. You have to either change the service method to accept the dto and not the entity or you have to create a @Component class which implements Converter, override the convert method and do the necessary field changes there and then @Autowire GenericConversionService in your controller and call genericConversionService.convert(userDto, User.class);

The converter should look like this:

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class UserDtoToUser implements Converter<UserDto, User> {

    @Override
    public User convert(UserDto source) {
        User user = new User();
        // user.set ..... for all necessary fields
        return user;
    }

}

EDIT

In case you want to check the validity of the fields you're receiving you can simply use the following annotations to ensure your data is correct: @NotBlank - this checks if a field is null or an empty string, @NotNull - this checks if a field is null, @NotEmpty - this checks if a field is null or an empty collection. Important to remember - you must add the @Valid annotation before the object you want to validate (side note - in case of nested objects you also need to add it to your object fields) so it looks like this @RequestBody @Valid UserDto userDto,

And then for the dto it should look something like this:

import java.util.List;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

public class UserDto {
    @NotNull
    private Integer id;

    @NotBlank
    private String username;

    @NotBlank
    private String password;

    @NotEmpty
    private List<String> roles;
}

Change to fields to whatever is in your dto of course. Also in case you need to do more validations there are a number of other validation annotations you can add.


来源: stackexchange

问:
Purpose of function prototypes
From a class exercise:

```Fill in the blanks to print
"it works!" on the screen,
type in the function
prototype before its call.```

```<code>void some_func();
int main()
{
    some_func();
    return 0;
}
void some_func() {
    cout << "it works!" << endl;
}
</code>```

If I am using the function right after I declared it, why did this code define it in the end?
I mean, we could just have declared and defined and then call in the main.
I don't get the point of declaring, calling and then defining.

I have just started learning about functions. I am a beginner.

EDIT from perspective of C.S. teacher: This student is wondering about the purpose of function prototypes generally. This is a typical case of teaching a concept with an example that is simple enough to master, yet so simple it doesn't yet serve a purpose. Perhaps it is still not the right question for StackOverflow, but should at least be closed for the right reason. It is a very common and well-defined question.

答:
It is perfectly fine to put the definition before the use in most cases. The only time the C language requires you to put a non-definition declaration before use is when two or more functions use each other, so one or more of them have to be declared before the others can be defined. I prefer building up a module from smaller/lower parts to larger parts, so I generally put function definitions before the routines that use them. However, the teacher may be presenting this exercise to teach concepts about declarations, not to teach you to use a particular style.

If you have not yet learned about them, you will soon learn about header files. As programs grow more complicated, we no longer want to keep all the source code in one file, for several reasons. (It becomes more difficult to manage more code. Grouping functions by some type of service they provide or some sort of common data they work with can help us organize the source code and keep it more sensible to human understanding. It also makes it easier to reuse functions in other programs.) Once we break a program up into separate source files, some definitions will no longer be in the same source file as routine to use them. So, instead of definitions, we put declarations in the source files as necessary. A routine foo defined in one source file, and other files that use it will have declarations of foo.

This brings up a problem that declarations are then repeated in many places. That becomes a burden to maintain—any time the definition of foo is changed, all the declarations of it have to be changed. And it is easy to make mistakes, which can bugs in the program, because declaring a function differently from how it is defined can cause undesired behavior. To deal with this, declarations for one set of things, typically all those defined in one source file (and intended to be used by other source files), are gathered into one file, called a header file and typically given a name ending in .h. Then other source files merely include the header files that contain the declarations they need, using an #include directive that tells the compiler to include contents the header file in the current compilation as if it were a part of the current source file.

Because of this, you must learn about various ways declarations can be used, including putting them before functions that use the declared functions.

(I would include C++, but its declarations can be more complicated.)

ContentLicense: CC BY-SA 4.0

Title: Purpose of function prototypes

Body:
From a class exercise:

Fill in the blanks to print
"it works!" on the screen,
type in the function
prototype before its call.

void some_func();
int main()
{
    some_func();
    return 0;
}
void some_func() {
    cout << "it works!" << endl;
}

If I am using the function right after I declared it, why did this code define it in the end?
I mean, we could just have declared and defined and then call in the main.
I don't get the point of declaring, calling and then defining.

I have just started learning about functions. I am a beginner.

EDIT from perspective of C.S. teacher: This student is wondering about the purpose of function prototypes generally. This is a typical case of teaching a concept with an example that is simple enough to master, yet so simple it doesn't yet serve a purpose. Perhaps it is still not the right question for StackOverflow, but should at least be closed for the right reason. It is a very common and well-defined question.


问:
get Google Assistant to always complete same action depending on the speaker?
I'm trying to play a prank on a roommate. We have a Google Nest Mini linked to my Google Assistant in the house, I would like it that anytime this particular person talks to the Google Nest, no matter what the command, it will always just play the song "Sweet Home Alabama", is this possible using Google's Dialogflow API?

I've gone through the documentation but haven't found anything on how to check who is actually speaking, or any way to create a blanket command that will do the same action for any command.

答: While you can create routines that take a certain set of phrases and map them to custom behavior, there is no general way to override all behavior for a given user.</p>


问:
Terraform variable to assign using function
```<code>variable "cidr" {
  type = map(string)
  default = {
      development = "x.1.0.0/16"
      qa = "x.1.0.0/16"
      default = "x.1.0.0/16"
  }
}
</code>```

```<code>variable "network_address_space" {
  default = lookup(var.cidr, var.environment_name,"default")
}
</code>```

<p>Am getting error that "Error: Function calls not allowed" </p>

```<code>variable "subnet_address_space": cidr_subnet2_address_space = cidrsubnet(var.network_address_space,8,1)
</code>```

答:
A Terraform Input Variable is analogous to a function argument in a general-purpose programming language: its value comes from an expression in the calling module, not from the current module.

The default mechanism allows us to substitute a value for when the caller doesn't specify one, but because variables are intended for getting data into a module from the outside, it doesn't make sense to set the default to something from inside that module: that would cause the result to potentially be something the caller of the module could never actually specify, because they don't have access to the necessary data.

Terraform has another concept Local Values which are roughly analogous to a local variable within a function in a general-purpose programming language. These can draw from function results and other objects in the current module to produce their value, and so we can use input variables and local values together to provide fallback behaviors like you've illustrated in your question:

```<code>var "environment_name" {
  type = string
}

var "environment_default_cidr_blocks" {
  type = map(string)
  default = {
      development = "10.1.0.0/16"
      qa          = "10.2.0.0/16"
  }
}

var "override_network_range" {
  type    = string
  default = null   # If not set by caller, will be null
}

locals {
  subnet_cidr_block = (
    var.override_network_range != null ?
    var.override_network_range :
    var.environment_default_cidr_blocks[var.environment_name]
  )
}
</code>```

Elsewhere in the module you can use local.subnet_cidr_block to refer to the final CIDR block selection, regardless of whether it was set explicitly by the caller or by lookup into the table of defaults.

When a module uses computation to make a decision like this, it is sometimes useful for the module to export its result as an Output Value so that the calling module can make use of it too, similar to how Terraform resources also export additional attributes recording decisions made by the provider or by the remote API:

```<code>output "subnet_cidr_block" {
  value = local.subnet_cidr_block
}
</code>```

Body:
variable "cidr" {
  type = map(string)
  default = {
      development = "x.1.0.0/16"
      qa = "x.1.0.0/16"
      default = "x.1.0.0/16"
  }
}

variable "network_address_space" {
  default = lookup(var.cidr, var.environment_name,"default")
}

Am getting error that "Error: Function calls not allowed"

variable "subnet_address_space": cidr_subnet2_address_space = cidrsubnet(var.network_address_space,8,1)

Body:
A Terraform Input Variable is analogous to a function argument in a general-purpose programming language: its value comes from an expression in the calling module, not from the current module.

The default mechanism allows us to substitute a value for when the caller doesn't specify one, but because variables are intended for getting data into a module from the outside, it doesn't make sense to set the default to something from inside that module: that would cause the result to potentially be something the caller of the module could never actually specify, because they don't have access to the necessary data.

Terraform has another concept Local Values which are roughly analogous to a local variable within a function in a general-purpose programming language. These can draw from function results and other objects in the current module to produce their value, and so we can use input variables and local values together to provide fallback behaviors like you've illustrated in your question:

var "environment_name" {
  type = string
}

var "environment_default_cidr_blocks" {
  type = map(string)
  default = {
      development = "10.1.0.0/16"
      qa          = "10.2.0.0/16"
  }
}

var "override_network_range" {
  type    = string
  default = null   # If not set by caller, will be null
}

locals {
  subnet_cidr_block = (
    var.override_network_range != null ?
    var.override_network_range :
    var.environment_default_cidr_blocks[var.environment_name]
  )
}

Elsewhere in the module you can use local.subnet_cidr_block to refer to the final CIDR block selection, regardless of whether it was set explicitly by the caller or by lookup into the table of defaults.

When a module uses computation to make a decision like this, it is sometimes useful for the module to export its result as an Output Value so that the calling module can make use of it too, similar to how Terraform resources also export additional attributes recording decisions made by the provider or by the remote API:

output "subnet_cidr_block" {
  value = local.subnet_cidr_block
}


问:
DAX sum filtered by multiple columns of related tables
I have a measure, which is being added to a table and a Card. The measure is used to show the total hours posted where Calls.[Sch Engineer]=Hours.Employee AND Calls.ProjID=Hours.ProjID

The value on each row of the table is correct. However the total value for this measure is incorrect in the table and also the Card, and I cant work out why.

So the measure is:

```<code>SchEngHrsOnly =
VAR main =
    MAX ( Calls[Sch Engineer] )
RETURN
    CALCULATE ( SUM ( 'Hours'[Hrs] ), Hours[Employee] = main )
</code>```

When I add this to a table visual I get the following - both Table total and Card value for measure are incorrect - they should be 163.50:

If I select a row in the table visual, then the Card visual shows a correct value, otherwise it shows an incorrect value:

My data model is:

My relationships are:

What I am looking to get is:

Also, please see here the PBIX file:

PBIX File

Can anyone help with this issue please?

答:
You can create it as a calculated column and then sum it up to get the value:

```<code>Hours Calc = CALCULATE(MAX(Hours[Hrs]),FILTER(Hours,Hours[ProjID]=Calls[ProjID]))
</code>```

The above calculation will add a column with the maximum of hours for each project ID. Then you can sum it up in the final table and should get the desired results. Hope this helps.

Body:
I have a measure, which is being added to a table and a Card. The measure is used to show the total hours posted where Calls.[Sch Engineer]=Hours.Employee AND Calls.ProjID=Hours.ProjID

The value on each row of the table is correct. However the total value for this measure is incorrect in the table and also the Card, and I cant work out why.

So the measure is:

SchEngHrsOnly =
VAR main =
    MAX ( Calls[Sch Engineer] )
RETURN
    CALCULATE ( SUM ( 'Hours'[Hrs] ), Hours[Employee] = main )

When I add this to a table visual I get the following - both Table total and Card value for measure are incorrect - they should be 163.50:

If I select a row in the table visual, then the Card visual shows a correct value, otherwise it shows an incorrect value:

My data model is:

My relationships are:

What I am looking to get is:

Also, please see here the PBIX file:

PBIX File

Can anyone help with this issue please?

Body:
You can create it as a calculated column and then sum it up to get the value:

Hours Calc = CALCULATE(MAX(Hours[Hrs]),FILTER(Hours,Hours[ProjID]=Calls[ProjID]))

The above calculation will add a column with the maximum of hours for each project ID. Then you can sum it up in the final table and should get the desired results. Hope this helps.


问:
Remove scripts from html string using regex
I want to remove

but this won't:

How can I update the regex to fix this?

答:
Since JavaScript does not support the Singleline /s flag you will need to do a workaround for .:

```<code>/<script.*?>[\s\S]*?<\/script>/gi
</code>```

https://regex101.com/r/7iFLnA/1

Body:
Since JavaScript does not support the Singleline /s flag you will need to do a workaround for .:

/<script.*?>[\s\S]*?<\/script>/gi

https://regex101.com/r/7iFLnA/1


问:
EXCEL isThisWeek()
I would like a formula that would return true if a given date is in this week, for example:
Lets say Today() is 2/18/2020
I would want it to return true if the GivenDate() is anywhere between 2/16/2020 and 2/22/2020.
I would also like a formula for isNextWeek().</p>

答:
Assuming the expected date is in cell A1, get the previous Monday:

```<code>=TODAY()-WEEKDAY(TODAY(),2)+1
</code>```

Get the coming Sunday:

```<code>=TODAY()-WEEKDAY(TODAY(),2)+7
</code>```

You can change the +1 to +8 for the next Monday, and the +7 to +14 for the next Sunday.  So in effect,

```<code>=IF(AND(A1>=(TODAY()-WEEKDAY(TODAY(),2)+1),A1<=(TODAY()-WEEKDAY(TODAY(),2)+7)),"YES","NO")
</code>```

This will return YES if A1 is between Monday and Sunday of this week.

```<code>=IF(AND(A1>=(TODAY()-WEEKDAY(TODAY(),2)+8),A1<=(TODAY()-WEEKDAY(TODAY(),2)+14)),"YES","NO")
</code>```

This will return YES if A1 is between Monday and Sunday of next week.

I'm certain this can be simplified.

Title: EXCEL isThisWeek()

Body:
Assuming the expected date is in cell A1, get the previous Monday:

=TODAY()-WEEKDAY(TODAY(),2)+1

Get the coming Sunday:

=TODAY()-WEEKDAY(TODAY(),2)+7

You can change the +1 to +8 for the next Monday, and the +7 to +14 for the next Sunday.  So in effect,

=IF(AND(A1>=(TODAY()-WEEKDAY(TODAY(),2)+1),A1<=(TODAY()-WEEKDAY(TODAY(),2)+7)),"YES","NO")

This will return YES if A1 is between Monday and Sunday of this week.

=IF(AND(A1>=(TODAY()-WEEKDAY(TODAY(),2)+8),A1<=(TODAY()-WEEKDAY(TODAY(),2)+14)),"YES","NO")

This will return YES if A1 is between Monday and Sunday of next week.

I'm certain this can be simplified.


问:
Shortest way to access VARCHAR by index
In C/++/#/Java/everything I would just my_str[desired_index] and that's all.

But in SQL (at least Oracle) the only way I've found so far:

```<code>SUBSTR( my_str, desired_index, 1)
</code>```

But it's so awkward, I can't believe in 2011 I have to do this.

Is there other way?

答:
That is the standard way to do it in SQL.  Some DBMS have a dialect of SQL that supports an alternative notation; for example, Informix supports my_str[desired_index] (and, for a three-character substring, my_str[12,14] where both values are offsets).

The question is - why do you need to write that in SQL?

ContentLicense: CC BY-SA 3.0

Title: Shortest way to access VARCHAR by index

Body:
In C/++/#/Java/everything I would just my_str[desired_index] and that's all.

But in SQL (at least Oracle) the only way I've found so far:

SUBSTR( my_str, desired_index, 1)

But it's so awkward, I can't believe in 2011 I have to do this.

Is there other way?


问:
Transpose Pandas dataframe preserving the index
I have a problem while transposing a Pandas DataFrame that has the following structure:

```
            0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16
foo         0  4  0  0  0  0  0  0  0  0  14   1   0   1   0   0   0
bar         0  6  0  0  4  0  5  0  0  0   0   0   0   0   1   0   0
lorem       1  3  0  0  0  1  0  0  2  0   3   0   1   2   1   1   0
ipsum       1  2  0  1  0  0  1  0  0  0   0   0   4   0   6   0   0
dolor       1  2  4  0  1  0  0  0  0  0   2   0   0   1   0   0   2
..
```

With index:

```<code>foo,bar,lorem,ipsum,dolor,...
</code>```

And this is basically a terms-documents matrix, where rows are terms and the headers (0-16) are document indexes.
Since my purpose is clustering documents and not terms, I want to transpose the dataframe and use this to perform a cosine-distance computation between documents themselves.
But when I transpose with:

```<code>pd.transpose()
</code>```

I get:

```
   foo       bar    ...       pippo                     lorem
0    0         0    ...       0                         0
1    4         6    ...       0                         0
2    0         0    ...       0                         0
3    0         0    ...       0                         0
4    0         4    ...       0                         0
..
16   0         2    ...       0                         1
```

With index:

```<code>0 , 1 , 2 , 3 , ... , 15, 16
</code>```

What I would like?
I'm looking for a way to make this operation preserving the dataframe index. Basically the first row of my new df should be the index.

Thank you

Body:
I have a problem while transposing a Pandas DataFrame that has the following structure:

            0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16
foo         0  4  0  0  0  0  0  0  0  0  14   1   0   1   0   0   0
bar         0  6  0  0  4  0  5  0  0  0   0   0   0   0   1   0   0
lorem       1  3  0  0  0  1  0  0  2  0   3   0   1   2   1   1   0
ipsum       1  2  0  1  0  0  1  0  0  0   0   0   4   0   6   0   0
dolor       1  2  4  0  1  0  0  0  0  0   2   0   0   1   0   0   2
..

With index:

foo,bar,lorem,ipsum,dolor,...

And this is basically a terms-documents matrix, where rows are terms and the headers (0-16) are document indexes.
Since my purpose is clustering documents and not terms, I want to transpose the dataframe and use this to perform a cosine-distance computation between documents themselves.
But when I transpose with:

pd.transpose()

I get:

   foo       bar    ...       pippo                     lorem
0    0         0    ...       0                         0
1    4         6    ...       0                         0
2    0         0    ...       0                         0
3    0         0    ...       0                         0
4    0         4    ...       0                         0
..
16   0         2    ...       0                         1

With index:

0 , 1 , 2 , 3 , ... , 15, 16

What I would like?
I'm looking for a way to make this operation preserving the dataframe index. Basically the first row of my new df should be the index.

Thank you

Body:
We can use a series of unstack

df2 = df.unstack().to_frame().unstack(1).droplevel(0,axis=1)

print(df2)

   foo bar lorem ipsum dolor
0    0   0     1     1     1
1    4   6     3     2     2
2    0   0     0     0     4
3    0   0     0     1     0
4    0   4     0     0     1
5    0   0     1     0     0
6    0   5     0     1     0
7    0   0     0     0     0
8    0   0     2     0     0
9    0   0     0     0     0
10  14   0     3     0     2
11   1   0     0     0     0
12   0   0     1     4     0
13   1   0     2     0     1
14   0   1     1     6     0
15   0   0     1     0     0
16   0   0     0     0     2


问:
foreign key constraints not enforced on MariaDB, what am I doing wrong?
Even though I thought I understood the logic in foreign keys, I cannot make this small example to work.

In this example, I am inserting values that break the foreign key constrain. I would expect to receive an error -- but I do not.

```<code>/* info about my server */
select version();
show variables where variable_name = "foreign_key_checks";

/* example starts here */
create table foo (id int primary key) engine = 'InnoDB';
insert into foo values (1);
create table bar (id int primary key references foo(id)) engine = 'InnoDB';
insert into bar values (2); -- should complain here, but does not
commit;
select * from foo;
select * from bar;
</code>```

This results in:

```<code>MariaDB [test]> select version();
+-----------------+
| version()       |
+-----------------+
| 10.3.21-MariaDB |
+-----------------+
1 row in set (0.000 sec)

MariaDB [test]> show variables where variable_name = "foreign_key_checks";
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| foreign_key_checks | ON    |
+--------------------+-------+
1 row in set (0.002 sec)

MariaDB [test]> create table foo (id int primary key) engine = 'InnoDB';
Query OK, 0 rows affected (0.358 sec)

MariaDB [test]> insert into foo values (1);
Query OK, 1 row affected (0.040 sec)

MariaDB [test]> create table bar (id int primary key references foo(id)) engine = 'InnoDB';
Query OK, 0 rows affected (0.205 sec)

MariaDB [test]> insert into bar values (2);
Query OK, 1 row affected (0.024 sec)

MariaDB [test]> commit;
Query OK, 0 rows affected (0.000 sec)

MariaDB [test]> select * from foo;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.001 sec)

MariaDB [test]> select * from bar;
+----+
| id |
+----+
|  2 |
+----+
1 row in set (0.000 sec)
</code>```

So since "It looks like [my] post is mostly code; please add some more details.", let me paraphrase here. In the above,

I checked that my server is set up to enforce foreign key contraints,

I explicitly use the InnoDB engine -- the one actually enforcing foreign key contraints.

Despite that, bar contains an id of 2 that is not present in foo. What am I doing wrong here?

答:
insert into foo values (1);
create table bar (id int not null primary key, id_foo int, foreign key (id_foo) references foo(id)); should works for you.

insert into bar values (2,1);

Body:
Even though I thought I understood the logic in foreign keys, I cannot make this small example to work.

In this example, I am inserting values that break the foreign key constrain. I would expect to receive an error -- but I do not.

/* info about my server */
select version();
show variables where variable_name = "foreign_key_checks";

/* example starts here */
create table foo (id int primary key) engine = 'InnoDB';
insert into foo values (1);
create table bar (id int primary key references foo(id)) engine = 'InnoDB';
insert into bar values (2); -- should complain here, but does not
commit;
select * from foo;
select * from bar;

This results in:

MariaDB [test]> select version();
+-----------------+
| version()       |
+-----------------+
| 10.3.21-MariaDB |
+-----------------+
1 row in set (0.000 sec)

MariaDB [test]> show variables where variable_name = "foreign_key_checks";
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| foreign_key_checks | ON    |
+--------------------+-------+
1 row in set (0.002 sec)

MariaDB [test]> create table foo (id int primary key) engine = 'InnoDB';
Query OK, 0 rows affected (0.358 sec)

MariaDB [test]> insert into foo values (1);
Query OK, 1 row affected (0.040 sec)

MariaDB [test]> create table bar (id int primary key references foo(id)) engine = 'InnoDB';
Query OK, 0 rows affected (0.205 sec)

MariaDB [test]> insert into bar values (2);
Query OK, 1 row affected (0.024 sec)

MariaDB [test]> commit;
Query OK, 0 rows affected (0.000 sec)

MariaDB [test]> select * from foo;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.001 sec)

MariaDB [test]> select * from bar;
+----+
| id |
+----+
|  2 |
+----+
1 row in set (0.000 sec)

So since "It looks like [my] post is mostly code; please add some more details.", let me paraphrase here. In the above,

I checked that my server is set up to enforce foreign key contraints,

I explicitly use the InnoDB engine -- the one actually enforcing foreign key contraints.

Despite that, bar contains an id of 2 that is not present in foo. What am I doing wrong here?


问:
Can't bind value to ngModel in p-autocomplete
I have component , where I use primeNG p-autocomplete

Here is html of this component

```<code><form #addressForm="ngForm" novalidate name="AddressForm">
<div class="form-group">
    <label for="Line1">{{ 'AddressLine1' | localize }} *</label>
    <p-autoComplete
        #addressLine1="ngModel"
        [(ngModel)]="address.line1"
        [suggestions]="addresses"
        field="name"
        [inputStyle]="{ width: '100%' }"
        name="lin1"
        (completeMethod)="searchAddress($event)"
        [size]="10"
        placeholder="{{ 'Line1Placeholder' | localize }}"
        (onSelect)="onSelectAddress($event)"
        [minLength]="3"
        required
        (change)="checkValidity()"
    ></p-autoComplete>
    <validation-messages [formCtrl]="addressLine1"></validation-messages>
  {{address.line1}}
</div>

<div class="form-group">
    <label for="Line2">{{ 'AddressLine2' | localize }}</label>
    <input
        id="Line2"
        class="form-control"
        #line2Input="ngModel"
        type="text"
        name="Line2"
        placeholder="{{ 'Line2Placeholder' | localize }}"
        [(ngModel)]="address.line2"
        maxlength="128"
        (change)="checkValidity()"
    />
</div>
<div class="form-group">
    <label for="Line3">{{ 'AddressLine3' | localize }} </label>
    <input
        id="Line3"
        class="form-control"
        #line3Input="ngModel"
        type="text"
        name="Line3"
        [(ngModel)]="address.line3"
        maxlength="128"
        (change)="checkValidity()"
    />
    <validation-messages [formCtrl]="line3Input"></validation-messages>
</div>
</code>```

and here is typescript part of component

```<code> import { Component, Injector, forwardRef, ViewChild, AfterContentChecked, ElementRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, ValidationErrors } from '@angular/forms';
import { AddressType } from '@shared/AppEnums';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AddressDto } from '@shared/service-proxies/service-proxies';
import { SelectItem } from 'primeng/primeng';
import PlaceResult = google.maps.places.PlaceResult;
import { Feature } from '../../dto/mapboxOutput';
import { MapboxServiceService } from '../mapbox-service';

@Component({
    selector: 'edit-main-address',
    templateUrl: './edit-main-address.component.html',
    providers: [
        { provide: NG_VALUE_ACCESSOR, useExisting: EditMainAddressComponent, multi: true },
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => EditMainAddressComponent),
            multi: true,
        },
    ],
})
export class EditMainAddressComponent extends AppComponentBase implements ControlValueAccessor, AfterContentChecked {
    @ViewChild('addressForm') addressForm;
    @ViewChild('search') public searchElement: ElementRef;
    @ViewChild('postCode') public postCodeElement: ElementRef;
    @ViewChild('town') public townElement: ElementRef;
    @ViewChild('country') public countryElement: ElementRef;
    required: string | boolean;

    private changed = [];
    private touched = [];

    public selectedAddress: PlaceResult;
    disabled: boolean;
    address: AddressDto = new AddressDto();
    addressTypes: SelectItem[] = [];
    addresses: any[] = [];
    selectedAddresses: any = null;
    public lat: any;
    public lng: any;
    public postCode: string;
    public country: string;
    public city: string;
    public line1: any;

    constructor(injector: Injector, private mapboxService: MapboxServiceService) {
        super(injector);
        this.addressTypes.push({ label: this.l('Address.Main'), value: AddressType.Main });
        this.addressTypes.push({ label: this.l('Address.Billing'), value: AddressType.Billing });
        this.addressTypes.push({ label: this.l('Address.Delivery'), value: AddressType.Delivery });
        this.addressTypes.push({ label: this.l('Address.Correspondence'), value: AddressType.Correspondence });
    }

    ngAfterContentChecked(): void {
        this.checkValidity();
    }

    checkValidity(): void {}

    get value(): AddressDto {
        return this.address;
    }

    set value(value: AddressDto) {
        if (this.address !== value) {
            this.address = value;
            this.changed.forEach(f => f(value));
        }
    }

    registerOnChange(fn: any): void {
        this.changed.push(fn);
    }

    registerOnTouched(fn: any): void {
        this.touched.push(fn);
    }

    setDisabledState(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    writeValue(obj: AddressDto): void {
        if (obj) {
            this.address = obj;
            this.checkValidity();
        }
    }

    validate(): ValidationErrors {
        if (!this.addressForm.valid) {
            return { message: 'custom error' };
        }
        return null;
    }

    registerOnValidatorChange(fn: () => void): void {
        this.checkValidity = fn;
    }

    searchAddress(event: any): any {
        const searchTerm = event.query.toLowerCase();
        if (searchTerm && searchTerm.length > 0) {
            this.mapboxService.addressSearch(searchTerm).subscribe((features: Feature[]) => {
                this.addresses = [...features.map(e => ({ name: e.place_name, id: e.place_name, feature: e }))];
            });
        } else {
            this.addresses = [];
        }
    }

   onSelectAddress(event: any): any {
    if (event.feature.id.startsWith('address')) {
        this.address.line1 = event.name;
        this.address.longitude = event.feature.center[0];
        this.address.latitude = event.feature.center[1];
        this.address.postTown = event.feature.context.filter(element =>
            element.id.startsWith('place')
        )[0].text;
        this.address.county = event.feature.context.filter(element =>
            element.id.startsWith('district')
        )[0].text;
        this.address.country = event.feature.context.filter(element =>
            element.id.startsWith('country')
        )[0].text;
        this.address.postCode = event.feature.context.filter(element =>
            element.id.startsWith('postcode')
        )[0].text;
    }
    if (event.feature.id.startsWith('postcode')) {
        this.address.line1 = event.name;
        this.address.longitude = event.feature.center[0];
        this.address.latitude = event.feature.center[1];
        this.address.postTown =event.feature.context.filter(element =>
            element.id.startsWith('place')
        )[0].text;
        this.address.county = event.feature.context.filter(element =>
            element.id.startsWith('district')
        )[0].text;
        this.address.country = event.feature.context.filter(element =>
            element.id.startsWith('country')
        )[0].text;
        this.address.postCode = event.feature.text;
    }
}
    ngOnInit(): void {}
}
</code>```

My problem is all fields with ngModel set great, but p-autocomplete is not setted

but if I wrote {{address.line1}} under input, all okay. You can see it from the screenshot.

Where can be my trouble, and how I can fix it?

答:
You search addresses with searchAddress() which fills the addresses property.
Addresses are complex objects not simple strings, right?

```<code> [suggestions]="addresses"
 (completeMethod)="searchAddress($event)"
 [(ngModel)]="address.line1"
</code>```

so the ngModel of the p-autocomplete will be the selected address object.
but then you bind ngModel to address.line1 which is expected to be a string.
Furthermore the address.line1 is then filled by the onSelectAddress method:

```<code>this.address.line1 = event.name;
</code>```

I recommend you separate the selected address object from the address.line1 and bind the ngModel to a different property - say [(ngModel)]="selectedAddress"

Body:
I have component , where I use primeNG p-autocomplete

Here is html of this component

<form #addressForm="ngForm" novalidate name="AddressForm">

    {{ 'AddressLine1' | localize }} *

    <validation-messages [formCtrl]="addressLine1"></validation-messages>
  {{address.line1}}

    {{ 'AddressLine2' | localize }}
    <input
        id="Line2"
        class="form-control"
        #line2Input="ngModel"
        type="text"
        name="Line2"
        placeholder="{{ 'Line2Placeholder' | localize }}"
        [(ngModel)]="address.line2"
        maxlength="128"
        (change)="checkValidity()"
    />

    {{ 'AddressLine3' | localize }}
    <input
        id="Line3"
        class="form-control"
        #line3Input="ngModel"
        type="text"
        name="Line3"
        [(ngModel)]="address.line3"
        maxlength="128"
        (change)="checkValidity()"
    />
    <validation-messages [formCtrl]="line3Input"></validation-messages>

and here is typescript part of component

 import { Component, Injector, forwardRef, ViewChild, AfterContentChecked, ElementRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, ValidationErrors } from '@angular/forms';
import { AddressType } from '@shared/AppEnums';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AddressDto } from '@shared/service-proxies/service-proxies';
import { SelectItem } from 'primeng/primeng';
import PlaceResult = google.maps.places.PlaceResult;
import { Feature } from '../../dto/mapboxOutput';
import { MapboxServiceService } from '../mapbox-service';

@Component({
    selector: 'edit-main-address',
    templateUrl: './edit-main-address.component.html',
    providers: [
        { provide: NG_VALUE_ACCESSOR, useExisting: EditMainAddressComponent, multi: true },
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => EditMainAddressComponent),
            multi: true,
        },
    ],
})
export class EditMainAddressComponent extends AppComponentBase implements ControlValueAccessor, AfterContentChecked {
    @ViewChild('addressForm') addressForm;
    @ViewChild('search') public searchElement: ElementRef;
    @ViewChild('postCode') public postCodeElement: ElementRef;
    @ViewChild('town') public townElement: ElementRef;
    @ViewChild('country') public countryElement: ElementRef;
    required: string | boolean;

    private changed = [];
    private touched = [];

    public selectedAddress: PlaceResult;
    disabled: boolean;
    address: AddressDto = new AddressDto();
    addressTypes: SelectItem[] = [];
    addresses: any[] = [];
    selectedAddresses: any = null;
    public lat: any;
    public lng: any;
    public postCode: string;
    public country: string;
    public city: string;
    public line1: any;

    constructor(injector: Injector, private mapboxService: MapboxServiceService) {
        super(injector);
        this.addressTypes.push({ label: this.l('Address.Main'), value: AddressType.Main });
        this.addressTypes.push({ label: this.l('Address.Billing'), value: AddressType.Billing });
        this.addressTypes.push({ label: this.l('Address.Delivery'), value: AddressType.Delivery });
        this.addressTypes.push({ label: this.l('Address.Correspondence'), value: AddressType.Correspondence });
    }

    ngAfterContentChecked(): void {
        this.checkValidity();
    }

    checkValidity(): void {}

    get value(): AddressDto {
        return this.address;
    }

    set value(value: AddressDto) {
        if (this.address !== value) {
            this.address = value;
            this.changed.forEach(f => f(value));
        }
    }

    registerOnChange(fn: any): void {
        this.changed.push(fn);
    }

    registerOnTouched(fn: any): void {
        this.touched.push(fn);
    }

    setDisabledState(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    writeValue(obj: AddressDto): void {
        if (obj) {
            this.address = obj;
            this.checkValidity();
        }
    }

    validate(): ValidationErrors {
        if (!this.addressForm.valid) {
            return { message: 'custom error' };
        }
        return null;
    }

    registerOnValidatorChange(fn: () => void): void {
        this.checkValidity = fn;
    }

    searchAddress(event: any): any {
        const searchTerm = event.query.toLowerCase();
        if (searchTerm && searchTerm.length > 0) {
            this.mapboxService.addressSearch(searchTerm).subscribe((features: Feature[]) => {
                this.addresses = [...features.map(e => ({ name: e.place_name, id: e.place_name, feature: e }))];
            });
        } else {
            this.addresses = [];
        }
    }

   onSelectAddress(event: any): any {
    if (event.feature.id.startsWith('address')) {
        this.address.line1 = event.name;
        this.address.longitude = event.feature.center[0];
        this.address.latitude = event.feature.center[1];
        this.address.postTown = event.feature.context.filter(element =>
            element.id.startsWith('place')
        )[0].text;
        this.address.county = event.feature.context.filter(element =>
            element.id.startsWith('district')
        )[0].text;
        this.address.country = event.feature.context.filter(element =>
            element.id.startsWith('country')
        )[0].text;
        this.address.postCode = event.feature.context.filter(element =>
            element.id.startsWith('postcode')
        )[0].text;
    }
    if (event.feature.id.startsWith('postcode')) {
        this.address.line1 = event.name;
        this.address.longitude = event.feature.center[0];
        this.address.latitude = event.feature.center[1];
        this.address.postTown =event.feature.context.filter(element =>
            element.id.startsWith('place')
        )[0].text;
        this.address.county = event.feature.context.filter(element =>
            element.id.startsWith('district')
        )[0].text;
        this.address.country = event.feature.context.filter(element =>
            element.id.startsWith('country')
        )[0].text;
        this.address.postCode = event.feature.text;
    }
}
    ngOnInit(): void {}
}

My problem is all fields with ngModel set great, but p-autocomplete is not setted

but if I wrote {{address.line1}} under input, all okay. You can see it from the screenshot.

Where can be my trouble, and how I can fix it?

Body:
You search addresses with searchAddress() which fills the addresses property.
Addresses are complex objects not simple strings, right?

 [suggestions]="addresses"
 (completeMethod)="searchAddress($event)"
 [(ngModel)]="address.line1"

so the ngModel of the p-autocomplete will be the selected address object.
but then you bind ngModel to address.line1 which is expected to be a string.
Furthermore the address.line1 is then filled by the onSelectAddress method:

this.address.line1 = event.name;

I recommend you separate the selected address object from the address.line1 and bind the ngModel to a different property - say [(ngModel)]="selectedAddress"


问:
Dynamic Join condition Depending on Ranking
I have 3 tables

```<code>CREATE TABLE TableA(SomeID INT NOT NULL, Ranking smallint not null)

INSERT INTO TableA(1,1)
INSERT INTO TableA(2,2)
INSERT INTO TableA(3,1)
INSERT INTO TableA(4,1)
INSERT INTO TableA(5,2)
</code>```

I have 2 detailed tables and want to join to determine Join condition from TableA depending on Ranking column

```<code>CREATE TABLE TableB(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableB(1,'2019-10-21')
INSERT INTO TableB(2,'2018-10-21')
INSERT INTO TableB(3,'2017-10-21')
INSERT INTO TableB(4,'2016-10-21')
INSERT INTO TableB(5,'2015-10-21')

CREATE TABLE TableC(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableC(1,'2016-10-21')
INSERT INTO TableC(2,'2015-10-21')
INSERT INTO TableC(3,'2014-10-21')
INSERT INTO TableC(4,'2013-10-21')
INSERT INTO TableC(5,'2012-10-21')
</code>```

I want to Join TableA with TableB or TableC depending on value of Ranking.
If Ranking=1 Join TableA with TableB
If Ranking=2 Join TableA with TableC

Expected OUTPUT is

```<code>SomeID,Somedetailedinfo
1,'2019-10-21'
2,'2015-10-21'
3,'2017-10-21'
4,'2016-10-21'
5,'2012-10-21'
</code>```

How do I do this?

答:
Assuming that your Sample data should look like this:

```<code>CREATE TABLE TableA(SomeID INT NOT NULL, Ranking smallint not null)

INSERT INTO TableA VALUES (1,1)
INSERT INTO TableA VALUES (2,2)
INSERT INTO TableA VALUES (3,1)
INSERT INTO TableA VALUES (4,1)
INSERT INTO TableA VALUES (5,2)
GO

CREATE TABLE TableB(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableB VALUES (1,'2019-10-21')
INSERT INTO TableB VALUES (2,'2018-10-21')
INSERT INTO TableB VALUES (3,'2017-10-21')
INSERT INTO TableB VALUES (4,'2016-10-21')
INSERT INTO TableB VALUES (5,'2015-10-21')

CREATE TABLE TableC(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableC VALUES (1,'2016-10-21')
INSERT INTO TableC VALUES (2,'2015-10-21')
INSERT INTO TableC VALUES (3,'2014-10-21')
INSERT INTO TableC VALUES (4,'2013-10-21')
INSERT INTO TableC VALUES (5,'2012-10-21')
</code>```

The requirement implies that you have a denormalisation problem, however, you can do this with 2 LEFT JOINs:

```<code>SELECT A.SomeID,
       ISNULL(B.Somedetailedinfo,C.Somedetailedinfo) AS Somedetailedinfo
FROM TableA A
     LEFT JOIN TableB B ON A.SomeID = B.SomeID
                       AND A.Ranking = 1
     LEFT JOIN TableC C ON A.SomeID = C.SomeID
                       AND A.Ranking = 2;
</code>```

Body:
I have 3 tables

CREATE TABLE TableA(SomeID INT NOT NULL, Ranking smallint not null)

INSERT INTO TableA(1,1)
INSERT INTO TableA(2,2)
INSERT INTO TableA(3,1)
INSERT INTO TableA(4,1)
INSERT INTO TableA(5,2)

I have 2 detailed tables and want to join to determine Join condition from TableA depending on Ranking column

CREATE TABLE TableB(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableB(1,'2019-10-21')
INSERT INTO TableB(2,'2018-10-21')
INSERT INTO TableB(3,'2017-10-21')
INSERT INTO TableB(4,'2016-10-21')
INSERT INTO TableB(5,'2015-10-21')

CREATE TABLE TableC(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableC(1,'2016-10-21')
INSERT INTO TableC(2,'2015-10-21')
INSERT INTO TableC(3,'2014-10-21')
INSERT INTO TableC(4,'2013-10-21')
INSERT INTO TableC(5,'2012-10-21')

I want to Join TableA with TableB or TableC depending on value of Ranking.
If Ranking=1 Join TableA with TableB
If Ranking=2 Join TableA with TableC

Expected OUTPUT is

SomeID,Somedetailedinfo
1,'2019-10-21'
2,'2015-10-21'
3,'2017-10-21'
4,'2016-10-21'
5,'2012-10-21'

How do I do this?

Body:
Assuming that your Sample data should look like this:

CREATE TABLE TableA(SomeID INT NOT NULL, Ranking smallint not null)

INSERT INTO TableA VALUES (1,1)
INSERT INTO TableA VALUES (2,2)
INSERT INTO TableA VALUES (3,1)
INSERT INTO TableA VALUES (4,1)
INSERT INTO TableA VALUES (5,2)
GO

CREATE TABLE TableB(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableB VALUES (1,'2019-10-21')
INSERT INTO TableB VALUES (2,'2018-10-21')
INSERT INTO TableB VALUES (3,'2017-10-21')
INSERT INTO TableB VALUES (4,'2016-10-21')
INSERT INTO TableB VALUES (5,'2015-10-21')

CREATE TABLE TableC(SomeID INT NOT NULL, Somedetailedinfo varchar(10))
INSERT INTO TableC VALUES (1,'2016-10-21')
INSERT INTO TableC VALUES (2,'2015-10-21')
INSERT INTO TableC VALUES (3,'2014-10-21')
INSERT INTO TableC VALUES (4,'2013-10-21')
INSERT INTO TableC VALUES (5,'2012-10-21')

The requirement implies that you have a denormalisation problem, however, you can do this with 2 LEFT JOINs:

SELECT A.SomeID,
       ISNULL(B.Somedetailedinfo,C.Somedetailedinfo) AS Somedetailedinfo
FROM TableA A
     LEFT JOIN TableB B ON A.SomeID = B.SomeID
                       AND A.Ranking = 1
     LEFT JOIN TableC C ON A.SomeID = C.SomeID
                       AND A.Ranking = 2;


问:
Problems running mvn for apache-maven
In the image below, it says JAVA_HOME is set to an invalid directory.  However, that is where my Java folder is located.. in C:\Program Files\Java... I don't think it is case sensitive, right?  What would you deduce is wrong with running mvn?

Thanks for any thoughts and ideas. :)

答: Most likely java is not installed in C:\Program Files\Java but in C:\Program Files\Java\jdk1.6.0_25 or a similar subfolder.

Title: Problems running mvn for apache-maven


问:
Renderpartial in a foreach loop only sends the first element in list
I'm trying to send a User in a list of users to a partial view but the partial view only takes the first user in the list. The code correctly displays the username and the actionlink to profile but for some reason only the first user in the list is sent to the partial view in every iteration.

What I want to do is to dynamically show the "confirmDelete" partial view when the delete button is clicked and delete the correct user.

Help is appreciated!

Edit:
I think I see the problem now, I name the url pointing to the Delete-Action "RedirectTo" in every partial view, and also all the divisions have the same id.. Still don't know how to fix it though.

MainView:

```<code>@foreach (var item in ViewBag.UsersList as List<CommonLibrary.User>)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.ActionLink("Profile", "ProfilePage", new { id = item.UserId }) |
            @{
                var user = Homepage.Service.SessionHelper.GetSessionUser(Context);
                if (user != null && user.GetType().ToString() == "CommonLibrary.Operator" && item.UserId != user.UserId)
                {
                    <button id="@item.UserId" class="btn-danger" onclick="confirmDelete()">Delete</button>
                    <div style="width:40%; float:right;">

                        @{

                            await Html.RenderPartialAsync("_ConfirmDelete", item);
                        }
                    </div>

                }
            }
        </td>
    </tr>
}
</code>```

Partial View:

```<code>@model CommonLibrary.User

@Html.Hidden("RedirectTo", Url.Action("Delete", "Users", new { id = Model.UserId }))
<div style="display:none" id="confDelete">
    <div>
        <b>Are you sure you want to delete user: @Model.UserName?</b>
    </div>
    <button id="Yes" class="btn-danger" onclick="deleteConfirmed()">Yes</button>
    <button id="No" class="btn-secondary" onclick="hideDelete()">No</button>
</div>

<script>
    function confirmDelete() {
        $("#confDelete").show();
        $("#del_btn").hide();
    }
    function hideDelete() {
        $("#confDelete").hide();
        $("#del_btn").show();
    }
    function deleteConfirmed() {
        var url = $("#RedirectTo").val();
        location.href = url;
    }
</script>
</code>```

答:
I figured it out by using UserId as id for the different elements.

Main View:

```<code>  <tbody>
        @foreach (var item in ViewBag.UsersList as List<CommonLibrary.User>)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.UserName)
                </td>
                <td>
                    @Html.ActionLink("Profile", "ProfilePage", new { id = item.UserId }) |
                    @{
                        var user = Homepage.Service.SessionHelper.GetSessionUser(Context);
                        if (user != null && user.GetType().ToString() == "CommonLibrary.Operator" && item.UserId != user.UserId)
                        {
                            <button id="@item.UserId" class="btn btn-danger" onclick="confirmDelete(this.id)">Delete</button>
                            <div style="width:40%; float:right;">
                                @{
                                    await Html.RenderPartialAsync("_ConfirmDelete", item);
                                }
                            </div>

                        }
                    }
                </td>
            </tr>
        }
    </tbody>
</table>
<script>
    function confirmDelete(id) {
        var element = document.getElementById("div" + id);
        element.style.display = "block";
    }
    function hideDelete(id) {
        var element = document.getElementById("div" + id);
        element.style.display = "none";
    }
    function deleteConfirmed(id) {
        var url = "/Users/Delete/" + id;
        window.location.href = url;
    }
</script>
</code>```

Partial View:

```<code>@model CommonLibrary.User

@{
    var divId = "div" + Model.UserId.ToString();
}
<div style="display:none" id="@divId">
    <div>
        <b>Are you sure you want to delete user: @Model.UserName?</b>
    </div>
    <button id="@Model.UserId.ToString()" class="btn btn-danger" onclick="deleteConfirmed(this.id)">Yes</button>
    <button id="@Model.UserId.ToString()" class="btn btn-secondary" onclick="hideDelete(this.id)">No</button>
</div>
</code>```

Body:
I'm trying to send a User in a list of users to a partial view but the partial view only takes the first user in the list. The code correctly displays the username and the actionlink to profile but for some reason only the first user in the list is sent to the partial view in every iteration.

What I want to do is to dynamically show the "confirmDelete" partial view when the delete button is clicked and delete the correct user.

Help is appreciated!

Edit:
I think I see the problem now, I name the url pointing to the Delete-Action "RedirectTo" in every partial view, and also all the divisions have the same id.. Still don't know how to fix it though.

MainView:

@foreach (var item in ViewBag.UsersList as List<CommonLibrary.User>)
{

            @Html.DisplayFor(modelItem => item.UserName)

            @Html.ActionLink("Profile", "ProfilePage", new { id = item.UserId }) |
            @{
                var user = Homepage.Service.SessionHelper.GetSessionUser(Context);
                if (user != null && user.GetType().ToString() == "CommonLibrary.Operator" && item.UserId != user.UserId)
                {
                    <button id="@item.UserId" class="btn-danger" onclick="confirmDelete()">Delete</button>

                        @{

                            await Html.RenderPartialAsync("_ConfirmDelete", item);
                        }

                }
            }

}

Partial View:

@model CommonLibrary.User

@Html.Hidden("RedirectTo", Url.Action("Delete", "Users", new { id = Model.UserId }))

        Are you sure you want to delete user: @Model.UserName?

    <button id="Yes" class="btn-danger" onclick="deleteConfirmed()">Yes</button>
    <button id="No" class="btn-secondary" onclick="hideDelete()">No</button>

Body:
I figured it out by using UserId as id for the different elements.

Main View:

  <tbody>
        @foreach (var item in ViewBag.UsersList as List<CommonLibrary.User>)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.UserName)
                </td>
                <td>
                    @Html.ActionLink("Profile", "ProfilePage", new { id = item.UserId }) |
                    @{
                        var user = Homepage.Service.SessionHelper.GetSessionUser(Context);
                        if (user != null && user.GetType().ToString() == "CommonLibrary.Operator" && item.UserId != user.UserId)
                        {
                            <button id="@item.UserId" class="btn btn-danger" onclick="confirmDelete(this.id)">Delete</button>
                            <div style="width:40%; float:right;">
                                @{
                                    await Html.RenderPartialAsync("_ConfirmDelete", item);
                                }
                            </div>

                        }
                    }
                </td>
            </tr>
        }
    </tbody>
</table>
<script>
    function confirmDelete(id) {
        var element = document.getElementById("div" + id);
        element.style.display = "block";
    }
    function hideDelete(id) {
        var element = document.getElementById("div" + id);
        element.style.display = "none";
    }
    function deleteConfirmed(id) {
        var url = "/Users/Delete/" + id;
        window.location.href = url;
    }
</script>

Partial View:

@model CommonLibrary.User

@{
    var divId = "div" + Model.UserId.ToString();
}
<div style="display:none" id="@divId">
    <div>
        <b>Are you sure you want to delete user: @Model.UserName?</b>
    </div>
    <button id="@Model.UserId.ToString()" class="btn btn-danger" onclick="deleteConfirmed(this.id)">Yes</button>
    <button id="@Model.UserId.ToString()" class="btn btn-secondary" onclick="hideDelete(this.id)">No</button>
</div>


答:
Assuming data is square matrix (n x n) and if I understand the question correctly</p>

```<code> df = pd.DataFrame([[0, 4,0], [0,6,0], [1,3,0]],
                   index =['foo', 'bar', 'lorem'],
                   columns=[0, 1, 2]
                   )
 df_T = pd.DataFrame(df.values.T, index=df.index, columns=df.columns)
</code>```

Title: Transpose Pandas dataframe preserving the index

Body:
Assuming data is square matrix (n x n) and if I understand the question correctly

 df = pd.DataFrame([[0, 4,0], [0,6,0], [1,3,0]],
                   index =['foo', 'bar', 'lorem'],
                   columns=[0, 1, 2]
                   )
 df_T = pd.DataFrame(df.values.T, index=df.index, columns=df.columns)


问:
Can `pip install foo-package==1.0.0` download different code today than it did yesterday
I need to make sure that the package which was allowed for a secure system will remain static if installed again in the future.  Can a bad actor (the package owner) trick user into downloading insecure/unvetted source code?</p>

答:
PyPI maintainer here: Yes, it is possible, since pip will install whichever distribution is the optimal distribution. This commonly happens when a project uploads a source distribution (sdist) and then later uploads platform-specific wheels for a given release: pip will always prefer the wheel over the source distribution.

If you'd like to prevent this, you can specify the file hashes when installing via hash-checking mode.


问:
Annotate queryset with percentage grouped by date
Suppose I have the following model:

```<code>class Order(models.Model):
    category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE)
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

I need to annotate an Order queryset with the percentage of each category grouped by month (based on the created_at field). I managed to write a query to count every Order grouped by month:

```<code>orders_per_month = (Order.objects
    .annotate(month=TruncMonth('created_at'))
    .values('month')
    .annotate(count=Count('id'))
    .order_by('month')
    .values('month', 'count')
)
</code>```

Changing just the last .values() to .values('month', 'category', 'count'), I can get the count grouped by both category and month.

Is it possible to get the percentage of each category grouped by month using Django's ORM? For example, if I had the following data:

```<code>MONTH | CATEGORY
Jan   | 'A'
Jan   | 'B'
Feb   | 'A'
</code>```

I would like to get something similar to this:

```<code>[
    (Jan, 'A', 0.5),
    (Jan, 'B', 0.5),
    (Feb, 'A', 1),
]
</code>```

Thanks in advance.

答:
Using Django's Window functions, as suggested by @ac2001 in the comments, I managed to get what I needed.

Using the example model and supposing I want the percentage of each category grouped by month:

```<code>orders_per_month = (Order.objects
    .annotate(month=TruncMonth('created_at'))
    .values('month', 'category')
    .distinct()
    .annotate(month_total=Window(
        expression=Count('id'),
        partition_by=[F('month')],
    ))
    .annotate(month_category=Window(
        expression=Count('id'),
        partition_by=[F('month'), F('category')],
    ))
    .annotate(percentage=ExpressionWrapper(
        F('month_category') * 100.0 / F('month_total'),
        output_field=FloatField()
    ))
    .values('month', 'percentage', 'category')
)
</code>```

Any suggestions on simplifying this further are welcome.

Body:
Suppose I have the following model:

class Order(models.Model):
    category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE)
    created_at = models.DateTimeField(auto_now_add=True)

I need to annotate an Order queryset with the percentage of each category grouped by month (based on the created_at field). I managed to write a query to count every Order grouped by month:

orders_per_month = (Order.objects
    .annotate(month=TruncMonth('created_at'))
    .values('month')
    .annotate(count=Count('id'))
    .order_by('month')
    .values('month', 'count')
)

Changing just the last .values() to .values('month', 'category', 'count'), I can get the count grouped by both category and month.

Is it possible to get the percentage of each category grouped by month using Django's ORM? For example, if I had the following data:

MONTH | CATEGORY
Jan   | 'A'
Jan   | 'B'
Feb   | 'A'

I would like to get something similar to this:

[
    (Jan, 'A', 0.5),
    (Jan, 'B', 0.5),
    (Feb, 'A', 1),
]

Thanks in advance.

Body:
Using Django's Window functions, as suggested by @ac2001 in the comments, I managed to get what I needed.

Using the example model and supposing I want the percentage of each category grouped by month:

orders_per_month = (Order.objects
    .annotate(month=TruncMonth('created_at'))
    .values('month', 'category')
    .distinct()
    .annotate(month_total=Window(
        expression=Count('id'),
        partition_by=[F('month')],
    ))
    .annotate(month_category=Window(
        expression=Count('id'),
        partition_by=[F('month'), F('category')],
    ))
    .annotate(percentage=ExpressionWrapper(
        F('month_category') * 100.0 / F('month_total'),
        output_field=FloatField()
    ))
    .values('month', 'percentage', 'category')
)

Any suggestions on simplifying this further are welcome.


问:
npgsql executescalar() allways returns nothing
I'm using npgsql as a nuget package in visual studio 2017 with visual basic.
Various commands do work very well but an ExecuteScalar allways returns 'nothing' although it should give a result.

The command looks like this:

```<code>   Dim ser As Integer
   Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = '@code';", conn)
   Dim fcode = New NpgsqlParameter("code", NpgsqlTypes.NpgsqlDbType.Varchar)

   find.Parameters.Add(fcode)
   find.Prepare()

   fcode.Value = "XYZ"

   ser = find.ExecuteScalar()     ==>  nothing
</code>```

When the command string is copied as a value during debugging and pasted into the query tool of PGADMIN it delivers the correct result. The row is definitely there.

Different Commands executed with ExecuteNonQuery() work well, including ones performing UPDATE statements on the row in question.

When I look into the properties of the parameter fcode immediately before the ExecuteScalar it shows 'fcode.DataTypeName' caused an exception 'System.NotImplementedException'.

If I change my prepared statement to "SELECT @code" and set the value of the parameter to an arbitrary value just this value is returned. There is no access to the table taking place because the table name is not part of the SELECT in this case. If I remove the WHERE CLAUSE in the SELECT and just select one column, I would also expect that something has to be returned. But again it is nothing.

Yes there is a column named serial. It is of type bigint and can not contain NULL.
A Query shows that there is no single row that contains NULL in any column.

Latest findings:
I queried a different table where the search column and the result column happen to have the same datatype. It works, so syntax, passing of parameter, prepare etc. seems to work in principal.
The System.NotImplementedException in the DataTypeName property of the parameter occurs as well but it works anyway.
I rebuilt the index of the table in question. No change.
Still: when I copy/paste the CommandText and execute it in PGAdmin it shows the correct result.
Modifying the Command and using plain text there without parameter and without prepare still does yield nothing. The plain text CommandText was copy/pasted from PGAdmin where it was successfully executed before.
Very strange.

Reverting search column and result column also gives nothing as a result.

答:
I finally found it. It's often the small things that can have a big impact.
When the value was assigned to the parameter a substring index was incorect.
Now it works perfectly.
Thanks to everybody who spent his time on this.</p>

Body:
I'm using npgsql as a nuget package in visual studio 2017 with visual basic.
Various commands do work very well but an ExecuteScalar allways returns 'nothing' although it should give a result.

The command looks like this:

   Dim ser As Integer
   Dim find = New NpgsqlCommand("SELECT serial from dbo.foreigncode WHERE code = '@code';", conn)
   Dim fcode = New NpgsqlParameter("code", NpgsqlTypes.NpgsqlDbType.Varchar)

   find.Parameters.Add(fcode)
   find.Prepare()

   fcode.Value = "XYZ"

   ser = find.ExecuteScalar()     ==>  nothing

When the command string is copied as a value during debugging and pasted into the query tool of PGADMIN it delivers the correct result. The row is definitely there.

Different Commands executed with ExecuteNonQuery() work well, including ones performing UPDATE statements on the row in question.

When I look into the properties of the parameter fcode immediately before the ExecuteScalar it shows 'fcode.DataTypeName' caused an exception 'System.NotImplementedException'.

If I change my prepared statement to "SELECT @code" and set the value of the parameter to an arbitrary value just this value is returned. There is no access to the table taking place because the table name is not part of the SELECT in this case. If I remove the WHERE CLAUSE in the SELECT and just select one column, I would also expect that something has to be returned. But again it is nothing.

Yes there is a column named serial. It is of type bigint and can not contain NULL.
A Query shows that there is no single row that contains NULL in any column.

Latest findings:
I queried a different table where the search column and the result column happen to have the same datatype. It works, so syntax, passing of parameter, prepare etc. seems to work in principal.
The System.NotImplementedException in the DataTypeName property of the parameter occurs as well but it works anyway.
I rebuilt the index of the table in question. No change.
Still: when I copy/paste the CommandText and execute it in PGAdmin it shows the correct result.
Modifying the Command and using plain text there without parameter and without prepare still does yield nothing. The plain text CommandText was copy/pasted from PGAdmin where it was successfully executed before.
Very strange.

Reverting search column and result column also gives nothing as a result.


问:
UCMA subscribing to presence of many users
we're currently working on the design for an UCMA application that should be able to subscribe to presence updates of up 15k users. Reading the (rather outdated) documentation we noted the following:

Lync Server 2013 also places a limit on the subscription response body length, so an application that subscribes to a large number of users (typically more than 1000 users) might receive an error response from Lync Server 2013.

Does anyone know if this still true for Skype for Business 2015/2019 or where to find current docs?

Further down the same doc states that, for a large number of subscriptions, it is recommended to limit the categories we subscribe to. We're only interested in the presence state, so that's a good workaround for us. However I can't find much information about what difference that makes, like if we subscribe to only the presence state, can we have 2x or 5x or 100x the number of subscriptions?

Searching around I found this post that seems to say we can subscribe to many more users if we create batches of a few hundreds. So does the above limit of 1000 users apply per BeginSubscription() call?

Many thanks in advance!

答:
Sounds like you are reading the UCMA 4 (Lync 2013) documentation.
There is the UCMA 5 (SfB 2015) documentation but there are no real differences.
UCMA 6 (SfB 2019) is available but there isn't any documentation.

From personal experience, you can use any of the UCMA versions to get the job done.  The details haven't changed.

If you want to subscribe to SfB online accounts, you will have to use UCMA 5 on SfB 2015 or UCMA 6 on SfB 2019 as UCMA 4 on SfB 2015 / 2019 doesn't work for SfB online accounts.  The is the only gotcha I have found.

I've gone up into a 100's of subscriptions and I think some of our customers are up to around the 1k mark using batch subscriptions.  I use a batch size of 100 and it's working ok for me.

You are not going to know until you test it yourself to see how to performs with batch sizes you test with if it's to slow or fast enough.

At the 15k mark, it's getting to be a lot of subscriptions to take care of.  This may start putting unwanted overhead onto the SfB system at that level of subscriptions due to the extra messages / subscription polling going on.  You may need to look into splitting the subscriptions between applications / machines to load balance the work.

If you find that it's not working very well you may need to think about switching from a UCMA application to a Server App (sip proxy) application that runs on the FE machines and sniffs the sip traffic to view the presence change traffic as they happen.  It's a lot more work but would not generate as much overhead as a UCMA application.


问:
Crontab and testing a command to be executed
I'm quite new to cron and crontab.

I've edited the crontab file and I need to execute manually one of commands so I can try it and test it beforehand. How do I do that? If it fails, is there a mode that shows the errors?

答:
To execute a script "manually" you first have to make it executable by doing:

```<code>$ chmod +x yourScriptName
</code>```

Then do either

```<code>$ ./yourScriptName
</code>```

if you execute it from its path or

```<code>$ /full/path/to/yourScriptName
</code>```

from anywhere.

Body:
To execute a script "manually" you first have to make it executable by doing:

$ chmod +x yourScriptName

Then do either

$ ./yourScriptName

if you execute it from its path or

$ /full/path/to/yourScriptName

from anywhere.


问:
Converting Complex SQL to Python Pandas Merge and/or Join
I currently have a Python script which converts two pandas DataFrames to tables in a SQLite database in memory, before reading reading and running SQL code on the tables.  I would like the script to be more "Pythonic", merging and/or joining the DataFrames, but am having a difficult time finding Python code examples for the equivalent of SELECTing specific, and not all, elements from both tables, along with FROM, WHERE and ORDER BY clauses.  I am fairly new to Python, and being the Guinea Pig of my department, so if I can get this working, it will become a template for MANY more scripts from my partners in my work group.  Actual element names have been changed do to proprietary information, but the structure is the same.  Thanks in advance for the help!

```<code>SELECT
   dfE.Element05 AS [Alt Element05],
   dfE.Element03 AS [Alt Element03],
   dfE.Element04 AS [Alt Element04],
   dfN.Element03,
   dfN.Element04,
   dfN.Element08,
   dfN.Element09,
   dfN.Element10,
   dfN.Element17,
   dfN.Element18,
   dfN.Element19,
   dfN.Element20,
   dfN.Element23,
   dfN.Element26,
   dfN.Element13
FROM dfE INNER JOIN dfN ON (dfE.Element17 = dfN.Element17) AND (dfE.Element20 = dfN.Element20)
WHERE (((dfN.Element03)<>dfE.Element03))
GROUP BY
   dfE.Element05,
   dfE.Element03,
   dfE.Element04,
   dfN.Element03,
   dfN.Element04,
   dfN.Element08,
   dfN.Element09,
   dfN.Element10,
   dfN.Element17,
   dfN.Element18,
   dfN.Element19,
   dfN.Element20,
   dfN.Element23,
   dfN.Element26,
   dfN.Element13
ORDER BY
   dfE.Element03,
   dfN.Element03,
   dfN.Element08
</code>```

答:
I would start by copying the DataFrames that you want to join and selecting the specific columns there. I have included "Element17" & "Element20" from dfE because you need to have it when joining.

Ex.

```<code>df1 = dfE['Element05,'Element03','Element04','Element17','Element20'].copy()

</code>```

In order to rename the columns use the following:

```<code>df1.rename(columns={'Element05':'Alt Element05','Element03':'Alt Element03','Element04':'Alt Element04'},inplace=True)
</code>```

Once you have the other df set up (lets name it df2) you would use pd.merge() to join them as you would in SQL. *When using pd.merge, the columns on which you are going to join have to have the same name or it won't work! (Lets say df1['A'] shares the same data as df2['B'] and you want to join the DataFrames. You would have to change the name on one of the DataFrames so that it is equal to the column name of the Df you are joining to or it won't work.)

Ex.

```<code>df3 = pd.merge(df1,df1,how='inner',on=['Element17','Element20'])
</code>```

For the Where I would do the following.

```<code>df3= df3[df3['Alt Element03']!=df3['Element']]
</code>```

For Order By you could use .sort() but I'm not comfortable with giving you advice on how to use it as I haven't used it much.

I hope this helps! Let me know if you have questions.

*** This might not be the best way to do things. I apologize beforehand if I'm leading you to develop bad habits. I'm new to python as well!

Body:
I currently have a Python script which converts two pandas DataFrames to tables in a SQLite database in memory, before reading reading and running SQL code on the tables.  I would like the script to be more "Pythonic", merging and/or joining the DataFrames, but am having a difficult time finding Python code examples for the equivalent of SELECTing specific, and not all, elements from both tables, along with FROM, WHERE and ORDER BY clauses.  I am fairly new to Python, and being the Guinea Pig of my department, so if I can get this working, it will become a template for MANY more scripts from my partners in my work group.  Actual element names have been changed do to proprietary information, but the structure is the same.  Thanks in advance for the help!

SELECT
   dfE.Element05 AS [Alt Element05],
   dfE.Element03 AS [Alt Element03],
   dfE.Element04 AS [Alt Element04],
   dfN.Element03,
   dfN.Element04,
   dfN.Element08,
   dfN.Element09,
   dfN.Element10,
   dfN.Element17,
   dfN.Element18,
   dfN.Element19,
   dfN.Element20,
   dfN.Element23,
   dfN.Element26,
   dfN.Element13
FROM dfE INNER JOIN dfN ON (dfE.Element17 = dfN.Element17) AND (dfE.Element20 = dfN.Element20)
WHERE (((dfN.Element03)<>dfE.Element03))
GROUP BY
   dfE.Element05,
   dfE.Element03,
   dfE.Element04,
   dfN.Element03,
   dfN.Element04,
   dfN.Element08,
   dfN.Element09,
   dfN.Element10,
   dfN.Element17,
   dfN.Element18,
   dfN.Element19,
   dfN.Element20,
   dfN.Element23,
   dfN.Element26,
   dfN.Element13
ORDER BY
   dfE.Element03,
   dfN.Element03,
   dfN.Element08

Body:
I would start by copying the DataFrames that you want to join and selecting the specific columns there. I have included "Element17" & "Element20" from dfE because you need to have it when joining.

Ex.

df1 = dfE['Element05,'Element03','Element04','Element17','Element20'].copy()

In order to rename the columns use the following:

df1.rename(columns={'Element05':'Alt Element05','Element03':'Alt Element03','Element04':'Alt Element04'},inplace=True)

Once you have the other df set up (lets name it df2) you would use pd.merge() to join them as you would in SQL. *When using pd.merge, the columns on which you are going to join have to have the same name or it won't work! (Lets say df1['A'] shares the same data as df2['B'] and you want to join the DataFrames. You would have to change the name on one of the DataFrames so that it is equal to the column name of the Df you are joining to or it won't work.)

Ex.

df3 = pd.merge(df1,df1,how='inner',on=['Element17','Element20'])

For the Where I would do the following.

df3= df3[df3['Alt Element03']!=df3['Element']]

For Order By you could use .sort() but I'm not comfortable with giving you advice on how to use it as I haven't used it much.

I hope this helps! Let me know if you have questions.

*** This might not be the best way to do things. I apologize beforehand if I'm leading you to develop bad habits. I'm new to python as well!


问:
Filter out objects in array if one value is the same
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

```<code>  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]
</code>```

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

```<code>  arrayName[eachObject].Language === "English"
</code>```

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().

答:
You could take a hash table and filter the array by checking Name and Language.

var array = [{ Name: "blah", Date: "1992-02-18T00:00:00.000Z", Language: "English" }, { Name: "blahzay", Date: "1998-02-18T00:00:00.000Z", Language: "French" }, { Name: "blah", Date: "1999-02-18T00:00:00.000Z", Language: "English" }],
    hash = {},
    result = array.filter(({ Name, Language }) => {
        var key = `${Name}|${Language}`;
        if (!hash[key]) return hash[key] = true;
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

  arrayName[eachObject].Language === "English"

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().

Body:
You could take a hash table and filter the array by checking Name and Language.

var array = [{ Name: "blah", Date: "1992-02-18T00:00:00.000Z", Language: "English" }, { Name: "blahzay", Date: "1998-02-18T00:00:00.000Z", Language: "French" }, { Name: "blah", Date: "1999-02-18T00:00:00.000Z", Language: "English" }],
    hash = {},
    result = array.filter(({ Name, Language }) => {
        var key = `${Name}|${Language}`;
        if (!hash[key]) return hash[key] = true;
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Can't push to github with SourceTree despite having identity added in agent: Permission denied (publickey)
If I run ssh-add -l I see my identity in the list as expected. If I run ssh -vT git@github.com I get this output:

```<code>OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/myself/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Connecting to github.com [140.82.113.4] port 22.
debug1: Connection established.
debug1: identity file /Users/myself/.ssh/id_rsa type -1
debug1: identity file /Users/myself/.ssh/id_rsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_dsa type -1
debug1: identity file /Users/myself/.ssh/id_dsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_ecdsa type -1
debug1: identity file /Users/myself/.ssh/id_ecdsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_ed25519 type -1
debug1: identity file /Users/myself/.ssh/id_ed25519-cert type -1
debug1: identity file /Users/myself/.ssh/id_xmss type -1
debug1: identity file /Users/myself/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
debug1: Remote protocol version 2.0, remote software version babeld-849b9b5f
debug1: no match: babeld-849b9b5f
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: rsa-sha2-512
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /Users/myself/.ssh/known_hosts:1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: Will attempt key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Will attempt key: /Users/myself/.ssh/id_rsa
debug1: Will attempt key: /Users/myself/.ssh/id_dsa
debug1: Will attempt key: /Users/myself/.ssh/id_ecdsa
debug1: Will attempt key: /Users/myself/.ssh/id_ed25519
debug1: Will attempt key: /Users/myself/.ssh/id_xmss
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,rsa-sha2-512,rsa-sha2-256,ssh-dss>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Server accepts key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([140.82.113.4]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending environment.
debug1: Sending env LC_TERMINAL_VERSION = 3.3.8
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_TERMINAL = iTerm2
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi myself! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 3564, received 2484 bytes, in 0.2 seconds
Bytes per second: sent 18846.5, received 13135.4
debug1: Exit status 1
</code>```

I still can't push code to github despite getting the You've successfully authenticated message in this debug output, the SSH identity being generated by SourceTree itself, and ensuring my SSH Agent is running by doing eval "$(ssh-agent)".

I can also see the expected key in my github profile.

What is wrong here?

答:
my SSH Agent is running by doing eval "$(ssh-agent)".

This is likely the problem. ssh knows to talk to ssh-agent via the SSH_AUTH_SOCK environment variables. Environment variables are only visible to a process and its children.

eval "$(ssh-agent)" sets SSH_AUTH_SOCK for this shell and its children only; that is anything you ran from that shell. If you then run git in this shell it should work. But if you have some stand alone program not launched from this shell, like Atlassian Sourcetree, when it runs ssh it will not know to talk to that ssh-agent.

You could launch Sourcetree from that shell, but that's not a very good solution.

To fix this, and a host of other ssh related problems, start your ssh-agent at login. This should be done for you by your operating system, or if not follow the instructions for your operating system. Otherwise, follow the advice in the various answers here.

Body:
If I run ssh-add -l I see my identity in the list as expected. If I run ssh -vT git@github.com I get this output:

OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/myself/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Connecting to github.com [140.82.113.4] port 22.
debug1: Connection established.
debug1: identity file /Users/myself/.ssh/id_rsa type -1
debug1: identity file /Users/myself/.ssh/id_rsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_dsa type -1
debug1: identity file /Users/myself/.ssh/id_dsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_ecdsa type -1
debug1: identity file /Users/myself/.ssh/id_ecdsa-cert type -1
debug1: identity file /Users/myself/.ssh/id_ed25519 type -1
debug1: identity file /Users/myself/.ssh/id_ed25519-cert type -1
debug1: identity file /Users/myself/.ssh/id_xmss type -1
debug1: identity file /Users/myself/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
debug1: Remote protocol version 2.0, remote software version babeld-849b9b5f
debug1: no match: babeld-849b9b5f
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: rsa-sha2-512
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /Users/myself/.ssh/known_hosts:1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: Will attempt key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Will attempt key: /Users/myself/.ssh/id_rsa
debug1: Will attempt key: /Users/myself/.ssh/id_dsa
debug1: Will attempt key: /Users/myself/.ssh/id_ecdsa
debug1: Will attempt key: /Users/myself/.ssh/id_ed25519
debug1: Will attempt key: /Users/myself/.ssh/id_xmss
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,rsa-sha2-512,rsa-sha2-256,ssh-dss>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Server accepts key: Generated by Sourcetree on macOS for myself-GitHub RSA SHA256:WnUQPEasG3tUVyEkE7Ufo9fGoRqCdUeY9ohZ7OU6fsc agent
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([140.82.113.4]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending environment.
debug1: Sending env LC_TERMINAL_VERSION = 3.3.8
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_TERMINAL = iTerm2
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi myself! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 3564, received 2484 bytes, in 0.2 seconds
Bytes per second: sent 18846.5, received 13135.4
debug1: Exit status 1

I still can't push code to github despite getting the You've successfully authenticated message in this debug output, the SSH identity being generated by SourceTree itself, and ensuring my SSH Agent is running by doing eval "$(ssh-agent)".

I can also see the expected key in my github profile.

What is wrong here?


问:
SQL retrieve all rows between two dates and a specific number of rows before the date ordered by date
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

```<code>20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701
</code>```

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

```<code>result
20200201
20200101
20191201
20191101
20191001
20190901
</code>```

my current query returns a random set of high dates between the union for some reason:

```<code>(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
</code>```

Any idea where I am going wrong?

答:
One method uses lead():

```<code>select t.*
from (select t.*,
             lead(date, 3) over (order by date) as next_date_3
      from t
     ) t
where (date < '202o-02-01' and (next_date_3 >= '2020-02-01' or next_date_3 is null) ) or
      (date between '2020-02-01' and '2019-12-01')
</code>```

Body:
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

result
20200201
20200101
20191201
20191101
20191001
20190901

my current query returns a random set of high dates between the union for some reason:

(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)

Any idea where I am going wrong?

Body:
One method uses lead():

select t.*
from (select t.*,
             lead(date, 3) over (order by date) as next_date_3
      from t
     ) t
where (date < '202o-02-01' and (next_date_3 >= '2020-02-01' or next_date_3 is null) ) or
      (date between '2020-02-01' and '2019-12-01')


问:
I cant install Flask
I am trying to install flask but everytime i get this error
ModuleNotFoundError: No module named 'flask'. I have added python to path and have even reinstalled it but it just isnt working. I followed steps of activating virtual environment and using pip install flask but it still doesn't seem to work. I need to get my a level coursework completed in a week! Please help.

答:
I can't tell what OS you're using, so I'll make a recommendation for you that's pretty easy to set up on the majority of OS's/Distros:

If you're really in a pinch use Anaconda.

I find Conda (Anaconda) quite nice for managing python pip environments.
Get it working in your operating system, then pip install Flask in a new Conda environment. This is a useful cheatsheet for Conda.
Once you've activated the environment for your Flask project development should be a breeze.

Good luck.

Title: I cant install Flask