问:
MYSQL - SUM values of last 10 days
I have this table in mysql:

```<code>|   player1   |  player2 |    date    |   fs_1   |   fs_2   |
    Jack         Tom       2015-03-02       10         2
    Mark        Riddley    2015-05-02       3          1
     ...
</code>```

I need to know how many aces (fs_1) player 1 have done BEFORE the match reported in date_g (10 days before for example).

This is what i tried without success:

OPTION 1

```<code>    SELECT
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(IF(date_sub(date_g, interval 10 day)< date_g, FS_1, 0)) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;
</code>```

OPTION 2

```<code>SELECT
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(CASE WHEN date_g between date_g and date_sub(date_g, interval 10 day) then fs_1 else 0 end) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;
</code>```

I have edited the code, now is more easy to read and understand.

```<code> SELECT
     id1 AS 'PLAYER 1',
     id2 AS 'PLAYER 2',
     DATE(date_g) AS 'DATE',
     result_g AS 'RESULT',
     FS_1,
     FS_2,
     SUM(CASE
         WHEN date_g BETWEEN date_g AND DATE_SUB(date_g, INTERVAL 10 DAY) THEN fs_1
     END) AS 'last 20 days' FROM
     stat_atp stat_atp
         JOIN
     backup3.games_atp ON id1_g = id1 AND id2_g = id2
         AND id_t_g = id_t
         AND id_r_g = id_r GROUP BY ID1;
</code>```

Thanx in advance.

答:
Maybe this could help you:

```<code>SELECT
    id1,
    SUM(fs_1)
FROM
     stat_atp
WHERE
     date_g <= DATE_SUB('2015-03-02', INTERVAL 1 DAY) AND date_g >= DATE_SUB('2015-03-02', INTERVAL 10 DAY)
AND
    id1='Jack'
GROUP BY id1;
</code>```

Remember that RDBMS are used to construct rigorous data sets that are linked between each others by clear ids (keys when talking about SQL). It's easier to respect the three first normal forms. That's why you should use keys to identify your match itself. By this way you could use subqueries (subsets) to achieve your goal.

Then, keep in mind that SQL is STRUCTURED. It's its force and weakness cause you won't be able to use it as a Turing complete programming langage with loops and conditions. But in any situation you will be able to find the same structure for a query. However you can interact with a SQL query result with another langage and use loops and condition on the result set itself. That's up to you.

Anyway, you may want to read about the MySQL GROUP BY clause which is different from the ISO SQL form : https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

Title: MYSQL - SUM values of last 10 days

Body:
I have this table in mysql:

|   player1   |  player2 |    date    |   fs_1   |   fs_2   |
    Jack         Tom       2015-03-02       10         2
    Mark        Riddley    2015-05-02       3          1
     ...

I need to know how many aces (fs_1) player 1 have done BEFORE the match reported in date_g (10 days before for example).

This is what i tried without success:

OPTION 1

    SELECT
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(IF(date_sub(date_g, interval 10 day)< date_g, FS_1, 0)) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;

OPTION 2

SELECT
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(CASE WHEN date_g between date_g and date_sub(date_g, interval 10 day) then fs_1 else 0 end) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;

I have edited the code, now is more easy to read and understand.

 SELECT
     id1 AS 'PLAYER 1',
     id2 AS 'PLAYER 2',
     DATE(date_g) AS 'DATE',
     result_g AS 'RESULT',
     FS_1,
     FS_2,
     SUM(CASE
         WHEN date_g BETWEEN date_g AND DATE_SUB(date_g, INTERVAL 10 DAY) THEN fs_1
     END) AS 'last 20 days' FROM
     stat_atp stat_atp
         JOIN
     backup3.games_atp ON id1_g = id1 AND id2_g = id2
         AND id_t_g = id_t
         AND id_r_g = id_r GROUP BY ID1;

Thanx in advance.

Body:
Maybe this could help you:

SELECT
    id1,
    SUM(fs_1)
FROM
     stat_atp
WHERE
     date_g <= DATE_SUB('2015-03-02', INTERVAL 1 DAY) AND date_g >= DATE_SUB('2015-03-02', INTERVAL 10 DAY)
AND
    id1='Jack'
GROUP BY id1;

Remember that RDBMS are used to construct rigorous data sets that are linked between each others by clear ids (keys when talking about SQL). It's easier to respect the three first normal forms. That's why you should use keys to identify your match itself. By this way you could use subqueries (subsets) to achieve your goal.

Then, keep in mind that SQL is STRUCTURED. It's its force and weakness cause you won't be able to use it as a Turing complete programming langage with loops and conditions. But in any situation you will be able to find the same structure for a query. However you can interact with a SQL query result with another langage and use loops and condition on the result set itself. That's up to you.

Anyway, you may want to read about the MySQL GROUP BY clause which is different from the ISO SQL form : https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


来源: stackexchange

问:
In TSQL, how to evaluate an expression and assign it to a BIT field?
I'm struggling on something very simple. I'm trying to assign the results of a boolean expression to a BIT variable.

Basically I would like to do something like:

```<code>DECLARE @is_search_term_empty BIT

SET @is_search_term_empty = (@search_term = '')
</code>```

where @search_term is a NVARCHAR(128) declared somewhere else in the code.

I cannot work out the syntax to evaluate something and assign it to a BIT variable, ie:

```<code>SET @is_search_term_empty = (1 > 2)
</code>```

Thanks.

答:
One of the reasons this is so hard to do is that T-SQL uses three-valued boolean logic. TRUE and FALSE are not the only options; there's also UNKNOWN. We have a similar concept with NULL values, and lots of language features exist to translate from values to boolean expressions (=, IS NULL, IS NOT NULL, etc.), but there's no such thing as IS UNKNOWN, or other language features to translate directly from a boolean expression to a bit datatype.

Here's an example solution. Unfortunately this requires that the expression you are testing (1 = NULL, here) needs to be duplicated in code -- you could avoid this with sp_executesql and output parameters if you really needed to:

```<code>DECLARE @bit1 bit = 0,
        @bit2 bit = 0,
        @result bit;

IF (1 = NULL) SET @bit1 = 1;
IF NOT(1 = NULL) SET @bit2 = 1;

IF @bit1 = @bit2 SET @result = NULL;
ELSE IF @bit1 = 1 SET @result = 1;
ELSE IF @bit2 = 1 SET @result = 0;

SELECT @result as [bit];
</code>```

This example relies on the fact that NOT(UNKNOWN) returns UNKNOWN, not TRUE. This obviously relies on your BIT column being nullable. Similarly, if you wish to avoid three-valued boolean logic, you must ensure that none of your expression inputs can ever be null.

ContentLicense: CC BY-SA 2.5

Body:
I'm struggling on something very simple. I'm trying to assign the results of a boolean expression to a BIT variable.

Basically I would like to do something like:

DECLARE @is_search_term_empty BIT

SET @is_search_term_empty = (@search_term = '')

where @search_term is a NVARCHAR(128) declared somewhere else in the code.

I cannot work out the syntax to evaluate something and assign it to a BIT variable, ie:

SET @is_search_term_empty = (1 > 2)

Thanks.

Body:
One of the reasons this is so hard to do is that T-SQL uses three-valued boolean logic. TRUE and FALSE are not the only options; there's also UNKNOWN. We have a similar concept with NULL values, and lots of language features exist to translate from values to boolean expressions (=, IS NULL, IS NOT NULL, etc.), but there's no such thing as IS UNKNOWN, or other language features to translate directly from a boolean expression to a bit datatype.

Here's an example solution. Unfortunately this requires that the expression you are testing (1 = NULL, here) needs to be duplicated in code -- you could avoid this with sp_executesql and output parameters if you really needed to:

DECLARE @bit1 bit = 0,
        @bit2 bit = 0,
        @result bit;

IF (1 = NULL) SET @bit1 = 1;
IF NOT(1 = NULL) SET @bit2 = 1;

IF @bit1 = @bit2 SET @result = NULL;
ELSE IF @bit1 = 1 SET @result = 1;
ELSE IF @bit2 = 1 SET @result = 0;

SELECT @result as [bit];

This example relies on the fact that NOT(UNKNOWN) returns UNKNOWN, not TRUE. This obviously relies on your BIT column being nullable. Similarly, if you wish to avoid three-valued boolean logic, you must ensure that none of your expression inputs can ever be null.

ContentLicense: CC BY-SA 3.0


