问:
ElasticSearch - Multi-match Query returning no hits for data even though its there - NodeJS
I'm trying to fetch a list of items that have the field: resellable: true.

Here is my data set I can see by visiting: my-domain.com/_all/listings/_search

```<code>{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "collectibles",
        "_type" : "listing",
        "_id" : "SseZfNbpdpBxc3O",
        "_score" : 1.0,
        "_source" : {
          "data" : {
            "resellable" : true,
            "active" : true,
            "description" : "<p>1234 123 123 123</p>",
            "title" : "2134",
            "has_store" : true,
            "createdAt" : "Wed May 27 2020 04:23:18 GMT+0000 (Coordinated Universal Time)",
            "apiURL" : "kJ9zsIsdQG8TZrRfPco4",
            "id" : "SseZfNbpdpBxc3O",
            "state" : "PENDING",
            "amount" : "21",
          }
        }
      }
}
</code>```

My query is using *NodeJS and ElasticSearch.js*

```<code>let results = await client.search({
    index: params.category,
    type: "listing",
    body: {
        query: {
            multi_match: {
                query: true,
                fields: ['resellable', 'active'],
                type: 'best_fields',
            }
        }
    }
})
</code>```

The response is always no hits. I've tried a match, I've tried no best_fields and it doesn't seem to match the value.

What am I doing wrong here? Is there something else you need to do to query the _source.data level items?

ElasticSearch version: 7.4

答:
You are using the "true" in string format when using multi_match, while you indexed data in boolean format true and thats the reason you are not getting any hits.

I just noticed both of your multi_match fields(resellable and active) are boolean then why you are using the multi_match query, you should instead use the boolean filter query which is cached as well and gives better performance.

From the doc

Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

Sample index Mapping

```<code>{
    "mappings": {
        "properties": {
            "active": {
                "type": "boolean"
            },
            "resellable" :{
                "type" : "boolean"
            }
        }
    }
}
</code>```

Index various example  documents

```<code>{
   "active" : true,
   "resellable" : true
}

{
   "active" : true,
   "resellable" : false
}

{
   "active" : false,
   "resellable" : false
}

{
   "active" : false,
   "resellable" : true
}
</code>```

Search query to get the doc where both values are true

```<code>{
    "query": {
        "bool": {
            "filter": [
                {
                    "match": {
                        "active": true
                    }
                },
                {
                    "match": {
                        "resellable": true
                    }
                }
            ]
        }
    }
}
</code>```

Result

```<code> "hits": [
         {
            "_index": "filterbool",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.0,
            "_source": {
               "active": true,
               "resellable": true
            }
         }
      ]
</code>```

Body:
I'm trying to fetch a list of items that have the field: resellable: true.

Here is my data set I can see by visiting: my-domain.com/_all/listings/_search

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "collectibles",
        "_type" : "listing",
        "_id" : "SseZfNbpdpBxc3O",
        "_score" : 1.0,
        "_source" : {
          "data" : {
            "resellable" : true,
            "active" : true,
            "description" : "
1234 123 123 123
",
            "title" : "2134",
            "has_store" : true,
            "createdAt" : "Wed May 27 2020 04:23:18 GMT+0000 (Coordinated Universal Time)",
            "apiURL" : "kJ9zsIsdQG8TZrRfPco4",
            "id" : "SseZfNbpdpBxc3O",
            "state" : "PENDING",
            "amount" : "21",
          }
        }
      }
}

My query is using *NodeJS and ElasticSearch.js*

let results = await client.search({
    index: params.category,
    type: "listing",
    body: {
        query: {
            multi_match: {
                query: true,
                fields: ['resellable', 'active'],
                type: 'best_fields',
            }
        }
    }
})

The response is always no hits. I've tried a match, I've tried no best_fields and it doesn't seem to match the value.

What am I doing wrong here? Is there something else you need to do to query the _source.data level items?

ElasticSearch version: 7.4

Body:
You are using the "true" in string format when using multi_match, while you indexed data in boolean format true and thats the reason you are not getting any hits.

I just noticed both of your multi_match fields(resellable and active) are boolean then why you are using the multi_match query, you should instead use the boolean filter query which is cached as well and gives better performance.

From the doc

Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

Sample index Mapping

{
    "mappings": {
        "properties": {
            "active": {
                "type": "boolean"
            },
            "resellable" :{
                "type" : "boolean"
            }
        }
    }
}

Index various example  documents

{
   "active" : true,
   "resellable" : true
}

{
   "active" : true,
   "resellable" : false
}

{
   "active" : false,
   "resellable" : false
}

{
   "active" : false,
   "resellable" : true
}

Search query to get the doc where both values are true

{
    "query": {
        "bool": {
            "filter": [
                {
                    "match": {
                        "active": true
                    }
                },
                {
                    "match": {
                        "resellable": true
                    }
                }
            ]
        }
    }
}

Result

 "hits": [
         {
            "_index": "filterbool",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.0,
            "_source": {
               "active": true,
               "resellable": true
            }
         }
      ]


来源: stackexchange

问:
Format a number to string, fill 0 when it's not enough two characters
I want to format the number to String and fill 0 when it's not enough two characters

```<code>fun formatDuration(val duration):String {
    val minutes = duration.toInt() / 60
    return  "$minutes"
}
</code>```

For example, if minutes is 6， it should displayed 06 rather than 6.

答:
You can achive this with padStart

Example:

