问:
Why shouldn't custom methods use the URL for transferring data?
TL,DR; When implementing custom methods, "the HTTP configuration [...] must use the body:* clause and all remaining request message fields shall map to the HTTP request body.". Why?

I have a problem with Google's API Design Guide  which I'm attempting to follow with gRPC with Cloud Endpoints.

The HttpRule is used to transcode HTTP/JSON to gRPC. The HttpRule reference states:

Note that when using * in the body mapping, it is not possible to have
  HTTP parameters, as all fields not bound by the path end in the body.

[...] The common usage of * is in custom methods which don't use the
  URL at all for transferring data.

...an opinion also repeated in Google's Custom Methods documentation and reinforced with Google's API Linter,

When using a named representation in the body mapping there is a well defined space left to add metadata in the form of querystring parameters; E.g. for pagination, links, deprecation warnings, error messages).

service Messaging {
  rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
    option (google.api.http) = {
      put: "/v1/messages/{message_id}"

      // A named reference makes it possible to use querystring params
      // and the HTTP body.
      body: "data"
    };
  }
}
message UpdateMessageRequest {
  message Data {
    string foo = 1;
    string bar = 2;
    string baz = 3;
  }

  // mapped to the URL as querystring params
  bool format = 1;
  string revision = 2;

  // mapped to the body
  Data data = 3;
}
```

<p>This allows for an HTTP PUT request to <code>/v1/messages/123456?format=true&revision=2</code> with a body</p>

```foo="I am foo"
bar="I am bar"
baz="I am baz"
```

<p>Since the mapping binds <code>body</code> to the type <code>UpdateMessageRequest.Data</code>, the remaining fields end up in the querystring. This is the approach used in standard methods, but not with custom) methods.</p>

<p>Custom methods must map <code>body</code> to <code>*</code>. The same API with a custom method would be</p>

<pre class="lang-proto prettyprint-override"><code>service Messaging {
  rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
    option (google.api.http) = {
      put: "/v1/messages/{message_id}"

      // Every field not bound by the path template should be
      // mapped to the request body.
      body: "*"
    };
  }
}
message UpdateMessageRequest {
  message Data {
    string foo = 1;
    string bar = 2;
    string baz = 3;
  }

  // mapped to the body
  bool format = 1;
  string revision = 2;
  Data data = 3;
}
</code>```

If the same metadata is used across both standard and custom) methods, it must be added either as querystring params, or placed in the body.

For example, an Angular app would use HttpParams

// standard method
const params = new HttpParams().append('format', true).append('revision', 2);
const request = {
  foo: "I am foo",
  bar: "I am bar",
  baz: "I am baz",
}
this.http.post<Document>(url, request, {params});
```

<p>However, a custom method requires the client to place everything in the body:</p>

<pre class="lang-js prettyprint-override"><code>// custom method
const request = {
  format: true,
  revision: 2,
  data: {
    foo: "I am foo",
    bar: "I am bar",
    baz: "I am baz",
  },
}
this.http.post<Document>(url, request);
</code>```

Question: What is the reason for this?

答:
Great question.

For reference, I wrote the AIP on this topic as well as the lint rule, and am also the current maintainer of the design guide that you referenced.

First off, I will mention that our latest guidance (linked above) specifically says should rather than must for this. In other words, it is the right thing to do the majority of the time, but there may be exceptions. Nothing in the gRPC transcoding implementation stops you from using a different body -- we tell you to use * for custom methods, but we do not place any technical barriers against doing something else.

I can think of a couple of good "exception cases" where a body other than * might make sense. The first would be a custom method that is modeled on one of the standard methods, but should be custom for some reason. The second would be if a custom method accepted a full resource, and wanted to set the body to that resource. This would make that method consistent with Create and Update, which obviously has value to the API's users.

If you have a case where you have a clear argument for using something else as the body (particularly if that something is the resource itself), by all means, use a different body and tell the linter to be quiet. We wrote "should" for a reason.

You also asked: Why do we have that recommendation in the first place?

There are a few reasons. The biggest one is that the exceptional cases described above are rare. I do hundreds of API reviews internally, and I can not actually think of one off the top of my head (which is not to say they do not exist). The majority of the time, the best thing for users is for the request message to mirror the HTTP payload.

Another reason is a key limitation: assigning a particular field to be the body limits what you can add outside of that field, since query strings are limited in what they can represent in both type (just primitives) and quantity (URI length constraints). Because altering the body later constitutes a breaking change, this ties your hands somewhat. That might be fine for your use case, obviously, but it is important to note.

Anyway, I hope that helps -- oh, and thanks for using my stuff. :-)

Body:
TL,DR; When implementing custom methods, "the HTTP configuration [...] must use the body:* clause and all remaining request message fields shall map to the HTTP request body.". Why?

I have a problem with Google's API Design Guide  which I'm attempting to follow with gRPC with Cloud Endpoints.

The HttpRule is used to transcode HTTP/JSON to gRPC. The HttpRule reference states:

Note that when using * in the body mapping, it is not possible to have
  HTTP parameters, as all fields not bound by the path end in the body.

[...] The common usage of * is in custom methods which don't use the
  URL at all for transferring data.

...an opinion also repeated in Google's Custom Methods documentation and reinforced with Google's API Linter,

When using a named representation in the body mapping there is a well defined space left to add metadata in the form of querystring parameters; E.g. for pagination, links, deprecation warnings, error messages).

service Messaging {
  rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
    option (google.api.http) = {
      put: "/v1/messages/{message_id}"

      // A named reference makes it possible to use querystring params
      // and the HTTP body.
      body: "data"
    };
  }
}
message UpdateMessageRequest {
  message Data {
    string foo = 1;
    string bar = 2;
    string baz = 3;
  }

  // mapped to the URL as querystring params
  bool format = 1;
  string revision = 2;

  // mapped to the body
  Data data = 3;
}

This allows for an HTTP PUT request to /v1/messages/123456?format=true&revision=2 with a body

foo="I am foo"
bar="I am bar"
baz="I am baz"

Since the mapping binds body to the type UpdateMessageRequest.Data, the remaining fields end up in the querystring. This is the approach used in standard methods, but not with custom) methods.

Custom methods must map body to *. The same API with a custom method would be

service Messaging {
  rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
    option (google.api.http) = {
      put: "/v1/messages/{message_id}"

      // Every field not bound by the path template should be
      // mapped to the request body.
      body: "*"
    };
  }
}
message UpdateMessageRequest {
  message Data {
    string foo = 1;
    string bar = 2;
    string baz = 3;
  }

  // mapped to the body
  bool format = 1;
  string revision = 2;
  Data data = 3;
}

If the same metadata is used across both standard and custom) methods, it must be added either as querystring params, or placed in the body.

For example, an Angular app would use HttpParams

// standard method
const params = new HttpParams().append('format', true).append('revision', 2);
const request = {
  foo: "I am foo",
  bar: "I am bar",
  baz: "I am baz",
}
this.http.post<Document>(url, request, {params});

However, a custom method requires the client to place everything in the body:

// custom method
const request = {
  format: true,
  revision: 2,
  data: {
    foo: "I am foo",
    bar: "I am bar",
    baz: "I am baz",
  },
}
this.http.post<Document>(url, request);

Question: What is the reason for this?


来源: stackexchange

问:
IoT Edge Test certificates expiration
As far as I know IoT Edge will generate test (self signed) certificates (Device CA etc.) at startup if none were provided, right? Those are valid for 30 days.

What happens after those certificates expire?
Is IoT Edge going to create new ones when it is restarted?

答:
When IoT Edge is restarted, the certificates are renewed.  However, this is not a production feasible approach imho. :)

You should have your own certificates installed on the device, but those certificats will offcourse expire as well on some day.  So, you'll need some kind of certificate rolling operation, but there doesn't seem to be any good documentation regarding this.  Therefore, I've created an issue on github for this

ContentLicense: CC BY-SA 4.0

Title: IoT Edge Test certificates expiration


问:
Align navigation bootstrap center
I want to center align the navigation links from Bootstrap but since I'm not using the list structure, all solutions don't work.

```<code>    <section id="menuNavigation">
        <div class="container-fluid">
            <nav class="navbar navbar-expand-lg">

                <button class="navbar-toggler" type="´button" data-toggle="collapse" data-target="#navbarHeader">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarHeader">
                    <ul class="navbar-nav">
                        <a href="index.php" class="nav-item nav-link">Uniongs</a>
                        <a href="sobre.php" class="nav-item nav-link">Sobre</a>
                        <a href="seja-um-doador.php" class="nav-item nav-link">Seja Assinante</a>
                        <a href="blog.php" class="nav-item nav-link">Blog</a>
                        <a href="seja-assinante.php" class="nav-item nav-link">Publicidade</a>
                    </ul>
                </div>

            </nav>
        </div>
    </section>
</code>```

I tried everything: text-center, text-align: center, justify-content-center and nothing works.

答:
Just CSS code added. hope this help you.

.navbar-nav {
  text-align: center;
  width: 100%;
  float: left;
  display: inline-block;
}