问:
How can an array value be SIX chars long and echoing nothing (string(6) " ")?
This is really weird. Look what is on my screen right now :

```<code>$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}
</code>```

This is just the output of :

```<code>var_dump($albumGenre);
</code>```

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

答: Not all characters are printable. Some display as spaces, and some don't display at all - i.e. the text position is not even moved. This can also depend on the "encoding" of the text, and whether the program is using the same encoding as the file's creator intended.</p>

Body:
This is really weird. Look what is on my screen right now :

$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}

This is just the output of :

var_dump($albumGenre);

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?


问:
JS Calendar two days short
I'm building a calendar using Javascript (Vue JS). I have this little method to help get the days in the month:

```<code>daysInYearMonth(y,m){
  return new Date(y, m, 0).getDate()
}
</code>```

If I console.log the above I get 31 as it's July. However, when it comes time to use this value:

```<code>this.days = [...Array(this.daysInYearMonth(this.year,
  this.month)).keys()]
}
</code>```

I console.log this.days and get 29 days, two short. If I simply try to add two then the other months are off. Here is my CodePen.

NOTE: I am intentionally not using Moment.js and even though I agree it's better, the team decided to go with only Vue and vanilla JS.

答:
daysInYearMonth() is returning the number of days in the month before the one you ask for. When you use day 0 in a date, it means the last day of the month before it. That's why you get 30 for July, not 31. So to get the last day of the current month, you need to use the next month.

```<code>daysInYearMonth(y,m){
  return new Date(y, m+1, 0).getDate()
}
</code>```

The next problem is that array keys start at 0, but days in months start at 1. So when you do Array(this.daysInYearMonth(this.year,
  this.month)).keys() it returns an array from 0 to 30 rather than 1 to 31. The simplest way to fix this is to write a loop that starts at 1, rather than playing games with arrays.

```<code>let lastday = this.daysInYearMonth(this.year, this.month);
this.days = [];
for (let d = 1; d <= lastday; d++) {
    this.days.push(d);
}
</code>```

Title: JS Calendar two days short

Body:
I'm building a calendar using Javascript (Vue JS). I have this little method to help get the days in the month:

daysInYearMonth(y,m){
  return new Date(y, m, 0).getDate()
}

If I console.log the above I get 31 as it's July. However, when it comes time to use this value:

this.days = [...Array(this.daysInYearMonth(this.year,
  this.month)).keys()]
}

I console.log this.days and get 29 days, two short. If I simply try to add two then the other months are off. Here is my CodePen.

NOTE: I am intentionally not using Moment.js and even though I agree it's better, the team decided to go with only Vue and vanilla JS.

Body:
daysInYearMonth() is returning the number of days in the month before the one you ask for. When you use day 0 in a date, it means the last day of the month before it. That's why you get 30 for July, not 31. So to get the last day of the current month, you need to use the next month.

daysInYearMonth(y,m){
  return new Date(y, m+1, 0).getDate()
}

The next problem is that array keys start at 0, but days in months start at 1. So when you do Array(this.daysInYearMonth(this.year,
  this.month)).keys() it returns an array from 0 to 30 rather than 1 to 31. The simplest way to fix this is to write a loop that starts at 1, rather than playing games with arrays.

let lastday = this.daysInYearMonth(this.year, this.month);
this.days = [];
for (let d = 1; d <= lastday; d++) {
    this.days.push(d);
}


问:
How to put a space in a sphinx url for windows drive
I'm trying to create a hyperlink to a folder that has a space in it.
The space is removed because of the way rst is processing the link.

Unfortunately I can't change the name of the folder because I'm not the owner.

This was solved below by adding %20 but now there is a second problem:

The path should be "file:///T:/my_path/A&B Tools".

It can also be represented as "\\network.com\my_path\A&B Tools".

```<code>* First link   `hyperlink-name-1`_
* Second link  `hyperlink-name-2`_

.. _hyperlink-name-1: file:///T:/my_path/A&B%20Tools
.. _hyperlink-name-2: \\\\network.com\\my_path\\A&B%20Tools
</code>```

The first link works when I map network.com to T:

Edit:

Thanks to Steve I looked at the html I see when I use second link. The windows path starting with \ doesn't seem to work properly. I think this is a windows interpretation of the path.

答:
Try URL-encoding the space:

```<code>* A link  `hyperlink-name`_

.. _hyperlink-name: file://my_path/A&B%20Tools
</code>```

EDIT

And now with your example above, Sphinx generates the following HTML:

```<code><ul class="simple">
<li>First link   <a class="reference external" href="file:///T:/my_path/A&B%20Tools">hyperlink-name-1</a></li>
<li>Second link  <a class="reference external" href="\\network.com\my_path\A&B%20Tools">hyperlink-name-2</a></li>
</ul>
</code>```

I suspect you copy-pastad an invisible character (gremlin) into your .rst file.  I noticed that you mixed examples in your question, too: A&B Tools vs. M&S Tools.  I'd slow down and check all my assumptions.

Body:
I'm trying to create a hyperlink to a folder that has a space in it.
The space is removed because of the way rst is processing the link.

Unfortunately I can't change the name of the folder because I'm not the owner.

This was solved below by adding %20 but now there is a second problem:

The path should be "file:///T:/my_path/A&B Tools".

It can also be represented as "\\network.com\my_path\A&B Tools".

* First link   `hyperlink-name-1`_
* Second link  `hyperlink-name-2`_

.. _hyperlink-name-1: file:///T:/my_path/A&B%20Tools
.. _hyperlink-name-2: \\\\network.com\\my_path\\A&B%20Tools

The first link works when I map network.com to T:

Edit:

Thanks to Steve I looked at the html I see when I use second link. The windows path starting with \ doesn't seem to work properly. I think this is a windows interpretation of the path.

Body:
Try URL-encoding the space:

* A link  `hyperlink-name`_

.. _hyperlink-name: file://my_path/A&B%20Tools

EDIT

And now with your example above, Sphinx generates the following HTML:

<ul class="simple">
<li>First link   <a class="reference external" href="file:///T:/my_path/A&amp;B%20Tools">hyperlink-name-1</a></li>
<li>Second link  <a class="reference external" href="\\network.com\my_path\A&amp;B%20Tools">hyperlink-name-2</a></li>
</ul>

I suspect you copy-pastad an invisible character (gremlin) into your .rst file.  I noticed that you mixed examples in your question, too: A&B Tools vs. M&S Tools.  I'd slow down and check all my assumptions.


问:
How to get data before Router is loaded after Auth Service using angular 2+?
I hope this is not duplicated.

I have this component to Login with a user, that calls a service and gives me a Token.

When the login is success I save the token to localStorage and I get the user Data with getUserData service and save it to a localStorage with saveUderData service.

```<code>  onLoginSuccess(token: Token) {

    this.authService.saveToken(token);

    this.authService.getUserData().subscribe(
      userData =>  this.onGetUserDataSuccess(userData)
    );
  }

  onGetUserDataSuccess(userData: UserDataModel) {
    this.authService.saveUserData(userData);
    this.router.navigate(['/'])
  }
</code>```

The problem is that when I go to the main component the data is not
  loaded and I have to refresh the page.

I have this in my main component.

```<code>if (localStorage.getItem('_UserToken') && localStorage.getItem('_UserData') && (!this.authService.userToken || !this.authService.userToken.access_token)) {
      this.authService.saveToken(JSON.parse(localStorage.getItem('_UserToken')));
      this.authService.saveUserData(JSON.parse(localStorage.getItem('_UserData')));

      this.userData = this.authService.userData;

    }
</code>```

with this.userData I get the data.

I solved it in another component with Resolve but here I can't do it because i don't know how.

I tried this in onLoginSuccess(token: Token)

```<code>this.route.data.subscribe(
      userData => console.log(userData['user'])
    );
</code>```

but the userData is undefined

here my routes.

```<code>const appRoutes: Routes = [
  {path: '', canActivate: [AuthGuardService], data: { title: 'Inicio'}, resolve: {user: UserDataResolve},
    children: [
      {path: '', component: HomeComponent},
      {path: '', component: MenuComponent},
    ]},
  {path: 'login', component: LoginComponent, data: { title: 'Iniciar Sesión'} },

];
</code>```

and here is my Resolve

```<code>@Injectable()
export class UserDataResolve implements Resolve<UserDataModel> {

  constructor(private authService: AuthService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<UserDataModel> {
    return this.authService.getUserData();
  }

}
</code>```