```<code>val padWithSpace = "125".padStart(5)
println("'$padWithSpace'") // '  125'

val padWithChar = "a".padStart(5, '.')
println("'$padWithChar'") // '....a'

// string is returned as is, when its length is greater than the specified
val noPadding = "abcde".padStart(3)
println("'$noPadding'") // 'abcde'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to format the number to String and fill 0 when it's not enough two characters

fun formatDuration(val duration):String {
    val minutes = duration.toInt() / 60
    return  "$minutes"
}

For example, if minutes is 6， it should displayed 06 rather than 6.

Body:
You can achive this with padStart

Example:

val padWithSpace = "125".padStart(5)
println("'$padWithSpace'") // '  125'

val padWithChar = "a".padStart(5, '.')
println("'$padWithChar'") // '....a'

// string is returned as is, when its length is greater than the specified
val noPadding = "abcde".padStart(3)
println("'$noPadding'") // 'abcde'


问:
How do I tell the difference between a positional parameter and a parameter that needs words before it
I saw this in the documentation for Google Drive

If I'm not a computer science expert, how am I to know that I need to do list(fileId="string") and not list("string")
and how was I to guess that there would be a .execute() thingy after it to get the goods?  Do you learn it in college or is there some other documentation on drive api basics or some course that professionals all know.  I'm not trying to be facetious.  It just seems really inaccessible if you're not a real programmer as if only real programmers should try this stuff.  In the future, where would I look to find these methods or how would I understand the way these parameters are to be passed into these functions?

Here's an additional picture of what I mean.  It seems to be the case that other believe as do I that if there are no equal sign with a default in the signature, then it is eligible for positional parameter treatment.

I was wrong and if you believe that, either you or google is wrong.  I'm no programmer.  I think I"m wrong.  So how do I tell the difference between a positional parameter and one I can refer to with words like I would in visual basic.?

答:
When you want to implement a Google API method, the first thing your should do is to consult the method reference

This documentation shows you which parameters exist, what they are good for, which of them are required and which are optional

There is also a Try this API functionality you can use for testing

The Try this API has fields and values for the parameters

Once you found the right request syntax for the Try this API that executes  in the desired way, you can transform the request into your language of choice

The python quickstart gives you an idea of how to translate your request into Python

The documentation linked under Further reading redirects you to the Drive API PyDoc documentation that  gives you specific information for each method

As a rule of thumb: The required parameters (in you case the fileId)  can be specified as "string" instead of fileId="string" (because the method expects you to provide it), while the optional parameters have to be preceded by the field name in order to avoid ambiguity

Otherwise, if you just specify "None" - how would the method know if this means pageSize=None or pageToken=None?

It is never wrong to precede all parameters (included the required ones) with their field name, especially if you indicate them in a non-standard order (e.g. if filedId is not the first parameter)

execute() needs to be used for all Google API methods in Python to indicate that you finished assigning all parameters to your request and now want to actually execute it.


问:
Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?
I have the following sample result when I query a database :

```<code>dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]
</code>```

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

```<code>{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }
</code>```

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

```<code>
    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

</code>```

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答:
You can use Collectors.toMap with Function.identity() as below,

```<code>list.stream()
        .collect(toMap(e->e.get("rollno"), Function.identity()));
</code>```

Body:
I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

Body:
You can use Collectors.toMap with Function.identity() as below,

list.stream()
        .collect(toMap(e->e.get("rollno"), Function.identity()));


问:
Problem with converting int to string in Linq to entities
```<code>var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
                Text = c.Name
            };
var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
                Text = c.Name
            };
</code>```

Is there anyway I can achieve this?
Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!

答:
I ran into this same problem when I was converting my MVC 2 app to MVC 3 and just to give another (clean) solution to this problem I want to post what I did...

```<code>IEnumerable<SelectListItem> producers = new SelectList(Services.GetProducers(),
    "ID", "Name", model.ProducerID);