.nav-link {
  float: none;
  display: inline-block;
  padding:0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="menuNavigation">
  <div class="container-fluid">
    <nav class="navbar navbar-expand-lg">

      <button class="navbar-toggler" type="´button" data-toggle="collapse" data-target="#navbarHeader">
                    <span class="navbar-toggler-icon"></span>
                </button>

      <div class="collapse navbar-collapse" id="navbarHeader">
        <ul class="navbar-nav">
          Uniongs
          Sobre
          Seja Assinante
          Blog
          Publicidade
        </ul>
      </div>

    </nav>
  </div>
</section></code>```

Title: Align navigation bootstrap center

Body:
I want to center align the navigation links from Bootstrap but since I'm not using the list structure, all solutions don't work.

                <button class="navbar-toggler" type="´button" data-toggle="collapse" data-target="#navbarHeader">

                </button>

                        Uniongs
                        Sobre
                        Seja Assinante
                        Blog
                        Publicidade

I tried everything: text-center, text-align: center, justify-content-center and nothing works.

Body:
Just CSS code added. hope this help you.

.navbar-nav {
  text-align: center;
  width: 100%;
  float: left;
  display: inline-block;
}

.nav-link {
  float: none;
  display: inline-block;
  padding:0 10px;
}

<section id="menuNavigation">
  <div class="container-fluid">
    <nav class="navbar navbar-expand-lg">

      <button class="navbar-toggler" type="´button" data-toggle="collapse" data-target="#navbarHeader">
                    <span class="navbar-toggler-icon"></span>
                </button>

      <div class="collapse navbar-collapse" id="navbarHeader">
        <ul class="navbar-nav">
          <a href="index.php" class="nav-item nav-link">Uniongs</a>
          <a href="sobre.php" class="nav-item nav-link">Sobre</a>
          <a href="seja-um-doador.php" class="nav-item nav-link">Seja Assinante</a>
          <a href="blog.php" class="nav-item nav-link">Blog</a>
          <a href="seja-assinante.php" class="nav-item nav-link">Publicidade</a>
        </ul>
      </div>

    </nav>
  </div>
</section>


问:
@RequestParam with any value
I have the following metod in my @Restcontroller:

```<code>@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "phone", required = false) String phone) {

    List<User> userList;
    if ((email != null && !email.isEmpty()) && (phone == null || phone.isEmpty())) {
        userList = super.getByEmail(email);
    } else if ((email == null || email.isEmpty()) && (phone != null)) {
        userList = super.getByPhone(phone);
    } else {
        userList = super.getAll();
    }
    return userList;
}
</code>```

This method allows to handle following GET-requests:

```<code>GET:   /customers/
GET:   /customers?email=emai@email.com
GET:   /customers?phone=8-812-872-23-34
</code>```

But if necessary to add some more parameters for request. If it will be 10 or... 20 params,body of above method arrise outrageously!
If there any way to pass value of @RequestParam to the method-body, I could realize, for example:

```<code>@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "any", required = false) String any) {

    if (value=="email") {
        userList = super.getByEmail(email);
    } else if (value=="email") {
        userList = super.getByPhone(email);
    } else if .....
}
</code>```

Is there any way to use @RequestParam-value in method-body?

答: You can't use single @RequestParam for different name-value on the request. Another way for you can be retrieve all @RequestParam of the request like this aswer</p>

Title: @RequestParam with any value

Body:
I have the following metod in my @Restcontroller:

@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "phone", required = false) String phone) {

    List<User> userList;
    if ((email != null && !email.isEmpty()) && (phone == null || phone.isEmpty())) {
        userList = super.getByEmail(email);
    } else if ((email == null || email.isEmpty()) && (phone != null)) {
        userList = super.getByPhone(phone);
    } else {
        userList = super.getAll();
    }
    return userList;
}

This method allows to handle following GET-requests:

GET:   /customers/
GET:   /customers?email=emai@email.com
GET:   /customers?phone=8-812-872-23-34

But if necessary to add some more parameters for request. If it will be 10 or... 20 params,body of above method arrise outrageously!
If there any way to pass value of @RequestParam to the method-body, I could realize, for example:

@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "any", required = false) String any) {

    if (value=="email") {
        userList = super.getByEmail(email);
    } else if (value=="email") {
        userList = super.getByPhone(email);
    } else if .....
}

Is there any way to use @RequestParam-value in method-body?


问:
binding to observable collection silverlight 4, grid
Can I bind a simple 'grid' to an observable collection? So i have a grid with just one column and several rows. The rows get populated at runtime with some hyperlinks which can get deleted/added etc. I don't want to write functions to add/remove them from the grid everytime and would prefer to use an observable collection and let the grid update itself. Can a simple grid do that ? i tried but it didn't even compile.

Thanks

[EDIT] Solved. The marked answer is correct [/EDIT]

答:
Other answers cover various bases but your specific requirement is filled by the ItemsControl.  You would probably want to contain it in ScrollViewer just in case where you have more links than can be seen at one time.  You would have markup something like this:-

```<code><ScrollViewer>
   <ItemsControl ItemsSource="{Binding MyObsCollectionOfUrlInfo">
       <ItemsControl.ItemTemplate>
          <DataTemplate>
              <HyperLinkButton NavigateUri={Binding Uri} Content={Binding Title} />
          </DataTemplate>
       </ItemsControl.ItemTemplate>
   </ItemsControl>