I hope you can understand me, my english is not the best. thanks =).

答:
Try using a getter instead of a simple property in your component:

```<code>get userData(): string {
    this.authService.userData;
}
</code>```

That way any time changes are detected it will get the current userData from your service.

Body:
I hope this is not duplicated.

I have this component to Login with a user, that calls a service and gives me a Token.

When the login is success I save the token to localStorage and I get the user Data with getUserData service and save it to a localStorage with saveUderData service.

  onLoginSuccess(token: Token) {

    this.authService.saveToken(token);

    this.authService.getUserData().subscribe(
      userData =>  this.onGetUserDataSuccess(userData)
    );
  }

  onGetUserDataSuccess(userData: UserDataModel) {
    this.authService.saveUserData(userData);
    this.router.navigate(['/'])
  }

The problem is that when I go to the main component the data is not
  loaded and I have to refresh the page.

I have this in my main component.

if (localStorage.getItem('_UserToken') && localStorage.getItem('_UserData') && (!this.authService.userToken || !this.authService.userToken.access_token)) {
      this.authService.saveToken(JSON.parse(localStorage.getItem('_UserToken')));
      this.authService.saveUserData(JSON.parse(localStorage.getItem('_UserData')));

      this.userData = this.authService.userData;

    }

with this.userData I get the data.

I solved it in another component with Resolve but here I can't do it because i don't know how.

I tried this in onLoginSuccess(token: Token)

this.route.data.subscribe(
      userData => console.log(userData['user'])
    );

but the userData is undefined

here my routes.

const appRoutes: Routes = [
  {path: '', canActivate: [AuthGuardService], data: { title: 'Inicio'}, resolve: {user: UserDataResolve},
    children: [
      {path: '', component: HomeComponent},
      {path: '', component: MenuComponent},
    ]},
  {path: 'login', component: LoginComponent, data: { title: 'Iniciar Sesión'} },

];

and here is my Resolve

@Injectable()
export class UserDataResolve implements Resolve<UserDataModel> {

  constructor(private authService: AuthService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<UserDataModel> {
    return this.authService.getUserData();
  }

}

I hope you can understand me, my english is not the best. thanks =).

Body:
Try using a getter instead of a simple property in your component:

get userData(): string {
    this.authService.userData;
}

That way any time changes are detected it will get the current userData from your service.


问:
Customized Buttons on a UIActionsheet
I am trying to create a UIActionsheet with several buttons as options.

Is it possible?.

If it is, will apple let in onto apps store. I have seen in some blogs that these types of windows are rejected?

if not possible is there an alternative to UIActionsheet, that will achieve similar functionallity?.

答: It is possible and I don't think Apple will reject it (why would they ?).</p>

Title: Customized Buttons on a UIActionsheet


问:
Azure Search- replicating result of nested SQL query
I have a database comprising of the following schema depicting the linkage between individuals who connect with multiple Advisors and these Advisors have affiliations with multiple organizations

```<code>Individuals--> Advisors (m:n relationship)
Advisors --> Enterprises (m:n relationship)
</code>```

The business need is to enable search on all these concepts and organize results around AdvisorIds. As an example, display of a search result could be as follows

```<code>a) Advisor1-> connected to Individuals A,B,C; and linked to Enterprises X,Y

b) Advisor2-> connected to Individuals A, E; and linked to Enterprises M,X,Z
</code>```

Towards this, we created a flattened table on these concepts and the relationship between them. Hence the same AdvisorId would appear in multiple rows

When I search for a string, I want to ensure that ALL records around an AdvisorId to be returned together irrespective of search score of the individual records.

One approach could be

```<code> a) first run an Azure Search and get a result of AdvisorId, ordered by search score of each record. This will repeat Advisor Ids

b) take a distinct set of  AdvisorIds (across pages) via standard SQL

c) for each AdvisorId, pick all the related records via standard SQL
</code>```

2 questions

Here a lot of processing in (b) and (c) will be done outside Azure leading to delays. Also, if I were to use pagination for (a), I am never sure of number of AdvisorId's, I end up with after the distinct operation

I wanted to check if there is a way to get the nested search implemented in Azure to do (a), (b) and (c) as a single API call

If I were to use facets for handling (a) and (b) together, how do I ensure that the ordering is based on the best search-score document within a facet

答:
There isn't a way to achieve what you want in a single request unless you model your data differently. Instead of denormalizing the Individuals-Advisors and Advisors-Enterprises relationships, it may be possible instead to have one document per Advisor and use collections to store information about the related Individuals and Enterprises. This may or may not work for you depending on whether you need to supported correlated filtering on Individuals and Enterprises that are related to an Advisor. There is a whitepaper here that should help you evaluate whether this approach would work for you.

Another option might be to model Individuals, Advisors, and Enterprises as separate indexes, issue three queries, and do a client-side join. However, this is limited by the number of Advisor IDs you'd need to send in the queries on Individuals and Enterprises. Azure Search has limits on the size of filters that can make this impractical unless your queries have low recall.

We are working on making Azure Search better for scenarios like yours. For example, we're currently working on adding support for complex types. Please vote on User Voice and feel free to suggest other features that would help.

Body:
I have a database comprising of the following schema depicting the linkage between individuals who connect with multiple Advisors and these Advisors have affiliations with multiple organizations

Individuals--> Advisors (m:n relationship)
Advisors --> Enterprises (m:n relationship)

The business need is to enable search on all these concepts and organize results around AdvisorIds. As an example, display of a search result could be as follows

a) Advisor1-> connected to Individuals A,B,C; and linked to Enterprises X,Y

b) Advisor2-> connected to Individuals A, E; and linked to Enterprises M,X,Z

Towards this, we created a flattened table on these concepts and the relationship between them. Hence the same AdvisorId would appear in multiple rows

When I search for a string, I want to ensure that ALL records around an AdvisorId to be returned together irrespective of search score of the individual records.

One approach could be

 a) first run an Azure Search and get a result of AdvisorId, ordered by search score of each record. This will repeat Advisor Ids

b) take a distinct set of  AdvisorIds (across pages) via standard SQL

c) for each AdvisorId, pick all the related records via standard SQL

2 questions

Here a lot of processing in (b) and (c) will be done outside Azure leading to delays. Also, if I were to use pagination for (a), I am never sure of number of AdvisorId's, I end up with after the distinct operation

I wanted to check if there is a way to get the nested search implemented in Azure to do (a), (b) and (c) as a single API call

If I were to use facets for handling (a) and (b) together, how do I ensure that the ordering is based on the best search-score document within a facet


问:
Generic Linq query NotSupportedException: Could not parse expression
I'm trying to filter some results in Entity Framework core generically through a helper class but I'm getting this error and I don't know why:

NotSupportedException: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1[eVendCustomerDAL.DomainModels.Bin]).Any(__funcTest_0)': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.

And this is where the error is happening:

```<code>    public virtual Revision<DTO> GetStateAsRevision(
        Expression<Func<Domain, bool>> query) {
        //get all the stateful data from the database
        DbSet<Domain> oriSet = db.Set<Domain>();
        //query all the data
        List<Domain> oriList = oriSet.Where(query).ToList();
</code>```

The error seems to occur because of the query parameter that I'm pushing through and it only occurs as runtime. I'm not sure if the fact it's generic is to blame. The generics are classes and not interfaces also.

```<code>where DTO : BaseRevisionDTO
where Domain : BaseTrackedObject
where DomainRevision : BaseRevision
</code>```

I then build the expression using the following snippets:

```<code>    private Expression<Func<Domain, bool>> GetDomainSearchExpression(Func<Domain, bool> shortFunction) {
        DbSet<Domain> modelTable = CustomerContext.Set<Domain>();

        Expression<Func<Domain, bool>> expr =
        d =>
        modelTable.Any(shortFunction);

        return expr;
    }

    protected override Func<DomainModels.Bin, bool> GetDomainSearchFunction() {
        return x => x.Station.Machine.UniqueId == MachineID;
    }
</code>```

Edit 1:

So if I call the above code like so:

```<code>        GetStateAsRevision(GetDomainSearchExpression(GetDomainSearchFunction()));
</code>```

It will error at:

```<code>        List<Domain> oriList = oriSet.Where(query).ToList();
</code>```

And this is the entire stack trace:

```<code>NotSupportedException: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[eVendCustomerDAL.DomainModels.Bin]).Any(__shortFunction_0)': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.CreateExpressionNode(Type nodeType, MethodCallExpressionParseInfo parseInfo, Object[] additionalConstructorParameters)
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(string associatedIdentifier, IExpressionNode source, IEnumerable<Expression> arguments, MethodCallExpression expressionToParse)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, string associatedIdentifier)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)
Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)
System.Linq.Expressions.ExpressionVisitor.VisitLambda<T>(Expression<T> node)
System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)
System.Linq.Enumerable+SelectListPartitionIterator.ToArray()
System.Linq.Enumerable.ToArray<TSource>(IEnumerable<TSource> source)
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(string associatedIdentifier, IExpressionNode source, IEnumerable<Expression> arguments, MethodCallExpression expressionToParse)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, string associatedIdentifier)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)
Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore<TResult>(Expression query, INodeTypeProvider nodeTypeProvider, IDatabase database, ILogger logger, Type contextType)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<>c__DisplayClass19_0.<CompileQuery>b__0()
Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore<TFunc>(object cacheKey, Func<Func<QueryContext, TFunc>> compiler)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute<TResult>(Expression query)
Remotion.Linq.QueryableBase.GetEnumerator()
System.Collections.Generic.List..ctor(IEnumerable<T> collection)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
eVendWebAPI.Helpers.DALHelpers.GetRevisionHelper.GetStateAsRevision(Expression<Func<DomainModel, bool>> query) in GetRevisionHelper.cs
+
            List<DomainModel> oriList = oriSet.Where(query).ToList();
eVendWebAPI.Helpers.DALHelpers.GetRevisionHelper.GetRevision(Expression<Func<DomainModel, bool>> query) in GetRevisionHelper.cs
+
            return GetStateAsRevision(query);
eVendWebAPI.Areas.Customer.Controllers.Base.BaseAPIRevisionController.Get() in BaseAPIRevisionController.cs
+
            return Ok(helper.GetRevision(searchExpr));
lambda_method(Closure , object , Object[] )
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__27.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__25.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
</code>```

答:
Your shortFunction is a Func<> and not an Expression so it can't be converted to SQL. Try making it's type Expression<Func<>> instead.

The C# compiler has special logic to convert a lambda into two types - if the desired result type is Func<> then it converts it to compiled code and if the result type is Expression it converts it to an Expression tree that represents the code (a cheat added for LINQ). A data provider can read that expression tree and emit code for the database in question (such as SQL) but it can't decompile the compiled IL code back into something it can output in another language.

Body:
I'm trying to filter some results in Entity Framework core generically through a helper class but I'm getting this error and I don't know why:

NotSupportedException: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1[eVendCustomerDAL.DomainModels.Bin]).Any(__funcTest_0)': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.

And this is where the error is happening:

    public virtual Revision<DTO> GetStateAsRevision(
        Expression<Func<Domain, bool>> query) {
        //get all the stateful data from the database
        DbSet<Domain> oriSet = db.Set<Domain>();
        //query all the data
        List<Domain> oriList = oriSet.Where(query).ToList();

The error seems to occur because of the query parameter that I'm pushing through and it only occurs as runtime. I'm not sure if the fact it's generic is to blame. The generics are classes and not interfaces also.

where DTO : BaseRevisionDTO
where Domain : BaseTrackedObject
where DomainRevision : BaseRevision

I then build the expression using the following snippets:

    private Expression<Func<Domain, bool>> GetDomainSearchExpression(Func<Domain, bool> shortFunction) {
        DbSet<Domain> modelTable = CustomerContext.Set<Domain>();

        Expression<Func<Domain, bool>> expr =
        d =>
        modelTable.Any(shortFunction);

        return expr;
    }

    protected override Func<DomainModels.Bin, bool> GetDomainSearchFunction() {
        return x => x.Station.Machine.UniqueId == MachineID;
    }

Edit 1:

So if I call the above code like so:

        GetStateAsRevision(GetDomainSearchExpression(GetDomainSearchFunction()));

It will error at:

        List<Domain> oriList = oriSet.Where(query).ToList();

And this is the entire stack trace:

NotSupportedException: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[eVendCustomerDAL.DomainModels.Bin]).Any(__shortFunction_0)': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.CreateExpressionNode(Type nodeType, MethodCallExpressionParseInfo parseInfo, Object[] additionalConstructorParameters)
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(string associatedIdentifier, IExpressionNode source, IEnumerable<Expression> arguments, MethodCallExpression expressionToParse)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, string associatedIdentifier)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)
Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)
System.Linq.Expressions.ExpressionVisitor.VisitLambda<T>(Expression<T> node)
System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
Remotion.Linq.Parsing.ExpressionVisitors.SubQueryFindingExpressionVisitor.Visit(Expression expression)
System.Linq.Enumerable+SelectListPartitionIterator.ToArray()
System.Linq.Enumerable.ToArray<TSource>(IEnumerable<TSource> source)
Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(string associatedIdentifier, IExpressionNode source, IEnumerable<Expression> arguments, MethodCallExpression expressionToParse)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, string associatedIdentifier)
Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree)
Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore<TResult>(Expression query, INodeTypeProvider nodeTypeProvider, IDatabase database, ILogger logger, Type contextType)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<>c__DisplayClass19_0.<CompileQuery>b__0()
Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore<TFunc>(object cacheKey, Func<Func<QueryContext, TFunc>> compiler)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute<TResult>(Expression query)
Remotion.Linq.QueryableBase.GetEnumerator()
System.Collections.Generic.List..ctor(IEnumerable<T> collection)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
eVendWebAPI.Helpers.DALHelpers.GetRevisionHelper.GetStateAsRevision(Expression<Func<DomainModel, bool>> query) in GetRevisionHelper.cs
+
            List<DomainModel> oriList = oriSet.Where(query).ToList();
eVendWebAPI.Helpers.DALHelpers.GetRevisionHelper.GetRevision(Expression<Func<DomainModel, bool>> query) in GetRevisionHelper.cs
+
            return GetStateAsRevision(query);
eVendWebAPI.Areas.Customer.Controllers.Base.BaseAPIRevisionController.Get() in BaseAPIRevisionController.cs
+
            return Ok(helper.GetRevision(searchExpr));
lambda_method(Closure , object , Object[] )
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__27.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__25.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

ContentLicense: CC BY-SA 4.0


问:
Responsive grid made out of circles
I am creating a grid with two different sizes of circles and I am having a problem creating a new row of circles without it leaving a gap (shown in my code)
I am trying to get it to look similar to this:

Here is my code:

ul {
width:97%;
height:100%;

}

li.small {
float: left;
margin: 12px;
overflow: hidden;
width:200px;
height:200px;
background-color:palegreen;
border-radius: 50%
}