</code>```

GetProducers() simply returns an entity collection of Producers.
P.S. The SqlFunctions.StringConvert didn't work for me.

ContentLicense: CC BY-SA 2.5

Body:
var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
                Text = c.Name
            };
var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
                Text = c.Name
            };

Is there anyway I can achieve this?
Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!

Body:
I ran into this same problem when I was converting my MVC 2 app to MVC 3 and just to give another (clean) solution to this problem I want to post what I did...

IEnumerable<SelectListItem> producers = new SelectList(Services.GetProducers(),
    "ID", "Name", model.ProducerID);

GetProducers() simply returns an entity collection of Producers.
P.S. The SqlFunctions.StringConvert didn't work for me.

ContentLicense: CC BY-SA 3.0


问:
Use of Take() LINQ Method in Entity Framework Core v3.1.4
I'm trying to add a limit GET query parameter in my API request (i.e. ?limit=10) and the value of this limit will then be used by the Take() LINQ method to get only the number of results I want. What I want to do is to include the LINQ Take() method as part of the LINQ-TO-T-SQL query and perform the limit as part of the SQL query. I tried the following codes below. I also captured the error stack trace.

Code 1: For this code, I'm trying to use the Take() on my top level resource in the query. Then afterwards (in the declaration of q), I'm performing sub-queries related to the top level resource.

```<code>baseQuery = baseQuery.Take(2);

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();
</code>```

Error stack trace for code 1:

```<code>fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (5ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT [t].[DoctorID], [t].[Address], [t].[AvailableInvites], [t].[Birthdate], [t].[City], [t].[CityID], [t].[ContactNumber], [t].[Country], [t].[DateRegistered], [t].[Description], [t].[DoctorUrl], [t].[Email], [t].[EmailActivated], [t].[EmailUID], [t].[EmailVerifiedFirstTime], [t].[Facebook], [t].[FirstName], [t].[Gender], [t].[GooglePlus], [t].[HomeNumber], [t].[Image], [t].[LastName], [t].[LinkedIn], [t].[MainSpecialty], [t].[ManuallyVerified], [t].[MedicalSchool], [t].[MedicalSchoolYear], [t].[MiddleName], [t].[MobileNumber], [t].[Nationality], [t].[OriginalIssueDate], [t].[PRCNumber], [t].[PageOkay], [t].[PatientNumber], [t].[PhicNumber], [t].[PractisingSince], [t].[Province], [t].[PtrNumber], [t].[Residency], [t].[ResidencyYear], [t].[S2Number], [t].[ShowPublicProfile], [t].[Status], [t].[Street], [t].[Suffix], [t].[Title], [t].[Twitter], [t].[UserID], [t].[Website], [t].[WorkNumber], [t].[Zipcode], [t0].[SpecialtyID], [t0].[Specialty], [t0].[Id], [t2].[ClinicID], [t2].[Street], [t2].[ClinicName], [t2].[ContactNumber], [t2].[City], [t2].[Province], [t2].[HomeNumber], [t2].[MobileNumber], [t2].[WorkNumber], [t2].[Email], [t2].[ScheduleID], [t2].[Active], [t2].[ClinicID0], [t2].[DateModified], [t2].[DayOfWeek], [t2].[DoctorID], [t2].[Notes], [t2].[StartFrom], [t2].[TimeEnd], [t2].[TimeStart], [t2].[Until]
      FROM (
          SELECT TOP(@__p_0) [d].[DoctorID], [d].[Address], [d].[AvailableInvites], [d].[Birthdate], [d].[City], [d].[CityID], [d].[ContactNumber], [d].[Country], [d].[DateRegistered], [d].[Description], [d].[DoctorUrl], [d].[Email], [d].[EmailActivated], [d].[EmailUID], [d].[EmailVerifiedFirstTime], [d].[Facebook], [d].[FirstName], [d].[Gender], [d].[GooglePlus], [d].[HomeNumber], [d].[Image], [d].[LastName], [d].[LinkedIn], [d].[MainSpecialty], [d].[ManuallyVerified], [d].[MedicalSchool], [d].[MedicalSchoolYear], [d].[MiddleName], [d].[MobileNumber], [d].[Nationality], [d].[OriginalIssueDate], [d].[PRCNumber], [d].[PageOkay], [d].[PatientNumber], [d].[PhicNumber], [d].[PractisingSince], [d].[Province], [d].[PtrNumber], [d].[Residency], [d].[ResidencyYear], [d].[S2Number], [d].[ShowPublicProfile], [d].[Status], [d].[Street], [d].[Suffix], [d].[Title], [d].[Twitter], [d].[UserID], [d].[Website], [d].[WorkNumber], [d].[Zipcode]
          FROM [Doctor] AS [d]
          WHERE [d].[Status] = 'good'
      ) AS [t]
      LEFT JOIN (
          SELECT [s].[SpecialtyID], [s].[Specialty], [d0].[Id], [d0].[DoctorID]
          FROM [DoctorSpecialty] AS [d0]
          INNER JOIN [Specialty] AS [s] ON [d0].[SpecialtyID] = [s].[SpecialtyID]
      ) AS [t0] ON [t].[DoctorID] = [t0].[DoctorID]
      LEFT JOIN (
          SELECT [c].[ClinicID], [c].[Street], [c].[ClinicName], [c].[ContactNumber], [c].[City], [c].[Province], [c].[HomeNumber], [c].[MobileNumber], [c].[WorkNumber], [c].[Email], [t1].[ScheduleID], [t1].[Active], [t1].[ClinicID] AS [ClinicID0], [t1].[DateModified], [t1].[DayOfWeek], [t1].[DoctorID], [t1].[Notes], [t1].[StartFrom], [t1].[TimeEnd], [t1].[TimeStart], [t1].[Until], [c].[DoctorID] AS [DoctorID0]
          FROM [Clinic] AS [c]
          LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
          WHERE [c].[Active] = CAST(1 AS bit)
      ) AS [t2] ON [t].[DoctorID] = [t2].[DoctorID0]
      ORDER BY [t].[DoctorID], [t0].[Id], [t0].[SpecialtyID], [t2].[ClinicID], [t2].[ScheduleID]
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'SeriousMDCommonsCore.Models.Database.SeriousmdEntitiesContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
         at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
         at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
         at System.Data.Common.DbCommand.ExecuteReader()
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
      ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
      Error Number:4104,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03JVLBFS8O", Request id "0HM03JVLBFS8O:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
</code>```

Code 2: Here, instead of performing the Take() in the baseQuery, I'm performing the Take() in the final query expression q. I also added a doctor.DoctorID as some sort of id that I think is required to be fed to the Take() LINQ method

```<code>var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            doctor.DoctorID,
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

q = q.Take(2);

var rs = q.ToList();
</code>```

Error stack trace for code 2: Here, the error changed from that of code 2 and it seems that the added index is being used by the Take() LINQ method but still throws an error.

```<code>fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03K296O68T", Request id "0HM03K296O68T:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Processing of the LINQ expression '(ProjectionBindingExpression: 0)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
</code>```

Back to my question, how can I integrate the Take() LINQ method as part of my LINQ-TO-T-SQL query so that all of my queries will go through EF Core and all query operations will be performed in database?

答:
In the first query try changing doctor.DoctorID in:

```<code>let schedule = (from sc in db.Schedule
                where sc.ClinicID == c.ClinicID
                && sc.DoctorID == doctor.DoctorID
                && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                select sc)
</code>```

to c.DoctorID:

```<code>let schedule = (from sc in db.Schedule
                where sc.ClinicID == c.ClinicID
                && sc.DoctorID == c.DoctorID
                && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                select sc)
</code>```

UPD

If you go through the SQL you will see the code generated for schedules:

```<code>LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
</code>```

Check out the where clause it has WHERE ([s0].[DoctorID] = [d].[DoctorID]) condition which references [d].[DoctorID] which is not accessible cause it is accessible only in the root subselect which performs Take. It seems that there is a convoluted bug in EF Core.

Body:
I'm trying to add a limit GET query parameter in my API request (i.e. ?limit=10) and the value of this limit will then be used by the Take() LINQ method to get only the number of results I want. What I want to do is to include the LINQ Take() method as part of the LINQ-TO-T-SQL query and perform the limit as part of the SQL query. I tried the following codes below. I also captured the error stack trace.

Code 1: For this code, I'm trying to use the Take() on my top level resource in the query. Then afterwards (in the declaration of q), I'm performing sub-queries related to the top level resource.

baseQuery = baseQuery.Take(2);

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

var rs = q.ToList();

Error stack trace for code 1:

fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (5ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SELECT [t].[DoctorID], [t].[Address], [t].[AvailableInvites], [t].[Birthdate], [t].[City], [t].[CityID], [t].[ContactNumber], [t].[Country], [t].[DateRegistered], [t].[Description], [t].[DoctorUrl], [t].[Email], [t].[EmailActivated], [t].[EmailUID], [t].[EmailVerifiedFirstTime], [t].[Facebook], [t].[FirstName], [t].[Gender], [t].[GooglePlus], [t].[HomeNumber], [t].[Image], [t].[LastName], [t].[LinkedIn], [t].[MainSpecialty], [t].[ManuallyVerified], [t].[MedicalSchool], [t].[MedicalSchoolYear], [t].[MiddleName], [t].[MobileNumber], [t].[Nationality], [t].[OriginalIssueDate], [t].[PRCNumber], [t].[PageOkay], [t].[PatientNumber], [t].[PhicNumber], [t].[PractisingSince], [t].[Province], [t].[PtrNumber], [t].[Residency], [t].[ResidencyYear], [t].[S2Number], [t].[ShowPublicProfile], [t].[Status], [t].[Street], [t].[Suffix], [t].[Title], [t].[Twitter], [t].[UserID], [t].[Website], [t].[WorkNumber], [t].[Zipcode], [t0].[SpecialtyID], [t0].[Specialty], [t0].[Id], [t2].[ClinicID], [t2].[Street], [t2].[ClinicName], [t2].[ContactNumber], [t2].[City], [t2].[Province], [t2].[HomeNumber], [t2].[MobileNumber], [t2].[WorkNumber], [t2].[Email], [t2].[ScheduleID], [t2].[Active], [t2].[ClinicID0], [t2].[DateModified], [t2].[DayOfWeek], [t2].[DoctorID], [t2].[Notes], [t2].[StartFrom], [t2].[TimeEnd], [t2].[TimeStart], [t2].[Until]
      FROM (
          SELECT TOP(@__p_0) [d].[DoctorID], [d].[Address], [d].[AvailableInvites], [d].[Birthdate], [d].[City], [d].[CityID], [d].[ContactNumber], [d].[Country], [d].[DateRegistered], [d].[Description], [d].[DoctorUrl], [d].[Email], [d].[EmailActivated], [d].[EmailUID], [d].[EmailVerifiedFirstTime], [d].[Facebook], [d].[FirstName], [d].[Gender], [d].[GooglePlus], [d].[HomeNumber], [d].[Image], [d].[LastName], [d].[LinkedIn], [d].[MainSpecialty], [d].[ManuallyVerified], [d].[MedicalSchool], [d].[MedicalSchoolYear], [d].[MiddleName], [d].[MobileNumber], [d].[Nationality], [d].[OriginalIssueDate], [d].[PRCNumber], [d].[PageOkay], [d].[PatientNumber], [d].[PhicNumber], [d].[PractisingSince], [d].[Province], [d].[PtrNumber], [d].[Residency], [d].[ResidencyYear], [d].[S2Number], [d].[ShowPublicProfile], [d].[Status], [d].[Street], [d].[Suffix], [d].[Title], [d].[Twitter], [d].[UserID], [d].[Website], [d].[WorkNumber], [d].[Zipcode]
          FROM [Doctor] AS [d]
          WHERE [d].[Status] = 'good'
      ) AS [t]
      LEFT JOIN (
          SELECT [s].[SpecialtyID], [s].[Specialty], [d0].[Id], [d0].[DoctorID]
          FROM [DoctorSpecialty] AS [d0]
          INNER JOIN [Specialty] AS [s] ON [d0].[SpecialtyID] = [s].[SpecialtyID]
      ) AS [t0] ON [t].[DoctorID] = [t0].[DoctorID]
      LEFT JOIN (
          SELECT [c].[ClinicID], [c].[Street], [c].[ClinicName], [c].[ContactNumber], [c].[City], [c].[Province], [c].[HomeNumber], [c].[MobileNumber], [c].[WorkNumber], [c].[Email], [t1].[ScheduleID], [t1].[Active], [t1].[ClinicID] AS [ClinicID0], [t1].[DateModified], [t1].[DayOfWeek], [t1].[DoctorID], [t1].[Notes], [t1].[StartFrom], [t1].[TimeEnd], [t1].[TimeStart], [t1].[Until], [c].[DoctorID] AS [DoctorID0]
          FROM [Clinic] AS [c]
          LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]
          WHERE [c].[Active] = CAST(1 AS bit)
      ) AS [t2] ON [t].[DoctorID] = [t2].[DoctorID0]
      ORDER BY [t].[DoctorID], [t0].[Id], [t0].[SpecialtyID], [t2].[ClinicID], [t2].[ScheduleID]
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'SeriousMDCommonsCore.Models.Database.SeriousmdEntitiesContext'.
      Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
         at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
         at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
         at System.Data.Common.DbCommand.ExecuteReader()
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
      ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
      Error Number:4104,State:1,Class:16
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03JVLBFS8O", Request id "0HM03JVLBFS8O:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.SqlClient.SqlException (0x80131904): The multi-part identifier "d.DoctorID" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
ClientConnectionId:0b10b611-bd0f-4fcb-a543-fdbe530fc029
Error Number:4104,State:1,Class:16

Code 2: Here, instead of performing the Take() in the baseQuery, I'm performing the Take() in the final query expression q. I also added a doctor.DoctorID as some sort of id that I think is required to be fed to the Take() LINQ method

var q = from doctor in baseQuery

        let sp = (from ds in db.DoctorSpecialty
                  join s in db.Specialty on ds.SpecialtyID equals s.SpecialtyID
                  where ds.DoctorID == doctor.DoctorID
                  select new
                  {
                      s.SpecialtyID,
                      s.Specialty1
                  }).ToList()

        let clinics = (from c in db.Clinic
                  where c.DoctorID == doctor.DoctorID && c.Active == true

                  let schedule = (from sc in db.Schedule
                                  where sc.ClinicID == c.ClinicID
                                    && sc.DoctorID == doctor.DoctorID
                                    && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                                  select sc).ToList()

                  select new
                  {
                      c.ClinicID,
                      c.Street,
                      c.ClinicName,
                      c.ContactNumber,
                      c.City,
                      c.Province,
                      c.HomeNumber,
                      c.MobileNumber,
                      c.WorkNumber,
                      c.Email,
                      Schedules = schedule,
                  }).ToList()
        select new
        {
            doctor.DoctorID,
            Doctor = doctor,
            Specialties = sp,
            Clinics = clinics

        };

q = q.Take(2);

var rs = q.ToList();

Error stack trace for code 2: Here, the error changed from that of code 2 and it seems that the added index is being used by the Take() LINQ method but still throws an error.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM03K296O68T", Request id "0HM03K296O68T:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Processing of the LINQ expression '(ProjectionBindingExpression: 0)' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at System.Linq.Expressions.NewExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

Back to my question, how can I integrate the Take() LINQ method as part of my LINQ-TO-T-SQL query so that all of my queries will go through EF Core and all query operations will be performed in database?

Body:
In the first query try changing doctor.DoctorID in:

let schedule = (from sc in db.Schedule
                where sc.ClinicID == c.ClinicID
                && sc.DoctorID == doctor.DoctorID
                && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                select sc)

to c.DoctorID:

let schedule = (from sc in db.Schedule
                where sc.ClinicID == c.ClinicID
                && sc.DoctorID == c.DoctorID
                && DoctorDirectoryConstants.ValidScheduleNotes.Contains(sc.Notes)
                select sc)

UPD

If you go through the SQL you will see the code generated for schedules:

LEFT JOIN (
              SELECT [s0].[ScheduleID], [s0].[Active], [s0].[ClinicID], [s0].[DateModified], [s0].[DayOfWeek], [s0].[DoctorID], [s0].[Notes], [s0].[StartFrom], [s0].[TimeEnd], [s0].[TimeStart], [s0].[Until]
              FROM [Schedule] AS [s0]
              WHERE ([s0].[DoctorID] = [d].[DoctorID]) AND [s0].[Notes] IN (N'Walk-In', N'By Appointment')
          ) AS [t1] ON [c].[ClinicID] = [t1].[ClinicID]

Check out the where clause it has WHERE ([s0].[DoctorID] = [d].[DoctorID]) condition which references [d].[DoctorID] which is not accessible cause it is accessible only in the root subselect which performs Take. It seems that there is a convoluted bug in EF Core.


问:
How do I make Dartfmt "friendly" for Matrices?
For a Matrix that supposed to look like this:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0,
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);
</code>```

But dartfmt changed it to become like this:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393,
          0.769,
          0.189,
          0,
          0,
          0.349,
          0.686,
          0.168,
          0,
          0,
          0.272,
          0.534,
          0.131,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
        ]);