</ScrollViewer>
</code>```

Your observable collection would contain a list of objects of a type like:-

```<code> public class UrlInfo
 {
      public Uri Uri {get; set; }
      public string Title {get; set; }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Other answers cover various bases but your specific requirement is filled by the ItemsControl.  You would probably want to contain it in ScrollViewer just in case where you have more links than can be seen at one time.  You would have markup something like this:-

<ScrollViewer>
   <ItemsControl ItemsSource="{Binding MyObsCollectionOfUrlInfo">
       <ItemsControl.ItemTemplate>
          <DataTemplate>
              <HyperLinkButton NavigateUri={Binding Uri} Content={Binding Title} />
          </DataTemplate>
       </ItemsControl.ItemTemplate>
   </ItemsControl>
</ScrollViewer>

Your observable collection would contain a list of objects of a type like:-

 public class UrlInfo
 {
      public Uri Uri {get; set; }
      public string Title {get; set; }
 }


问:
Alternative of UNION in sql server
I have 2 tables which contains 5 unique cities each. I want all 10 cities but i don't want to use UNION. Is there any alternative for UNION.</p>

```<code>SELECT DISTINCT CITY FROM TABLE1
UNION
SELECT DISTINCT CITY FROM TABLE2
</code>```

答:
If the first table is sure to contains all the records of the second table, then one can check if the id could be found inside a subquery with an OR clause.

I'm using an ORM framework which doesn't support the UNION operator (Apache OJB) and, with the above assumption, this strategy has proven to be faster than with the use of FULL OUTER JOIN.

For instance if the table STUDENT contains all the students of a province/state with a field for their current main school and another table, STUDENT_SECONDARY_SCHOOL, contains information for those students attending a second school part time, I can get the union of all students attending a particular school either full time or part time this way :

```<code>SELECT STD_ID FROM STUDENT
WHERE
    STD_SCHOOL='the_school'
    OR
    STD_ID IN (SELECT STD_ID FROM STUDENT_SECONDARY_SCHOOL WHERE STD_SCHOOL='the_school')
</code>```

Again, I want to emphasize that this is NOT the equivalent of a UNION but can be useful in some situations.

Title: Alternative of UNION in sql server

Body:
I have 2 tables which contains 5 unique cities each. I want all 10 cities but i don't want to use UNION. Is there any alternative for UNION.

SELECT DISTINCT CITY FROM TABLE1
UNION
SELECT DISTINCT CITY FROM TABLE2

Body:
If the first table is sure to contains all the records of the second table, then one can check if the id could be found inside a subquery with an OR clause.

I'm using an ORM framework which doesn't support the UNION operator (Apache OJB) and, with the above assumption, this strategy has proven to be faster than with the use of FULL OUTER JOIN.

For instance if the table STUDENT contains all the students of a province/state with a field for their current main school and another table, STUDENT_SECONDARY_SCHOOL, contains information for those students attending a second school part time, I can get the union of all students attending a particular school either full time or part time this way :

SELECT STD_ID FROM STUDENT
WHERE
    STD_SCHOOL='the_school'
    OR
    STD_ID IN (SELECT STD_ID FROM STUDENT_SECONDARY_SCHOOL WHERE STD_SCHOOL='the_school')

Again, I want to emphasize that this is NOT the equivalent of a UNION but can be useful in some situations.


问:
transfer ownership and billing of storage buckets
I am currently hosting several cloud storage buckets with archived data for some of my clients.
For one client I would like to transfer the ownership and subsequent billing of multiple storage buckets to that client, but continue to administer them myself.

The buckets in question are already in their own (the clients name) project, but the are all hosted within my company domain.

How would I go about that transfer? Does my client need to create their own company domain and I then somehow transfer the project to them? Or do they get user access within my company domain and get a separate billing instance within my company domain?

It all a bit confusing to me.

答:
Buckets are owned by the Project ID. Objects within the bucket are owned by the IAM Member ID that created the objects.

Billing for buckets is controlled by the Project ID. If the customer already owns the project (which can be changed), all you need to do is change the billing account for the project.

You can continue to have access by granting your IAM Member ID access to the bucket and its objects.

Access to a bucket and its contents via a domain name is not a Cloud Storage issue. This is controlled via the HTTP(S) Load Balancer. You can domain transfer the domain to the customer via normal registrar transfer procedures. Ownership of the domain will not affect the load balancer. The project that owns the load balancer will, so you may need to recreate it to transfer billing responsibility.


问:
Regex match character only when NOT preceeded by specific word
The goal is to have regex match all newline character which are not preceded by a 2-decimal number. Here's some example text:

```<code>This line ends with text
this line ends with a number: 55
this line ends with a 2-decimal number: 5.00
here's 22.22, not at the end of the line
</code>```

Regex should match the end of lines 1, 2, and 4 (assuming a newline after the 4th line).  I thought negative lookahead was the answer so I tried

```<code>(?!\d*\.\d\d)\n
</code>```

without success as seen in this regex101 snippet: https://regex101.com/r/qbrKlt/4

<s>Edit: I later discovered the reason this didn't work is because Python's Regex doesn't support variable length negative lookahead - it only supports fixed-length negative lookahead.</s>

Unfortunately fixed-length look-ahead still didnt work:

```<code>(?!\.\d\d)\n
</code>```

Instead I did a workaround by running regex twice & subtracting the result:

find all indices of newline characters: \n

find all indices of newline characters preceded by 2-decimal numbers: \d*\.\d\d\n

remove indices found in step 2 from those found in step 1 for the answer

But I'm sure there's a way to do this in 1 go and I'd be grateful to anyone out there that can help in discovering the solution :)

答: Why get esoteric with regexes, when you can just capture the final word using string.split()[-1] and test that for the form you need?  Python isn't Perl (fortunately).</p>

Body:
The goal is to have regex match all newline character which are not preceded by a 2-decimal number. Here's some example text:

This line ends with text
this line ends with a number: 55
this line ends with a 2-decimal number: 5.00
here's 22.22, not at the end of the line

Regex should match the end of lines 1, 2, and 4 (assuming a newline after the 4th line).  I thought negative lookahead was the answer so I tried

(?!\d*\.\d\d)\n

without success as seen in this regex101 snippet: https://regex101.com/r/qbrKlt/4

<s>Edit: I later discovered the reason this didn't work is because Python's Regex doesn't support variable length negative lookahead - it only supports fixed-length negative lookahead.</s>

Unfortunately fixed-length look-ahead still didnt work:

(?!\.\d\d)\n

Instead I did a workaround by running regex twice & subtracting the result:

find all indices of newline characters: \n

find all indices of newline characters preceded by 2-decimal numbers: \d*\.\d\d\n

remove indices found in step 2 from those found in step 1 for the answer

But I'm sure there's a way to do this in 1 go and I'd be grateful to anyone out there that can help in discovering the solution :)


问:
What is Read ONLY Role to give to Oracle developers to veiw the Flashback Data via versions Query
I have created Oracle FDA and its tracking the DMLS on the tables but can i know if there is a specific role that could be granted to users to view the data using VERSIONS BETWEEN Query

GRANT FLASHBACK ANY TABLE or GRAN FLASHBACK on tblname seems to have access to flashack the table as well.
Is there a way for a user to just view the data using Query

答:
The documentation provides this information

To flash back a table to an earlier SCN or timestamp, you must have either the FLASHBACK object privilege on the table or the FLASHBACK ANY TABLE system privilege. In addition, you must have the SELECT, INSERT, DELETE, and ALTER object privileges on the table.

So if you grant only SELECT and FLASHBACK on a table, the granted user is allowed to make a flashback query, but is not allowed to FLASHBACK the table.

The attempt of FLASHBACK TABLE will fail with

```<code> ORA-01031: insufficient privileges
</code>```

Body:
The documentation provides this information

To flash back a table to an earlier SCN or timestamp, you must have either the FLASHBACK object privilege on the table or the FLASHBACK ANY TABLE system privilege. In addition, you must have the SELECT, INSERT, DELETE, and ALTER object privileges on the table.

So if you grant only SELECT and FLASHBACK on a table, the granted user is allowed to make a flashback query, but is not allowed to FLASHBACK the table.

The attempt of FLASHBACK TABLE will fail with

 ORA-01031: insufficient privileges


问:
Python: why for loop is in the middle of join() function?
I don't understand the following code in the return statement. How come a for loop is inside a built-in function, join(), and not at the beginning in the middle of statement?

How is this working?

```<code>def randomString(stringLength=10):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))
</code>```

答:
It basically loops over it stringLength time and in every loop sends a character to inside the parameter, which then add up next to each other

```<code>return ''.join(random.choice(letters) for i in range(stringLength))
</code>```

It adds some stuff right next to the string ''

```<code>OUTPUT

>>> ayyertffds
</code>```

Body:
I don't understand the following code in the return statement. How come a for loop is inside a built-in function, join(), and not at the beginning in the middle of statement?

How is this working?

def randomString(stringLength=10):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))

Body:
It basically loops over it stringLength time and in every loop sends a character to inside the parameter, which then add up next to each other

return ''.join(random.choice(letters) for i in range(stringLength))

It adds some stuff right next to the string ''

OUTPUT

>>> ayyertffds


问:
Pandas: Summation on date range with a startdate and enddate
I'm trying to create a DataFrame so I can analyse how often a uID has been active in a certain time period.

I have a input DataFrame as follows:

```<code>uID   startdate     stopdate      active_sub
1    01-01-2019     31-01-2019    1
2    01-02-2019     31-12-2019    1
1    15-01-2019     31-12-2019    1
3    01-06-2019     31-11-2019    1
</code>```

What I'm trying to achieve is to get a DataFrame for each Date and uID that has a summation on active subscriptions for each user.

```<code>Date        uID:1  uID:2  uID:3
01-01-2019  1      0      0
02-01-2019  1      0      0
03-01-2019  1      0      0
...
15-01-2019  2      0      0   #uID:1  has 2 active subcriptions on this day
...
31-12-2019  1      1      1
</code>```

I have the following code that is working, but not for duplicate uID's. The input dataset is large and has a lot of duplicated uID's.

```<code>#Create date dataframe
df = pd.DataFrame(
    index = pd.date_range('01-01-2019', '31-12-2019').normalize(),
    columns = input_df['uID']
)

for row in input_df.iterrows():
    df[row[1][0]].loc[row[1][1]] = 1 #StartDate
    df[row[1][0]].loc[row[1][2]] = 0 #EndDate
    df[row[1][0]] = df[row[1][0]].fillna(method= 'ffill')

df = df.fillna(0)

</code>```

Is there a quick fix possible or is there another way to quickly achieve this desired dataframe?

答:
First, please note that date "31-11-2019" simply does not exists :-)
However after fixing this error, maybe this is what is required to do:

```<code>from io import StringIO
import pandas as pd
data = (
'uID   startdate     stopdate      active_sub\n'
'1    01-01-2019     31-01-2019    1\n'
'2    01-02-2019     31-12-2019    1\n'
'1    15-01-2019     31-12-2019    1\n'
'3    01-06-2019     30-11-2019    1\n')

df = pd.read_fwf(StringIO(data))

df['startdate'] = pd.to_datetime(df['startdate'], format='%d-%m-%Y')
df['stopdate'] = pd.to_datetime(df['stopdate'], format='%d-%m-%Y')
df['uID'] = df['uID'].astype(str)

df_result = df.apply(lambda x: pd.Series(x['uID'],
                             index=pd.date_range(x['startdate'].floor('D'),
                                                 x['stopdate'].ceil('D'),
                                                 freq='D')), axis=1)\
  .stack().str.get_dummies().reset_index(level=0, drop=True)

df_result2 = df_result.groupby(df_result.index).agg(sum)
</code>```

Body:
I'm trying to create a DataFrame so I can analyse how often a uID has been active in a certain time period.

I have a input DataFrame as follows:

uID   startdate     stopdate      active_sub
1    01-01-2019     31-01-2019    1
2    01-02-2019     31-12-2019    1
1    15-01-2019     31-12-2019    1
3    01-06-2019     31-11-2019    1

What I'm trying to achieve is to get a DataFrame for each Date and uID that has a summation on active subscriptions for each user.

Date        uID:1  uID:2  uID:3
01-01-2019  1      0      0
02-01-2019  1      0      0
03-01-2019  1      0      0
...
15-01-2019  2      0      0   #uID:1  has 2 active subcriptions on this day
...
31-12-2019  1      1      1

I have the following code that is working, but not for duplicate uID's. The input dataset is large and has a lot of duplicated uID's.

#Create date dataframe
df = pd.DataFrame(
    index = pd.date_range('01-01-2019', '31-12-2019').normalize(),
    columns = input_df['uID']
)

for row in input_df.iterrows():
    df[row[1][0]].loc[row[1][1]] = 1 #StartDate
    df[row[1][0]].loc[row[1][2]] = 0 #EndDate
    df[row[1][0]] = df[row[1][0]].fillna(method= 'ffill')

