问:
Why does FilePond render incorrectly on my website?
I can't figure this out for the life of me. When I implement FilePond on my website, it renders incorrectly. See this screenshot.

As you can see, there are 2 instances of FilePond there. The second one looks correct, but I did that in a hacky way that falls apart as soon as you start adding files to it. In the same screenshot you can see that I opened developer tools and highlighted a line. That highlighted line and the one below it are the problem. They show the transformations that FilePond has calculated for those divs which are the wrong transformations and they are what cause the gray area to be too short.

What could I be doing wrong in my project to cause Filepond to suddenly calculate the wrong css transformations for .filepond--panel-center and .filepond--panel-bottom? Please help!

I am aware that the most common mistake is that people forget to add <!DOCTYPE html> at the top of their page. I did not forget that.

Okay so here's my website deployed so that you can see it for yourself: http://laf.devign.nl/items/new

Log in using user1@example.com and secret.

If you happen to be on a Mac, for some reason it does render correctly in Safari. So you can compare it with that to see what it should look like. It's Chrome in which it doesn't render correctly.

答:
So thanks to Rik's comment I started to look for css rules that applied to both the <input type="file" /> element and to all the html that Filepond generated after transforming the file input.

Here's all the css that I found that interfered:

Like Rik said, there was this weird css rule in the code: * { max-height: 1000000px; }. This was responsible for the filepond divs rendering too short as seen in the screenshot in my OP. (In my defense, I didn't write that rule, the css was delivered to me by someone else on the team )

Besides that, my form was being generated from a bootstrap template and therefore my file-input was generated with a class <input type="file" class="custom-file-input" />.

After removing that css rule and that class from the file-input Filepond finally rendered correctly in all the browsers.


来源: stackexchange

问:
Facebook API : feed a carousel post (multi-photos)
For some time now, Facebook offers a new carousel post (basic feeding with link and many pictures) similar to the carousel ads, but every picture's link lead to the same page, it's a basic publication with text, link, image...
An sample of what I need (it's french, but sample images speak for itself:
http://www.leptidigital.fr/reseaux-sociaux/comment-creer-publication-facebook-carrousel-5612/

and the result about this news :
https://www.facebook.com/leptidigital/posts/868750466554694

I've only find documentation about the carousel ads (payable) via marketing API.
Any body know if is possible with the standard API ? My research come to nothing...
Special thanks for every one !

答:
Thanks to CBroe for the comment left explaining where to find this information.

If you look at that post in Graph API Explorer, you see that the images are in the child_attachment structure. And apparently, you can use that field when creating page posts, too

Facebook feed documentation

Here's an example in Python on how to accomplish what the documentation means:

```<code>import requests

post_data = {"access_token": "your access token",
             "message": "whatever you want to say"
             "link": "https://some.link"
             "child_attachments": '''[
                 {
                     "link": "http://some.link",
                     "picture": "https://app.replypro.io/media/wb3.jpg"
                 },
                 {
                     "link": "http://some.link",
                     "picture": "https://app.replypro.io/media/wb3.jpg"
                 }]'''}}
requests.post("https://graph.facebook.com/v5.0/<your page id>/feed", data=post_data)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thanks to CBroe for the comment left explaining where to find this information.

If you look at that post in Graph API Explorer, you see that the images are in the child_attachment structure. And apparently, you can use that field when creating page posts, too

Facebook feed documentation

Here's an example in Python on how to accomplish what the documentation means:

import requests

post_data = {"access_token": "your access token",
             "message": "whatever you want to say"
             "link": "https://some.link"
             "child_attachments": '''[
                 {
                     "link": "http://some.link",
                     "picture": "https://app.replypro.io/media/wb3.jpg"
                 },
                 {
                     "link": "http://some.link",
                     "picture": "https://app.replypro.io/media/wb3.jpg"
                 }]'''}}
requests.post("https://graph.facebook.com/v5.0/<your page id>/feed", data=post_data)

ContentLicense: CC BY-SA 4.0


问:
Are arrays being transformed when using an enhanced for loop?
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.</p>

```<code>for( String : args ){
// Do stuff
}
</code>```

答:
Since you seem to be wondering about enhanced for loops in particular, the answer is that they are special-cased, not unboxed. From §14.14.2:

The enhanced for statement has the form:

```<code>EnhancedForStatement:
    for ( VariableModifiersopt Type Identifier: Expression) Statement
</code>```

The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.

In fact, if the expression is an array, it is translated into the equivalent indexed for loop rather than actually using an iterator. The precise expansions are covered in the same section of the language spec.

Body:
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.

for( String : args ){
// Do stuff
}

Body:
Since you seem to be wondering about enhanced for loops in particular, the answer is that they are special-cased, not unboxed. From §14.14.2:

The enhanced for statement has the form:

EnhancedForStatement:
    for ( VariableModifiersopt Type Identifier: Expression) Statement

The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.

In fact, if the expression is an array, it is translated into the equivalent indexed for loop rather than actually using an iterator. The precise expansions are covered in the same section of the language spec.


问:
SQLReset rank based on row or flag
Here is my input and expected output. I tried using ranks and flags to identify how to reset the rank and can’t seem to get it to work.

Input:

```<code>Type  Date Rank
PA 1/1/2000  1
ON 1/2/2000  2
Acq 1/4/2000 3
PA  2/1/2000 4
ON  4/2/2000 5
ON  6/3/2000 6
PA  6/11/2000 7
</code>```

Output:

```<code>Type  Date Rank
PA 1/1/2000  1
ON 1/2/2000  2
Acq 1/4/2000 3
PA  2/1/2000 1
ON  4/2/2000 2
ON  6/3/2000 3
PA  6/11/2000 1
</code>```

Basically whenever type equals PA it should reset the count.

Trying to do this is in BigQuery

答:
You can create a virtual group using PA.
So every time a new PA row comes group index increases by 1.
I named that column as reset_group.

Then, I used this column as the partition column and used row_number() to calculate rank within the group.

```<code>WITH
data AS
(
  SELECT 'PA' as Type, '2000-01-01' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-01-02' as DATE UNION ALL
  SELECT 'Acq' as Type, '2000-01-04' as DATE UNION ALL
  SELECT 'PA' as Type, '2000-02-01' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-03-02' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-06-03' as DATE UNION ALL
  SELECT 'PA' as Type, '2000-06-11' as DATE
),
reset_groups AS
(
  select *, SUM(IF(Type = 'PA', 1, 0)) OVER (ORDER BY Date) as reset_group
  from data
)
select *, ROW_NUMBER() OVER (PARTITION BY reset_group ORDER BY Date) as rank
from reset_groups
</code>```

Title: SQLReset rank based on row or flag

Body:
Here is my input and expected output. I tried using ranks and flags to identify how to reset the rank and can’t seem to get it to work.

Input:

Type  Date Rank
PA 1/1/2000  1
ON 1/2/2000  2
Acq 1/4/2000 3
PA  2/1/2000 4
ON  4/2/2000 5
ON  6/3/2000 6
PA  6/11/2000 7

Output:

Type  Date Rank
PA 1/1/2000  1
ON 1/2/2000  2
Acq 1/4/2000 3
PA  2/1/2000 1
ON  4/2/2000 2
ON  6/3/2000 3
PA  6/11/2000 1

Basically whenever type equals PA it should reset the count.

Trying to do this is in BigQuery

Body:
You can create a virtual group using PA.
So every time a new PA row comes group index increases by 1.
I named that column as reset_group.

Then, I used this column as the partition column and used row_number() to calculate rank within the group.

WITH
data AS
(
  SELECT 'PA' as Type, '2000-01-01' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-01-02' as DATE UNION ALL
  SELECT 'Acq' as Type, '2000-01-04' as DATE UNION ALL
  SELECT 'PA' as Type, '2000-02-01' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-03-02' as DATE UNION ALL
  SELECT 'ON' as Type, '2000-06-03' as DATE UNION ALL
  SELECT 'PA' as Type, '2000-06-11' as DATE
),
reset_groups AS
(
  select *, SUM(IF(Type = 'PA', 1, 0)) OVER (ORDER BY Date) as reset_group
  from data
)
select *, ROW_NUMBER() OVER (PARTITION BY reset_group ORDER BY Date) as rank
from reset_groups


问:
Handle string and int received in json
I have a json which looks like so...

```<code>{
    id = 123456;
    isDeleted = 0;
    name = testName;
    parentId = "<null>"; // This can also be integer
    plantId = 1223;      // This can also be string
    type = 1;
}
</code>```

In the response above, I can get either a string or an int for both parentId & plantId. How can I handle both the cases..?

This is how my structure looks...

```<code>struct Root : Decodable {
    let organizations : [Organization1]
}

struct Organization1 : Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: Int?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?

}
</code>```

答:
You can do that like this</p>

```<code>struct GeneralProduct: Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: String?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        isDeleted = try container.decode(Bool.self, forKey: .isDeleted)
        name = try container.decode(String.self, forKey: .id)
        type = try container.decode(Int.self, forKey: .type)
        loggedInUserId = try container.decode(Int.self, forKey: .loggedInUserId)

        if let value = try? container.decode(Int.self, forKey: .parentId) {
            parentId = String(value)
        } else {
            parentId = try container.decode(String.self, forKey: .id)
        }

        if let value = try? container.decode(Int.self, forKey: .plantId) {
                   plantId = String(value)
               } else {
                   plantId = try container.decode(String.self, forKey: .id)
               }
    }

}
</code>```

Title: Handle string and int received in json

Body:
I have a json which looks like so...

{
    id = 123456;
    isDeleted = 0;
    name = testName;
    parentId = "<null>"; // This can also be integer
    plantId = 1223;      // This can also be string
    type = 1;
}

In the response above, I can get either a string or an int for both parentId & plantId. How can I handle both the cases..?

This is how my structure looks...

struct Root : Decodable {
    let organizations : [Organization1]
}

struct Organization1 : Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: Int?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?

}

Body:
You can do that like this

struct GeneralProduct: Decodable {
    let id: Int
    let isDeleted: Bool
    let name: String
    let parentId: String?
    let type: Int
    let plantId: String?
    let loggedInUserId: Int?

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        isDeleted = try container.decode(Bool.self, forKey: .isDeleted)
        name = try container.decode(String.self, forKey: .id)
        type = try container.decode(Int.self, forKey: .type)
        loggedInUserId = try container.decode(Int.self, forKey: .loggedInUserId)

        if let value = try? container.decode(Int.self, forKey: .parentId) {
            parentId = String(value)
        } else {
            parentId = try container.decode(String.self, forKey: .id)
        }

        if let value = try? container.decode(Int.self, forKey: .plantId) {
                   plantId = String(value)
               } else {
                   plantId = try container.decode(String.self, forKey: .id)
               }
    }

}


问:
Google apps script : Share files with custom message
I wrote a function to share files automatically with users using google apps script. However, I want to add a custom message while sharing (like we do with manual sharing). I want this so that I don't have to send emails to the users separately. I was initially sending email along with file url but the email was blocked (since message contained links). Is there a way to add custom message?</p>

```<code>function fileshare(url, email) {

  var f = SpreadsheetApp.openByUrl(url);
  var id = f.getId();
  try{
    //f.addViewer(email);
    DriveApp.getFileById(id).addViewer(email);

  }
  catch (e) {
    Logger.log("File could not be shared, please check if email address is valid");
  }
}
</code>```

答:
I believe your goal as follows.

You want to put the custom message in the invitation email when you share a file with an user.

You want to achieve this using Google Apps Script.

For this, how about this answer?

Modification points:

In order to use the custom message to the invitation email of shared file, in this case, Drive API is used. When the method of "Permissions: insert" in Drive API is used, the custom message can be added.

In the current stage, the version of Drive API at Advanced Google services is v2.

When your script is modified, it becomes as follows.

Modified script:

Before you run the script, please enable Drive API at Advanced Google services.

From:

```<code>DriveApp.getFileById(id).addViewer(email);
</code>```

To:

```<code>var customMessage = "sample message";  // Please set the custom message here.
var resource = {role: "reader", type: "user", value: email};
Drive.Permissions.insert(resource, id, {emailMessage: customMessage});
</code>```

In this modification, the user is set as a reader. This is the same with addViewer.

References:

Advanced Google services

Permissions: insert

Body:
I wrote a function to share files automatically with users using google apps script. However, I want to add a custom message while sharing (like we do with manual sharing). I want this so that I don't have to send emails to the users separately. I was initially sending email along with file url but the email was blocked (since message contained links). Is there a way to add custom message?

function fileshare(url, email) {

  var f = SpreadsheetApp.openByUrl(url);
  var id = f.getId();
  try{
    //f.addViewer(email);
    DriveApp.getFileById(id).addViewer(email);

  }
  catch (e) {
    Logger.log("File could not be shared, please check if email address is valid");
  }
}

Body:
I believe your goal as follows.

You want to put the custom message in the invitation email when you share a file with an user.

You want to achieve this using Google Apps Script.

For this, how about this answer?

Modification points:

In order to use the custom message to the invitation email of shared file, in this case, Drive API is used. When the method of "Permissions: insert" in Drive API is used, the custom message can be added.

In the current stage, the version of Drive API at Advanced Google services is v2.

When your script is modified, it becomes as follows.

Modified script:

Before you run the script, please enable Drive API at Advanced Google services.

From:

DriveApp.getFileById(id).addViewer(email);

To:

var customMessage = "sample message";  // Please set the custom message here.
var resource = {role: "reader", type: "user", value: email};
Drive.Permissions.insert(resource, id, {emailMessage: customMessage});

In this modification, the user is set as a reader. This is the same with addViewer.

References:

Advanced Google services

Permissions: insert


问:
Azure Data Studio data script for indexes
I can't access the option "Scrip as Create" for indexes using Azure Data Studio. I just have the refresh option

I think that should be like that, no?

I've searched on Internet some solution, but I didn't found anything. Someone could help me?

答: There is no script as create option for index. The solution is to click on script as create over the table. It will generate the creation script of the table along with the indexes and constraints.


问:
Best practices for auto increment a number EF Core
I'm looking for best practices in order to increment some numbers in my DB using EF Core..

I have a DB model called PARENT. In my application, I can have several PARENTS. Each PARENT has several CHILDS.

PARENT1: CHILD1 - CHILD2

PARENT2: CHILD1 - CHILD2 - CHILD3

I want, inside each PARENT, each children be numbered incrementally by a column: int Number. This means,

PARENT1.CHILD1 = 001;

PARENT1.CHILD2 = 002;

PARENT2.CHILD1 = 001;

PARENT2.CHILD2 = 002;

...

So, it has to be only unique and incremented by parent..

Can anyone give me some best practices in order to achieve this in an efficient way?

UPDATE:

```<code>public class Bar {
    public Guid BarId {get;set;}
    public ICollection<Client> Clients {get;set;}
}