</code>```

This is hard to read. Thus, how can I keep the original format so that the Matrix can be seen more "friendly". Or at least how can I make Dartfmt not to reformat any List?

答:
This scenario is described in the FAQ of dart_style which dartfmt is based on:

https://github.com/dart-lang/dart_style/wiki/FAQ#why-does-the-formatter-mess-up-my-collection-literals

In short, you just need to add a comment somewhere in you matrix definition like:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0, //
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);
</code>```

Then dartfmt will not try to format the newlines in the matrix. It will however, still fixes non-needed spaces so it will make your example into:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
  0.393, 0.769, 0.189, 0, 0, //
  0.349, 0.686, 0.168, 0, 0,
  0.272, 0.534, 0.131, 0, 0,
  0, 0, 0, 1, 0,
]);
</code>```

Which can be fixed by changing the 0 to 0.000:

```<code>const ColorFilter sepia = ColorFilter.matrix(<double>[
  0.393, 0.769, 0.189, 0, 0, //
  0.349, 0.686, 0.168, 0, 0,
  0.272, 0.534, 0.131, 0, 0,
  0.000, 0.000, 0.000, 1, 0,
]);
</code>```

Body:
For a Matrix that supposed to look like this:

const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0,
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);

But dartfmt changed it to become like this:

const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393,
          0.769,
          0.189,
          0,
          0,
          0.349,
          0.686,
          0.168,
          0,
          0,
          0.272,
          0.534,
          0.131,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
        ]);

This is hard to read. Thus, how can I keep the original format so that the Matrix can be seen more "friendly". Or at least how can I make Dartfmt not to reformat any List?

Body:
This scenario is described in the FAQ of dart_style which dartfmt is based on:

https://github.com/dart-lang/dart_style/wiki/FAQ#why-does-the-formatter-mess-up-my-collection-literals

In short, you just need to add a comment somewhere in you matrix definition like:

const ColorFilter sepia = ColorFilter.matrix(<double>[
          0.393, 0.769, 0.189, 0, 0, //
          0.349, 0.686, 0.168, 0, 0,
          0.272, 0.534, 0.131, 0, 0,
          0,     0,     0,     1, 0,
        ]);

Then dartfmt will not try to format the newlines in the matrix. It will however, still fixes non-needed spaces so it will make your example into:

const ColorFilter sepia = ColorFilter.matrix(<double>[
  0.393, 0.769, 0.189, 0, 0, //
  0.349, 0.686, 0.168, 0, 0,
  0.272, 0.534, 0.131, 0, 0,
  0, 0, 0, 1, 0,
]);

Which can be fixed by changing the 0 to 0.000:

const ColorFilter sepia = ColorFilter.matrix(<double>[
  0.393, 0.769, 0.189, 0, 0, //
  0.349, 0.686, 0.168, 0, 0,
  0.272, 0.534, 0.131, 0, 0,
  0.000, 0.000, 0.000, 1, 0,
]);


问:
Creating a floating "div" within a responsive site
Hi I'm a computer science student, in order to expand my knowledge I decided to build a responsive shopping site. I built the site using bootstrap. And the whole site is ready. Now I want to show the user the amount of his purchase. When he clicks on the shopping cart icon - pops div - fixed on the site. And when the user clicks on the shopping cart again - the div is deleted. To add and delete the shopping cart - use the ontoggle event.

My question is how can I add a div that will contain text for the products the user wants to buy - by "hovering" or staying "fixed" on the screen?

I tried to use fixed, or relative and absolute positioning. But in all times they took part of the site - and not "float" on it
I uploaded the full code to github.

Thanks for the help

答:
If you want your popup to float on the site, you want to use position: fixed.
Then you can play with z-index if you have many elements to put one above the other.
Note that it would also work with position: absolute. Both of those positioning take the item on another level of the layout, keeping the rest unchanged.

jsfiddle example : https://jsfiddle.net/p86nfrxc/1


问:
vscode run as different user in Linux
so few months ago I started using VScode. Im pretty amazed by the functionalities it offers
through lots of extensions available and configurability.

Few days ago I encountered this error, I installed VScode as user1, everything works, but when trying to run vscode as another user (user2) I get this error: "ENOENT: no such file or directory, mkdir".
I was hoping that all settings, snippets and extensions will be available to all the users on the machine, but apparenly I'm missing something even when running as another user. Can someone help ?

答: Apparently VScode is not concepted like this. Every user should have its own settings folder (~/.config/Code/User) and extension folder (~/.vscode/extensions). In order to sync settings and extensions between users simple copy/paste should do or some sync extension can be used.

Title: vscode run as different user in Linux


问:
Filter Data Model PivotTable by cell value
I have tried many different solutions like the ones given here but none of them work for me.

I have the following code:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Intersect(Target, Range("C1")) Is Nothing Then Exit Sub

    Dim pt As PivotTable
    Dim Field As PivotField
    Dim NewCat As Integer '<-I have tred String or not defining it at all

    Set pt = Worksheets("Sheet1").PivotTables("myPivot")
    Set Field = pt.PivotFields("[Test].[Category].[Category]")
    NewCat = Worksheets("Sheet1").Range("C1").Value

     With pt
        Field.ClearAllFilters
        Field.CurrentPage = NewCat '<- Here I have tried many variations
        pt.RefreshTable
    End With

End Sub
</code>```