df = df.fillna(0)

Is there a quick fix possible or is there another way to quickly achieve this desired dataframe?

Body:
First, please note that date "31-11-2019" simply does not exists :-)
However after fixing this error, maybe this is what is required to do:

from io import StringIO
import pandas as pd
data = (
'uID   startdate     stopdate      active_sub\n'
'1    01-01-2019     31-01-2019    1\n'
'2    01-02-2019     31-12-2019    1\n'
'1    15-01-2019     31-12-2019    1\n'
'3    01-06-2019     30-11-2019    1\n')

df = pd.read_fwf(StringIO(data))

df['startdate'] = pd.to_datetime(df['startdate'], format='%d-%m-%Y')
df['stopdate'] = pd.to_datetime(df['stopdate'], format='%d-%m-%Y')
df['uID'] = df['uID'].astype(str)

df_result = df.apply(lambda x: pd.Series(x['uID'],
                             index=pd.date_range(x['startdate'].floor('D'),
                                                 x['stopdate'].ceil('D'),
                                                 freq='D')), axis=1)\
  .stack().str.get_dummies().reset_index(level=0, drop=True)

df_result2 = df_result.groupby(df_result.index).agg(sum)


问:
Linq replace values until first X value
I have a list:

```<code>var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
</code>```

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

```<code>var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)
</code>```

Actual Result:

```<code>{null,null,null,null,null,null,null,5,6,3,0,null,null,3}
</code>```

Expected Result:

```<code>{null,null,null,null,null,null,4,5,6,3,0,0,2,3}
</code>```

MRE:

```<code>public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}
</code>```

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

答:
One way to achieve this in Linq is to build a ReplaceWhile function:

Count how many element match your condition.

While you didnt reach the position replace with the subsitute.

Code:

```<code>public static IEnumerable<T> ReplaceWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, T substitute)
{
    var zerosLength = source.TakeWhile(predicate).Count();
    return source.Select((x, i) => i >= zerosLength ? x : substitute);
}
</code>```

Try it Online!

Title: Linq replace values until first X value

Body:
I have a list:

var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)

Actual Result:

{null,null,null,null,null,null,null,5,6,3,0,null,null,3}

Expected Result:

{null,null,null,null,null,null,4,5,6,3,0,0,2,3}

MRE:

public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

Body:
One way to achieve this in Linq is to build a ReplaceWhile function:

Count how many element match your condition.

While you didnt reach the position replace with the subsitute.

Code:

public static IEnumerable<T> ReplaceWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, T substitute)
{
    var zerosLength = source.TakeWhile(predicate).Count();
    return source.Select((x, i) => i >= zerosLength ? x : substitute);
}

Try it Online!


问:
How to scan DynamoDB table for retrieving only one item in each partition key
Let say I have a table with partition key "ID" and range key "Time" with the following items:

```<code>ID  | Time | Data
------------------
A   | 1    | abc
A   | 2    | def
B   | 2    | ghi
B   | 3    | jkl
</code>```

And I want to scan only one item in each partition that has the highest time value in each partition. So the outcome of the scan should look like:

```<code>ID  | Time | Data
------------------
A   | 2    | def
B   | 3    | jkl
</code>```

Is this possible with the DynamoDB's scan feature?
(I want to avoid scan all and do such filtering by myself).

答:
If you want to fetch just a few IDs along with their highest Time, you can query with reverse index, so for every ID, you will have only 1 item read. But for this you need an existing list of IDs.

So for each ID, there will be:

1 query

1 item read

Otherwise, the only way is to scan everything unfortunately.

Body:
Let say I have a table with partition key "ID" and range key "Time" with the following items:

ID  | Time | Data
------------------
A   | 1    | abc
A   | 2    | def
B   | 2    | ghi
B   | 3    | jkl

And I want to scan only one item in each partition that has the highest time value in each partition. So the outcome of the scan should look like:

ID  | Time | Data
------------------
A   | 2    | def
B   | 3    | jkl

Is this possible with the DynamoDB's scan feature?
(I want to avoid scan all and do such filtering by myself).


问:
Biopython gives ValueError: Sequences must all be the same length even though sequences are of the same length
I'm trying to create a phylogenetic tree by making a .phy file from my data.

I have a dataframe

ndf=

ESV      trunc

1  esv1    TACGTAGGTG...

2  esv2    TACGGAGGGT...

3  esv3    TACGGGGGG...

7  esv7    TACGTAGGGT...

I checked the length of the elements of the column "trunc":

length_checker = np.vectorize(len)

arr_len = length_checker(ndf['trunc'])

The resulting arr_len gives the same length (=253) for all the elements.

I saved this dataframe as .phy file, which looks like this:

23  253

esv1    TACGTAGGTGGCGAGCGTTATCCGGAATTATTGGGCGTAAAGCGCGCGCAGGCGGTTTCTTAAGTCTGATGTGAAAGCCCACGGCTCAACCGTGGAGGGTCATTGGAAACTGGGAAACTTGAGTGCAGAAGAGGAAAGCGGAATTCCACGTGTAGCGGTGAAATGCGTAGAGATGTGGAGGAACACCAGTGGCGAAGGCGGCTTTCTGGTCTGTAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG

esv2    TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG

esv3    TACGGGGGGGGCAAGCGTTGTTCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGCCAGACCAAGTCGAGTGTGAAATTGCAGGGCTTAACTTTGCAGGGTCGCTCGATACTGGTCGGCTAGAGTGTGGAAGAGGGTACTGGAATTCCCGGTGTAGCGGTGAAATGCGTAGATATCGGGAGGAACACCAGCGGCGAAGGCGGGTACCTGGGCCAACACTGACGCTGAGGCGCGAAAGCTAGGGGAGCAAACAG

This is similar to the file used in this tutorial.

However, when I run the command
aln = AlignIO.read('msa.phy', 'phylip')

I get "ValueError: Sequences must all be the same length"

I don't know why I'm getting this or how to fix it. Any help is greatly appreciated!

Thanks

答:
Generally phylip is the fiddliest format in phylogenetics between different programs. There is strict phylip format and relaxed phylip format etc ... t is not easy to know which is the separator being used, a space character and/or a carriage return.

I think that you appear to have left a space between the name of the taxon (i.e. the sequence label) and sequence name, viz.

```<code>2. esv2
</code>```

Phylip format is watching for the space between the label and the sequence data. In this example the sequence would be 3bp long. The use of a "." is generally not a great idea as well. The integer doesn't appear to denote a line number.

The other issue is you could/should try keeping the sequence on the same line as the label and remove the carriage return, viz.

```<code>esv2 TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG
</code>```

Sometimes a carriage return does work (this could be relaxed phylip format), the traditional format uses a space character " ". I always maintained a uniform number of spaces to preserve the alignment ... not sure if that is needed.

Note if you taxon name exceeeds 10 characters you will need relaxed phylip format and this format in any case is generally a good idea.

The final solution is all else fails is to convert to fasta, import as fasta and then convert to phylip. If all this fails ... post back there's more trouble-shooting

Fasta format removes the "23 254" header and then each sequence looks like this,

```<code>>esv2
TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG
</code>```

There is always a carriage return between ">esv2" and the sequence. In addition, ">" is always present to prefix the label (taxon name) without any spae. You can simply convert via reg-ex or "re" in Python. Using a perl one-liner it will be s/^([az]+[0-9]+)/>$1/g type code. I'm pretty sure they'll be an online website that will do this.

You then simply replace the "phylip" with "fasta" in your import command. Once imported you ask BioPython to convert to whatever format you want and it should not have any problem.

Body:
Generally phylip is the fiddliest format in phylogenetics between different programs. There is strict phylip format and relaxed phylip format etc ... t is not easy to know which is the separator being used, a space character and/or a carriage return.

I think that you appear to have left a space between the name of the taxon (i.e. the sequence label) and sequence name, viz.

2. esv2

Phylip format is watching for the space between the label and the sequence data. In this example the sequence would be 3bp long. The use of a "." is generally not a great idea as well. The integer doesn't appear to denote a line number.

The other issue is you could/should try keeping the sequence on the same line as the label and remove the carriage return, viz.

esv2 TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG

Sometimes a carriage return does work (this could be relaxed phylip format), the traditional format uses a space character " ". I always maintained a uniform number of spaces to preserve the alignment ... not sure if that is needed.

Note if you taxon name exceeeds 10 characters you will need relaxed phylip format and this format in any case is generally a good idea.

The final solution is all else fails is to convert to fasta, import as fasta and then convert to phylip. If all this fails ... post back there's more trouble-shooting

Fasta format removes the "23 254" header and then each sequence looks like this,

>esv2
TACGGAGGGTGCAAGCGTTATCCGGATTCACTGGGTTTAAAGGGTGCGTAGGTGGGTTGGTAAGTCAGTGGTGAAATCTCCGAGCTTAACTTGGAAACTGCCATTGATACTATTAATCTTGAATATTGTGGAGGTTAGCGGAATATGTCATGTAGCGGTGAAATGCTTAGAGATGACATAGAACACCAATTGCGAAGGCAGCTGGCTACACATATATTGACACTGAGGCACGAAAGCGTGGGGATCAAACAGG