public class Client {
    public Guid ClientId {get;set;}
    public Guid BarId {get;set;}
    public int ClientNumber {get;set;}
}

public class Context : DBContext {
    entity.HasKey(e => new { e.BarId, e.ClientId }).HasName("PK_CLIENT");
                entity.Property(e => e.ClientId).ValueGeneratedWhenDefault();
    entity.Property(e => e.ClientNumber).ValueGeneratedOnAdd();
    entity.HasIndex(e => new {e.BarId, e.ClientNumber}).IsUnique()
        .HasName("IX_CLIENT_NUMBER");
}
</code>```

By calling ValueGeneratedOnAdd() I make the number column increment, but I want it to increment for each Bar, so it should allow duplicated client numbers between different bars, but not at the same Bar, and also increment them by Bar, not just by the Client entity.

答:
One way would be to do the following;

1) Use integers as keys, and set ClientNumber property to be nullable.

```<code>    public class Bar
    {
        public int BarId { get; set; }
        public ICollection<Client> Clients { get; set; }
    }

    public class Client
    {
        public int ClientId { get; set; }
        public Bar Bar { get; set; }
        public int BarId { get; set; }
        public int? ClientNumber { get; set; }
    }
</code>```

2) Set ClientId to identity (automatic increment) and ClientNumber to database generated (otherwise EF Core will not re-read the value from database after insert)

```<code>entity.Property(e => e.ClientId).ValueGeneratedOnAdd();
entity.Property(e => e.ClientNumber).ValueGeneratedOnAddOrUpdate();
</code>```

3) Add a trigger to modify the ClientNumber after insert

    create trigger ClientNumber on Clients after insert
    as
    begin
        set nocount on;
        update c set ClientNumber = n.RowNum from Clients c
        inner join (
            select ClientId, ROW_NUMBER() OVER(PARTITION BY BarId ORDER BY ClientId ASC) as RowNum
            from Clients
        ) n on n.ClientId = c.ClientId
    where c.ClientId in (select ClientId from inserted)
    end
```

<p>Now all works automatically on insert:</p>

```            var bar1 = new Bar() { Clients = new List<Client>() };
            var bar2 = new Bar() { Clients = new List<Client>() };

            bar1.Clients.Add(new Client());
            bar1.Clients.Add(new Client());

            bar2.Clients.Add(new Client());
            bar2.Clients.Add(new Client());

            context.Bars.AddRange(new[] { bar1, bar2 });
            await context.SaveChangesAsync();

            bar1.Clients.Add(new Client());
            bar2.Clients.Add(new Client());
            bar1.Clients.Add(new Client());
            await context.SaveChangesAsync();
```

<p>Will render</p>

```ClientId    BarId   ClientNumber
1   1   1
2   1   2
6   1   3
7   1   4
3   2   1
4   2   2
5   2   3
```

Downside is that you cannot use the unique index IX_CLIENT_NUMBER since ClientNumber will be NULL until the trigger executes.

Body:
I'm looking for best practices in order to increment some numbers in my DB using EF Core..

I have a DB model called PARENT. In my application, I can have several PARENTS. Each PARENT has several CHILDS.

PARENT1: CHILD1 - CHILD2

PARENT2: CHILD1 - CHILD2 - CHILD3

I want, inside each PARENT, each children be numbered incrementally by a column: int Number. This means,

PARENT1.CHILD1 = 001;

PARENT1.CHILD2 = 002;

PARENT2.CHILD1 = 001;

PARENT2.CHILD2 = 002;

...

So, it has to be only unique and incremented by parent..

Can anyone give me some best practices in order to achieve this in an efficient way?

UPDATE:

public class Bar {
    public Guid BarId {get;set;}
    public ICollection<Client> Clients {get;set;}
}

public class Client {
    public Guid ClientId {get;set;}
    public Guid BarId {get;set;}
    public int ClientNumber {get;set;}
}

public class Context : DBContext {
    entity.HasKey(e => new { e.BarId, e.ClientId }).HasName("PK_CLIENT");
                entity.Property(e => e.ClientId).ValueGeneratedWhenDefault();
    entity.Property(e => e.ClientNumber).ValueGeneratedOnAdd();
    entity.HasIndex(e => new {e.BarId, e.ClientNumber}).IsUnique()
        .HasName("IX_CLIENT_NUMBER");
}

By calling ValueGeneratedOnAdd() I make the number column increment, but I want it to increment for each Bar, so it should allow duplicated client numbers between different bars, but not at the same Bar, and also increment them by Bar, not just by the Client entity.