I am mostly getting a 1004 error at the line Field.CurrentPage. The 'Category' variable that I am trying to filter is made out of integers. The whole Pivot Table is based on a Data Model. I can't figure out what is wrong, help!

答:
I figured this out, finally. The issue is that the NewCat value must be in the format [QueryName].[Category].&[CategoryValue]. I am guessing this has to do with the Pivot being used on a Data Model.

So I used a simple string concenation to get my value in the correct format:

```<code>myValue = Worksheets("Sheet1").Range("C1").Value
leftP = "&["
rightP = "]"
NewCat = "[Test].[Category]." & leftP& myValue & rightP
</code>```

Hopefully this saves others time...

Body:
I have tried many different solutions like the ones given here but none of them work for me.

I have the following code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Intersect(Target, Range("C1")) Is Nothing Then Exit Sub

    Dim pt As PivotTable
    Dim Field As PivotField
    Dim NewCat As Integer '<-I have tred String or not defining it at all

    Set pt = Worksheets("Sheet1").PivotTables("myPivot")
    Set Field = pt.PivotFields("[Test].[Category].[Category]")
    NewCat = Worksheets("Sheet1").Range("C1").Value

     With pt
        Field.ClearAllFilters
        Field.CurrentPage = NewCat '<- Here I have tried many variations
        pt.RefreshTable
    End With

End Sub

I am mostly getting a 1004 error at the line Field.CurrentPage. The 'Category' variable that I am trying to filter is made out of integers. The whole Pivot Table is based on a Data Model. I can't figure out what is wrong, help!

Body:
I figured this out, finally. The issue is that the NewCat value must be in the format [QueryName].[Category].&[CategoryValue]. I am guessing this has to do with the Pivot being used on a Data Model.

So I used a simple string concenation to get my value in the correct format:

myValue = Worksheets("Sheet1").Range("C1").Value
leftP = "&["
rightP = "]"
NewCat = "[Test].[Category]." & leftP& myValue & rightP

Hopefully this saves others time...