There is always a carriage return between ">esv2" and the sequence. In addition, ">" is always present to prefix the label (taxon name) without any spae. You can simply convert via reg-ex or "re" in Python. Using a perl one-liner it will be s/^([az]+[0-9]+)/>$1/g type code. I'm pretty sure they'll be an online website that will do this.

You then simply replace the "phylip" with "fasta" in your import command. Once imported you ask BioPython to convert to whatever format you want and it should not have any problem.


问:
PostGIS Geometry saving: "Invalid endian flag value encountered."
I have a Spring Roo + Hibernate project which takes a JTS well-known text (WKT) String input from the client application, converts it into a JTS Geometry object, and then attempts to write it to the PostGIS database. I had some problems with the JDBC connection and types, but these seem to have been resolved with:

```<code>@Column(columnDefinition = "Geometry", nullable = true)
private Geometry centerPoint;
</code>```

And the conversion does:

```<code>Geometry geom = new WKTReader(new GeometryFactory(new PrecisionModel(), 4326)).read(source);
</code>```

However now when Hibernate tries to write my Geometry object to the database, I get an error:

```<code>2012-08-31 21:44:14,096 [tomcat-http--18] ERROR org.hibernate.util.JDBCExceptionReporter - Batch entry 0 insert into land_use (center_point, version, id) values ('<stream of 1152 bytes>', '0', '1') was aborted.  Call getNextException to see the cause.
2012-08-31 21:44:14,096 [tomcat-http--18] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: Invalid endian flag value encountered.
</code>```

It seems clear that the error is related to the binary representation, which is presumably generated as a well-known binary (WKB) with some endianness. However with Hibernate hiding all the persistence away, I can't really tell which way things are going.

I've been fighting this Geometry stuff for days, and there's very little information out there on these error, so does anyone have any bright ideas? Can I specify the endianness somewhere (Hibernate or PostGIS), or perhaps store in a different format (WKT)?

EDIT: I should also mention that I'm using the newest of everything, which generally seems to be compatible:

Spring 3.1.1, Roo 1.2.1

hibernate 3.6.9

hibernate-spatial 4.0-M1

jts 1.12

PostgreSQL 9.1

postgis-jdbc 1.5.3 (not the latest, but recommended for hibernate-spatial, compiled from source)

postgis-jdbc 2.0.1 (just tried this now to match the version installed with PostgreSQL, same problem)

The Hibernate Spatial 4 tutorial suggests I do the property annotation as:

```<code>@Type(type="org.hibernate.spatial.GeometryType")
private Geometry centerPoint;
</code>```

... but when I do this I get this other error, which the current annotation resolves.

答:
After some fight with given problem here are steps that helped me to solve it.
First I should mention I'm using WildFly 17 server, PostgreSQL 12 and PostGIS 3.0.0.
And now steps that I think are important in this problem:

Make jboss-deployment-structure.xml file in META-INF (if you don't have one), and exclude hibernate that comes with WildFly

```<code><jboss-deployment-structure>
    <deployment>
        <exclusions>
            <module name="org.hibernate" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>
</code>```

In your pom.xml add dependencies

```<code><dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    <version>5.4.12.Final</version>
</dependency>
</code>```

and

```<code><dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-spatial</artifactId>
    <version>5.4.12.Final</version>
</dependency>
</code>```

Make sure that hibernate core and hibernate spatial have same version (use whatever version you like).

Your persistence.xml should have property

```<code><property name="hibernate.dialect" value="org.hibernate.spatial.dialect.postgis.PostgisDialect"/>
</code>```

And finally, I don't think this is very important but I used org.locationtech.jts for geometry in Java.

I hope I didn't skip anything important and that these are required steps. It is possible that there is something else, but many hours have passed in trying different solutions and it is possible that I forgot to include some dependency/property. Answer is based on personal experience, therefore feel free to comment, to prove me wrong or to expand answer. Anyhow I hope someone will find this answer useful.

Body:
I have a Spring Roo + Hibernate project which takes a JTS well-known text (WKT) String input from the client application, converts it into a JTS Geometry object, and then attempts to write it to the PostGIS database. I had some problems with the JDBC connection and types, but these seem to have been resolved with:

@Column(columnDefinition = "Geometry", nullable = true)
private Geometry centerPoint;

And the conversion does:

Geometry geom = new WKTReader(new GeometryFactory(new PrecisionModel(), 4326)).read(source);

However now when Hibernate tries to write my Geometry object to the database, I get an error:

2012-08-31 21:44:14,096 [tomcat-http--18] ERROR org.hibernate.util.JDBCExceptionReporter - Batch entry 0 insert into land_use (center_point, version, id) values ('<stream of 1152 bytes>', '0', '1') was aborted.  Call getNextException to see the cause.
2012-08-31 21:44:14,096 [tomcat-http--18] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: Invalid endian flag value encountered.

It seems clear that the error is related to the binary representation, which is presumably generated as a well-known binary (WKB) with some endianness. However with Hibernate hiding all the persistence away, I can't really tell which way things are going.

I've been fighting this Geometry stuff for days, and there's very little information out there on these error, so does anyone have any bright ideas? Can I specify the endianness somewhere (Hibernate or PostGIS), or perhaps store in a different format (WKT)?

EDIT: I should also mention that I'm using the newest of everything, which generally seems to be compatible:

Spring 3.1.1, Roo 1.2.1

hibernate 3.6.9

hibernate-spatial 4.0-M1

jts 1.12

PostgreSQL 9.1

postgis-jdbc 1.5.3 (not the latest, but recommended for hibernate-spatial, compiled from source)

postgis-jdbc 2.0.1 (just tried this now to match the version installed with PostgreSQL, same problem)

The Hibernate Spatial 4 tutorial suggests I do the property annotation as:

@Type(type="org.hibernate.spatial.GeometryType")
private Geometry centerPoint;

... but when I do this I get this other error, which the current annotation resolves.

Body:
After some fight with given problem here are steps that helped me to solve it.
First I should mention I'm using WildFly 17 server, PostgreSQL 12 and PostGIS 3.0.0.
And now steps that I think are important in this problem:

Make jboss-deployment-structure.xml file in META-INF (if you don't have one), and exclude hibernate that comes with WildFly

<jboss-deployment-structure>
    <deployment>
        <exclusions>
            <module name="org.hibernate" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>

In your pom.xml add dependencies

<dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    <version>5.4.12.Final</version>
</dependency>

and

<dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-spatial</artifactId>
    <version>5.4.12.Final</version>
</dependency>

Make sure that hibernate core and hibernate spatial have same version (use whatever version you like).

Your persistence.xml should have property

<property name="hibernate.dialect" value="org.hibernate.spatial.dialect.postgis.PostgisDialect"/>

And finally, I don't think this is very important but I used org.locationtech.jts for geometry in Java.

I hope I didn't skip anything important and that these are required steps. It is possible that there is something else, but many hours have passed in trying different solutions and it is possible that I forgot to include some dependency/property. Answer is based on personal experience, therefore feel free to comment, to prove me wrong or to expand answer. Anyhow I hope someone will find this answer useful.


问:
How do I round millions and thousands in JavaScript?
I am trying to round large digits. For instance, if I have this number:

12,645,982

I want to round this number and display it as:

13 mil

Or, if I have this number:

1,345

I want to round it and display it as:

1 thousand

How do I do this in JavaScript or jQuery?

答:
Paul Sweatte's answer is good

Deepak Thomas's answer is nice

My answer is way more flexible/customizable and easier to read, so here goes:

Code

function NumbFormat(options) {

  let number = Math.abs(Number(options.number));

  // Nine zeros for Billions
  if (Number(number) >= 1.0e+9) {
    return (number / 1.0e+9).toFixed(options.billion.decimal) + ` ${options.billion.unit}`;
  }

  // Six zeros for Millions
  if (Number(number) >= 1.0e+6) {
    return (number / 1.0e+6).toFixed(options.million.decimal) + ` ${options.million.unit}`;
  }

  // Thrhee zeros for Thousands
  if (Number(number) >= 1.0e+3) {
    return (number / 1.0e+3).toFixed(options.thousand.decimal) + ` ${options.thousand.unit}`;
  }

  return number;
}

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));```

With the above code you are in control of how many decimals you want for billions, millions or thousands, you are also in control of which unit you wish to display :)

Body:
Paul Sweatte's answer is good

Deepak Thomas's answer is nice

My answer is way more flexible/customizable and easier to read, so here goes:

Code

function NumbFormat(options) {

  let number = Math.abs(Number(options.number));

  // Nine zeros for Billions
  if (Number(number) >= 1.0e+9) {
    return (number / 1.0e+9).toFixed(options.billion.decimal) + ` ${options.billion.unit}`;
  }

  // Six zeros for Millions
  if (Number(number) >= 1.0e+6) {
    return (number / 1.0e+6).toFixed(options.million.decimal) + ` ${options.million.unit}`;
  }

  // Thrhee zeros for Thousands
  if (Number(number) >= 1.0e+3) {
    return (number / 1.0e+3).toFixed(options.thousand.decimal) + ` ${options.thousand.unit}`;
  }

  return number;
}

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

With the above code you are in control of how many decimals you want for billions, millions or thousands, you are also in control of which unit you wish to display :)


问:
How to get all submitted MultipartFiles, regardless of their name
I would like a user to be able to submit any number of files with arbitrary name and origfilename.

How would one get a list of submitted files in a request?

```<code>@RequestParam(name = "*") MultipartFile[] files
</code>```

I was hoping using regex or similar in name parameter would work, but all my testing failed.

Equivalent in Flask would be

```<code>request.files
</code>```

Any ideas?

答:
Related question: Getting files in controller without @RequestParam name

You can get requested multipart files by using MultipartRequest#getFileMap like this:

```<code>MultipartRequest multipartRequest = .....
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);
...
</code>```

Also you can get all the files by using MultipartRequest#getMultiFileMap even when the same parameter name is assigned to multiple files for example:

```<code>    <input type="file" name="file1"/>file1
    <input type="file" name="file2"/>file2
    <input type="file" name="file2"/>file2X