li.big {
float: left;
margin: 10px;
overflow: hidden;
width:460px;
height:460px;
background-color:black;
border-radius: 50%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <ul>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>

</ul></code>```

I understand that it is somewhat responsive now, such as it collapses, but I would like it to collapse to only 2 columns.

Thanks in advance to anyone who is willing to help!

答:
You can give a try to the new CSS grid display : https://css-tricks.com/snippets/css/complete-guide-grid/

example below or a codepen to play with .

ul {
padding:0;
margin:0;
display:grid;
grid-template-rows: repeat(auto-fill, 220px);
grid-template-columns: repeat(auto-fill, 220px);
grid-gap:0px;
}

li.small {
width:200px;
height:200px;
background-color:palegreen;
border-radius: 50%;
grid-row:auto / span 1;
grid-column:auto / span 1;
margin:10px 0;
}

li.big {
margin:0;
width:400px;
height:400px;
background-color:black;
border-radius: 50%;
grid-row:auto / span 2;
grid-column: auto / span 2
}
li {
display:block;
padding:0;
margin:0;
align-self:center;
justify-self: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>

</ul></code>```

or take a look at the masonry javascript grid layout library https://masonry.desandro.com/

Title: Responsive grid made out of circles

Body:
I am creating a grid with two different sizes of circles and I am having a problem creating a new row of circles without it leaving a gap (shown in my code)
I am trying to get it to look similar to this:

Here is my code:

ul {
width:97%;
height:100%;

}

li.small {
float: left;
margin: 12px;
overflow: hidden;
width:200px;
height:200px;
background-color:palegreen;
border-radius: 50%
}

li.big {
float: left;
margin: 10px;
overflow: hidden;
width:460px;
height:460px;
background-color:black;
border-radius: 50%
}

I understand that it is somewhat responsive now, such as it collapses, but I would like it to collapse to only 2 columns.

Thanks in advance to anyone who is willing to help!

Body:
You can give a try to the new CSS grid display : https://css-tricks.com/snippets/css/complete-guide-grid/

example below or a codepen to play with .

ul {
padding:0;
margin:0;
display:grid;
grid-template-rows: repeat(auto-fill, 220px);
grid-template-columns: repeat(auto-fill, 220px);
grid-gap:0px;
}

li.small {
width:200px;
height:200px;
background-color:palegreen;
border-radius: 50%;
grid-row:auto / span 1;
grid-column:auto / span 1;
margin:10px 0;
}

li.big {
margin:0;
width:400px;
height:400px;
background-color:black;
border-radius: 50%;
grid-row:auto / span 2;
grid-column: auto / span 2
}
li {
display:block;
padding:0;
margin:0;
align-self:center;
justify-self: center;
}

<ul>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="big"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>
<li class="small"></li>

</ul>

or take a look at the masonry javascript grid layout library https://masonry.desandro.com/


问:
How to make a regex to check for other symbols than a given string?
I need to make a regex that checks if an input string contains symbols other than symbols that I have in the charRange string.

given string:

```<code>string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";
</code>```

答:
If you're just checking whether a string doesn't contain a character in another string, use Linq:

```<code>var stringContainsOtherSymbol = !stringToCheck.All(c => stringOfAllowedChars.Contains(c))
</code>```

Using Regex is just going to trip you up because you have to escape regex metacharacters in stringOfAllowedChars.

Body:
I need to make a regex that checks if an input string contains symbols other than symbols that I have in the charRange string.

given string:

string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

Body:
If you're just checking whether a string doesn't contain a character in another string, use Linq:

var stringContainsOtherSymbol = !stringToCheck.All(c => stringOfAllowedChars.Contains(c))

Using Regex is just going to trip you up because you have to escape regex metacharacters in stringOfAllowedChars.


答: It's probably a number of "zero length" characters, like ASCII control characters or one of the Unicode "zero length" spaces.</p>

Title: How can an array value be SIX chars long and echoing nothing (string(6) " ")?


问:
How to get user's roles, Discord, Python
I've been improving and improving my bot.
Now, I've figured out how to make the bot purge messages, but a purge message, shouldn't be allowed to any member, only to people with certain role.

I've done this code:

```<code>if author.roles.has("BotModerator"):
</code>```

I've looked for it, on this website(https://anidiotsguide.gitbooks.io/discord-js-bot-guide/information/understanding_roles.html), but seems that they're coding with Java, how can I do it in Python?

By the way, the error shown in the output is 'list' object has no atribute 'has'

答:
It looks like author.roles is a python list. You may be able to check for the presence of your "BotModerator" role like so:

```<code>if "BotModerator" in author.roles:
</code>```

Haven't tried it myself, so can't verify currently.

Alternatively, if each role is an object, you may need something like:

```<code>role_names = [role.name for role in author.roles]
if "BotModerator" in role_names
</code>```

If each role is a dict, try the same as above, but with either role['name'] or role.get('name') instead of role.name.

Body:
I've been improving and improving my bot.
Now, I've figured out how to make the bot purge messages, but a purge message, shouldn't be allowed to any member, only to people with certain role.

I've done this code:

if author.roles.has("BotModerator"):

I've looked for it, on this website(https://anidiotsguide.gitbooks.io/discord-js-bot-guide/information/understanding_roles.html), but seems that they're coding with Java, how can I do it in Python?

By the way, the error shown in the output is 'list' object has no atribute 'has'

Body:
It looks like author.roles is a python list. You may be able to check for the presence of your "BotModerator" role like so:

if "BotModerator" in author.roles:

Haven't tried it myself, so can't verify currently.

Alternatively, if each role is an object, you may need something like:

role_names = [role.name for role in author.roles]
if "BotModerator" in role_names

If each role is a dict, try the same as above, but with either role['name'] or role.get('name') instead of role.name.


问:
Animation Delay will not add
I am trying to create a delay on my flip animation by adding the animation-delay property like so:

```<code>.flip-container:hover .flipper {
    -webkit-transform: rotateY(180deg);
    -moz-transform: rotateY(180deg);
    -webkit-animation-delay: 2s;
    /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}

.flipper {
    -webkit-transition: 0.6s;
    -webkit-transform-style: preserve-3d;
    -moz-transition: 0.6s;
    -moz-transform-style: preserve-3d;
    position: relative;
    -webkit-animation-delay: 2s;
    /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}
</code>```

This is not working for me in the slightest however. Is there a better method?

Codepen here

答:
You are using transitions not animations

Try using transition-delay instead of animation-delay.

Title: Animation Delay will not add

Body:
I am trying to create a delay on my flip animation by adding the animation-delay property like so:

.flip-container:hover .flipper {
    -webkit-transform: rotateY(180deg);
    -moz-transform: rotateY(180deg);
    -webkit-animation-delay: 2s;
    /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}

.flipper {
    -webkit-transition: 0.6s;
    -webkit-transform-style: preserve-3d;
    -moz-transition: 0.6s;
    -moz-transform-style: preserve-3d;
    position: relative;
    -webkit-animation-delay: 2s;
    /* Safari 4.0 - 8.0 */
    animation-delay: 2s;
}

This is not working for me in the slightest however. Is there a better method?

Codepen here


答:
For a given range and value

```<code>string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

string value = "-7Rt1Vp2RV";
</code>```

Linq solution (shorter and more readable):

```<code>bool hasOutOfRangeChar = value.Any(c => !charRange.Contains(c));
</code>```

If you insist on regular expressions:

```<code>bool hasOutOfRangeChar = !Regex.IsMatch(value, "^[" + Regex.Escape(charRange) + "]*$");
</code>```

please, notice Regex.Escape since - has a special meaning when within [...] - range form to; e.g. ;-? means any symbol from ; to ?

Title: How to make a regex to check for other symbols than a given string?

Body:
For a given range and value

string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

string value = "-7Rt1Vp2RV";

Linq solution (shorter and more readable):

bool hasOutOfRangeChar = value.Any(c => !charRange.Contains(c));

If you insist on regular expressions:

bool hasOutOfRangeChar = !Regex.IsMatch(value, "^[" + Regex.Escape(charRange) + "]*$");

please, notice Regex.Escape since - has a special meaning when within [...] - range form to; e.g. ;-? means any symbol from ; to ?


问:
Condensing Left Join Result Set into one row
I have a sql query which currently, due to a couple of Left joins, returns multiple rows:-

Id
  Action
  Group

12345 NULL NULL

12345 ADD NULL

12345 NULL ABC Group

How do I go about condensing these 3 rows into one e.g.
12345 ADD ABC Group

答:
The constraints of your question are a bit unclear.  If for every ID, there is only one possible non-NULL value of the other columns, you could use MIN or MAX to pull those values out.  For example, put the query with the LEFT JOINS into a CTE, then do </p>

```<code>SELECT ID, MAX(col2),MAX(col3)
FROM CTE
GROUP BY ID
</code>```

<p>If there is the potential for multiple non-NULL values per column, you will need to be more specific about what you would want the output to look like.  </p>

Body:
The constraints of your question are a bit unclear.  If for every ID, there is only one possible non-NULL value of the other columns, you could use MIN or MAX to pull those values out.  For example, put the query with the LEFT JOINS into a CTE, then do

SELECT ID, MAX(col2),MAX(col3)
FROM CTE
GROUP BY ID

If there is the potential for multiple non-NULL values per column, you will need to be more specific about what you would want the output to look like.


问:
Azure Search- order facets by highest scored document in each facet
Is there a way the facets in Azure Search can be ordered by the highest scored document in each facet. The default approach is ordered by number of documents in each facet which not as useful when match accuracy is critical. I understand the 'sort' is within the facet- not across facets.

I am hoping that this will help solve the following need in an indirect way
Azure Search- replicating result of nested SQL query

答: Currently Azure Search only supports sorting facets by document count or value, not by document score. Feel free to suggest this as a new feature on User Voice</p>


问:
Tensorflow semantic segmentation gives zero loss
I am training a model for segmenting machine printed text from the images. The images might contain barcodes and handwritten text also. Ground truths images are processed so that 0 represents machine print and 1 represents the remaining. And I am using 5 layer CNN with dilation which outputs 2 maps in the end.

And my loss is calculated as follows:

```<code>def loss(logits, labels):

    logits = tf.reshape(logits, [-1, 2])
    labels = tf.reshape(labels, [-1])

    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
</code>```

And I have some images which contain only handwritten text and their corresponding ground truths are blank pages which are represented by 1s.

When I train the model, for these images I am getting a loss of 0 and training accuracy of 100%. Is this correct? How can this loss be zero?
For other images which contain barcodes or machine print, am getting some loss and they are converging properly.

And when I test this model, barcodes are correctly ignored. But it outputs both machine print and handwritten text where I need only machine print.

Can someone guide me on where I am going wrong, please!

UPDATE 1:

I was using a learning rate of 0.01 before and changing it to 0.0001 gave me some loss and it seems to converge but not very well.
But, then how a high learning rate will give a loss of 0?

When I use the same model in Caffe with learning rate of 0.01 it gave some loss and it converges well compared to in Tensorflow.

答: Your loss calculation looks fine but a loss of zero is weird in your case. Have you tried playing with the learning rate? Maybe decrease it. I have encountered weird loss values and decreasing the learning rate helped me. </p>

Body:
I am training a model for segmenting machine printed text from the images. The images might contain barcodes and handwritten text also. Ground truths images are processed so that 0 represents machine print and 1 represents the remaining. And I am using 5 layer CNN with dilation which outputs 2 maps in the end.

And my loss is calculated as follows:

def loss(logits, labels):

    logits = tf.reshape(logits, [-1, 2])
    labels = tf.reshape(labels, [-1])

    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')

And I have some images which contain only handwritten text and their corresponding ground truths are blank pages which are represented by 1s.

When I train the model, for these images I am getting a loss of 0 and training accuracy of 100%. Is this correct? How can this loss be zero?
For other images which contain barcodes or machine print, am getting some loss and they are converging properly.

And when I test this model, barcodes are correctly ignored. But it outputs both machine print and handwritten text where I need only machine print.

Can someone guide me on where I am going wrong, please!

UPDATE 1:

I was using a learning rate of 0.01 before and changing it to 0.0001 gave me some loss and it seems to converge but not very well.
But, then how a high learning rate will give a loss of 0?

When I use the same model in Caffe with learning rate of 0.01 it gave some loss and it converges well compared to in Tensorflow.


问:
Show only results in query with more then 2 hits
didnt find a solution yet... ;-)