问:
How would I write to the input field of Stdin in Golang without inputting it?
So I am new to low level stuff so pardon my ignorance. I am attempting to write a minimal shell. To that end I want to implement command history similar to bash or zsh where an up-arrow can bring the most recent command up and put it in your typing field without actually inputting it.

Currently I am reading input like follows:

```<code>for {
        // prompter
        promptColor.Printf(shellPrompt)

        // read string from STDIN until newline
        input, _ := reader.ReadString('\n')
        // convert CRLF to LF
        input = strings.Replace(input, "\n", "", -1)

        // read input tokens
        tokens := SplitString(input)

        // parse tokens and execute relevant command
        Parse(tokens)
    }
</code>```

using bufio.Reader to read in. I looked and I cannot find a method of writing to that input.

答:
Most packages that want to implement this behavior will use the GNU Readline library. Even the Bash shell is using (modified copy) of this readline library. Consider one of two options:

Use the go-readline package - a wrapper for the GNU Readline library for the Go programming language. https://github.com/fiorix/go-readline

Use the pure-GO replacement implementation for GNU-Readline kind library. https://github.com/chzyer/readline

The first path will give you the battle-proof ReadLine library, but will require building the "C" code. You can decide based no your experience/constraints which path to go.

Body:
So I am new to low level stuff so pardon my ignorance. I am attempting to write a minimal shell. To that end I want to implement command history similar to bash or zsh where an up-arrow can bring the most recent command up and put it in your typing field without actually inputting it.

Currently I am reading input like follows:

for {
        // prompter
        promptColor.Printf(shellPrompt)

        // read string from STDIN until newline
        input, _ := reader.ReadString('\n')
        // convert CRLF to LF
        input = strings.Replace(input, "\n", "", -1)

        // read input tokens
        tokens := SplitString(input)

        // parse tokens and execute relevant command
        Parse(tokens)
    }

using bufio.Reader to read in. I looked and I cannot find a method of writing to that input.


问:
Convert exponential to number in sql
I have a large amount of card tokens (16 digits) uploaded from xml file to sql-server. The problem is I see them as expression, sample below:

```<code>3.3733E+15
3.3737E+15
3.3737E+15
3.3737E+15
3.37391E+15
3.37391E+15
3.37398E+15
3.37453E+15
3.37468E+15
3.37468E+15
3.3747E+15
3.37486E+15
3.37486E+15
3.37567E+15
3.3759E+15
3.3759E+15
</code>```

Any suggestion to change them to a 16 digit number? I have tried to change the data type, but got error"Conversion failed when converting the varchar value '3.37201E+15' to data type int"

Thanks for help!

Edit:

@X.L.Ant see my code below. I create this table from another one, which is just purely inserted from xml file. Is this may cause an error because some rows are empty in column TOKEN?

```<code> CREATE TABLE MULTICURRENCY_CHECK
    (
    TOKEN varchar(255)
    )
    /*Merges all card tokens into 1 column, as in xml they are spread across different columns*/
    INSERT INTO MULTICURRENCY_CHECK
    (
    TOKEN
    )
    SELECT no FROM gpstransactionsnew2
        UNION ALL
    SELECT no19 FROM gpstransactionsnew2
        UNION ALL
    SELECT no68 FROM gpstransactionsnew2
        UNION ALL
    SELECT no93 FROM gpstransactionsnew2
        UNION ALL
    SELECT no107 FROM gpstransactionsnew2
        UNION ALL
    SELECT no121 FROM gpstransactionsnew2

    SELECT REPLACE(TOKEN, 'OW1', ' ')
    FROM MULTICURRENCY_CHECK

    /*Converts exponential expression to number*/
    SELECT CONVERT(numeric(16,0), CAST(TOKEN AS FLOAT))
    FROM MULTICURRENCY_CHECK
</code>```

答:
```<code>SELECT colmn_name || '' FROM table_name
</code>```

This should work.

Title: Convert exponential to number in sql

Body:
I have a large amount of card tokens (16 digits) uploaded from xml file to sql-server. The problem is I see them as expression, sample below:

3.3733E+15
3.3737E+15
3.3737E+15
3.3737E+15
3.37391E+15
3.37391E+15
3.37398E+15
3.37453E+15
3.37468E+15
3.37468E+15
3.3747E+15
3.37486E+15
3.37486E+15
3.37567E+15
3.3759E+15
3.3759E+15

Any suggestion to change them to a 16 digit number? I have tried to change the data type, but got error"Conversion failed when converting the varchar value '3.37201E+15' to data type int"

Thanks for help!

Edit:

@X.L.Ant see my code below. I create this table from another one, which is just purely inserted from xml file. Is this may cause an error because some rows are empty in column TOKEN?

 CREATE TABLE MULTICURRENCY_CHECK
    (
    TOKEN varchar(255)
    )
    /*Merges all card tokens into 1 column, as in xml they are spread across different columns*/
    INSERT INTO MULTICURRENCY_CHECK
    (
    TOKEN
    )
    SELECT no FROM gpstransactionsnew2
        UNION ALL
    SELECT no19 FROM gpstransactionsnew2
        UNION ALL
    SELECT no68 FROM gpstransactionsnew2
        UNION ALL
    SELECT no93 FROM gpstransactionsnew2
        UNION ALL
    SELECT no107 FROM gpstransactionsnew2
        UNION ALL
    SELECT no121 FROM gpstransactionsnew2

    SELECT REPLACE(TOKEN, 'OW1', ' ')
    FROM MULTICURRENCY_CHECK

    /*Converts exponential expression to number*/
    SELECT CONVERT(numeric(16,0), CAST(TOKEN AS FLOAT))
    FROM MULTICURRENCY_CHECK

Body:
SELECT colmn_name || '' FROM table_name

This should work.


问:
How do I upgrade PHP from 7.2 to 7.3 using the yum command on CentOS?
I am running an EC2 server on AWS and I was looking into upgrading php from 7.2 to 7.3. However, all the tutorials I found were on Ubuntu and they all used the apt command instead of yum.

I also ran the command cat /etc/os-release to find out what the operating system of my server is and the ID_LIKE line said ID_LIKE="centos rhel fedora".

I found instructions on the upgrade that are relatively simple on Ubuntu.
Does anyone know how I would translate the following commands for CentOS using yum instead of apt on Ubuntu?

```<code>sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y php7.3
</code>```

答:
In CentOS you have to enable the extra epel repository first and change the php version.

```<code>sudo yum -y install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum -y install epel-release yum-utils

sudo yum-config-manager --disable remi-php54
sudo yum-config-manager --enable remi-php73
</code>```

Then you should be able to install the new php version. Try yum update or reinstall the packages.

https://computingforgeeks.com/how-to-install-php-7-3-on-centos-7-fedora/