</code>```

Spring's DispatcherServlet/MultipartFilter wraps HttpServletRequest object in MultipartHttpServletRequest(extending MultipartRequest) object when you send a multipart/form-data with a request and MultipartRequest can be a controller's method argument.

So your controller's method will be something like this:

```<code>    @RequestMapping("upload")
    public String upload(MultipartRequest multipartRequest) {

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);

        // Use when the same parameter name is assigned to multiple files.
        // MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        // MultipartFile[] files = multiFileMap.values().stream().flatMap(values -> values.stream()).toArray(MultipartFile[]::new);

        for (MultipartFile multipartFile : files) {
            System.out.println("param name: " + multipartFile.getName());
            System.out.println("filename: " + multipartFile.getOriginalFilename());
            System.out.println("size: " + multipartFile.getSize());

        }

        return ".....";
    }
</code>```

When you send '1.jpg'(parameter name is 'file1') and '2.jpg'(parameter name is 'file2'), you get the output like this:

```<code>param name: file1
filename: 1.jpg
size: 155152
param name: file2
filename: 2.jpg
size: 154015
</code>```

[UPDATE]

I have found a more simple solution. Map<String, MultipartFile>/MultiValueMap<String, MultipartFile>can also be a controller's method argument with @RequestParam annotation whose name attribute is empty.
Therefore you can simplify the controller's method like this:

```<code>@RequestMapping("upload")
public String upload(@RequestParam Map<String, MultipartFile> fileMap) {
    MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);
    .......
    return ......
}
</code>```

or

```<code>@RequestMapping("upload")
public String upload(@RequestParam MultiValueMap<String, MultipartFile> multiFileMap) {

    MultipartFile[] files = multiFileMap.values().stream().flatMap(values -> values.stream())
            .toArray(MultipartFile[]::new);
     .......
     return ......
}
</code>```

See Also

Javadoc of DispatcherServlet#checkMultipart

Javadoc of MultipartFilter

Javadoc of MultipartResolver#resolveMultipart

Javadoc of MultipartHttpServletRequest

Javadoc of RequestParamMapMethodArgumentResolver[UPDATE]

Body:
I would like a user to be able to submit any number of files with arbitrary name and origfilename.

How would one get a list of submitted files in a request?

@RequestParam(name = "*") MultipartFile[] files

I was hoping using regex or similar in name parameter would work, but all my testing failed.

Equivalent in Flask would be

request.files

Any ideas?

Body:
Related question: Getting files in controller without @RequestParam name

You can get requested multipart files by using MultipartRequest#getFileMap like this:

MultipartRequest multipartRequest = .....
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);
...

Also you can get all the files by using MultipartRequest#getMultiFileMap even when the same parameter name is assigned to multiple files for example:

    <input type="file" name="file1"/>file1
    <input type="file" name="file2"/>file2
    <input type="file" name="file2"/>file2X

Spring's DispatcherServlet/MultipartFilter wraps HttpServletRequest object in MultipartHttpServletRequest(extending MultipartRequest) object when you send a multipart/form-data with a request and MultipartRequest can be a controller's method argument.

So your controller's method will be something like this:

    @RequestMapping("upload")
    public String upload(MultipartRequest multipartRequest) {

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);

        // Use when the same parameter name is assigned to multiple files.
        // MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
        // MultipartFile[] files = multiFileMap.values().stream().flatMap(values -> values.stream()).toArray(MultipartFile[]::new);

        for (MultipartFile multipartFile : files) {
            System.out.println("param name: " + multipartFile.getName());
            System.out.println("filename: " + multipartFile.getOriginalFilename());
            System.out.println("size: " + multipartFile.getSize());

        }

        return ".....";
    }

When you send '1.jpg'(parameter name is 'file1') and '2.jpg'(parameter name is 'file2'), you get the output like this:

param name: file1
filename: 1.jpg
size: 155152
param name: file2
filename: 2.jpg
size: 154015

[UPDATE]

I have found a more simple solution. Map<String, MultipartFile>/MultiValueMap<String, MultipartFile>can also be a controller's method argument with @RequestParam annotation whose name attribute is empty.
Therefore you can simplify the controller's method like this:

@RequestMapping("upload")
public String upload(@RequestParam Map<String, MultipartFile> fileMap) {
    MultipartFile[] files = fileMap.values().toArray(new MultipartFile[0]);
    .......
    return ......
}

or

@RequestMapping("upload")
public String upload(@RequestParam MultiValueMap<String, MultipartFile> multiFileMap) {

    MultipartFile[] files = multiFileMap.values().stream().flatMap(values -> values.stream())
            .toArray(MultipartFile[]::new);
     .......
     return ......
}

See Also

Javadoc of DispatcherServlet#checkMultipart

Javadoc of MultipartFilter

Javadoc of MultipartResolver#resolveMultipart

Javadoc of MultipartHttpServletRequest

Javadoc of RequestParamMapMethodArgumentResolver[UPDATE]


问:
How to Connect EC2 Instance with VSCode Directly using pem file in SFTP
I'm trying to connect EC2 Instance directly from VS Code using SFTP. I can able to connect other ftp service using [password] type, but for EC2 instance i'm having only .pem file.
Expecting something like this but using public key .pem file </p>

```<code>{
"protocol": "sftp",
"host": "localhost",
"port": 22,
"username": "username",
"remotePath": "/"
}
</code>```

答:
If you want to connect your VS Code to AWS EC2, use the Remote Development extension pack (if it's not installed already). The .pem private key file and the standard SSH config (extensionless text file) will reside at:

C:\Users\YourName\.ssh\aws-example-user.pem

C:\Users\YourName\.ssh\config

Make the latter have contents like this:

```<code>Host aws-ec2
     HostName example.dev
     User example
     IdentityFile "C:\Users\YourName\.ssh\aws-example-user.pem"