suppose this is the result of a query:

```<code>ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .
</code>```

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

答:
You can use exists, assuming the dates are different:

```<code>select t.*
from t
where exists (select 1
              from t t2
              where t2.id = t.id and t2.date <> t.date
             );
</code>```

Based on the context of the question, I interpret "more than 2" to actually be "2 or more".  Otherwise an aggregation would be necessary.

Body:
didnt find a solution yet... ;-)

suppose this is the result of a query:

ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

Body:
You can use exists, assuming the dates are different:

select t.*
from t
where exists (select 1
              from t t2
              where t2.id = t.id and t2.date <> t.date
             );

Based on the context of the question, I interpret "more than 2" to actually be "2 or more".  Otherwise an aggregation would be necessary.


问:
what is PAT (Pre Acceptance Testing)?
What is exactly PAT, When we will do the pre acceptance testing?</p>

答: I don't think it's a widely-used term or part of a standard. Therefore, what exactly it means is organization-specific and should be defined in a glossary somewhere. More likely though you'll just have to ask people what it means.</p>

Title: what is PAT (Pre Acceptance Testing)?


问:
Scroll to UITableViewCell from String
I want to automatically scroll to a UITableViewCell. I know how to do this by the row number like

```<code>var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
</code>```

But, I want to scroll to the cell that equals a string. I have a struct

```<code>struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]
</code>```

And the UITableViewCell's title is equal to the title and the subtitle is equal to the artist. Whenever a user taps on a UIButton, I want it to scroll to the cell that is Song(title: "Title 3", artist "Artist 3"). How would I do this?

答: When they press the button, simply loop through your songs array and check for the song that has the given title and artist you're looking up.  When you find it, scroll to the cell whose index path aligns with the index in the array you found that song at.</p>

Title: Scroll to UITableViewCell from String

Body:
I want to automatically scroll to a UITableViewCell. I know how to do this by the row number like

var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

But, I want to scroll to the cell that equals a string. I have a struct

struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]

And the UITableViewCell's title is equal to the title and the subtitle is equal to the artist. Whenever a user taps on a UIButton, I want it to scroll to the cell that is Song(title: "Title 3", artist "Artist 3"). How would I do this?


问:
Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')
Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon').

This is my manifest... I'm extremely new to this, just started this morning and have no previous programming experience.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asdf"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
 </application>
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="ExampleActivity"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</application>

</manifest>
</code>```

答:
If you are 100% sure that directories and files are ok, have a look at the project location.

There is a limit on the path length of files in the Operating System. Perhaps this limit is being exceded in your project files.

Move the project to a shorter folder (say C:/MyProject) and try again!

This was the problem for me!

Body:
Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon').

This is my manifest... I'm extremely new to this, just started this morning and have no previous programming experience.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asdf"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
 </application>
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="ExampleActivity"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</application>

</manifest>


问:
ConstraintLayout constraints are too wide
I'm trying to get more used to ConstraintLayout to see how useful it can be to avoid nesting views. I have two LinearLayouts below a FrameLayout that are constrained to the top/bottom of each other, like this:

I constrained these two (with the second constrained to the parent bottom) so that the landscape layout would adjust accordingly. However, the gap between these linearlayouts is too wide, since it's spread out over the entire vertical view. Is there a way I can shorten this gap while avoiding nesting them into a parent LinearLayout?

My XML:

```<code><LinearLayout
        android:id="@+id/dropbox_upload_btn"
        android:layout_width="306dp"
        android:layout_height="35dp"
        android:gravity="center"
        android:background="@android:color/background_light"
        app:layout_constraintBottom_toTopOf="@+id/box_upload_btn"
        app:layout_constraintTop_toBottomOf="@+id/imageFrameLayout"
        android:layout_marginLeft="45dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="45dp"
        app:layout_constraintRight_toRightOf="parent"
        android:elevation="2dp"
        app:layout_constraintVertical_bias="0.22">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/dropbox_android"
            android:layout_marginStart="15dp"
            android:layout_weight="0.35"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/dropbox_upload"
            android:layout_weight="2.43"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/box_upload_btn"
        android:layout_width="306dp"
        android:layout_height="35dp"
        android:gravity="center"
        android:background="@android:color/background_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dropbox_upload_btn"
        android:layout_marginLeft="45dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="45dp"
        app:layout_constraintRight_toRightOf="parent"
        android:elevation="2dp"
        app:layout_constraintVertical_bias="0.076">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/box_logo"
            android:layout_marginStart="15dp"
            android:layout_weight="0.35"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/box_upload"
            android:layout_weight="2.43"/>

    </LinearLayout>