Body:
One way would be to do the following;

1) Use integers as keys, and set ClientNumber property to be nullable.

    public class Bar
    {
        public int BarId { get; set; }
        public ICollection<Client> Clients { get; set; }
    }

    public class Client
    {
        public int ClientId { get; set; }
        public Bar Bar { get; set; }
        public int BarId { get; set; }
        public int? ClientNumber { get; set; }
    }

2) Set ClientId to identity (automatic increment) and ClientNumber to database generated (otherwise EF Core will not re-read the value from database after insert)

entity.Property(e => e.ClientId).ValueGeneratedOnAdd();
entity.Property(e => e.ClientNumber).ValueGeneratedOnAddOrUpdate();

3) Add a trigger to modify the ClientNumber after insert

    create trigger ClientNumber on Clients after insert
    as
    begin
        set nocount on;
        update c set ClientNumber = n.RowNum from Clients c
        inner join (
            select ClientId, ROW_NUMBER() OVER(PARTITION BY BarId ORDER BY ClientId ASC) as RowNum
            from Clients
        ) n on n.ClientId = c.ClientId
    where c.ClientId in (select ClientId from inserted)
    end

Now all works automatically on insert:

            var bar1 = new Bar() { Clients = new List<Client>() };
            var bar2 = new Bar() { Clients = new List<Client>() };

            bar1.Clients.Add(new Client());
            bar1.Clients.Add(new Client());

            bar2.Clients.Add(new Client());
            bar2.Clients.Add(new Client());

            context.Bars.AddRange(new[] { bar1, bar2 });
            await context.SaveChangesAsync();

            bar1.Clients.Add(new Client());
            bar2.Clients.Add(new Client());
            bar1.Clients.Add(new Client());
            await context.SaveChangesAsync();

Will render

ClientId    BarId   ClientNumber
1   1   1
2   1   2
6   1   3
7   1   4
3   2   1
4   2   2
5   2   3

Downside is that you cannot use the unique index IX_CLIENT_NUMBER since ClientNumber will be NULL until the trigger executes.


问:
Issue with "TypeError: Class extends value undefined is not a constructor or null" in React Class
I have created a react app through this command npx create-react-app myApp. I want to create a class inside App.js that extends React.Component. The problem is I am not able to fire up the app because the browser shows this error:
Error

is there anything wrogn with creating classes in App.js?

Here is my code of App.js

```<code>import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component() {
render(){
  return (
    <div>
      Hello!
    </div>
  )
}
}

export default App;
</code>```

答:
Looks like a typo. Change to:

```<code>class App extends React.Component {
</code>```

You seem to have React.Component()

Body:
I have created a react app through this command npx create-react-app myApp. I want to create a class inside App.js that extends React.Component. The problem is I am not able to fire up the app because the browser shows this error:
Error

is there anything wrogn with creating classes in App.js?

Here is my code of App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component() {
render(){
  return (

      Hello!

  )
}
}

export default App;

Body:
Looks like a typo. Change to:

class App extends React.Component {

You seem to have React.Component()


问:
Not able to send logs to /var/mongodb/logs/mongod.log file and not able to mongod is forked and run as a daemon and i coudnt add user
Error when doing thisI am taking course in MongoDB university, They're having a lab section that we need to solve. I am stuck with Chapter 1: The Mongod Lab: Logging to a Different Facility.

I tried using these commands "mongod --logpath /var/mongodb/logs/mongod.log" and "mongod --config mongod.conf" after running these couldnt add the user to validate the question

Can anyone help me detail procedure of the question?

mongod sends logs to /var/mongodb/logs/mongod.log

mongod is forked and run as a daemon (this will not work without specifying logpath)

答:
I think you may use only the configuration file to achieve whatever you need, you can configure a mongo instance to use a certain log file and to fork properly mongodb. As you can see in this mongodb documentation section. You can edit your configuration file like this:

```<code>systemLog:
   destination: file
   path: "/var/mongodb/logs/mongod.log "
   logAppend: true
processManagement:
   fork: true
</code>```

And then execute mongodb using this command: mongod --config mongod.conf

Body:
I think you may use only the configuration file to achieve whatever you need, you can configure a mongo instance to use a certain log file and to fork properly mongodb. As you can see in this mongodb documentation section. You can edit your configuration file like this:

systemLog:
   destination: file
   path: "/var/mongodb/logs/mongod.log "
   logAppend: true
processManagement:
   fork: true

And then execute mongodb using this command: mongod --config mongod.conf


问:
:before psuedo element is not working in IE 11
This is the code is not working in IE11, It's working fine in chrome and Mozilla.
I am trying to add a background color on hover a div.border-green, It's failing in IE 11</p>

```<code>.border-green{
    border-bottom: 5px solid #50BE87 !important;
    display: block;
}

.border-green::before{
    content: " ";
    display: block;
    background: linear-gradient(to top, #50BE87 59%, #6a7b886b 20%);
    visibility: hidden;
    transition: all 450ms ease-out;
    position: absolute;
    opacity: 0;
    left: 15px;
    top: 0%;
    height: 96%;
    width: 91%;
    z-index: 1;
 }

 .border-green:hover::before {
    opacity: 1;
    visibility: visible;
}
</code>```

答:
Internet Explorer does not understand RGBA hexadecimal color codes (4 bytes)..

If you drop the transparency, it works fine:

background: linear-gradient(to top, #50BE87 59%, #6a7b88 20%);

Or you can create a kind of mixin by including both lines. This seems to work as well:

```<code>background: linear-gradient(to top, #50BE87 59%, #6a7b88 20%);
background: linear-gradient(to top, #50BE87 59%, #6a7b886b 20%);
</code>```

Chrome and Mozilla will eventually take the second line. But because the second line fails in IE, IE seems to fall back to the first line. I'm not sure if this is a safe strategy, however.

Or you could just use the rgba function. That works fine in IE as well:

background: linear-gradient(to top, #50BE87 59%, rgba(106, 123, 136, 0.42) 20%);

Body:
This is the code is not working in IE11, It's working fine in chrome and Mozilla.
I am trying to add a background color on hover a div.border-green, It's failing in IE 11

.border-green{
    border-bottom: 5px solid #50BE87 !important;
    display: block;
}

.border-green::before{
    content: " ";
    display: block;
    background: linear-gradient(to top, #50BE87 59%, #6a7b886b 20%);
    visibility: hidden;
    transition: all 450ms ease-out;
    position: absolute;
    opacity: 0;
    left: 15px;
    top: 0%;
    height: 96%;
    width: 91%;
    z-index: 1;
 }

 .border-green:hover::before {
    opacity: 1;
    visibility: visible;
}

Body:
Internet Explorer does not understand RGBA hexadecimal color codes (4 bytes)..

If you drop the transparency, it works fine:

background: linear-gradient(to top, #50BE87 59%, #6a7b88 20%);

Or you can create a kind of mixin by including both lines. This seems to work as well:

background: linear-gradient(to top, #50BE87 59%, #6a7b88 20%);
background: linear-gradient(to top, #50BE87 59%, #6a7b886b 20%);

Chrome and Mozilla will eventually take the second line. But because the second line fails in IE, IE seems to fall back to the first line. I'm not sure if this is a safe strategy, however.

Or you could just use the rgba function. That works fine in IE as well:

background: linear-gradient(to top, #50BE87 59%, rgba(106, 123, 136, 0.42) 20%);


问:
The configuration section 'webFarms' cannot be read because it is missing a section declaration
i issued new SSL certificate and install it on the server but when i assign it to the default (localhost) for testing i get the below errors </p>

```<code>Detailed Error Information:
Module     ApplicationRequestRouting
Notification       MapRequestHandler
Handler    ExtensionlessUrlHandler-Integrated-4.0
Error Code     0x80070490
Config Error       The configuration section 'webFarms' cannot be read because it is missing a section declaration
Config File    \\?\C:\inetpub\temp\apppools\DefaultAppPool\DefaultAppPool.config
</code>```

<p>anybody can give me solution ?? </p>

答:
According to the error message, please try to create a ‘webFarms’ section declaration inside of configSections, or delete and recreate it again.

https://forums.iis.net/t/1191686.aspx?WFF+2+2+Missing+Section+Error

Besides, incorrect application pool settings can also cause this problem, please just change the .NET Framework version of pool to V4.0 in IIS.

When you encounter this issue, please just change the .NET Framework
  Version of pool to V4.0 in IIS.

See these links for more details.

The configuration section 'uri' cannot be read because it is missing a section declaration

https://forums.asp.net/t/1839088.aspx

Body:
i issued new SSL certificate and install it on the server but when i assign it to the default (localhost) for testing i get the below errors

Detailed Error Information:
Module     ApplicationRequestRouting
Notification       MapRequestHandler
Handler    ExtensionlessUrlHandler-Integrated-4.0
Error Code     0x80070490
Config Error       The configuration section 'webFarms' cannot be read because it is missing a section declaration
Config File    \\?\C:\inetpub\temp\apppools\DefaultAppPool\DefaultAppPool.config

anybody can give me solution ??


问:
Dynamic Filtering a Dataframe based date in Pandas with condition
I am trying to filter a dataframe based on date field.

```<code> Date    Value
201810   100
201811   150
201812   95
201901   125
201902   150
201903   200
201904   225
</code>```

The filtering is to be done dynamically. E.g. the first date and end date should not be 'hard coded'.
So my approach is as follows:

```<code>month = pd.DataFrame(set(df['Date']),columns=['Date'])
df['Date'] = pd.to_datetime(df['Date'],format='%Y%m)
</code>```

From here, I have to filter based on date and create a new dataframe. In this the last date, say 201903.

```<code>dt_first = month['Date'].head(1)   <---first date is being dynamically created
dt_last = month.iloc[-2]           <-- last date, dynamically created.
df_filter = df[(df.Date.ge(dt_first))&(df.Date.le(dt_last))]
</code>```

But the last line is generating a blank dataframe. The resultant dataframe should look like

```<code> Date    Value
 201810   100
 201811   150
 201812   95
 201901   125
 201902   150
 201903   200
</code>```

I know I am missing out something.

Can anybody please suggest how to effectively filter the above dataframe based on condition?

答:
Here is necessary compare by scalar, so is extracted first and last value of column by Series.iat:

Btw, if compare by ge for greater or equal in sorted values with first val it match all data, so this condition always return Trues, so should be removed with same output:

```<code>df['Date'] = pd.to_datetime(df['Date'],format='%Y%m')

df_filter = df[(df.Date.ge(df['Date'].iat[0]))&(df.Date.lt(df['Date'].iat[-1]))]
</code>```

Same like:

```<code>df_filter = df[(df.Date.lt(df['Date'].iat[-1]))]

print (df)
        Date  Value
0 2018-10-01    100
1 2018-11-01    150
2 2018-12-01     95
3 2019-01-01    125
4 2019-02-01    150
5 2019-03-01    200
6 2019-04-01    225
</code>```

Body:
I am trying to filter a dataframe based on date field.

 Date    Value
201810   100
201811   150
201812   95
201901   125
201902   150
201903   200
201904   225

The filtering is to be done dynamically. E.g. the first date and end date should not be 'hard coded'.
So my approach is as follows:

month = pd.DataFrame(set(df['Date']),columns=['Date'])
df['Date'] = pd.to_datetime(df['Date'],format='%Y%m)

From here, I have to filter based on date and create a new dataframe. In this the last date, say 201903.

dt_first = month['Date'].head(1)   <---first date is being dynamically created
dt_last = month.iloc[-2]           <-- last date, dynamically created.
df_filter = df[(df.Date.ge(dt_first))&(df.Date.le(dt_last))]

But the last line is generating a blank dataframe. The resultant dataframe should look like

 Date    Value
 201810   100
 201811   150
 201812   95
 201901   125
 201902   150
 201903   200

I know I am missing out something.

Can anybody please suggest how to effectively filter the above dataframe based on condition?

Body:
Here is necessary compare by scalar, so is extracted first and last value of column by Series.iat:

Btw, if compare by ge for greater or equal in sorted values with first val it match all data, so this condition always return Trues, so should be removed with same output:

df['Date'] = pd.to_datetime(df['Date'],format='%Y%m')

df_filter = df[(df.Date.ge(df['Date'].iat[0]))&(df.Date.lt(df['Date'].iat[-1]))]

Same like:

df_filter = df[(df.Date.lt(df['Date'].iat[-1]))]

print (df)
        Date  Value
0 2018-10-01    100
1 2018-11-01    150
2 2018-12-01     95
3 2019-01-01    125
4 2019-02-01    150
5 2019-03-01    200
6 2019-04-01    225


问:
The increment size of the sequence is set to [50] in the entity mapping while the associated database sequence increment size is 1
I'm trying to configure the properties for postgreSQL Database in my first sprinboot application. But when I run this application I am getting the following error:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in
    ... 39 common frames omitted

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
    at
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_201]
Caused by: org.hibernate.MappingException: The increment size of the [project_seq] sequence is set to [50] in the entity mapping while the associated database sequence increment size is [1].
    at
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
    at
</code>```

PostgreSQL properties:

```<code>spring.datasource.url=jdbc:postgresql://localhost:5432/pma-springbootdb
spring.datasource.username=***
spring.datasource.password=***
spring.datasource.initialization-mode=never
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.show-sql=true
spring.thymeleaf.cache=false
</code>```

version=3.0.0

SQL Query:

CREATE SEQUENCE IF NOT EXISTS employee_seq;

CREATE TABLE IF NOT EXISTS employee (
   employee_id BIGINT NOT NULL DEFAULT nextval('employee_seq') PRIMARY KEY,
   email VARCHAR(100) NOT NULL,
   first_name VARCHAR(100) NOT NULL,
   last_name VARCHAR(100) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS project_seq;

CREATE TABLE IF NOT EXISTS project (
   project_id BIGINT NOT NULL DEFAULT nextval('project_seq') PRIMARY KEY,
   name VARCHAR(100) NOT NULL,
   stage VARCHAR(100) NOT NULL,
   description VARCHAR(500) NOT NULL
);

CREATE TABLE IF NOT EXISTS project_employee (
   project_id BIGINT REFERENCES project,
   employee_id BIGINT REFERENCES employee
);
```

<p>Project.java</p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class Project {

   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")
   private Long projectId;
   ....
   ....
}
</code>```

Employee.java:

@Entity
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_seq")
   private long employeeId;
   ...
   ..
}
```

答:
It looks like you should use the @SequenceGenerator annotation in conjunction with the @GeneratedValue annotation to explicitly specify the increment size of the project_seq sequence.

You can do it in this way:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")
@SequenceGenerator(name = "project_seq", sequenceName = "project_seq", allocationSize = 1)
private Long projectId;
```

By default the allocationSize is 50.

Body:
I'm trying to configure the properties for postgreSQL Database in my first sprinboot application. But when I run this application I am getting the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in
    ... 39 common frames omitted

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
    at
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.jrp.pma.entities.Project]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_201]
Caused by: org.hibernate.MappingException: The increment size of the [project_seq] sequence is set to [50] in the entity mapping while the associated database sequence increment size is [1].
    at
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
    at

PostgreSQL properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/pma-springbootdb
spring.datasource.username=***
spring.datasource.password=***
spring.datasource.initialization-mode=never
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.show-sql=true
spring.thymeleaf.cache=false

version=3.0.0

SQL Query:

CREATE SEQUENCE IF NOT EXISTS employee_seq;

CREATE TABLE IF NOT EXISTS employee (
   employee_id BIGINT NOT NULL DEFAULT nextval('employee_seq') PRIMARY KEY,
   email VARCHAR(100) NOT NULL,
   first_name VARCHAR(100) NOT NULL,
   last_name VARCHAR(100) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS project_seq;

CREATE TABLE IF NOT EXISTS project (
   project_id BIGINT NOT NULL DEFAULT nextval('project_seq') PRIMARY KEY,
   name VARCHAR(100) NOT NULL,
   stage VARCHAR(100) NOT NULL,
   description VARCHAR(500) NOT NULL
);

CREATE TABLE IF NOT EXISTS project_employee (
   project_id BIGINT REFERENCES project,
   employee_id BIGINT REFERENCES employee
);

Project.java

@Entity
public class Project {

   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")
   private Long projectId;
   ....
   ....
}

Employee.java:

@Entity
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_seq")
   private long employeeId;
   ...
   ..
}

Body:
It looks like you should use the @SequenceGenerator annotation in conjunction with the @GeneratedValue annotation to explicitly specify the increment size of the project_seq sequence.

You can do it in this way:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")
@SequenceGenerator(name = "project_seq", sequenceName = "project_seq", allocationSize = 1)
private Long projectId;

By default the allocationSize is 50.


问:
C# how to log file inside a DLL?
I'm developing a DLL and I want to log some data it generates.

I wanted to use "Log4Net", but I found the problem that in a DLL I don't have an "App.config" file where I can write the XML code, so I don't know how to implement this (I'm new in this matters).

I read about "Singleton" but I saw it's better to avoid it since it has it's issues (i.e hide some visibility of the code, problems with unit tests, ...).

So my question is: How and what is the best way to create a log file for the data generated by my DLL?

答:
The config file will be connected in running module.
It will be in exe file if it's a console application,
or in web.config in case of web application.

Title: C# how to log file inside a DLL?


问:
Connecting to MongoDB using NodeJS with Kerberos authentication from Windows fails with "The specified target is unknown or unreachable"
Using the sample code at https://github.com/mongodb/node-mongodb-native/blob/5a1b61c9f2baf8f6f3cec4c34ce2db52272cd49d/docs/reference/content/tutorials/connect/authenticating.md, my code is as simple as the following but throws "MongoServerSelectionError: InitializeSecurityContext: The specified target is unknown or unreachable".

```<code>const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require("fs");

// KDC Server
const server = "linux.mydomain";
const principal = "myname@mydomain";
const urlEncodedPrincipal = encodeURIComponent(principal);
const dbName = "devDB"
const url = `mongodb://${urlEncodedPrincipal}@${server}/${dbName}?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:mongodb,CANONICALIZE_HOST_NAME:false,SERVICE_REALM:windows`;

const caChain = fs.readFileSync("./ssl/ca-cert.pem");

let mongoConnectOptions = {
    ssl: true,
    sslValidate: true,
    sslCA: caChain,
    useNewUrlParser: true,
    useUnifiedTopology: true,
    replicaSet: "myReplica"
};

const client = new MongoClient(url, mongoConnectOptions);

// Let's write the actual connection code
client.connect(function(err) {
  assert.equal(null, err);

  client.close();
});
</code>```

While the package.json is as the following:

```<code>{
  "name": "Try_Connect",
  "version": "1.0.0",
  "description": "",
  "main": "Connect.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fs": "0.0.1-security",
    "kerberos": "^1.1.3",
    "mongodb": "3.5.5"
  }
}
</code>```

From my understanding, MongoDB server should also work as a proxy to send the authentication request to KDC server so no need to configure these on the client side. Not sure if the error is related to that or incorrect URL for a replicaSet?

Thanks

答:
Seems the issue is a bug in the latest version of mongodb driver and/or kerberos library as downgrading solved the issue.</p>

```<code>git diff .\package.json
diff --git a/package.json b/package.json
index d0172a7..0c893b4 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
   "license": "ISC",
   "dependencies": {
     "fs": "0.0.1-security",
-    "kerberos": "^1.1.3",
-    "mongodb": "3.5.5"
+    "kerberos": "1.1.2",
+    "mongodb": "3.1.13"
   }
 }
</code>```

Body:
Using the sample code at https://github.com/mongodb/node-mongodb-native/blob/5a1b61c9f2baf8f6f3cec4c34ce2db52272cd49d/docs/reference/content/tutorials/connect/authenticating.md, my code is as simple as the following but throws "MongoServerSelectionError: InitializeSecurityContext: The specified target is unknown or unreachable".

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require("fs");

// KDC Server
const server = "linux.mydomain";
const principal = "myname@mydomain";
const urlEncodedPrincipal = encodeURIComponent(principal);
const dbName = "devDB"
const url = `mongodb://${urlEncodedPrincipal}@${server}/${dbName}?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:mongodb,CANONICALIZE_HOST_NAME:false,SERVICE_REALM:windows`;

const caChain = fs.readFileSync("./ssl/ca-cert.pem");

let mongoConnectOptions = {
    ssl: true,
    sslValidate: true,
    sslCA: caChain,
    useNewUrlParser: true,
    useUnifiedTopology: true,
    replicaSet: "myReplica"
};

const client = new MongoClient(url, mongoConnectOptions);

// Let's write the actual connection code
client.connect(function(err) {
  assert.equal(null, err);

  client.close();
});

While the package.json is as the following:

{
  "name": "Try_Connect",
  "version": "1.0.0",
  "description": "",
  "main": "Connect.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fs": "0.0.1-security",
    "kerberos": "^1.1.3",
    "mongodb": "3.5.5"
  }
}

From my understanding, MongoDB server should also work as a proxy to send the authentication request to KDC server so no need to configure these on the client side. Not sure if the error is related to that or incorrect URL for a replicaSet?

Thanks

Body:
Seems the issue is a bug in the latest version of mongodb driver and/or kerberos library as downgrading solved the issue.

git diff .\package.json
diff --git a/package.json b/package.json
index d0172a7..0c893b4 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
   "license": "ISC",
   "dependencies": {
     "fs": "0.0.1-security",
-    "kerberos": "^1.1.3",
-    "mongodb": "3.5.5"
+    "kerberos": "1.1.2",
+    "mongodb": "3.1.13"
   }
 }


问:
Navigation menu can not show list when responsive smaller

As you can see here, in max-width: 960px; my navigation menu is showing but after that when I set responsive to 840px, it can not show, although I already click to the hamburger icon

I do not know why?
You can see my code here
index.html

```<code><header class="header-container">

  <div class="header-content">
    <!-- nav bar -->
    <div class="nav-bar">
      <div class="header-logo">
        <a href="#">
          <img id="image-logo-header" class="bottom img-logo" src="images/logo.png">
        </a>
      </div>

      <div class="menu-section">
        <nav role="navigation">
          <ul class="nav-content" id="menu">
            <li class="menu-item"><a class="active" href="#">Home</a></li>
            <li class="menu-item"><a href="#">Blog</a></li>
            <li class="menu-item"><a href="#">About</a></li>
            <li class="menu-item"><a href="#">Contact</a></li>
            <li class="menu-item"><a href="#">Login</a></li>
            <li class="menu-item"><a href="#">Sign up</a></li>
            <li class="menu-item"><a href="#" class="hamburger-icon" onclick="myFunction()"><img src="images/hamburger.png" alt="hamburger icon"></a></li>
          </ul>
        </nav>
      </div>
    </div>

    <h1 class="header-title">SHARE YOUR HOLIDDAY DREAM</h1>

    <div class="header-video">
      <img class="video-img" src="images/video-img.png">
    </div>
  </div>
</header>
</code>```

style.css

```<code> /* -------header------- */
 .header-container {
      background-image:  linear-gradient(
      0deg,
      rgba(35, 39, 49, -0.18),
      rgba(35, 39, 49, 1.82)
 ), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
   background-size: cover;
   box-sizing: border-box;
   position: relative;
   height: 743px;
   width: 100%;
 }

 /* nav bar */
 .nav-bar{
     margin-left: 7%;
     margin-right: 7%;
     height: 140px;
  }

  .nav-content li a.hamburger-icon  {
      display: none;
   }

   .header-logo{
      float: left;
   }

   .menu-section{
      float: right;
    }

   .nav-content{
       list-style-type: none;
       margin-top: 10%;
    }

   .menu-item{
       display: block;
       float: left;
       margin-left: 30px;

    }

   .menu-item a.active{
        color: #00B9F7
    }

   .nav-content li a{
       text-decoration: none;
       color: #fff;
       font-size: 18px;
    }

   .nav-content li a:hover {
       color: #00B9F7;
    }

   .header-title{
       color: #fff;
       font-size: 52px;
       line-height: 63px;
       text-align: center;
        margin: auto;
        width: 35%;

     }

    .header-video {
        margin: auto;
        width: fit-content;
        margin-top: 10%;
      }
</code>```

responsive.css

```<code>@media (max-width:960px) {
    .header-title {
        font-size: 32px;
    }

   .partner-name, .user-comment, .search-question {
        font-size: 18px;
    }

   .partner-description{
        font-size: 12px;
    }

   .activity_item:nth-child(5), .activity_item:nth-child(6) {
        height: 258px;
    }

   .search-input {
        padding-right: 59%;
   }

   .nav-content li a{
        display: none;
   }

  .nav-content li a.hamburger-icon  {
       display: block;
   }

  .menu-item{
      float: right;
   }

  }

 @media (max-width:960px) {
     .nav-content.responsive {position: relative;}
     .nav-content.responsive .hamburger-icon {
         position: absolute;
         right: 0;
         top: 0;
      }
     .nav-content.responsive a {
         float: none;
         display: block;
      }
     .nav-content{
         background-color: #000;
         padding: 0%;
         width: 160px;
         text-align: center;
     }

    .menu-item{
        float: none;
        margin-left: 0%;
        line-height: 35px;
    }

    .menu-item:hover{
        background-color: #00B9F7;
    }

   .nav-content li a:hover {
        color: #fff;
    }

   .hamburger-icon{
        float: right;
    }

   }
</code>```

javascript.js

```<code><script>
function myFunction() {
  var x = document.getElementById("menu");
  if (x.className === "nav-content") {
    x.className += " responsive";
  } else {
    x.className = "nav-content";
  }
}
</script>
</code>```

Can you guys help me please, I do not understand why? in 840px my navigation menu not show for me? I need your help

答:
Add display: block;  to .nav-content.responsive .hamburger-icon
The display should be set to block to become visible.

Like so:

```<code>.nav-content.responsive .hamburger-icon {
     position: absolute;
     display: block;
     right: 0;
     top: 0;
  }
</code>```

Body:
As you can see here, in max-width: 960px; my navigation menu is showing but after that when I set responsive to 840px, it can not show, although I already click to the hamburger icon

I do not know why?
You can see my code here
index.html

Home

Blog

About

Contact

Login

Sign up

SHARE YOUR HOLIDDAY DREAM

style.css

 /* -------header------- */
 .header-container {
      background-image:  linear-gradient(
      0deg,
      rgba(35, 39, 49, -0.18),
      rgba(35, 39, 49, 1.82)
 ), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
   background-size: cover;
   box-sizing: border-box;
   position: relative;
   height: 743px;
   width: 100%;
 }

 /* nav bar */
 .nav-bar{
     margin-left: 7%;
     margin-right: 7%;
     height: 140px;
  }

  .nav-content li a.hamburger-icon  {
      display: none;
   }

   .header-logo{
      float: left;
   }

   .menu-section{
      float: right;
    }

   .nav-content{
       list-style-type: none;
       margin-top: 10%;
    }

   .menu-item{
       display: block;
       float: left;
       margin-left: 30px;

    }

   .menu-item a.active{
        color: #00B9F7
    }

   .nav-content li a{
       text-decoration: none;
       color: #fff;
       font-size: 18px;
    }

   .nav-content li a:hover {
       color: #00B9F7;
    }

   .header-title{
       color: #fff;
       font-size: 52px;
       line-height: 63px;
       text-align: center;
        margin: auto;
        width: 35%;

     }

    .header-video {
        margin: auto;
        width: fit-content;
        margin-top: 10%;
      }

responsive.css

@media (max-width:960px) {
    .header-title {
        font-size: 32px;
    }

   .partner-name, .user-comment, .search-question {
        font-size: 18px;
    }

   .partner-description{
        font-size: 12px;
    }

   .activity_item:nth-child(5), .activity_item:nth-child(6) {
        height: 258px;
    }

   .search-input {
        padding-right: 59%;
   }

   .nav-content li a{
        display: none;
   }

  .nav-content li a.hamburger-icon  {
       display: block;
   }

  .menu-item{
      float: right;
   }

  }

 @media (max-width:960px) {
     .nav-content.responsive {position: relative;}
     .nav-content.responsive .hamburger-icon {
         position: absolute;
         right: 0;
         top: 0;
      }
     .nav-content.responsive a {
         float: none;
         display: block;
      }
     .nav-content{
         background-color: #000;
         padding: 0%;
         width: 160px;
         text-align: center;
     }

    .menu-item{
        float: none;
        margin-left: 0%;
        line-height: 35px;
    }

    .menu-item:hover{
        background-color: #00B9F7;
    }

   .nav-content li a:hover {
        color: #fff;
    }

   .hamburger-icon{
        float: right;
    }

   }

javascript.js

Can you guys help me please, I do not understand why? in 840px my navigation menu not show for me? I need your help

Body:
Add display: block;  to .nav-content.responsive .hamburger-icon
The display should be set to block to become visible.

Like so:

.nav-content.responsive .hamburger-icon {
     position: absolute;
     display: block;
     right: 0;
     top: 0;
  }


问:
Functions arcpy don't retrieve data
I try to run python script with these functions:

arcpy.ListTables()

, arcpy.ListFeatureClasses()

or

,arcpy.ListWorkspaces("*", "FileGDB")

but all the functions return right results on one computer and return "None"  on another.

Folder with GDB files was copied to both of these computers and has access by ArcCatalog correctly from the both computers.

What might be the problem? May be any security?

答: The problem solved.The path "d:\geodb\any.gdb" was specified in the configuration file. This representation of the path is correct for arcpy for the first computer, but invalid for the second computer. The path was rewritten in the following form "d:/geodb\any.gdb" (backslash and two slashes) for the second computer. The both computers have the same OS version (windows 10). I don't know what settings do this depend on.</p>

Title: Functions arcpy don't retrieve data


问:
Unable to get user's email ID in user_friends API of Facebook
I'm fetching the list of user's friends who all are using the application with Login with Facebook feature. In GraphAPI for "user_freinds" request, I'm requesting for id, email & name of the users. However the API is not returning the email of users. Only name and ID of users are being returned. Please check the code below.

```<code>func getFacebookFriends() {
    if AccessToken.current != nil {
        let fbUserID = AccessToken.current?.userId ?? ""
        let friendsPath = "/\(fbUserID)/friends"
        let params = ["fields": "id, name, email"]
        let fbFriendsRequest = GraphRequest(graphPath: friendsPath, parameters: params, httpMethod: .GET)
        fbFriendsRequest.start { (_, result) in
            switch result {
            case .success(let response):
                print(response.dictionaryValue as Any)
                let responseDict = response.dictionaryValue!
                let data = responseDict["data"] as! [[String:Any]]
                if data.count != 0 {
                    // Sync the list with API
                } else {
                    // Show error
                }
            case .failed(let error):
                // Show error
            }
        }
    }
}
</code>```

Is there anything I'm missing here?

Also note that I'm using test users of Facebook, created by Developer portal of Facebook. Friends are added and authorised via Developer portal only.

答:
Use Graph API Explorer to debug: https://developers.facebook.com/tools/explorer/

Try to get permissions: 'GET/{user-id}/permissions'

Try to get friends list and separate user info in this tool

Email couldn't be visible if user hides it on privacy settings page

Body:
I'm fetching the list of user's friends who all are using the application with Login with Facebook feature. In GraphAPI for "user_freinds" request, I'm requesting for id, email & name of the users. However the API is not returning the email of users. Only name and ID of users are being returned. Please check the code below.

func getFacebookFriends() {
    if AccessToken.current != nil {
        let fbUserID = AccessToken.current?.userId ?? ""
        let friendsPath = "/\(fbUserID)/friends"
        let params = ["fields": "id, name, email"]
        let fbFriendsRequest = GraphRequest(graphPath: friendsPath, parameters: params, httpMethod: .GET)
        fbFriendsRequest.start { (_, result) in
            switch result {
            case .success(let response):
                print(response.dictionaryValue as Any)
                let responseDict = response.dictionaryValue!
                let data = responseDict["data"] as! [[String:Any]]
                if data.count != 0 {
                    // Sync the list with API
                } else {
                    // Show error
                }
            case .failed(let error):
                // Show error
            }
        }
    }
}

Is there anything I'm missing here?

Also note that I'm using test users of Facebook, created by Developer portal of Facebook. Friends are added and authorised via Developer portal only.


问:
How to extract table names and column names from sql query?
So let assume we have such simple query:

```<code>Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;
</code>```

The result should  looks this way:

```<code>tb1 col1
tb1 col7
tb2 col2
tb2 col8
</code>```

I've tried to solve this problem using some python library:

1) Even extracting only tables using sqlparse might be a huge problem. For example this official book doesn't work properly at all.

2) Using regular expression seems to be really hard to achieve.

3) But then I found this , that might help. However the problem is that I can't connect to any database and execute that query.

Any ideas?

答:
sql-metadata is a Python library that uses a tokenized query returned by python-sqlparse and generates query metadata.

This metadata can return column and table names from your supplied SQL query. Here are a couple of example from the sql-metadata github readme:

```<code>>>> sql_metadata.get_query_columns("SELECT test, id FROM foo, bar")
[u'test', u'id']

>>> sql_metadata.get_query_tables("SELECT test, id FROM foo, bar")
[u'foo', u'bar']

>>> sql_metadata.get_query_limit_and_offset('SELECT foo_limit FROM bar_offset LIMIT 50 OFFSET 1000')
(50, 1000)
</code>```

A hosted version of the library exists at sql-app.infocruncher.com to see if it works for you.

Body:
So let assume we have such simple query:

Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;

The result should  looks this way:

tb1 col1
tb1 col7
tb2 col2
tb2 col8

I've tried to solve this problem using some python library:

1) Even extracting only tables using sqlparse might be a huge problem. For example this official book doesn't work properly at all.

2) Using regular expression seems to be really hard to achieve.

3) But then I found this , that might help. However the problem is that I can't connect to any database and execute that query.

Any ideas?

Body:
sql-metadata is a Python library that uses a tokenized query returned by python-sqlparse and generates query metadata.

This metadata can return column and table names from your supplied SQL query. Here are a couple of example from the sql-metadata github readme:

>>> sql_metadata.get_query_columns("SELECT test, id FROM foo, bar")
[u'test', u'id']

>>> sql_metadata.get_query_tables("SELECT test, id FROM foo, bar")
[u'foo', u'bar']

>>> sql_metadata.get_query_limit_and_offset('SELECT foo_limit FROM bar_offset LIMIT 50 OFFSET 1000')
(50, 1000)

A hosted version of the library exists at sql-app.infocruncher.com to see if it works for you.


问:
How do I sort a list based on a given sequence of one field?
I have a list read from database, something like:

```<code>var managers = _repo.Where(xxxx).ToList();
</code>```

data of managers displays in json is

```<code>[
    {
        "id":"b2071b2d-3d1a-4403-b044-0a59514c4431",
        "name":"Lucy",
        "mobile":"xxx"
    },
    {
        "id":"639c108f-ec00-4fcd-814a-c3859930b1c1",
        "name":"Franck",
        "mobile":"xxx2"
    },
    {
        "id":"943b2ad4-8ef0-4cf7-824e-de3a7837a1cd",
        "name":"Jerry",
        "mobile":"xxx3"
    }
]
</code>```

Now I need to reorder this list by a given name sequence, for example:

```<code>    var orderByName = _svc.GetManagerSortOrder(); // ["Jerry","Lucy","Franck"]
</code>```

Right now I'm using foreach to do this, it's too much to code. Is there any better way?

Here is my current solution:

```<code>var orderByName = new List<string>() { "Franck", "Jerry" };
var sortedManagers = new List<Manager>();
foreach(string orderName in orderByName) // loop, and sort manager list based on a given name list
{
    var manager = managers.Where(a => a.name == orderName).FirstOrDefault();
    if (manager == null)
        continue;
    sortedManagers.Add(manager);
}

if(sortedManagers.Count != managers.Count) // if counts not equal, there is someone not on the name list, so these men need to be appended to the sortedManagers list
{
    var sortedManagersId = sortedManagers.Select(s => s.id);
    var managersNotInclude = managers.Where(a => !sortedManagersId.Contains(a.id)).ToList();
    sortedManagers = sortedManagers.Concat(managersNotInclude).ToList();
}
</code>```

答:
So you have a sequence of Managers where every Manager has a Name; and you have a sequence of Names, something like ["Jerry","Lucy","Franck"].

You want to order your Managers, such that you first get all Managers named "Jerry", then all Managers names "Lucy", etc. You want to end with managers that were not in your sequence of names.

Consider creating an object that implements IComparer<Manager>: get two Managers, and decides who should go first. For instance: one Manger is named "Lucy", the other one is named "Jerry", so "Jerry" should bo first.

Usage would be:

```<code>IEnumerable<Manager> unorderedManagers = ...
IComparer<Manager> managerComparer = ...

IEnumerable<Manager> orderedManagers = unorderedManagers.OrderBy(managerComparer);
</code>```

So let's create a ManagerComparer class.

```<code>class ManagerComparer : IComparer<Manager>
{
    public ManagerComparer(IEnumerable<string> names)
    {
    }

    public int Compare(Manager x, Manager y) {...}
    // TODO implement
}
</code>```

If you have two managers as input: x and y, you want the manger with "Jerry" first. If there is no "Jerry" you want "Lucy" first, etc.

To make this efficient, we put all Names in a dictionary: Key is the name, Value is the index. So "Jerry" has index 0, "Lucy" index 1, etc

You get Manager X and Y: get their Names, get the index from the Dictionary. The one with the lowest index comes first.

Sounds like a good idea? Let's do it:

```<code>private readonly IDictionary<string, int> managerNames;

public ManagerComparer(IEnumerable<string> names)
{
    // TODO: what to do if no names?

    this.managerNames = names.Select( (name, i) => new
    {
        Name = name,
        Index = i,
    })
    .ToDictionary(item => item.Name, item => item.Index);
}
</code>```

The Compare method.

We know what to do when you get two Managers. Comparer the indexes of the names in the Dictionary. Return either -1 / 0 / +1, depending on the value. This can be done with if/then/else, it is easier to use the existing IComparer<int>:

```<code>private static readonly IComparer<int> indexComparer = Comparer<int>.Default;

public int Compare(Manager x, Manager y)
{
    // TODO: decide what to return if x or y null: first or last in your result
    if (x == null)
    {
        if (y == null)
           return 0;
        else
            return ... // -1 or +1;
    }
    else if (y == null)
        return ... // -1 or +1;

    // if here, both x and y not null
    string nameX = x.Name;
    string nameY = y.Name;

    int indexX = this.managerNames[nameX];
    int indexY = this.managerNames[nameY];

    // the one with the lowest index comes first:
    return indexComparer.Compare(indexX, indexY);
}
</code>```

Again usage:

```<code>IEnumerable<Manager> unorderedManagers = ...
IEnumerable<string> orderByNames = new sting[] {"Jerry", "Lucy", ...}
IComparer<Manager> managerComparer = new ManagerComparer(orderByNames);

IEnumerable<Manager> orderedManagers = unorderedManagers.OrderBy(managerComparer);
</code>```

Body:
I have a list read from database, something like:

var managers = _repo.Where(xxxx).ToList();

data of managers displays in json is

[
    {
        "id":"b2071b2d-3d1a-4403-b044-0a59514c4431",
        "name":"Lucy",
        "mobile":"xxx"
    },
    {
        "id":"639c108f-ec00-4fcd-814a-c3859930b1c1",
        "name":"Franck",
        "mobile":"xxx2"
    },
    {
        "id":"943b2ad4-8ef0-4cf7-824e-de3a7837a1cd",
        "name":"Jerry",
        "mobile":"xxx3"
    }
]

Now I need to reorder this list by a given name sequence, for example:

    var orderByName = _svc.GetManagerSortOrder(); // ["Jerry","Lucy","Franck"]

Right now I'm using foreach to do this, it's too much to code. Is there any better way?

Here is my current solution:

var orderByName = new List<string>() { "Franck", "Jerry" };
var sortedManagers = new List<Manager>();
foreach(string orderName in orderByName) // loop, and sort manager list based on a given name list
{
    var manager = managers.Where(a => a.name == orderName).FirstOrDefault();
    if (manager == null)
        continue;
    sortedManagers.Add(manager);
}

if(sortedManagers.Count != managers.Count) // if counts not equal, there is someone not on the name list, so these men need to be appended to the sortedManagers list
{
    var sortedManagersId = sortedManagers.Select(s => s.id);
    var managersNotInclude = managers.Where(a => !sortedManagersId.Contains(a.id)).ToList();
    sortedManagers = sortedManagers.Concat(managersNotInclude).ToList();
}

Body:
So you have a sequence of Managers where every Manager has a Name; and you have a sequence of Names, something like ["Jerry","Lucy","Franck"].

You want to order your Managers, such that you first get all Managers named "Jerry", then all Managers names "Lucy", etc. You want to end with managers that were not in your sequence of names.

Consider creating an object that implements IComparer<Manager>: get two Managers, and decides who should go first. For instance: one Manger is named "Lucy", the other one is named "Jerry", so "Jerry" should bo first.

Usage would be:

IEnumerable<Manager> unorderedManagers = ...
IComparer<Manager> managerComparer = ...

IEnumerable<Manager> orderedManagers = unorderedManagers.OrderBy(managerComparer);

So let's create a ManagerComparer class.

class ManagerComparer : IComparer<Manager>
{
    public ManagerComparer(IEnumerable<string> names)
    {
    }

    public int Compare(Manager x, Manager y) {...}
    // TODO implement
}

If you have two managers as input: x and y, you want the manger with "Jerry" first. If there is no "Jerry" you want "Lucy" first, etc.

To make this efficient, we put all Names in a dictionary: Key is the name, Value is the index. So "Jerry" has index 0, "Lucy" index 1, etc

You get Manager X and Y: get their Names, get the index from the Dictionary. The one with the lowest index comes first.

Sounds like a good idea? Let's do it:

private readonly IDictionary<string, int> managerNames;

public ManagerComparer(IEnumerable<string> names)
{
    // TODO: what to do if no names?

    this.managerNames = names.Select( (name, i) => new
    {
        Name = name,
        Index = i,
    })
    .ToDictionary(item => item.Name, item => item.Index);
}

The Compare method.

We know what to do when you get two Managers. Comparer the indexes of the names in the Dictionary. Return either -1 / 0 / +1, depending on the value. This can be done with if/then/else, it is easier to use the existing IComparer<int>:

private static readonly IComparer<int> indexComparer = Comparer<int>.Default;

public int Compare(Manager x, Manager y)
{
    // TODO: decide what to return if x or y null: first or last in your result
    if (x == null)
    {
        if (y == null)
           return 0;
        else
            return ... // -1 or +1;
    }
    else if (y == null)
        return ... // -1 or +1;

    // if here, both x and y not null
    string nameX = x.Name;
    string nameY = y.Name;

    int indexX = this.managerNames[nameX];
    int indexY = this.managerNames[nameY];

    // the one with the lowest index comes first:
    return indexComparer.Compare(indexX, indexY);
}

Again usage:

IEnumerable<Manager> unorderedManagers = ...
IEnumerable<string> orderByNames = new sting[] {"Jerry", "Lucy", ...}
IComparer<Manager> managerComparer = new ManagerComparer(orderByNames);

IEnumerable<Manager> orderedManagers = unorderedManagers.OrderBy(managerComparer);


问:
Commit issue in Execute sql task Pentaho spoon 7
I have once execute SQL task in my KTR and its has multiple Insert statement. I want to understand how transaction control work here. Do I need COMMIT after every Insert or only at end.  </p>

答: You do not need to commit while using 'execute SQL' step in Spoon. The commit happens automatically.</p>


问:
GridSearchCV and the tree classifier
In this post it is mentioned

```<code>  param_grid = {'max_depth': np.arange(3, 10)}
  tree = GridSearchCV(DecisionTreeClassifier(), param_grid)
  tree.fit(xtrain, ytrain)
  tree_preds = tree.predict_proba(xtest)[:, 1]
  tree_performance = roc_auc_score(ytest, tree_preds)
</code>```

Q1: once we perform the above steps and get the best parameters, we need to fit a tree with all data (training + validation) and the learned parameters?

Q2: max_depth is specifically mentioned in the parameters, and it is possible to get it by accessing tree.best_params_, what about other parameters that the grid has found? How is it possible to access those to build a good tree?

答:
Answering your first question, when you create your GridSearchCV object you can set parameter refit as True (the default value is True) which returns an estimator using the best found parameters on the whole dataset and it can be accessed by the best_estimator_ attribute. It behaves like a normal estimator and supports the .predict method like any other sklearn estimator does.

Now answering your second question, you can get access to all the parameter of the decision tree model that was using to fit the final estimator using the best_estimator_ attribute itself, but as I said earlier, there is no need for you to fit a new classifier with the best parameters since refit=True will do it for you.

Please follow the sample code below to understand this better:

```<code>import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(random_state=0)
param_grid = {'max_depth': np.arange(3, 10), 'min_samples_leaf':np.arange(2,10)}
tree = GridSearchCV(DecisionTreeClassifier(), param_grid)
tree.fit(X, y)
GridSearchCV(cv=None, error_score=nan,
             estimator=DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None,
                                              criterion='gini', max_depth=None,
                                              max_features=None,
                                              max_leaf_nodes=None,
                                              min_impurity_decrease=0.0,
                                              min_impurity_split=None,
                                              min_samples_leaf=1,
                                              min_samples_split=2,
                                              min_weight_fraction_leaf=0.0,
                                              presort='deprecated',
                                              random_state=None,
                                              splitter='best'),
             iid='deprecated', n_jobs=None,
             param_grid={'max_depth': array([3, 4, 5, 6, 7, 8, 9]),
                         'min_samples_leaf': array([2, 3, 4, 5, 6, 7, 8, 9])},
             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
             scoring=None, verbose=0)

# This is how your best estimator looks like
print(tree.best_estimator_)
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
                       max_depth=3, max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=6, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort='deprecated',
                       random_state=None, splitter='best')

# you can directly use it for prediction as shown below
tree.best_estimator_.predict(X)
array([0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1,
       0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0,
       0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
       1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1,
       0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0])
</code>```

Title: GridSearchCV and the tree classifier

Body:
In this post it is mentioned

  param_grid = {'max_depth': np.arange(3, 10)}
  tree = GridSearchCV(DecisionTreeClassifier(), param_grid)
  tree.fit(xtrain, ytrain)
  tree_preds = tree.predict_proba(xtest)[:, 1]
  tree_performance = roc_auc_score(ytest, tree_preds)

Q1: once we perform the above steps and get the best parameters, we need to fit a tree with all data (training + validation) and the learned parameters?

Q2: max_depth is specifically mentioned in the parameters, and it is possible to get it by accessing tree.best_params_, what about other parameters that the grid has found? How is it possible to access those to build a good tree?

Body:
Answering your first question, when you create your GridSearchCV object you can set parameter refit as True (the default value is True) which returns an estimator using the best found parameters on the whole dataset and it can be accessed by the best_estimator_ attribute. It behaves like a normal estimator and supports the .predict method like any other sklearn estimator does.

Now answering your second question, you can get access to all the parameter of the decision tree model that was using to fit the final estimator using the best_estimator_ attribute itself, but as I said earlier, there is no need for you to fit a new classifier with the best parameters since refit=True will do it for you.

Please follow the sample code below to understand this better:

import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(random_state=0)
param_grid = {'max_depth': np.arange(3, 10), 'min_samples_leaf':np.arange(2,10)}
tree = GridSearchCV(DecisionTreeClassifier(), param_grid)
tree.fit(X, y)
GridSearchCV(cv=None, error_score=nan,
             estimator=DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None,
                                              criterion='gini', max_depth=None,
                                              max_features=None,
                                              max_leaf_nodes=None,
                                              min_impurity_decrease=0.0,
                                              min_impurity_split=None,
                                              min_samples_leaf=1,
                                              min_samples_split=2,
                                              min_weight_fraction_leaf=0.0,
                                              presort='deprecated',
                                              random_state=None,
                                              splitter='best'),
             iid='deprecated', n_jobs=None,
             param_grid={'max_depth': array([3, 4, 5, 6, 7, 8, 9]),
                         'min_samples_leaf': array([2, 3, 4, 5, 6, 7, 8, 9])},
             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
             scoring=None, verbose=0)

# This is how your best estimator looks like
print(tree.best_estimator_)
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
                       max_depth=3, max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=6, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort='deprecated',
                       random_state=None, splitter='best')

# you can directly use it for prediction as shown below
tree.best_estimator_.predict(X)
array([0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1,
       0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0,
       0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
       1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1,
       0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0])


问:
Linked Pie Chart using Flot 0.7 returns "undefined" links
I am trying to create a Flot pie chart with a link in each wedge, so I can direct users to the appropriate details page on clicking.

There is already a similar post at With flot, how can I create a linked pie chart that takes you to other web pages?. I tried the answer on that page with with Flot 0.7 to obtain pie wedges with hyperlinked labels. However, series.URL returns "undefined" in the labelFormatter function. How do I resolve this issue?

On a side note: Its my first time posting here. I tried to ask this obviously related question at the link above so I don't create a new question for the same issue. However, it was deleted by the moderator. Wouldn't it have helped other users reading that post who suffered from the same issue to find a resolution? Not complaining, just trying to understand the rationale (have read the FAQs/Guidelines for asking questions..) behind the deletion.

答:
If you follow the code in your linked question, they get quite close to what you want.  The problem (which trips up many people) is that the item in the plotclick function is not the same as the series object in your raw data.  What you can do though, is refer back to your raw data using item.seriesIndex in plotclick:

```<code>//setup options
//setup data
var data = [
    {
    label: "Serie1",
    data: 10,
    url: "http://stackoverflow.com"},
...
];
//call plot
//setup plotclick
$("#placeholder").bind("plotclick", function (event, pos, item) {
   alert(data[item.seriesIndex].url);
});
</code>```

I don't have it following the link, but that should be easy for you to do.

Here is some sample code in full:  http://jsfiddle.net/ryleyb/pq4Q4/

Side note answer:  Generally they would prefer you ask a new question instead of piling into an old question with new sub-questions.  Especially in an "answered" question (I put answered in quotes because it doesn't seem that they came to a full answer, so I can see your confusion).

Body:
If you follow the code in your linked question, they get quite close to what you want.  The problem (which trips up many people) is that the item in the plotclick function is not the same as the series object in your raw data.  What you can do though, is refer back to your raw data using item.seriesIndex in plotclick:

//setup options
//setup data
var data = [
    {
    label: "Serie1",
    data: 10,
    url: "http://stackoverflow.com"},
...
];
//call plot
//setup plotclick
$("#placeholder").bind("plotclick", function (event, pos, item) {
   alert(data[item.seriesIndex].url);
});

I don't have it following the link, but that should be easy for you to do.

Here is some sample code in full:  http://jsfiddle.net/ryleyb/pq4Q4/

Side note answer:  Generally they would prefer you ask a new question instead of piling into an old question with new sub-questions.  Especially in an "answered" question (I put answered in quotes because it doesn't seem that they came to a full answer, so I can see your confusion).


问:
two ternary condition inside JSX block?
I have 2 useState, one for show activity indicator, another state is to check whether it has data or not.

```<code>  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);
</code>```

what i want to do is,
if i have data then, it should show the activity indicator for the loading time, then it should show the data in the screen. If i don't have the data, it should display simply "No Data Found."

This is my current code, it's only checking activity indicator.

```<code>{isLoading ? (<ActivityIndicator size="large" /> ) : ( <Component data = {data} /> )
</code>```

How can i check the other isData check here?

答:
You could simply nest your thernary operators, although it won`t be very pretty and can easily become messy.
In the False part of your current thernary operator simply add another check and thats all.
Something like this</p>

```<code>{isLoading ?
     (<ActivityIndicator size="large" /> )
     : isData ?
       ( <Component data = {data} /> )
       : ( Print Errror)
}
</code>```

Title: two ternary condition inside JSX block?

Body:
I have 2 useState, one for show activity indicator, another state is to check whether it has data or not.

  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);

what i want to do is,
if i have data then, it should show the activity indicator for the loading time, then it should show the data in the screen. If i don't have the data, it should display simply "No Data Found."

This is my current code, it's only checking activity indicator.

{isLoading ? (<ActivityIndicator size="large" /> ) : ( <Component data = {data} /> )

How can i check the other isData check here?

Body:
You could simply nest your thernary operators, although it won`t be very pretty and can easily become messy.
In the False part of your current thernary operator simply add another check and thats all.
Something like this

{isLoading ?
     (<ActivityIndicator size="large" /> )
     : isData ?
       ( <Component data = {data} /> )
       : ( Print Errror)
}


问:
Components with uppercase function names are rendered multiple times in React Hooks
I've been developing with Hooks for a long time, But I met a situation where I was confused.

Let me briefly describe this strange problem with a particular case.

I created a very simple functional component called Test:

// test.js
export default function Test () {

  useEffect(() => {
    console.log('Test')
  }, [])

  return (

      Test Component

  )
}
```

<p>It will print something at the first render</p>

<p>And the component will be referenced in <code>App</code></p>

<pre class="lang-js prettyprint-override"><code>// App.js
import React, { useEffect, useState } from "react";
import Test from './test';

export default function App() {
  const [number, updateNumber] = useState(0);

  const renderComponent = () => {
    return (
      <Test />
    )
  }

  const RenderComponent = () => {
    return (
      <Test />
    )
  }

  useEffect(() => {
    updateNumber(1)
    updateNumber(2)
  }, [])

  console.log('every-render')

  return (
    <div className="App">

      {renderComponent()}

      {/* <RenderComponent /> */}

      <h1>Rerender times: {number}</h1>
    </div>
  );
}
</code>```

So something strange happened

When I use this way, the Test component will be printed once

// Case 1
const renderComponent = () => {
    return (
      <Test />
    )
}

// ...

renderComponent()
```

<p>Something that it prints in Console</p>

<p>But when I use this way, the <code>Test</code> component will be printed twice</p>

<pre class="lang-js prettyprint-override"><code>// Case 2
const RenderComponent = () => {
    return (
      <Test />
    )
}

// ...

<RenderComponent />
</code>```

Something that it prints in Console

Of course, I wrote a demo for you to debug:
https://codesandbox.io/s/demo-for-hooks-8gkml?file=/src/App.js

I am confused why in case 2 the Test component will be remounted each time the Hooks are rerendered.

答:
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.

Consider 3 cases:

```<code>{renderComponent()}
<RenderComponent />
<Test />
</code>```

1) {renderComponent()}

Every render just return Test type, algorithm compares and sees that the type has not changed.
Result: mount Test component 1 time.

2) <RenderComponent />

Every render return new component type RenderComponent, algorithm compares and sees RenderComponent1 type != RenderComponent2 type, and:

Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch.

Result: mount child Test component 2 times.

Add console to mount RenderComponent:

```<code>const RenderComponent = () => {
    useEffect(() => console.log('RenderComponent mount'), []);
    return <Test />;
};
</code>```

RenderComponent too mount 2 times.

3) <Test />

Similarly 1 case.
Result: mount Test component 1 time.

Body:
I've been developing with Hooks for a long time, But I met a situation where I was confused.

Let me briefly describe this strange problem with a particular case.

I created a very simple functional component called Test:

// test.js
export default function Test () {

  useEffect(() => {
    console.log('Test')
  }, [])

  return (

      Test Component

  )
}

It will print something at the first render

And the component will be referenced in App

// App.js
import React, { useEffect, useState } from "react";
import Test from './test';

export default function App() {
  const [number, updateNumber] = useState(0);

  const renderComponent = () => {
    return (
      <Test />
    )
  }

  const RenderComponent = () => {
    return (
      <Test />
    )
  }

  useEffect(() => {
    updateNumber(1)
    updateNumber(2)
  }, [])

  console.log('every-render')

  return (

      {renderComponent()}

      {/* <RenderComponent /> */}

Rerender times: {number}

  );
}

So something strange happened

When I use this way, the Test component will be printed once

// Case 1
const renderComponent = () => {
    return (
      <Test />
    )
}

// ...

renderComponent()

Something that it prints in Console

But when I use this way, the Test component will be printed twice

// Case 2
const RenderComponent = () => {
    return (
      <Test />
    )
}

// ...

<RenderComponent />

Something that it prints in Console

Of course, I wrote a demo for you to debug:
https://codesandbox.io/s/demo-for-hooks-8gkml?file=/src/App.js

I am confused why in case 2 the Test component will be remounted each time the Hooks are rerendered.

Body:
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.

Consider 3 cases:

{renderComponent()}
<RenderComponent />
<Test />

1) {renderComponent()}

Every render just return Test type, algorithm compares and sees that the type has not changed.
Result: mount Test component 1 time.

2) <RenderComponent />

Every render return new component type RenderComponent, algorithm compares and sees RenderComponent1 type != RenderComponent2 type, and:

Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch.

Result: mount child Test component 2 times.

Add console to mount RenderComponent:

const RenderComponent = () => {
    useEffect(() => console.log('RenderComponent mount'), []);
    return <Test />;
};

RenderComponent too mount 2 times.

3) <Test />

Similarly 1 case.
Result: mount Test component 1 time.