</code>```

You can specify nonstandard port by Port 2222 and HostName can be an IP address (on AWS fixed IPs are called elastic). The key file (sometimes extensionless) has the words PRIVATE KEY in it. New: use the ed25519 type of key if it fails to connect. This is not just for AWS EC2, but any similar system such as Ubuntu in a VM or even a Raspberry Pi.

PS: I wrote an article detailing the whole VS Code to AWS EC2 setup.

Side note: VS Code server needs about 2GB of RAM to run smoothly, if you have less, try zram.

Body:
I'm trying to connect EC2 Instance directly from VS Code using SFTP. I can able to connect other ftp service using [password] type, but for EC2 instance i'm having only .pem file.
Expecting something like this but using public key .pem file

{
"protocol": "sftp",
"host": "localhost",
"port": 22,
"username": "username",
"remotePath": "/"
}

Body:
If you want to connect your VS Code to AWS EC2, use the Remote Development extension pack (if it's not installed already). The .pem private key file and the standard SSH config (extensionless text file) will reside at:

C:\Users\YourName\.ssh\aws-example-user.pem

C:\Users\YourName\.ssh\config

Make the latter have contents like this:

Host aws-ec2
     HostName example.dev
     User example
     IdentityFile "C:\Users\YourName\.ssh\aws-example-user.pem"

You can specify nonstandard port by Port 2222 and HostName can be an IP address (on AWS fixed IPs are called elastic). The key file (sometimes extensionless) has the words PRIVATE KEY in it. New: use the ed25519 type of key if it fails to connect. This is not just for AWS EC2, but any similar system such as Ubuntu in a VM or even a Raspberry Pi.

PS: I wrote an article detailing the whole VS Code to AWS EC2 setup.

Side note: VS Code server needs about 2GB of RAM to run smoothly, if you have less, try zram.


问:
Flutter listview not updating after data update
I have a ListView inside a bottomSheet, that is built using an array of elements. Currently I have one item in there "empty" which is then .clear()ed and populated after an async DB call.

The variable update is correct, and I try to use setState((){}) but the ListView isn't updated at all. I need to close the bottomSheet, reopen it, and the ListView then has the correct items.

Do I need to just call setState or does the bottomSheet builder need to be flagged to update?

Main ListView section:

```<code> @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Map'),
          backgroundColor: Colors.green[700],
        ),

        //Put in a stack widget so can layer other widgets on top of map widget
        body: Stack(
          children: <Widget>[
            GoogleMap(
              mapType: _currentMapType,
              markers: _markers,
              onMapCreated: _onMapCreated,
              onCameraMove: _onCameraMove,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          ...
                      ),

                    ),

                    SizedBox(width: 16.0),

                    FloatingActionButton(
                      ...
                    ),

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.file_download, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {
                            showBottomSheet(
                                context: context,
                                builder: (context) {
                                  return ListView(
                                    padding: EdgeInsets.all(15.0),
                                    children: <Widget>[

                                         ...

                                      Divider(),

                                      ListTile(
                                        title: Text("Remote JSON Download"),
                                        trailing:
                                        Icon(Icons.refresh),
                                        selected: true,
                                        onTap: _OnPressedReloadJSON,               <-------------
                                      ),

                                      Divider(),

                                      Container(
                                        height: 150.0,
                                        child: ListView.builder(               <-------------
                                          scrollDirection: Axis.horizontal,

                                          itemCount : testList.length,
                                          itemBuilder: (BuildContext context, int index) {
                                              return Container(
                                                padding: EdgeInsets.all(5.0),
                                                margin: EdgeInsets.all(5.0),
                                                width: 150.0,
                                                color: Colors.red,
                                                child: Text(testList[index]),
                                              );
                                          },

                                        ),
                                      ),
</code>```

Async Get:

```<code>class _MyAppState extends State<MyApp> {

  ...

  _OnPressedReloadJSON() {
    fetchJSONAndMakeListTile();
  }

  ...

  List<String> testList= ["empty"];

  Future<http.Response> fetchJSONAndMakeListTile() async {
    final response = await http.get('https://..... file.json');

    // If the server did return a 200 OK response, then parse the JSON.
    if (response.statusCode == 200) {
      List<db_manager.MyObject> myObjects = (json.decode(response.body) as List)
          .map((e) => db_manager.MyObject.fromJson(e))
          .toList();

      testList.clear();
      myObjects.forEach((db_manager.MyObject al) {
        testList.add(al.code);
        print("debug:"+al.code+" - "+al.name);        <------------- prints correctly
      });

      //TODO Does this even work?
      //Trigger update of state - ie redraw/reload UI elements
      setState(() {});

    } else {
      // If the server did not return a 200 OK response, then throw an exception.
      print(response);
      throw Exception('Failed to load json');
    }
  }
</code>```

UPDATE:

I've abstracted the BottomSheet builder into another class (as per another answer) as its own StatefulWidget but I can't seem to access the void onPress() method from my main dart file. If the BottomSheet creation/builder is in this separate dart file, how do I call it to build and then update its state with the async call updating the listview contents List?

BottomSheetWidget.dart

```<code>class BottomSheetDatabases extends StatefulWidget {
  @override
  _BottomSheetDatabases createState() => _BottomSheetDatabases();
}

class _BottomSheetDatabases extends State<BottomSheetDatabases> {

  void _onpress() {

  }

  void loadMe() {

  }

  List<String> testList= ["empty"];

  @override
  Widget build(BuildContext context) {
    return BottomSheet(

        builder: (context) {
          return ListView(
            padding: EdgeInsets.all(15.0),
            children: <Widget>[
              ListTile(
                ...

              ),

              Divider(),

              Container(
                height: 150.0,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,

                  itemCount: testList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      key: UniqueKey(),
                      //TODO  ??
                      padding: EdgeInsets.all(5.0),
                      margin: EdgeInsets.all(5.0),
                      width: 150.0,
                      color: Colors.red,
                      child: Text(testList[index]),
                    );
                  },

                ),
                //),
                //),
              ),

              ...
</code>```

Main.dart:

```<code>  void _loadSheetDatabases() {
    BottomSheetWidget bottomSheetwidget = BottomSheetWidget();
    bottomSheetwidget.loadMe();
  }
</code>```

答:
Seems to me that a Key are missing into widget that ListView.Builder returns, try to put a UniqueKey() or ValueKey into Container or Text:

```<code>Container(
   key: UniqueKey(),
   padding: EdgeInsets.all(5.0),
   margin: EdgeInsets.all(5.0),
   width: 150.0,
   color: Colors.red,
   child: Text(testList[index]),
);
</code>```

Body:
I have a ListView inside a bottomSheet, that is built using an array of elements. Currently I have one item in there "empty" which is then .clear()ed and populated after an async DB call.

The variable update is correct, and I try to use setState((){}) but the ListView isn't updated at all. I need to close the bottomSheet, reopen it, and the ListView then has the correct items.

Do I need to just call setState or does the bottomSheet builder need to be flagged to update?

Main ListView section:

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Map'),
          backgroundColor: Colors.green[700],
        ),

        //Put in a stack widget so can layer other widgets on top of map widget
        body: Stack(
          children: <Widget>[
            GoogleMap(
              mapType: _currentMapType,
              markers: _markers,
              onMapCreated: _onMapCreated,
              onCameraMove: _onCameraMove,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          ...
                      ),

                    ),

                    SizedBox(width: 16.0),

                    FloatingActionButton(
                      ...
                    ),

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.file_download, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {
                            showBottomSheet(
                                context: context,
                                builder: (context) {
                                  return ListView(
                                    padding: EdgeInsets.all(15.0),
                                    children: <Widget>[

                                         ...

                                      Divider(),

                                      ListTile(
                                        title: Text("Remote JSON Download"),
                                        trailing:
                                        Icon(Icons.refresh),
                                        selected: true,
                                        onTap: _OnPressedReloadJSON,               <-------------
                                      ),

                                      Divider(),

                                      Container(
                                        height: 150.0,
                                        child: ListView.builder(               <-------------
                                          scrollDirection: Axis.horizontal,

                                          itemCount : testList.length,
                                          itemBuilder: (BuildContext context, int index) {
                                              return Container(
                                                padding: EdgeInsets.all(5.0),
                                                margin: EdgeInsets.all(5.0),
                                                width: 150.0,
                                                color: Colors.red,
                                                child: Text(testList[index]),
                                              );
                                          },

                                        ),
                                      ),

Async Get:

class _MyAppState extends State<MyApp> {

  ...

  _OnPressedReloadJSON() {
    fetchJSONAndMakeListTile();
  }

  ...

  List<String> testList= ["empty"];

  Future<http.Response> fetchJSONAndMakeListTile() async {
    final response = await http.get('https://..... file.json');

    // If the server did return a 200 OK response, then parse the JSON.
    if (response.statusCode == 200) {
      List<db_manager.MyObject> myObjects = (json.decode(response.body) as List)
          .map((e) => db_manager.MyObject.fromJson(e))
          .toList();

      testList.clear();
      myObjects.forEach((db_manager.MyObject al) {
        testList.add(al.code);
        print("debug:"+al.code+" - "+al.name);        <------------- prints correctly
      });

      //TODO Does this even work?
      //Trigger update of state - ie redraw/reload UI elements
      setState(() {});

    } else {
      // If the server did not return a 200 OK response, then throw an exception.
      print(response);
      throw Exception('Failed to load json');
    }
  }

UPDATE:

I've abstracted the BottomSheet builder into another class (as per another answer) as its own StatefulWidget but I can't seem to access the void onPress() method from my main dart file. If the BottomSheet creation/builder is in this separate dart file, how do I call it to build and then update its state with the async call updating the listview contents List?

BottomSheetWidget.dart

class BottomSheetDatabases extends StatefulWidget {
  @override
  _BottomSheetDatabases createState() => _BottomSheetDatabases();
}

class _BottomSheetDatabases extends State<BottomSheetDatabases> {

  void _onpress() {

  }

  void loadMe() {

  }

  List<String> testList= ["empty"];

  @override
  Widget build(BuildContext context) {
    return BottomSheet(

        builder: (context) {
          return ListView(
            padding: EdgeInsets.all(15.0),
            children: <Widget>[
              ListTile(
                ...

              ),

              Divider(),

              Container(
                height: 150.0,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,

                  itemCount: testList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      key: UniqueKey(),
                      //TODO  ??
                      padding: EdgeInsets.all(5.0),
                      margin: EdgeInsets.all(5.0),
                      width: 150.0,
                      color: Colors.red,
                      child: Text(testList[index]),
                    );
                  },

                ),
                //),
                //),
              ),

              ...

Main.dart:

  void _loadSheetDatabases() {
    BottomSheetWidget bottomSheetwidget = BottomSheetWidget();
    bottomSheetwidget.loadMe();
  }

Body:
Seems to me that a Key are missing into widget that ListView.Builder returns, try to put a UniqueKey() or ValueKey into Container or Text:

Container(
   key: UniqueKey(),
   padding: EdgeInsets.all(5.0),
   margin: EdgeInsets.all(5.0),
   width: 150.0,
   color: Colors.red,
   child: Text(testList[index]),
);


问:
get the unique values from the associative array in PHP?
I am having the array like below

```<code>Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)
</code>```

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

答:
Where do you get that array from (presuming it doesn't magically appear)? If you're getting those results from a database, wouldn't it be much easier to limit them there? E.g.

```<code>SELECT DISTINCT cat_id, parent_id, catname FROM yourtable;
</code>```

Body:
I am having the array like below

Array
(
    [0] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [1] => Array
        (
            [catid] => 5
            [parent_id] => 2
            [catname] => Category 2
            [catdesc] =>
            [nleft] => 7
            [nright] => 8
            [nlevel] => 2
        )

    [2] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [3] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [4] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [5] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [6] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [7] => Array
        (
            [catid] => 7
            [parent_id] => 2
            [catname] => Flower
            [catdesc] =>
            [nleft] => 11
            [nright] => 18
            [nlevel] => 2
        )

    [8] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

    [9] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [10] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [11] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [12] => Array
        (
            [catid] => 10
            [parent_id] => 7
            [catname] => Jasmine
            [catdesc] =>
            [nleft] => 16
            [nright] => 17
            [nlevel] => 3
        )

    [13] => Array
        (
            [catid] => 3
            [parent_id] => 1
            [catname] => Uncategorized
            [catdesc] =>
            [nleft] => 20
            [nright] => 21
            [nlevel] => 1
        )

    [14] => Array
        (
            [catid] => 8
            [parent_id] => 7
            [catname] => Lillies
            [catdesc] =>
            [nleft] => 12
            [nright] => 13
            [nlevel] => 3
        )

)

From this array I want to get the Unique Arrays.ie. If catId is same it needs to eliminate from the list.
How can I do this?

Body:
Where do you get that array from (presuming it doesn't magically appear)? If you're getting those results from a database, wouldn't it be much easier to limit them there? E.g.

SELECT DISTINCT cat_id, parent_id, catname FROM yourtable;


问:
Python type hints for types not yet defined
How do I provide type hints for an alternative constructor for a class? For example if I have a method like this converting something to my new class,

```<code>class MyClass:
    @classmethod
    def from_string(cl: Type[????], s: str) -> ????:
        p, q = some_function(s)
        return cl(p, q)
</code>```

what should I write for ????? It should by nature just be MyClass, but that variable is not defined yet at the time when the method definition is executed.

答:
As PEP484 states, you can use strings as hints where the corresponding type is undefined at the time the type hint is read, but will be available later. This includes using strings as parts of type hints. Your code would therefore simply read

```<code>class MyClass:
    @classmethod
    def from_string(cl: Type['MyClass'], s: str) -> 'MyClass':
        p, q = some_function(s)
        return cl(p, q)
</code>```

but actually, if your cl is not MyClass, the return value will be different, so better use a type variable like this:

```<code>ParametersT = TypeVar("ParametersT", bound="Parameters")
class Parameters (
        NamedTuple("Parameters", [
            ("n_steps", halfyears),
        ])):
    @staticmethod
    def from_ns(ns: Namespace) -> 'Parameters':
        return Parameters(**vars(ns))
</code>```

Body:
How do I provide type hints for an alternative constructor for a class? For example if I have a method like this converting something to my new class,

class MyClass:
    @classmethod
    def from_string(cl: Type[????], s: str) -> ????:
        p, q = some_function(s)
        return cl(p, q)

what should I write for ????? It should by nature just be MyClass, but that variable is not defined yet at the time when the method definition is executed.

Body:
As PEP484 states, you can use strings as hints where the corresponding type is undefined at the time the type hint is read, but will be available later. This includes using strings as parts of type hints. Your code would therefore simply read

class MyClass:
    @classmethod
    def from_string(cl: Type['MyClass'], s: str) -> 'MyClass':
        p, q = some_function(s)
        return cl(p, q)

but actually, if your cl is not MyClass, the return value will be different, so better use a type variable like this:

ParametersT = TypeVar("ParametersT", bound="Parameters")
class Parameters (
        NamedTuple("Parameters", [
            ("n_steps", halfyears),
        ])):
    @staticmethod
    def from_ns(ns: Namespace) -> 'Parameters':
        return Parameters(**vars(ns))


问:
Angular7, get ElementRef
i need to get ElementRef in child nodes.

my template

```<code><div #charts *ngFor="let tag of _tags">
  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>
</div>
</code>```

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

```<code>for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }
</code>```

but my "child"  should be ElementRef type, and i don't know how to do it

答:
I think that it can't be an instance of ElementRef because you are using a ngFor, there are multiple references of what you call #charts.
It should instead be QueryList

https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

Title: Angular7, get ElementRef

Body:
i need to get ElementRef in child nodes.

my template

  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }

but my "child"  should be ElementRef type, and i don't know how to do it


问:
Does the DolphinDB language support not in syntax?
Suppose I have the following table,

```<code>t=table(1..5 as id,6..10 as v)
</code>```

I want to select the records from the table where id != 2 and id !=4 ,but I execute the following code ,

```<code>select * from t where  id  not in (2,4)
</code>```

The error message is as follows,

```<code>Function not is not a binary operator
</code>```

Does the DolphinDB language support not in syntax?

答:
DolphinDB doesn't support the operator not in. But you can use two operators not and into solve your problem.

```<code>select * from t where not id in (2,4)
</code>```

Body:
Suppose I have the following table,

t=table(1..5 as id,6..10 as v)

I want to select the records from the table where id != 2 and id !=4 ,but I execute the following code ,

select * from t where  id  not in (2,4)

The error message is as follows,

Function not is not a binary operator

Does the DolphinDB language support not in syntax?

Body:
DolphinDB doesn't support the operator not in. But you can use two operators not and into solve your problem.

select * from t where not id in (2,4)


问:
If with multiple ands, nested ifs, or ifs with booleans?
I have tried these multiple ways, and I still am not getting the result I need. I have a UserForm with multiple checkboxes. If two checkboxes are checked, I want one answer, but if the third checkbox is checked, a separate answer. What is the correct way to do this?
Nested Ifs:

```<code>Dim Cost As Range, SetUpCost As Range, Prices As Range
Set Cost = WB.Worksheets("Calculations").Range("F42")
Set Prices = WB.Worksheets("Calculations").Range("D42")

If QuarterlyCheck = True And SecurityLite = True Then
If NoSetUpCheck = False Then
    SecurityLitePrice.Caption = "$" & Cost.Value * 4
    SetUpFee.Caption = "$" & SetUpCost.Value
End If
ElseIf NoSetUpCheck = True Then
    SecurityLitePrice.Caption = "$" & Prices.Value * 4
    SetUpFee.Caption = ""
End If
</code>```

Or multiple ifs:

```<code>If QuarterlyCheck = True And SecurityLite = True And NoSetUpCheck = False Then
    SecurityLitePrice.Caption = "$" & Cost.Value * 4
    SetUpFee.Caption = "$" & SetUpCost.Value
End If
If QuarterlyCheck = True And SecurityLite = True And NoSetUpCheck = True Then
    SecurityLitePrice.Caption = "$" & Prices.Value * 4
    SetUpFee.Caption = ""
End If
</code>```

Neither are getting me the result I need.

答:
Maybe:</p>

```<code>If QuarterlyCheck = True And SecurityLite = True Then
    If NoSetUpCheck = True Then
        SecurityLitePrice.Caption = "$" & Prices.Value * 4
        SetUpFee.Caption = ""
    Else 'Means NoSetUpCheck = False
        SecurityLitePrice.Caption = "$" & Cost.Value * 4
        SetUpFee.Caption = "$" & SetUpCost.Value
    End If
Else
    'Whatever else ....
End If
</code>```

Body:
I have tried these multiple ways, and I still am not getting the result I need. I have a UserForm with multiple checkboxes. If two checkboxes are checked, I want one answer, but if the third checkbox is checked, a separate answer. What is the correct way to do this?
Nested Ifs:

Dim Cost As Range, SetUpCost As Range, Prices As Range
Set Cost = WB.Worksheets("Calculations").Range("F42")
Set Prices = WB.Worksheets("Calculations").Range("D42")

If QuarterlyCheck = True And SecurityLite = True Then
If NoSetUpCheck = False Then
    SecurityLitePrice.Caption = "$" & Cost.Value * 4
    SetUpFee.Caption = "$" & SetUpCost.Value
End If
ElseIf NoSetUpCheck = True Then
    SecurityLitePrice.Caption = "$" & Prices.Value * 4
    SetUpFee.Caption = ""
End If

Or multiple ifs:

If QuarterlyCheck = True And SecurityLite = True And NoSetUpCheck = False Then
    SecurityLitePrice.Caption = "$" & Cost.Value * 4
    SetUpFee.Caption = "$" & SetUpCost.Value
End If
If QuarterlyCheck = True And SecurityLite = True And NoSetUpCheck = True Then
    SecurityLitePrice.Caption = "$" & Prices.Value * 4
    SetUpFee.Caption = ""
End If

Neither are getting me the result I need.

Body:
Maybe:

If QuarterlyCheck = True And SecurityLite = True Then
    If NoSetUpCheck = True Then
        SecurityLitePrice.Caption = "$" & Prices.Value * 4
        SetUpFee.Caption = ""
    Else 'Means NoSetUpCheck = False
        SecurityLitePrice.Caption = "$" & Cost.Value * 4
        SetUpFee.Caption = "$" & SetUpCost.Value
    End If
Else
    'Whatever else ....
End If