</code>```

答:
It looks like you have those two views in a vertical chain. The default for this configuration is a chain style of CHAIN_SPREAD which will give you the gaps. Add the following to the top view of the chain.

```<code>layout_constraintVertical_chainStyle="CHAIN_PACKED"
</code>```

You can then control the spacing with margins or, maybe, vertical bias.

I hope this helps.

Body:
I'm trying to get more used to ConstraintLayout to see how useful it can be to avoid nesting views. I have two LinearLayouts below a FrameLayout that are constrained to the top/bottom of each other, like this:

I constrained these two (with the second constrained to the parent bottom) so that the landscape layout would adjust accordingly. However, the gap between these linearlayouts is too wide, since it's spread out over the entire vertical view. Is there a way I can shorten this gap while avoiding nesting them into a parent LinearLayout?

My XML:

<LinearLayout
        android:id="@+id/dropbox_upload_btn"
        android:layout_width="306dp"
        android:layout_height="35dp"
        android:gravity="center"
        android:background="@android:color/background_light"
        app:layout_constraintBottom_toTopOf="@+id/box_upload_btn"
        app:layout_constraintTop_toBottomOf="@+id/imageFrameLayout"
        android:layout_marginLeft="45dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="45dp"
        app:layout_constraintRight_toRightOf="parent"
        android:elevation="2dp"
        app:layout_constraintVertical_bias="0.22">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/dropbox_android"
            android:layout_marginStart="15dp"
            android:layout_weight="0.35"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/dropbox_upload"
            android:layout_weight="2.43"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/box_upload_btn"
        android:layout_width="306dp"
        android:layout_height="35dp"
        android:gravity="center"
        android:background="@android:color/background_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dropbox_upload_btn"
        android:layout_marginLeft="45dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="45dp"
        app:layout_constraintRight_toRightOf="parent"
        android:elevation="2dp"
        app:layout_constraintVertical_bias="0.076">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/box_logo"
            android:layout_marginStart="15dp"
            android:layout_weight="0.35"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/box_upload"
            android:layout_weight="2.43"/>

    </LinearLayout>

Body:
It looks like you have those two views in a vertical chain. The default for this configuration is a chain style of CHAIN_SPREAD which will give you the gaps. Add the following to the top view of the chain.

layout_constraintVertical_chainStyle="CHAIN_PACKED"

You can then control the spacing with margins or, maybe, vertical bias.

I hope this helps.


问:
Running PDO Statement in PHP returns bool(false)
I try to get a calculated value with this SQL Query in php: $sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

The I try to fetch the result with PDO in this function:

```<code>function getDatafromDB($query, $columnName){
    require 'db.php';

    try {
        $pdo = new PDO("mysql:host=localhost;dbname=$db_name", $db_user, $db_pass);

        $statement = $pdo->prepare($query);
        $retValue = $statement->fetch(PDO::FETCH_ASSOC);
        var_dump($retValue);

        return $retValue[$columnName];
    } catch (PDOException $e) {
        $error = "Error!: " . $e->getMessage() . "<br/>";

        return $error;
        die();
    }
}
</code>```

I call the function like this:

```<code>$sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

$retValue = getDatafromDB($sql, "IncomeSum");
</code>```

But when i var_dump($retValue) in the function above I always get

bool(false)

as result.

Is there a problem with the alias name or something else wrong in my thinking?

答:
You need to execute() before you fetch().

```<code>$statement = $pdo->prepare($query);
$statement->execute();
$retValue = $statement->fetch(PDO::FETCH_ASSOC);
</code>```

Please read the code examples in the documentation.

Body:
I try to get a calculated value with this SQL Query in php: $sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

The I try to fetch the result with PDO in this function:

function getDatafromDB($query, $columnName){
    require 'db.php';

    try {
        $pdo = new PDO("mysql:host=localhost;dbname=$db_name", $db_user, $db_pass);

        $statement = $pdo->prepare($query);
        $retValue = $statement->fetch(PDO::FETCH_ASSOC);
        var_dump($retValue);

        return $retValue[$columnName];
    } catch (PDOException $e) {
        $error = "Error!: " . $e->getMessage() . "
";

        return $error;
        die();
    }
}

I call the function like this:

$sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

$retValue = getDatafromDB($sql, "IncomeSum");

But when i var_dump($retValue) in the function above I always get

bool(false)

as result.

Is there a problem with the alias name or something else wrong in my thinking?

Body:
You need to execute() before you fetch().

$statement = $pdo->prepare($query);
$statement->execute();
$retValue = $statement->fetch(PDO::FETCH_ASSOC);

Please read the code examples in the documentation.


问:
Angular js objects of objects displaying last content
I have my model data like this:

```<code>     {
  "0": [
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "key": "Survey Meta Data"
    }
  ],
  "1": [
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    },
    {
      "key": "Assessment"
    }
  ]
}
</code>```

but I want to display in my html the key first and then all my  questions

Note: if I reverse my data then problem is the key will be display first but the questions order also get inverted I dont want to reverse my question , in short what I wan t is to display the key first and then the format of data must remain same i.e its something like pushing key to the top index
i.e something like this:

```<code>     {
  "0": [
    {
      "key": "Survey Meta Data"
    },
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    }
  ],
  "1": [
    {
      "key": "Assessment"
    },
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    }

  ]
}
</code>```

or

```<code>     {
  "0": [
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },

      "key": "Survey Meta Data"

  ],
  "1": [
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    },

      "key": "Assessment" //treat it as object value not object of object

  ]
}
</code>```

currently my html with ng-repeat is not working good it basically iterates the question first then the key is displayed but I want questions first then the key:

```<code>    <div ng-repeat="data in viewQuestions">
<div class="panel panel-default"  ng-repeat="value in data">
     {{value.key}}

   label>{{value.question}} </label>

     </div>
      </div>
</code>```

答:
The better options would be to get data from your api properly formatted of course, but if for some reason you cannot, you can do the following trick after getting data:

```<code><html ng-app="QuestionsApp">
<body ng-controller="QuestionsController">
  <div ng-repeat="data in viewQuestions">
    <div class="panel panel-default"  ng-repeat="value in data | orderBy : 'showIndex'">
      <strong ng-if="value.key">{{value.key}}</strong>
      <label ng-if="value.question">{{value.question}}</label>
    </div>
    <br>
  </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<script>
  var QuestionsApp = angular.module('QuestionsApp', []);

  QuestionsApp.controller('QuestionsController', function QuestionsController($scope) {
    var keyIndex = -1;
    var apiResponse = {
      "0": [
        {
          "question": "How often is real property re-assessed (or revalued)?",
          "id": 1,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "question": "How often second?",
          "id": 3,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "question": "How often third?",
          "id": 2,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "key": "Survey Meta Data"
        }
      ],
      "1": [
        {
          "question": "When are New Assessment Notices sent out?",
          "id": 3,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 1
        },
        {
          "key": "Assessment"
        }
      ]
    }

    angular.forEach(apiResponse, function (questions) {
      angular.forEach(questions, function (question, index) {
        if (question.key) question.showIndex = keyIndex;
        else question.showIndex = index;
      });
    });

    $scope.viewQuestions = apiResponse;
  });
</script>
</html>
</code>```

The trick is to add the showIndex field and value in data | orderBy : 'showIndex'

Body:
I have my model data like this:

     {
  "0": [
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "key": "Survey Meta Data"
    }
  ],
  "1": [
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    },
    {
      "key": "Assessment"
    }
  ]
}

but I want to display in my html the key first and then all my  questions

Note: if I reverse my data then problem is the key will be display first but the questions order also get inverted I dont want to reverse my question , in short what I wan t is to display the key first and then the format of data must remain same i.e its something like pushing key to the top index
i.e something like this:

     {
  "0": [
    {
      "key": "Survey Meta Data"
    },
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    }
  ],
  "1": [
    {
      "key": "Assessment"
    },
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    }

  ]
}

or

     {
  "0": [
    {
      "question": "How often is real property re-assessed (or revalued)?",
      "id": 1,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often second?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },
    {
      "question": "How often third?",
      "id": 2,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 0
    },

      "key": "Survey Meta Data"

  ],
  "1": [
    {
      "question": "When are New Assessment Notices sent out?",
      "id": 3,
      "section": "Assessment",
      "sectionId": 2,
      "check": true,
      "index": 1
    },

      "key": "Assessment" //treat it as object value not object of object

  ]
}

currently my html with ng-repeat is not working good it basically iterates the question first then the key is displayed but I want questions first then the key:

     {{value.key}}

   label>{{value.question}}

Body:
The better options would be to get data from your api properly formatted of course, but if for some reason you cannot, you can do the following trick after getting data:

<html ng-app="QuestionsApp">
<body ng-controller="QuestionsController">
  <div ng-repeat="data in viewQuestions">
    <div class="panel panel-default"  ng-repeat="value in data | orderBy : 'showIndex'">
      <strong ng-if="value.key">{{value.key}}</strong>
      <label ng-if="value.question">{{value.question}}</label>
    </div>
    <br>
  </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<script>
  var QuestionsApp = angular.module('QuestionsApp', []);

  QuestionsApp.controller('QuestionsController', function QuestionsController($scope) {
    var keyIndex = -1;
    var apiResponse = {
      "0": [
        {
          "question": "How often is real property re-assessed (or revalued)?",
          "id": 1,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "question": "How often second?",
          "id": 3,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "question": "How often third?",
          "id": 2,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 0
        },
        {
          "key": "Survey Meta Data"
        }
      ],
      "1": [
        {
          "question": "When are New Assessment Notices sent out?",
          "id": 3,
          "section": "Assessment",
          "sectionId": 2,
          "check": true,
          "index": 1
        },
        {
          "key": "Assessment"
        }
      ]
    }

    angular.forEach(apiResponse, function (questions) {
      angular.forEach(questions, function (question, index) {
        if (question.key) question.showIndex = keyIndex;
        else question.showIndex = index;
      });
    });

    $scope.viewQuestions = apiResponse;
  });
</script>
</html>

The trick is to add the showIndex field and value in data | orderBy : 'showIndex'


问:
Does the new Microsoft Lync 2010 Client API work in non-IE browsers?
I'm writing a Silverlight app that uses the Lync 2010 Client API to communicate with the Lync 2010 Client. Works fine in Internet Explorer, but in Chrome/Firefox i get this:

Microsoft.Lync.Model.UnsupportedBrowserException:
  Browser doesn't support ActiveX
         at Microsoft.Lync.Model.LyncClient.HandleJavascriptException(String
  error)
         at Microsoft.Lync.Model.LyncClient.EnsureOfficeIntegration()
         at Microsoft.Lync.Model.LyncClient.GetClient()
         at LyncSilverlightApplication2.Page.button1_Click(Object
  sender, RoutedEventArgs a)

The documentation hints that the API might only work in IE: "Internet Explorer 7 and Internet Explorer 8 currently support Lync Controls." This statement doesn't really exclude other browsers and the API could be independent from the controls. But still.

So; Does the new Microsoft Lync 2010 Client API work in non-IE browsers?

答: According to Wikipedia, most of the plugin options for FireFox are out of date.  In general, ActiveX implies IE only.</p>


问:
overwhelmed by UIDatePicker. trying to preset .hour and .minute for func in viewDidLoad()
i spend 2.5 hours searching google, i think i have never been on google search page number 10 in my entire life. untill today.

im a newbie with swift and i want the app to open the new viewcontroller with a UIDatePicker (datepickermode: time) preset to the time the user choose the last time he set a time with the datepicker. basically like the iphone alarm if that helps?

the struct 'Time' that contains .hour and .minute (integers) has its own class.

i want to have a tiny function that is executed with viewDidLoad() and sets the timepicker.

```<code>   @IBAction func timePicker(_ sender: UIDatePicker) {
    let picker = timePicker.date
    getTime(date: picker)
    print(globalTime.savedTime)
}