Body:
I am running an EC2 server on AWS and I was looking into upgrading php from 7.2 to 7.3. However, all the tutorials I found were on Ubuntu and they all used the apt command instead of yum.

I also ran the command cat /etc/os-release to find out what the operating system of my server is and the ID_LIKE line said ID_LIKE="centos rhel fedora".

I found instructions on the upgrade that are relatively simple on Ubuntu.
Does anyone know how I would translate the following commands for CentOS using yum instead of apt on Ubuntu?

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y php7.3

Body:
In CentOS you have to enable the extra epel repository first and change the php version.

sudo yum -y install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum -y install epel-release yum-utils

sudo yum-config-manager --disable remi-php54
sudo yum-config-manager --enable remi-php73

Then you should be able to install the new php version. Try yum update or reinstall the packages.

https://computingforgeeks.com/how-to-install-php-7-3-on-centos-7-fedora/


问:
Why tkinter shows same image in different widget even images are loaded separately?

First image is for background which is shows 2 times, And second one is a profile image which in not showing, Both photos are present in same root directory and have same format (jpg).

```<code>from tkinter import *
from PIL import ImageTk, Image
import json

with open('config.json') as config_data:
    data = json.load(config_data)['variables']

root = Tk()
root.title(data['title'])
##TODO: for full screen
# root.wm_attributes('-fullscreen', 'true')

# MAIN BG SECTION:
image = Image.open("bg.jpg")
image = image.resize((1620, 880), Image.ANTIALIAS)
bg_image = ImageTk.PhotoImage(image)

# PHOTO FRAME SECTION:
canvas = Canvas(width=data['canvas_width'], heigh=data['canvas_height'], bg="gray11")
canvas.pack()
canvas.create_image(0, 0, image=bg_image, anchor=NW)

frame_image = Image.open("profile.jpg")
frame_image = image.resize((400, 400), Image.ANTIALIAS)
f_image = ImageTk.PhotoImage(frame_image)
photo_Label = Label(root, image=f_image).pack()

root.mainloop()
</code>```

答: As @acw1668 mentioned frame_image = image.resize(...) should be frame_image = frame_image.resize(...)

Body:
First image is for background which is shows 2 times, And second one is a profile image which in not showing, Both photos are present in same root directory and have same format (jpg).

from tkinter import *
from PIL import ImageTk, Image
import json

with open('config.json') as config_data:
    data = json.load(config_data)['variables']

root = Tk()
root.title(data['title'])
##TODO: for full screen
# root.wm_attributes('-fullscreen', 'true')

# MAIN BG SECTION:
image = Image.open("bg.jpg")
image = image.resize((1620, 880), Image.ANTIALIAS)
bg_image = ImageTk.PhotoImage(image)

# PHOTO FRAME SECTION:
canvas = Canvas(width=data['canvas_width'], heigh=data['canvas_height'], bg="gray11")
canvas.pack()
canvas.create_image(0, 0, image=bg_image, anchor=NW)

frame_image = Image.open("profile.jpg")
frame_image = image.resize((400, 400), Image.ANTIALIAS)
f_image = ImageTk.PhotoImage(frame_image)
photo_Label = Label(root, image=f_image).pack()

root.mainloop()


问:
How to write color Unicode emoji in the IE
I want to write colored Unicode emoji in IE.

<!DOCTYPE html>

    <meta charset="UTF-8">

```

If I run the code above on chrome and edge, it comes out as a colored cat face emoticon.

But in IE, the emoticons come out all monochrome as below picture.

How to use color Unicode emoji in the IE browser?

I'm very sorry for the basic question.
But I didn't know which keyword to search for it.

Thank you for reading the questions and I hope you have a good day.

答:
Actually, I strongly suggest leaving IE alone, since there is no propper support on it anymore. But if you insist on doing this on IE, Microsoft provided a way to deal with this issue. It may seem tricky but AFAIK, it is the only way to make the emojis work as expected. So apparently, Microsoft polished emoji live in a specific system font named Segoe UI Emoji. In order to use it, you just have to define a class or something and then assign it to your specific elements with emojis.

So Your final code should be something like this:

.emoji {
  font-family: "Segoe UI Emoji";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>
  <span class="emoji"></span>
</body>

</html></code>```

NOTE: As @mplungjan told us in comments if you want to be more precise with cross browsing functionality you can use below one instead:

.emoji {
  font-family: apple color emoji, segoe ui emoji, noto color emoji, android emoji, emojisymbols, emojione mozilla, twemoji mozilla, segoe ui symbol;
}
```

Body:
I want to write colored Unicode emoji in IE.

<!DOCTYPE html>

    <meta charset="UTF-8">

If I run the code above on chrome and edge, it comes out as a colored cat face emoticon.

But in IE, the emoticons come out all monochrome as below picture.

How to use color Unicode emoji in the IE browser?

I'm very sorry for the basic question.
But I didn't know which keyword to search for it.

Thank you for reading the questions and I hope you have a good day.

Body:
Actually, I strongly suggest leaving IE alone, since there is no propper support on it anymore. But if you insist on doing this on IE, Microsoft provided a way to deal with this issue. It may seem tricky but AFAIK, it is the only way to make the emojis work as expected. So apparently, Microsoft polished emoji live in a specific system font named Segoe UI Emoji. In order to use it, you just have to define a class or something and then assign it to your specific elements with emojis.

So Your final code should be something like this:

.emoji {
  font-family: "Segoe UI Emoji";
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>
  <span class="emoji"></span>
</body>

</html>

NOTE: As @mplungjan told us in comments if you want to be more precise with cross browsing functionality you can use below one instead:

.emoji {
  font-family: apple color emoji, segoe ui emoji, noto color emoji, android emoji, emojisymbols, emojione mozilla, twemoji mozilla, segoe ui symbol;
}


问:
Paste text containing an apostrophe
I am trying to paste a fixed part of text to a variable part of text.

In my fixed part of text, a number of apostrophes appear. I get an error.

This is the part of the code that contains the apostrophes:

```<code>For j = 1 To nrOfItems
For i = 1 To nrOfLanguages

Set c1 = Nothing
Set c2 = Nothing
    If Not IsEmpty(Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, i * 2).Value) Then
        Set c1 = Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, (i * 2) + 1)
        Set c2 = Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, i * 2)

        code = code + "if(GETVALUE(""SD1TAAL"") ==" + _
        CStr(Sheets("INPUT WITH MOUSEOVER").Cells(1, i * 2).Value) + ")" + _
        "{ my $image =  '<img src=" ' . GRAPHICSPATH() . ' " + _
        fnConvert2HTML (c1) + _
        ".png "/>' ; my $toolTip =' " + _
        fnConvert2HTML (c2) + _
        "'; return TOOLTIP($image, $toolTip); } "
    End If

Next i
    Sheets("OUTPUT_IMAGE_WITH_MOUSEOVER").Cells(j, 1).Value = begincode + code + endcode
    code = ""
Next j
</code>```

Things are going wrong from ' . GRAPHICSPATH() . onward.

How can I replace the apostrophes?

答:
No need to specifically escape any apostrophe, if this is inside of a string delimited by double quotes. It is enough to escape the inside double quotes by doubling them:

Please, try the last string being built like this:

```<code>"{ my $image =  '<img src="" ' . GRAPHICSPATH() . ' " + _
        fnConvert2HTML(c1) + _
        ".png ""/>' ; my $toolTip =' " + _
        fnConvert2HTML(c2) + _
        "'; return TOOLTIP($image, $toolTip); } "
</code>```

Otherwise, VBA understands that everything after src=" is a comment...
And, also, try avoiding to use + for concatenation and make a habit to use & instead of it.

Title: Paste text containing an apostrophe

Body:
I am trying to paste a fixed part of text to a variable part of text.

In my fixed part of text, a number of apostrophes appear. I get an error.

This is the part of the code that contains the apostrophes:

For j = 1 To nrOfItems
For i = 1 To nrOfLanguages

Set c1 = Nothing
Set c2 = Nothing
    If Not IsEmpty(Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, i * 2).Value) Then
        Set c1 = Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, (i * 2) + 1)
        Set c2 = Sheets("INPUT IMAGE WITH MOUSEOVER").Cells(j + 2, i * 2)

        code = code + "if(GETVALUE(""SD1TAAL"") ==" + _
        CStr(Sheets("INPUT WITH MOUSEOVER").Cells(1, i * 2).Value) + ")" + _
        "{ my $image =  '' ; my $toolTip =' " + _
        fnConvert2HTML (c2) + _
        "'; return TOOLTIP($image, $toolTip); } "
    End If

Next i
    Sheets("OUTPUT_IMAGE_WITH_MOUSEOVER").Cells(j, 1).Value = begincode + code + endcode
    code = ""
Next j

Things are going wrong from ' . GRAPHICSPATH() . onward.

How can I replace the apostrophes?

Body:
No need to specifically escape any apostrophe, if this is inside of a string delimited by double quotes. It is enough to escape the inside double quotes by doubling them:

Please, try the last string being built like this:

"{ my $image =  '<img src="" ' . GRAPHICSPATH() . ' " + _
        fnConvert2HTML(c1) + _
        ".png ""/>' ; my $toolTip =' " + _
        fnConvert2HTML(c2) + _
        "'; return TOOLTIP($image, $toolTip); } "

Otherwise, VBA understands that everything after src=" is a comment...
And, also, try avoiding to use + for concatenation and make a habit to use & instead of it.


问:
Problem with ChromeDriver in Selenium 3.141.59
I'm using Selenium for Java in version 3.141.59 and the code is unable to start a chromium instance but throws an exception:

nested exception is org.openqa.selenium.SessionNotCreatedException:
  session not created: This version of ChromeDriver only supports Chrome
  version 81

The code is running on Ubuntu 18.04 with OpenJDK Runtime Environment (build 1.8.0_252-8u252-b09-1~18.04-b09) and the chromium and chromedriver versions should fit:

chromium-browser --version

Chromium 81.0.4044.138 Built on Ubuntu , running on Ubuntu 18.04

chromedriver --version

ChromeDriver 81.0.4044.138 (8c6c7ba89cc9453625af54f11fd83179e23450fa-refs/branch-heads/4044@{#999})

Both are in $PATH for the user running this code:

which chromedriver

/usr/bin/chromedriver

which chromium-browser

/usr/bin/chromium-browser

I also tried the Selenium version 4.0.0-alpha-5 but this didn't change the behaviour.
I also tried System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver"), which didn't help either.

Any help is appreciated.

答:
I found the problem: as this only happens when there are version conflicts, I looked up if there are any different versions installed:

```<code>dpkg -l |grep chrome
ii  chromium-chromedriver                 81.0.4044.138-0ubuntu0.18.04.1      amd64        WebDriver driver for the Chromium Browser
ii  google-chrome-stable                  83.0.4103.61-1                      amd64        The web browser from Google
</code>```

A simple

```<code>dpkg --purge google-chrome-stable
</code>```

solved the problem.

Body:
I found the problem: as this only happens when there are version conflicts, I looked up if there are any different versions installed:

dpkg -l |grep chrome
ii  chromium-chromedriver                 81.0.4044.138-0ubuntu0.18.04.1      amd64        WebDriver driver for the Chromium Browser
ii  google-chrome-stable                  83.0.4103.61-1                      amd64        The web browser from Google

A simple

dpkg --purge google-chrome-stable

solved the problem.


问:
cleverhans - clip_min, clip_max when they vary by channels
cleverhans has clip_min and clip_max to make sure that the perturbed data is still within the valid range. This works fine, e.g. if I'm working with an image where the range of values in the matrix is 0-255 or 0-1. However, when the range differs on different dimensions, a single value is not enough to constrain the image to be valid. For example, in most ImageNet models, the images are preprocessed by subtracting the mean and dividing by the standard deviation per channel, hence making a single value clip not ideal. Is there a smart workaround to this problem?

答:
I have the same question as you.

After investigation I found that, for Vgg and Resnet wihch channels go through different transformations, some one set clip_min and clip_max the same for different channels:
clip_min=min(channel1_min,channel2_min,channel3_min), channel1_min means the theoretical minimum value in channel1,
after anti-normalization(multiply std, add mean), the image will be clipped by [0,1].

I think this is a feasible approach.

By the way, I encountered some problems, please take a look.
The use of method which needs sess param in Cleverhans Library


答: Can you try putting chromedriver in /usr/local/bin? then run "sudo chmod +x chromedriver"</p>

Title: Problem with ChromeDriver in Selenium 3.141.59

Body:
I'm using Selenium for Java in version 3.141.59 and the code is unable to start a chromium instance but throws an exception:

nested exception is org.openqa.selenium.SessionNotCreatedException:
  session not created: This version of ChromeDriver only supports Chrome
  version 81

The code is running on Ubuntu 18.04 with OpenJDK Runtime Environment (build 1.8.0_252-8u252-b09-1~18.04-b09) and the chromium and chromedriver versions should fit:

chromium-browser --version

Chromium 81.0.4044.138 Built on Ubuntu , running on Ubuntu 18.04

chromedriver --version

ChromeDriver 81.0.4044.138 (8c6c7ba89cc9453625af54f11fd83179e23450fa-refs/branch-heads/4044@{#999})

Both are in $PATH for the user running this code:

which chromedriver

/usr/bin/chromedriver

which chromium-browser

/usr/bin/chromium-browser

I also tried the Selenium version 4.0.0-alpha-5 but this didn't change the behaviour.
I also tried System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver"), which didn't help either.

Any help is appreciated.