func oldTime(withTime: TimeStruct.Time) {

    var newTime = DateComponents()
    newTime.hour = withTime.hour
    newTime.minute = withTime.minute

    var newDate = Date()

    timePicker.calendar.

    //blabliblub i've lost it here. the code makes no sense anymore

}

func getTime(date: Date) {

let components = Calendar.current.dateComponents([.hour, .minute], from: date)
globalTime.savedTime.hour = components.hour!
globalTime.savedTime.minute = components.minute!

}
</code>```

getTime saves the time once set. oldTime gives the previously set time to the picker when viewed again to change again.

the user sets a time and clicks a save button that saves the current hour and minute to a variable of type 'Time'

oh and if possible, please help me with the use of Date(), not NSDate().

thank you so much for your time!

Felix ✌

答:
Have you tried using a normal picker instead? The date picker is a template with certain built in functions. However, a normal may be able to do all that you need it to do. For instance, simply create a normal picker with 3 components (0,1 and 2) which control Hour Minute and PM/AM by doing:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    self.Picker.delegate = self
    self.Picker.dataSource = self
    PickerData = [["0","1",/*...*/,"9"],["0","1",/*...*/,"9"],["AM","PM"]]
    self.Picker.selectRow(row: /*var*/, inComponent: /*component*/, animated: /*bool*/)
} /*Insert data from previous session above via a variable*/
</code>```

and

```<code>func numberOfComponents(in: UIPickerView) -> Int {
    return 3
}

//Number of rows
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return PickerData[component].count
}

//Data to return for the row and column being read
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return PickerData[component][row]
}

//Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}
</code>```

Body:
i spend 2.5 hours searching google, i think i have never been on google search page number 10 in my entire life. untill today.

im a newbie with swift and i want the app to open the new viewcontroller with a UIDatePicker (datepickermode: time) preset to the time the user choose the last time he set a time with the datepicker. basically like the iphone alarm if that helps?

the struct 'Time' that contains .hour and .minute (integers) has its own class.

i want to have a tiny function that is executed with viewDidLoad() and sets the timepicker.

   @IBAction func timePicker(_ sender: UIDatePicker) {
    let picker = timePicker.date
    getTime(date: picker)
    print(globalTime.savedTime)
}

func oldTime(withTime: TimeStruct.Time) {

    var newTime = DateComponents()
    newTime.hour = withTime.hour
    newTime.minute = withTime.minute

    var newDate = Date()

    timePicker.calendar.

    //blabliblub i've lost it here. the code makes no sense anymore

}

func getTime(date: Date) {

let components = Calendar.current.dateComponents([.hour, .minute], from: date)
globalTime.savedTime.hour = components.hour!
globalTime.savedTime.minute = components.minute!

}

getTime saves the time once set. oldTime gives the previously set time to the picker when viewed again to change again.

the user sets a time and clicks a save button that saves the current hour and minute to a variable of type 'Time'

oh and if possible, please help me with the use of Date(), not NSDate().

thank you so much for your time!

Felix ✌

Body:
Have you tried using a normal picker instead? The date picker is a template with certain built in functions. However, a normal may be able to do all that you need it to do. For instance, simply create a normal picker with 3 components (0,1 and 2) which control Hour Minute and PM/AM by doing:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    self.Picker.delegate = self
    self.Picker.dataSource = self
    PickerData = [["0","1",/*...*/,"9"],["0","1",/*...*/,"9"],["AM","PM"]]
    self.Picker.selectRow(row: /*var*/, inComponent: /*component*/, animated: /*bool*/)
} /*Insert data from previous session above via a variable*/

and

func numberOfComponents(in: UIPickerView) -> Int {
    return 3
}

//Number of rows
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return PickerData[component].count
}

//Data to return for the row and column being read
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return PickerData[component][row]
}

//Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}


问:
How to have user input index selection of object in list with specific criteria
I am trying to figure out how to have a user input the index number of an object in a list. My ultimate goal is to show a list of the spells in your spell book sorted by index number. I then want the user to be able to input the index number to choose the spell and perform a function with it. Here is a simple example:

(The spells are objects)

```<code>spells = [spell1(), spell2()]
print(spells.index(Spell),Spell.name)
</code>```

Should show:

```<code>0 spell1

1 spell2

x = input('Input number of spell')
print(spells[int(x)].description)
</code>```

So, by inputting the index number of the object in the list I retrieved its description. I have gotten the function itself to work. However, I am having difficulty setting up rules so that it does not accept any input other than the available indexes in the list. In this example, only 0 and 1 should be available inputs. I also wanted the option of 'p' to go back to the previous screen.

答: If you want mixed type input, then you need to need to treat everything as string and process it separately. A simple trick is that you can check for the alphabets first and the try casting anything else to int. This isn't completely break proof, since the user can enter other alphabets. The most efficient way is probably to use try catch statements, while casting to int.</p>

Body:
I am trying to figure out how to have a user input the index number of an object in a list. My ultimate goal is to show a list of the spells in your spell book sorted by index number. I then want the user to be able to input the index number to choose the spell and perform a function with it. Here is a simple example:

(The spells are objects)

spells = [spell1(), spell2()]
print(spells.index(Spell),Spell.name)

Should show:

0 spell1

1 spell2

x = input('Input number of spell')
print(spells[int(x)].description)

So, by inputting the index number of the object in the list I retrieved its description. I have gotten the function itself to work. However, I am having difficulty setting up rules so that it does not accept any input other than the available indexes in the list. In this example, only 0 and 1 should be available inputs. I also wanted the option of 'p' to go back to the previous screen.


问:
implement LIKE query in PDO
I am running problems in implementing LIKE in PDO

I have this query:

```<code>$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
</code>```

I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.

The result is none returned. Do my $query is syntactically correct?

答:
Simply use the following:</p>

```<code>$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
            OR address LIKE CONCAT('%', :var2, '%')";

$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
</code>```

Title: implement LIKE query in PDO

Body:
I am running problems in implementing LIKE in PDO

I have this query:

$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);

I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.

The result is none returned. Do my $query is syntactically correct?

Body:
Simply use the following:

$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
            OR address LIKE CONCAT('%', :var2, '%')";

$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }