问:
JAVA GRPC server side stream keeps increasing max-inbound-message-size
What are the best practices of streaming lots of data with GRPC?
I am sending a request to a GRPC server that will stream back data. The data send back can be a in the order of 100 protobuf messages or can be a couple of 100.000 protobuf messages.

```<code>service CrossEngineSelector {
    rpc QueryDB (QueryRequest) returns (stream QueryResponse) {}
}
</code>```

The server is a simple implementation that sends the protobuf messages.

```<code>@Override
public void queryBD(QueryRequest request, StreamObserver<QueryResponse> responseObserver) {

      Iterables.partition( dataLoader.getData(), 1000).forEach(batch -> {
          responseObserver.onNext(QueryResponse.newBuilder().addAllRows(batch).build());
      });
      responseObserver.onCompleted();
}
</code>```

The client side uses a blockingStub that calls this method (generated code by protobuf):

```<code>public Iterator<QueryResponse> queryDB(QueryRequest request) {
            return ClientCalls.blockingServerStreamingCall(this.getChannel(),
                   CrossEngineSelectorGrpc.getQueryEnginesMethod(),
                   this.getCallOptions(), request);
}
</code>```

Once the client calls this method I just iterate over the QueryResponse.

All of this works fine for streams that only send back a small amount of messages. Once I try to stream 100.000 messages the max-inbound-message-size keeps increasing and I end up with an error: RESOURCE_EXHAUSTED: Compressed gRPC message exceeds maximum size 4194304: 4196022 bytes read

My current fix for this is to set the max-inbound-message-size very high +1Gb. This is a hardcoded value, so it doesn't scale. The client has no idea how many messages the server will return. I might run into use cases were even the 1Gb max-inbound-message-size will not be enough.

I hope I am making an implementation mistake. I hope there is a way of resetting the message size for every stream (onNext()) from the server or is it normal it keeps increasing the message size?

I would assume that a single responseObserver.onNext(QueryResponse.newBuilder().addAllRows(batch).build()); sends a couple of Mb and that this would be considered as the message size and not the entire stream for as long as it runs.

I am using Micronaut for both server and client.

答:
The maxInboundMessageSize is for protecting receiver going out of memory if malicious peer sends very large payload to attack.
The real problem here is the 1000 chunks can be larger than 4MB (default maxInboundMessageSize).

you can fix this in two ways,

fix the sender to limit by size of the payload, not by # of rows.

or, the receiver have large enough maxInboundMessageSize to handle normal 1000 rows worth of data.

the later method is essentially what you implemented. It should be lower than 1GB+ though. gRPC won't use the maxInboundMessageSize amount of memory as I mentioned above this is purely for protecting. (added later)

Body:
What are the best practices of streaming lots of data with GRPC?
I am sending a request to a GRPC server that will stream back data. The data send back can be a in the order of 100 protobuf messages or can be a couple of 100.000 protobuf messages.

service CrossEngineSelector {
    rpc QueryDB (QueryRequest) returns (stream QueryResponse) {}
}

The server is a simple implementation that sends the protobuf messages.

@Override
public void queryBD(QueryRequest request, StreamObserver<QueryResponse> responseObserver) {

      Iterables.partition( dataLoader.getData(), 1000).forEach(batch -> {
          responseObserver.onNext(QueryResponse.newBuilder().addAllRows(batch).build());
      });
      responseObserver.onCompleted();
}

The client side uses a blockingStub that calls this method (generated code by protobuf):

public Iterator<QueryResponse> queryDB(QueryRequest request) {
            return ClientCalls.blockingServerStreamingCall(this.getChannel(),
                   CrossEngineSelectorGrpc.getQueryEnginesMethod(),
                   this.getCallOptions(), request);
}

Once the client calls this method I just iterate over the QueryResponse.

All of this works fine for streams that only send back a small amount of messages. Once I try to stream 100.000 messages the max-inbound-message-size keeps increasing and I end up with an error: RESOURCE_EXHAUSTED: Compressed gRPC message exceeds maximum size 4194304: 4196022 bytes read

My current fix for this is to set the max-inbound-message-size very high +1Gb. This is a hardcoded value, so it doesn't scale. The client has no idea how many messages the server will return. I might run into use cases were even the 1Gb max-inbound-message-size will not be enough.

I hope I am making an implementation mistake. I hope there is a way of resetting the message size for every stream (onNext()) from the server or is it normal it keeps increasing the message size?

I would assume that a single responseObserver.onNext(QueryResponse.newBuilder().addAllRows(batch).build()); sends a couple of Mb and that this would be considered as the message size and not the entire stream for as long as it runs.

I am using Micronaut for both server and client.


来源: stackexchange

问:
NotifyDataSetChanged- RecyclerView -Is it an asynchronous call?
I am trying to follow a set of statements after the execution of notifyDataSetChanged on a recyclerview. But when I am debugging my application, the debugger reaches the next few lines after my notifyDataSetChanged before going to the onBindViewHolder of the recyclerview's adapter. So my question is- Is the notifyDataSetChanged an asynchronous call? If yes do we get a callback?
PS: I have already googled this answer and I couldn't find a suitable answer that's why I am asking the community.

答:
I came across this issue because I needed to do some layout reconfiguration based on the size of my recyclerview, and since I had height set to wrap_content, the size was changing whenever its data would change. To effectively respond to layout changes, you can use a short subclass of your layout manager (in my case it was a LinearLayoutManager) and override onLayoutCompleted:

```<code>recyclerView.setLayoutManager(new LinearLayoutManager(getContext()){
        @Override
        public void onLayoutCompleted (RecyclerView.State state){
            super.onLayoutCompleted(state);
            // update UI for new layout
        }
    });
</code>```

In my case I needed to scroll my ScrollView after the size changed on the RecyclerView, and this code did the trick.

ContentLicense: CC BY-SA 3.0

Body:
I came across this issue because I needed to do some layout reconfiguration based on the size of my recyclerview, and since I had height set to wrap_content, the size was changing whenever its data would change. To effectively respond to layout changes, you can use a short subclass of your layout manager (in my case it was a LinearLayoutManager) and override onLayoutCompleted:

recyclerView.setLayoutManager(new LinearLayoutManager(getContext()){
        @Override
        public void onLayoutCompleted (RecyclerView.State state){
            super.onLayoutCompleted(state);
            // update UI for new layout
        }
    });

In my case I needed to scroll my ScrollView after the size changed on the RecyclerView, and this code did the trick.

ContentLicense: CC BY-SA 4.0


问:
How to import Vanilla JS ES6 modules in TypeScript?
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

```<code>declare module 'spotlight.js'
</code>```

as suggested by VSCode, then I tried every single import combination:

```<code>import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';
</code>```

but inside my code the spotlight expression is always an empty object.

What am I missing?

答: There is an open issue for that: https://github.com/nextapps-de/spotlight/issues/6</p>

Body:
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

declare module 'spotlight.js'

as suggested by VSCode, then I tried every single import combination:

import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';

but inside my code the spotlight expression is always an empty object.

What am I missing?


问:
Resize background image in div using css
Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

How can I stretch the images using css to fit into space required by div ?

```<code><style type="text/css">
#contentMain {
  margin-bottom: 5%;
  margin-top: 10%;
  margin-left: 10%;
  margin-right: 10%;
  background: url( /jQuery/mypage/img/background1.png )
}
#page1 {
  background: url( /jQuery/mypage/img/background2.png )
}
</style>
</code>```

答: With the background-size property in those browsers which support this very new feature of CSS.</p>


问:
Type-level list of a single type level-tuple in Haskell
Using DataKinds and TypeOperators, I can make type level-tuples of types, and type-level lists of types, but I cannot nest them:

```<code>> :k '['(Int, Int), '(Int, Int)]
error: parse error on input ‘'’`
</code>```

I can make a list of multiple tuples:

```<code>> :k ['(Int,Int),'(Int,Int)]
['(Int,Int),'(Int,Int)] :: [(*, *)]
</code>```

But this doesn't work with only one tuple gives:

```<code>:k ['(Int,Bool)]
<interactive>:1:2: error:
    • Expected a type, but ‘'(Int, Bool)’ has kind ‘(*, *)’
</code>```

It can be done using KindSignatures, but it is very verbose:

```<code>> :k '[('(Int,Bool) :: (*,*))]
'[('(Int,Bool) :: (*,*))] :: [(*, *)]
</code>```

Is there a less verbose way to do this, or is this the best way?

答:
You need to add a space:

```<code>> :k '['(Int, Int), '(Int, Int)]
<interactive>:1:1: error: parse error on input '
> :k '[ '(Int, Int), '(Int, Int)]
'[ '(Int, Int), '(Int, Int)] :: [(*, *)]
</code>```

Essentially, the parser is confused by the char literal '[' which happens to be at the beginning.

Body:
Using DataKinds and TypeOperators, I can make type level-tuples of types, and type-level lists of types, but I cannot nest them:

> :k '['(Int, Int), '(Int, Int)]
error: parse error on input ‘'’`

I can make a list of multiple tuples:

> :k ['(Int,Int),'(Int,Int)]
['(Int,Int),'(Int,Int)] :: [(*, *)]

But this doesn't work with only one tuple gives:

:k ['(Int,Bool)]
<interactive>:1:2: error:
    • Expected a type, but ‘'(Int, Bool)’ has kind ‘(*, *)’

It can be done using KindSignatures, but it is very verbose:

> :k '[('(Int,Bool) :: (*,*))]
'[('(Int,Bool) :: (*,*))] :: [(*, *)]

Is there a less verbose way to do this, or is this the best way?

Body:
You need to add a space:

> :k '['(Int, Int), '(Int, Int)]
<interactive>:1:1: error: parse error on input '
> :k '[ '(Int, Int), '(Int, Int)]
'[ '(Int, Int), '(Int, Int)] :: [(*, *)]

Essentially, the parser is confused by the char literal '[' which happens to be at the beginning.


问:
Unique row ID with reuse
I would like to generate 32 bit unique integer id for each row.

```<code>create table my_table (
    uid serial primary key,
    some_text text
);
</code>```

The number of rows at any time will not exceed 2147483647 (limit of 32 bit signed int), but rows can be deleted and new ones inserted. This may lead to the sequence reaching its end. Therefore I would like to reuse ids of deleted rows. What is the best way to do it?

答:
Getting up on my soapbox.
Let's be frank: there is no best way to do this, there is not even 'sort-of good' method. Maybe a least bad method? Well 2 possibilities:

Create a table 'reusable_unique_ids'. Then when you get the inevitable overflow select (and delete) a value from it. Good luck coordinating that.

There is actually nothing requiring unsigned values for a sequence generator. So create one that automatically wraps to large negative values on the inevitable overflow.

Let's investigate #2.

```<code>create sequence wrap_around_id_generator
     increment by 1
     minvalue -2147483646
     maxvalue  2147483646
     start     1
     cycle
;

create table my_table (
    uid integer default nextval('wrap_around_id_generator') primary key
  , some_text text
);
</code>```

Now when negative id start showing up you have time to prepare for correcting the imposed limit of your id.

Please raise the issue of "bigint is not allowed by the requirements" and get it changed especially since integer overflow is expected. The best method is change that requirement, it is the only reasonable solution given the expectation. And, at least IMHO it is your job to do so, don't hide behind "that is the requirement". Poor requirements produce poor systems. Always

OK, getting off the soapbox.

Title: Unique row ID with reuse

Body:
I would like to generate 32 bit unique integer id for each row.

create table my_table (
    uid serial primary key,
    some_text text
);

The number of rows at any time will not exceed 2147483647 (limit of 32 bit signed int), but rows can be deleted and new ones inserted. This may lead to the sequence reaching its end. Therefore I would like to reuse ids of deleted rows. What is the best way to do it?

Body:
Getting up on my soapbox.
Let's be frank: there is no best way to do this, there is not even 'sort-of good' method. Maybe a least bad method? Well 2 possibilities:

Create a table 'reusable_unique_ids'. Then when you get the inevitable overflow select (and delete) a value from it. Good luck coordinating that.

There is actually nothing requiring unsigned values for a sequence generator. So create one that automatically wraps to large negative values on the inevitable overflow.

Let's investigate #2.

create sequence wrap_around_id_generator
     increment by 1
     minvalue -2147483646
     maxvalue  2147483646
     start     1
     cycle
;

create table my_table (
    uid integer default nextval('wrap_around_id_generator') primary key
  , some_text text
);

Now when negative id start showing up you have time to prepare for correcting the imposed limit of your id.

Please raise the issue of "bigint is not allowed by the requirements" and get it changed especially since integer overflow is expected. The best method is change that requirement, it is the only reasonable solution given the expectation. And, at least IMHO it is your job to do so, don't hide behind "that is the requirement". Poor requirements produce poor systems. Always

OK, getting off the soapbox.


问:
XDE:010 The emulator is unable to create a differencing disk
After I reformat my computer and install Microsoft Emulator and Windows 10X Emulator,

The error shown as below:

and my settings.

any one facing the same issue?

答:
Can you make sure both the Microsoft Emulator app and the image package are installed on the C drive? Here's how:

Go to Apps in the Windows Settings

Search for Microsoft Emulator

Click the "Move" button. If it's not on the C drive (or whatever you
system drive is), move it there.

Now for the image...

Click the "Advanced options" for Microsoft Emulator in the Apps settings

Scroll down until you find the add-on for the image.

Click the "Move" button and move it to the C drive (or whatever your system drive is) if it's not there.

Update:
The C drive also has to be uncompressed.

Open File Explorer and right click on the C drive and click Properties

Make sure this check box is unchecked: "Compress this drive to save space"


问:
Multiple node instances, NGINX reverse proxy, serves page, 404 error on post requests?
So my stack is running on a Digital Ocean droplet. Initial node.js application is served at https://domain_name.com/. The requests are processed through NGINX reverse proxy to port 3000.

I now have a second application running on port 3001; both instances are running in PM2.
The second application is reached by way of https://domain_name.com/cards/.

When this address is accessed it delivers the first page as expected. However when a POST request is placed. to address https://domain_name.com/cards/api_route/. Console in the browser displays a 404 error. This, however, functions perfectly on Localhost node instance.

My sites-enabled 'default' file contains the following location blocks.

```<code>HTTPS â€” proxy all requests to the Node app

server {
     # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name domain_name.com;
    # Use the Letâ€™s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/domain_name.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain_name.com/privkey.pem;
    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";

 location /card {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:3001/;
      proxy_ssl_session_reuse off;
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
    }

  location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:3000/;
      proxy_ssl_session_reuse off;
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
      }
  }
</code>```

Paths are however correct to api routes

答:
Problem solved....

The location block

location /card {

needed to be

location /card/ {

Previously searching https://domain_name.com/cards

delivered the page and:

https://domain_name.com/cards/

Returned error: CANNOT GET //

Body:
So my stack is running on a Digital Ocean droplet. Initial node.js application is served at https://domain_name.com/. The requests are processed through NGINX reverse proxy to port 3000.

I now have a second application running on port 3001; both instances are running in PM2.
The second application is reached by way of https://domain_name.com/cards/.

When this address is accessed it delivers the first page as expected. However when a POST request is placed. to address https://domain_name.com/cards/api_route/. Console in the browser displays a 404 error. This, however, functions perfectly on Localhost node instance.

My sites-enabled 'default' file contains the following location blocks.

HTTPS â€” proxy all requests to the Node app

server {
     # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name domain_name.com;
    # Use the Letâ€™s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/domain_name.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain_name.com/privkey.pem;
    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";

 location /card {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:3001/;
      proxy_ssl_session_reuse off;
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
    }

  location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:3000/;
      proxy_ssl_session_reuse off;
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_redirect off;
      }
  }

Paths are however correct to api routes


问:
How to add SplitViewController on the third view in the application
I need some help.
I had created login page from that page user with redirect to tableview.
After selecting row the next view which i want to show is splitviewcontroller.
I cannot add these please help me.

Thanks in advance.

答:
You can check the following tutorial for using splitviewcontroller
SplitViewController Tutorial</p>


问:
MERGE command results in gaps in sequence numbers
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

```<code>-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

```<code>INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.

答:
You probably did this on other transactional databases (Oracle, SQL Server).  If you did this on warehousing/analytic databases (like Netezza) you would also find similar sequence behavior; this is because these systems are built for speed and bulk processing; so it gets a chunk of sequence values, which it may or may not use.  This does leave gaps; but given the max value of the sequence and your workflow, is it something where you will hit the ceiling in 30 o 300 years?  Arguably both are don't cares.

These analytic databases typically have a higher inherent cost to simply run any query; which is very tiny on a transactional database.  So they can get away with asking for a sequence value simply every time they need one (no holes!) - you can very easily see a big difference by doing individual inserts - which you may already know are discouraged by Snowflake.  Here's a simple test though: create a table and make 200 insert statements each inserting a single row.  Run this in mysql on your laptop; run this on a Medium sized Snowflake (or XS, but just making a point) - the mysql on the laptop is simply going to crush Snowflake for this particular test; because it is something it is designed to do.  There will be a massive difference in time for an individual insert and you'll see how quickly that accumulates even doing just a small batch of 200 rows.

Note that merge itself is a pretty transactional command, and on these types of databases has also not always been supported.  It may or may not be faster to simply do the individual operations yourself; as noted, you would probably end up with holes still between separate new file runs, but, within your single operations, be able to expect sequential sequences be allocated with no gap.

```<code>update target from source where business key exists in target;
insert into target from soure where business key not exists in target;
</code>```

the update is actually a delete+insert, if you retain sequences in some kind of sequence - business key map, you might be able to simplify (maybe speed up?) the process too;

```<code>insert sequence, key into map where key in source and not in target;
begin;
delete from target where key exists in source and target;
insert source joined to map on key to retrieve sequence into target;
commit;
</code>```

might be worth considering if the actual update can get a lot uglier.  (also a curious speed experiment)

Body:
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.

Body:
You probably did this on other transactional databases (Oracle, SQL Server).  If you did this on warehousing/analytic databases (like Netezza) you would also find similar sequence behavior; this is because these systems are built for speed and bulk processing; so it gets a chunk of sequence values, which it may or may not use.  This does leave gaps; but given the max value of the sequence and your workflow, is it something where you will hit the ceiling in 30 o 300 years?  Arguably both are don't cares.

These analytic databases typically have a higher inherent cost to simply run any query; which is very tiny on a transactional database.  So they can get away with asking for a sequence value simply every time they need one (no holes!) - you can very easily see a big difference by doing individual inserts - which you may already know are discouraged by Snowflake.  Here's a simple test though: create a table and make 200 insert statements each inserting a single row.  Run this in mysql on your laptop; run this on a Medium sized Snowflake (or XS, but just making a point) - the mysql on the laptop is simply going to crush Snowflake for this particular test; because it is something it is designed to do.  There will be a massive difference in time for an individual insert and you'll see how quickly that accumulates even doing just a small batch of 200 rows.

Note that merge itself is a pretty transactional command, and on these types of databases has also not always been supported.  It may or may not be faster to simply do the individual operations yourself; as noted, you would probably end up with holes still between separate new file runs, but, within your single operations, be able to expect sequential sequences be allocated with no gap.

update target from source where business key exists in target;
insert into target from soure where business key not exists in target;

the update is actually a delete+insert, if you retain sequences in some kind of sequence - business key map, you might be able to simplify (maybe speed up?) the process too;

insert sequence, key into map where key in source and not in target;
begin;
delete from target where key exists in source and target;
insert source joined to map on key to retrieve sequence into target;
commit;

might be worth considering if the actual update can get a lot uglier.  (also a curious speed experiment)


问:
My submit button does not allow to be clicked on in html
This is my HTML

```<code><form action="petDetails.php" id="animalInput">
   <ul>
       <li>
           <label for="dogName">Dog Name:</label><input id="dogName" type="text" name="dogName" />
       </li>
       <li>
          <label for="submit"></label><input id="submit" type="submit" value="Enter dog name" name="submit" />
       </li>
  </ul>
</form>
</code>```

I am trying to have the submit button be pressed and have an image under the button increase size. I also am just learning AJAX and I am unsure if that may be affecting it or maybe it is just my HTML.

答:
Your Implementation is correct and works for me, just open the developer tools of your browser, open the network tab, run your code snippet from below and click the submit button.
This will result in a request to the server, safari prints following output: e.g. [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (petDetails.php, line 0) which is as expected because the server side script petDetails.php is not present.

<form action="petDetails.php" id="animalInput">

           Dog Name:<input id="dogName" type="text" name="dogName" />

          <input id="submit" type="submit" value="Enter dog name" name="submit" />

</form>```
</div>
</div>
</p>

<p>To do the same with Ajax, you could do it like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Send data to backend via Ajax
function save_dog_name() {
    // Create XMLHttpRequest Object
    var http_handle = new XMLHttpRequest();
    // Define data which should be send to the server
    var data = 'dogName=' + document.getElementById("dogName").value;
    // Open the connection
    http_handle.open('POST', "petDetails.php", true);
    // Send header to specify that data in request body will be urlencoded
    http_handle.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    // Define what happens if the response has been received
    http_handle.onreadystatechange = function() {
        if(http_handle.readyState == 4 && http_handle.status == 200) {
            // Print response in case everything was OK
            console.log("Data has been received. Server response: " + http_handle.responseText);
        } else {
            // Print error message and response in case something went wrong
            console.log("An error occured. Server response: " + http_handle.status + " " + http_handle.statusText + " " + http_handle.responseText);
        }
    }
    http_handle.send(data);
}</code>```

        Dog Name:<input id="dogName" type="text" name="dogName" />

        <button onclick="save_dog_name()">Enter dog name</button>

```

For nice button design, you can use bootstrap, see: https://getbootstrap.com/docs/3.4/css/#buttons

Body:
This is my HTML

<form action="petDetails.php" id="animalInput">

           Dog Name:<input id="dogName" type="text" name="dogName" />

          <input id="submit" type="submit" value="Enter dog name" name="submit" />

</form>

I am trying to have the submit button be pressed and have an image under the button increase size. I also am just learning AJAX and I am unsure if that may be affecting it or maybe it is just my HTML.

Body:
Your Implementation is correct and works for me, just open the developer tools of your browser, open the network tab, run your code snippet from below and click the submit button.
This will result in a request to the server, safari prints following output: e.g. [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (petDetails.php, line 0) which is as expected because the server side script petDetails.php is not present.

<form action="petDetails.php" id="animalInput">
   <ul>
       <li>
           <label for="dogName">Dog Name:</label><input id="dogName" type="text" name="dogName" />
       </li>
       <li>
          <label for="submit"></label><input id="submit" type="submit" value="Enter dog name" name="submit" />
       </li>
   </ul>
</form>

To do the same with Ajax, you could do it like so:

// Send data to backend via Ajax
function save_dog_name() {
    // Create XMLHttpRequest Object
    var http_handle = new XMLHttpRequest();
    // Define data which should be send to the server
    var data = 'dogName=' + document.getElementById("dogName").value;
    // Open the connection
    http_handle.open('POST', "petDetails.php", true);
    // Send header to specify that data in request body will be urlencoded
    http_handle.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    // Define what happens if the response has been received
    http_handle.onreadystatechange = function() {
        if(http_handle.readyState == 4 && http_handle.status == 200) {
            // Print response in case everything was OK
            console.log("Data has been received. Server response: " + http_handle.responseText);
        } else {
            // Print error message and response in case something went wrong
            console.log("An error occured. Server response: " + http_handle.status + " " + http_handle.statusText + " " + http_handle.responseText);
        }
    }
    http_handle.send(data);
}

<ul>
    <li>
        <label for="dogName">Dog Name:</label><input id="dogName" type="text" name="dogName" />
    </li>
    <li>
        <label for="submit"></label><button onclick="save_dog_name()">Enter dog name</button>
    </li>
</ul>

For nice button design, you can use bootstrap, see: https://getbootstrap.com/docs/3.4/css/#buttons


问:
Using Sum function in R to set a variable from 3 different columns with specified amount
I am trying to create a character vector that stores the names of countries with 10 or more total medals in R. I am getting back an 'Error: attempt to apply non-function' when running the code.
Here is the code:
biggest_winners=olympic_df$name(sum(olympic_df$medals.gold & olympic_df$medals.silver & olympic_df$medals.bronze >=10))

here is a picture of the first 10 rows with column headers for reference:

答:
You can create a new column with the sum by row by using rowSums and then filter for values superior to 10:

olympic_df$Sum <- rowSums(olympic_df[,3:5])
olympic_df[olympic_df$Sum >= 10,]
```

<p>Or in a single line:</p>

<pre class="lang-r prettyprint-override"><code>olympic_df[rowSums(olympic_df[3:5]) >= 10,]
</code>```

Body:
You can create a new column with the sum by row by using rowSums and then filter for values superior to 10:

olympic_df$Sum <- rowSums(olympic_df[,3:5])
olympic_df[olympic_df$Sum >= 10,]

Or in a single line:

olympic_df[rowSums(olympic_df[3:5]) >= 10,]


问:
How to execute Ansible playbooks with LDAP authentication to hosts?
I am trying to configure a setup where my playbooks are executed by getting credential for the host from an external authentication source (LDAP/PAM).

I have a regular /etc/ansible/hosts inventory file, with IP and username of hosts. During execution of the playbook, it should dynamically acquire the password from an external LDAP/PAM server for each host's respective user.

Is this doable?

答:
As per your requirement, it is not doable ( not very much sure about this ) but what you can do is store the credentials in some file and then us it as extra-vars while running playbook.

otherwise you can use expect module to pass the password as extra variable.


问:
How to create REST URLs without verbs?
I'm struggling to determine how to design restful URLs.  I'm all for the restful approach of using URLs with nouns and not verbs don't understand how to do this.

We are creating a service to implement a financial calculator.  The calculator takes a bunch of parameters that we will upload via a CSV file.  The use cases would involve:

Upload new parameters

Get the latest parameters

Get parameters for a given business date

Make a set of parameters active

Validate a set of parameters

I gather the restful approach would be to have the following type URLs:

```<code>/parameters
/parameters/12-23-2009
</code>```

You could achieve the first three use cases with:

POST where you include the parameter file in the post request

GET of first URL

GET of second URL

But how do you do the 4th and 5th use case without a verb?  Wouldn't you need URLs like:

```<code>/parameters/ID/activate
/parameters/ID/validate
</code>```

??

答:
I feel a bit sad to see that after more than 10 years there is no answer really stating how such a thing as requested in the OP could be designed in a REST architecture, hence I feel the need to do this now.

First things first, what is REST?! The acronym REST or ReST stands for "Representational State Transfer" and defines the exchange of a resource's state in a certain representation format. The representation format is tide to the negotiated media type. In the case of application/html the representation format may be a stream of HTML formatted text content that is rendered in the browser, probably after applying some stylesheet formatting to position certain elements at certain locations.

REST is in principle a generalization of the browsable Web we all know, though targets all kinds of applications and not only browsers. Therefore, by design, the same concepts that apply to the Web also apply to a REST architecture. A question like how to achieve something in a "RESTful" way resolves around answering the question how to achieve something on a Web page and then apply the same concepts onto the application layer.

A Web based calculator may usually start off with some "page" that allows you to input some values to calculate before sending the entered data to the server. In HTML this is usually achieved via HTML <form> elements that teaches a client on the available parameters to set, the target location to send the request to as well as the representation format to apply upon sending the input data. This can i.e. look like this:

    ...

    <form action="/../someResource" method="post" enctype="application/x-www-form-urlencoded">
      First number:
      <input type="number" id="firstNumber" name="firstNumber"/>

      Second number:
      <input type="number" id="secondNumber" name="secondNumber"/>

      <input type="submit" value="Add numbers"/>
    </form>

```
<p>The sample above i.e. states that there are two input fields that can be filled out either by the user or by some other automata, and that upon invoking the submit input element the browser takes care of formatting the input data into a <code>application/x-www-form-urlencoded</code> representation format that is sent to the mentioned target location via the specified HTTP request method, <code>POST</code> in this case. If we enter <code>1</code> into the <code>firstNumber</code> input field and <code>2</code> into the <code>secondNumber</code> input field, the browser will generate a representation of <code>firstNumber=1&secondNumber=2</code> and send this as the body payload of the actual request to the target resource.</p>
<p>The raw HTTP request issued to the server therefore may look like this:</p>
```POST /../someResource
Host: www.acme.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 28
Accept: application/html

firstNumber=1&secondNumber=2
```

The server may perform the calculation and respond with a further HTML page that contains the result of the calculation, as the request indicated that the client understands this format.

As Breton pointed already out there is no such thing as a "RESTful" URL or URI. A URI/URL is its own kind of thing and should not convey any meaning to a client/user. In the calculator sample above a user simply isn't interested where to send the data to it is just interested in that upon triggering the submit input field the request is sent. All the required information needed to perform the task should already be given by the server.

A browser also might not be aware of that the request is actually feeding a calculator with some input parameters, it could as well be some kind of an order form that returns just the next form representation to continue the ordering process or some totally different kind of resource. It simply performs what the HTML spec demands in such a case and it couldn't care less what the server is actually doing. This concept enables a browser to use the same representation format to do all kind of things such as ordering some stuff from your preferred online shop, chatting with your best friends, signing into an online account and so on.

The affordance of certain elements, such in the submit input field case that is usually rendered as button, defines what you should to with it. In the case of a button or a link it basically tells you to click it. Other elements may convey different affordances. Such an affordance can also be expressed via link-relations as i.e. with preload annotated links that basically tell a client that it can already load the content of the linked resource in the background as the user will most likely grab this content next. Such link relations should of course be standardized or follow the extension mechanism for relation types as defined by Web linking.

These are the fundamental concept that are used on the Web and that should also be used in a REST architecture. According to "Uncle Bob" Robert C. Martin an architecture is about intent and the intention behind the REST architecture is the decoupling of clients from servers to allow servers to evolve freely in future without having to fear them breaking clients. This unfortunately requires a lot of discipline as it is so easy to introduce coupling or to add quick-fix solutions to get the job done and move on. As Jim Webber pointed out in a REST architecture you, as a service provider, should attempt to design an domain application protocol similar to a text based computer game of the 70s that clients will follow through until they reached the end of a process.

What plenty of so-called "REST" APIs unfortunately do in reality is everything but that. You see the exchange of mostly JSON based data that is specified in an API specific external documentation that is usually hard to dynamically integrate on the fly. The format how a request needs to look like are also hardcoded into the external documentation which lead to plenty of implementation interpreting URIs to return predefined typs instead of using some common representation format that is negotiated upfront. This prevents servers from changing as clients now expect to receive a certain data format (note not representation format!) for predefined URIs. This custom data format exchange furthermore prevents clients from interacting with other APIs as the "data format" is usually tide to a specific API. We know this concept from the past from RPC technologies such as Corba, RMI or SOAP which we condemn as somehow evil, even though Peppol moved to it again by replacing AS2 with AS4 as default transfer protocol as of recently.

In regards to the actual question asked, sending data as csv file is nothing different than using application/x-www-form-urlencoded representation or similar stuff. Jim Webber made it clear that after all HTTP is just a transport protocol whose application domain is the transfer of documents over the Web. Client and server should at least both support text/csv as defined in RFC 7111. This CSV file could be generated as a consequence of processing a media type that defines form elements, a target element or attribute to send the request to as well as the HTTP method to perform the upload of the configuration.

There are a couple of media types that support forms such as HTML, HAL Forms, halform, ion or Hydra. I am currently, though, not aware of a media type that automatically can encode the input data into text/csv directly hence one might need to be defined and registered with IANA's media type registry.

The upload and download of the complete parameter set shouldn't be an issue I guess. As mentioned before, the target URI is not of relevance as a client will just use the URI to retrieve new content to process. Filtering by business date should also not be to difficult. Here the server should however the client with all the possibilities the client simply can chose from. In recent years GraphQL and RestQL evolved which introduce an SQL like language that can be targeted at a certain endpoint to get a filtered response. However, in a true REST sense this violates the idea behind REST as a) GraphQL i.e. only uses a single endpoint which somehow prevents optimal usage of caching and b) requires the knowledge of available fields upfrong, which may lead to introducing a coupling of clients to the base data model of the resource.

Activating or deactivating certain configuration parameters is simply a matter of triggering the hypermedia controls that provide this affordance. In HTML forms this could be a simple checkbox or a multi-line selection in a list or that kind. Depending on the form and what method it defines it could then potentially send the whole configuration via PUT or be smart about the changes done and only perform a partial update via PATCH. The latter one requires basically a calculaton of the change representation to the one updated and feed the server with the required steps to tranform the current representation into the desired one. According to the PATH specification this has to be done within a transaction so that either all or none of the steps are applied.

HTTP allows and encourages a server to validate a received request upfront before applying the changes. For PUT the spec states:

An origin server SHOULD verify that the PUT representation is
consistent with any constraints the server has for the target
resource that cannot or will not be changed by the PUT.  This is
particularly important when the origin server uses internal
configuration information related to the URI in order to set the
values for representation metadata on GET responses.  When a PUT
representation is inconsistent with the target resource, the origin
server SHOULD either make them consistent, by transforming the
representation or changing the resource configuration, or respond
with an appropriate error message containing sufficient information
to explain why the representation is unsuitable.  The 409 (Conflict)
or 415 (Unsupported Media Type) status codes are suggested, with the
latter being specific to constraints on Content-Type values.

For example, if the target resource is configured to always have a
Content-Type of "text/html" and the representation being PUT has a
Content-Type of "image/jpeg", the origin server ought to do one of:

a.  reconfigure the target resource to reflect the new media type;

b.  transform the PUT representation to a format consistent with that
of the resource before saving it as the new resource state; or,

c.  reject the request with a 415 (Unsupported Media Type) response
indicating that the target resource is limited to "text/html",
perhaps including a link to a different resource that would be a
suitable target for the new representation.

HTTP does not define exactly how a PUT method affects the state of an
origin server beyond what can be expressed by the intent of the user
agent request and the semantics of the origin server response. ...

To sum this post up, you should either use an existing media type that allows you to teach a client about the required or supported input parameters, the target location to send the request to, the operation to use as well as the media-type the request has to be formatted in, or define your own one that you register with IANA. The latter might be necessary if you want to convert the input to text/csv and then upload the CSV representation to the server. The validation should occur before the changes are applied to the resource. The actual URI should not be of relevance to clients other than to determine where to send the request to and as such can be freely chosen by you, the service implementor. By following these steps you pretty much gain the freedom to change your server side at any time and clients will not break as a consequence if they support the used media-types.

Title: How to create REST URLs without verbs?

Body:
I'm struggling to determine how to design restful URLs.  I'm all for the restful approach of using URLs with nouns and not verbs don't understand how to do this.

We are creating a service to implement a financial calculator.  The calculator takes a bunch of parameters that we will upload via a CSV file.  The use cases would involve:

Upload new parameters

Get the latest parameters

Get parameters for a given business date

Make a set of parameters active

Validate a set of parameters

I gather the restful approach would be to have the following type URLs:

/parameters
/parameters/12-23-2009

You could achieve the first three use cases with:

POST where you include the parameter file in the post request

GET of first URL

GET of second URL

But how do you do the 4th and 5th use case without a verb?  Wouldn't you need URLs like:

/parameters/ID/activate
/parameters/ID/validate

??

Body:
I feel a bit sad to see that after more than 10 years there is no answer really stating how such a thing as requested in the OP could be designed in a REST architecture, hence I feel the need to do this now.

First things first, what is REST?! The acronym REST or ReST stands for "Representational State Transfer" and defines the exchange of a resource's state in a certain representation format. The representation format is tide to the negotiated media type. In the case of application/html the representation format may be a stream of HTML formatted text content that is rendered in the browser, probably after applying some stylesheet formatting to position certain elements at certain locations.

REST is in principle a generalization of the browsable Web we all know, though targets all kinds of applications and not only browsers. Therefore, by design, the same concepts that apply to the Web also apply to a REST architecture. A question like how to achieve something in a "RESTful" way resolves around answering the question how to achieve something on a Web page and then apply the same concepts onto the application layer.

A Web based calculator may usually start off with some "page" that allows you to input some values to calculate before sending the entered data to the server. In HTML this is usually achieved via HTML <form> elements that teaches a client on the available parameters to set, the target location to send the request to as well as the representation format to apply upon sending the input data. This can i.e. look like this:

<html>
  <head>
    ...
  </head>
  <body>
    <form action="/../someResource" method="post" enctype="application/x-www-form-urlencoded">
      <label for="firstNumber">First number:</label>
      <input type="number" id="firstNumber" name="firstNumber"/>

      <label for="secondNumber">Second number:</label>
      <input type="number" id="secondNumber" name="secondNumber"/>

      <input type="submit" value="Add numbers"/>
    </form>
  </body>
</html>

The sample above i.e. states that there are two input fields that can be filled out either by the user or by some other automata, and that upon invoking the submit input element the browser takes care of formatting the input data into a application/x-www-form-urlencoded representation format that is sent to the mentioned target location via the specified HTTP request method, POST in this case. If we enter 1 into the firstNumber input field and 2 into the secondNumber input field, the browser will generate a representation of firstNumber=1&secondNumber=2 and send this as the body payload of the actual request to the target resource.

The raw HTTP request issued to the server therefore may look like this:

POST /../someResource
Host: www.acme.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 28
Accept: application/html

firstNumber=1&secondNumber=2

The server may perform the calculation and respond with a further HTML page that contains the result of the calculation, as the request indicated that the client understands this format.

As Breton pointed already out there is no such thing as a "RESTful" URL or URI. A URI/URL is its own kind of thing and should not convey any meaning to a client/user. In the calculator sample above a user simply isn't interested where to send the data to it is just interested in that upon triggering the submit input field the request is sent. All the required information needed to perform the task should already be given by the server.

A browser also might not be aware of that the request is actually feeding a calculator with some input parameters, it could as well be some kind of an order form that returns just the next form representation to continue the ordering process or some totally different kind of resource. It simply performs what the HTML spec demands in such a case and it couldn't care less what the server is actually doing. This concept enables a browser to use the same representation format to do all kind of things such as ordering some stuff from your preferred online shop, chatting with your best friends, signing into an online account and so on.

The affordance of certain elements, such in the submit input field case that is usually rendered as button, defines what you should to with it. In the case of a button or a link it basically tells you to click it. Other elements may convey different affordances. Such an affordance can also be expressed via link-relations as i.e. with preload annotated links that basically tell a client that it can already load the content of the linked resource in the background as the user will most likely grab this content next. Such link relations should of course be standardized or follow the extension mechanism for relation types as defined by Web linking.

These are the fundamental concept that are used on the Web and that should also be used in a REST architecture. According to "Uncle Bob" Robert C. Martin an architecture is about intent and the intention behind the REST architecture is the decoupling of clients from servers to allow servers to evolve freely in future without having to fear them breaking clients. This unfortunately requires a lot of discipline as it is so easy to introduce coupling or to add quick-fix solutions to get the job done and move on. As Jim Webber pointed out in a REST architecture you, as a service provider, should attempt to design an domain application protocol similar to a text based computer game of the 70s that clients will follow through until they reached the end of a process.

What plenty of so-called "REST" APIs unfortunately do in reality is everything but that. You see the exchange of mostly JSON based data that is specified in an API specific external documentation that is usually hard to dynamically integrate on the fly. The format how a request needs to look like are also hardcoded into the external documentation which lead to plenty of implementation interpreting URIs to return predefined typs instead of using some common representation format that is negotiated upfront. This prevents servers from changing as clients now expect to receive a certain data format (note not representation format!) for predefined URIs. This custom data format exchange furthermore prevents clients from interacting with other APIs as the "data format" is usually tide to a specific API. We know this concept from the past from RPC technologies such as Corba, RMI or SOAP which we condemn as somehow evil, even though Peppol moved to it again by replacing AS2 with AS4 as default transfer protocol as of recently.

In regards to the actual question asked, sending data as csv file is nothing different than using application/x-www-form-urlencoded representation or similar stuff. Jim Webber made it clear that after all HTTP is just a transport protocol whose application domain is the transfer of documents over the Web. Client and server should at least both support text/csv as defined in RFC 7111. This CSV file could be generated as a consequence of processing a media type that defines form elements, a target element or attribute to send the request to as well as the HTTP method to perform the upload of the configuration.

There are a couple of media types that support forms such as HTML, HAL Forms, halform, ion or Hydra. I am currently, though, not aware of a media type that automatically can encode the input data into text/csv directly hence one might need to be defined and registered with IANA's media type registry.

The upload and download of the complete parameter set shouldn't be an issue I guess. As mentioned before, the target URI is not of relevance as a client will just use the URI to retrieve new content to process. Filtering by business date should also not be to difficult. Here the server should however the client with all the possibilities the client simply can chose from. In recent years GraphQL and RestQL evolved which introduce an SQL like language that can be targeted at a certain endpoint to get a filtered response. However, in a true REST sense this violates the idea behind REST as a) GraphQL i.e. only uses a single endpoint which somehow prevents optimal usage of caching and b) requires the knowledge of available fields upfrong, which may lead to introducing a coupling of clients to the base data model of the resource.

Activating or deactivating certain configuration parameters is simply a matter of triggering the hypermedia controls that provide this affordance. In HTML forms this could be a simple checkbox or a multi-line selection in a list or that kind. Depending on the form and what method it defines it could then potentially send the whole configuration via PUT or be smart about the changes done and only perform a partial update via PATCH. The latter one requires basically a calculaton of the change representation to the one updated and feed the server with the required steps to tranform the current representation into the desired one. According to the PATH specification this has to be done within a transaction so that either all or none of the steps are applied.

HTTP allows and encourages a server to validate a received request upfront before applying the changes. For PUT the spec states:

An origin server SHOULD verify that the PUT representation is
consistent with any constraints the server has for the target
resource that cannot or will not be changed by the PUT.  This is
particularly important when the origin server uses internal
configuration information related to the URI in order to set the
values for representation metadata on GET responses.  When a PUT
representation is inconsistent with the target resource, the origin
server SHOULD either make them consistent, by transforming the
representation or changing the resource configuration, or respond
with an appropriate error message containing sufficient information
to explain why the representation is unsuitable.  The 409 (Conflict)
or 415 (Unsupported Media Type) status codes are suggested, with the
latter being specific to constraints on Content-Type values.

For example, if the target resource is configured to always have a
Content-Type of "text/html" and the representation being PUT has a
Content-Type of "image/jpeg", the origin server ought to do one of:

a.  reconfigure the target resource to reflect the new media type;

b.  transform the PUT representation to a format consistent with that
of the resource before saving it as the new resource state; or,

c.  reject the request with a 415 (Unsupported Media Type) response
indicating that the target resource is limited to "text/html",
perhaps including a link to a different resource that would be a
suitable target for the new representation.

HTTP does not define exactly how a PUT method affects the state of an
origin server beyond what can be expressed by the intent of the user
agent request and the semantics of the origin server response. ...

To sum this post up, you should either use an existing media type that allows you to teach a client about the required or supported input parameters, the target location to send the request to, the operation to use as well as the media-type the request has to be formatted in, or define your own one that you register with IANA. The latter might be necessary if you want to convert the input to text/csv and then upload the CSV representation to the server. The validation should occur before the changes are applied to the resource. The actual URI should not be of relevance to clients other than to determine where to send the request to and as such can be freely chosen by you, the service implementor. By following these steps you pretty much gain the freedom to change your server side at any time and clients will not break as a consequence if they support the used media-types.


问:
Flutter assets error: EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE
flutter can not find my images assets, what can I be doing wrong?

I got the error on debugger:

Launching lib/main.dart on XT1097 in debug mode...
Built build/app/outputs/apk/debug/app-debug.apk.

```<code>I/flutter (  876): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══
I/flutter (  876): Unable to load asset: assets/images/user/background.jpg
I/flutter (  876): "assets/images/user/background.jpg", scale: 1.0)
</code>```

My pubspec.yml:

```<code>environment:
    sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
    sqflite: any
    path_provider: '>=0.3.0'
    charts_flutter: any
    cupertino_icons: ^0.1.2
    material_search: ^0.2.8
    dio: ^1.0.3
    flutter:
        sdk: flutter

dev_dependencies:
    flutter_test:
        sdk: flutter

flutter:
    uses-material-design: true
    assets:
        - assets/images/
</code>```

and the code:

```<code>                new UserAccountsDrawerHeader(
                    decoration : BoxDecoration(
                        image: new DecorationImage(
                            image: AssetImage('assets/images/user/background.jpg'),
                            fit: BoxFit.cover
                        ),
                        color: Colors.blue,
                    ),
                    accountName: new Text('Diego Botelho'),
                    accountEmail: new Text('dibmartins@gmail.com'),
                    currentAccountPicture: new GestureDetector(
                        onTap: () => print('Toque na imagem'),
                        child: new CircleAvatar(
                            backgroundImage: AssetImage('assets/images/user/avatar.png'),
                        )
                    )
                ),
</code>```

答:
In my case, while i was using relative path like that Image.asset('./../images/welcome.png'), it doesn't work.

But if i use absolute path like that Image.asset('images/welcome.png'), it works !

Body:
flutter can not find my images assets, what can I be doing wrong?

I got the error on debugger:

Launching lib/main.dart on XT1097 in debug mode...
Built build/app/outputs/apk/debug/app-debug.apk.

I/flutter (  876): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞══
I/flutter (  876): Unable to load asset: assets/images/user/background.jpg
I/flutter (  876): "assets/images/user/background.jpg", scale: 1.0)

My pubspec.yml:

environment:
    sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
    sqflite: any
    path_provider: '>=0.3.0'
    charts_flutter: any
    cupertino_icons: ^0.1.2
    material_search: ^0.2.8
    dio: ^1.0.3
    flutter:
        sdk: flutter

dev_dependencies:
    flutter_test:
        sdk: flutter

flutter:
    uses-material-design: true
    assets:
        - assets/images/

and the code:

                new UserAccountsDrawerHeader(
                    decoration : BoxDecoration(
                        image: new DecorationImage(
                            image: AssetImage('assets/images/user/background.jpg'),
                            fit: BoxFit.cover
                        ),
                        color: Colors.blue,
                    ),
                    accountName: new Text('Diego Botelho'),
                    accountEmail: new Text('dibmartins@gmail.com'),
                    currentAccountPicture: new GestureDetector(
                        onTap: () => print('Toque na imagem'),
                        child: new CircleAvatar(
                            backgroundImage: AssetImage('assets/images/user/avatar.png'),
                        )
                    )
                ),


问:
SQS maxNumberOfMessages
Using a Java client application I am querying an SQS queue for messages. The queue has 12,000 messages as setup for testing. I am using openJDK with aws-java-sdk latest (software.amazon.awssdk 2.10.62) pom.xml is shown further down.

The issue I am seeing is that despite setting the maxNumberOfMessages(10) I only ever get 3. I understand that it is a maximum not a guarantee of the number of messages however there is no waver in the number of messages returned. It is always 3.

AWS Documentation:  MaxNumberOfMessages
      The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be
  returned). Valid values: 1 to 10. Default: 1.
      Type: Integer
      Required: No

Consuming Messages Using Short Polling

When you consume messages from a queue using short polling, Amazon SQS
  samples a subset of its servers (based on a weighted random
  distribution) and returns messages from only those servers. Thus, a
  particular ReceiveMessage request might not return all of your
  messages. However, if you have fewer than 1,000 messages in your
  queue, a subsequent request will return your messages. If you keep
  consuming from your queues, Amazon SQS samples all of its servers, and
  you receive all of your messages.

So we have tested two clients in java using both the older aws sdk and the newer one with the same results. Always only 3 messages back.

Interestingly if instead of running the application externally (on my mighty desktop) you run it as an AWS Lambda you get 10 messages. This lambda test was done using JavaScript by a colleague.

So the question remains why do we only ever get 3 messages per request and seemingly within lambda you can get 10.

Given there is a cost per request is the weighted random distribution based on amazon profit =))

SQS Test Method:

```<code>public void SQStart()
{
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create("accessKeyID", "secretKeyID");
    AwsCredentialsProvider creds = StaticCredentialsProvider.create(awsCreds);
    SqsClient sqs = SqsClient.builder().credentialsProvider(creds).region(Region.EU_WEST_1).build();
    GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
            .queueName(QUEUE_NAME)
            .build();
    String queueUrl = sqs.getQueueUrl(getQueueRequest).queueUrl();

    for (int x =1; x < 100; x++) {
        ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .maxNumberOfMessages(10)
                .build();

        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).messages();
        if (messages.size() > 3 ) {
            System.out.println("YEY More than 3 Messages: "+ messages.size());
        }
    }
}
</code>```

POM.XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>SQSTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.10.62</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>

            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sqs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.720</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</project>
</code>```

答:
Given there is a cost per request is the weighted random distribution based on amazon profit =))

It's clear that your goal here is to reduce costs, whether that be by sending fewer requests to SQS, or by forcing SQS to deliver the maximum amount of messages available.

As you've stated in your question, SQS has no obligation to deliver the maximum amount of messages available. However, there is something I'd like to inform you about, assuming you're not already aware of it.

Long Polling

The Developer Guide of Amazon's Simple Queue Service states:

The process of consuming messages from a queue depends on whether you use short or long polling. By default, Amazon SQS uses short polling, querying only a subset of its servers (based on a weighted random distribution) to determine whether any messages are available for a response. You can use long polling to reduce your costs while allowing your consumers to receive messages as soon as they arrive in the queue.

The messages that you sent to SQS may have all been stored on separate servers. As the documentation states, only a subset of servers may be queried if your queue is set to use short polling. My guess is that you were unlucky when invoking receiveMessage and only 3 were returned every time.

If we look at the benefits of long polling on the same documentation page, it states:

Long polling offers the following benefits:

Eliminate empty responses by allowing Amazon SQS to wait until a message is available in a queue before sending a response. Unless the connection times out, the response to the ReceiveMessage request contains at least one of the available messages, up to the maximum number of messages specified in the ReceiveMessage action.

Eliminate false empty responses by querying all—rather than a subset of—Amazon SQS servers.

The second bullet is very important here. Even though you're not seeing empty responses, there may exist more messages stored on servers that aren't being queried. If you enable long polling, you hopefully should see an increase in the amount of messages returned, assuming there's more than 3 servers in total.

Therefore, my suggestion is to enable long polling on your queue. To do this, see the Setting Up Long Polling page.

As DevilCode mentioned in his comment below, he was able to resolve his issue by using a FIFO queue instead of a standard queue, and by enabling long polling on it.

Title: SQS maxNumberOfMessages

Body:
Using a Java client application I am querying an SQS queue for messages. The queue has 12,000 messages as setup for testing. I am using openJDK with aws-java-sdk latest (software.amazon.awssdk 2.10.62) pom.xml is shown further down.

The issue I am seeing is that despite setting the maxNumberOfMessages(10) I only ever get 3. I understand that it is a maximum not a guarantee of the number of messages however there is no waver in the number of messages returned. It is always 3.

AWS Documentation:  MaxNumberOfMessages
      The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be
  returned). Valid values: 1 to 10. Default: 1.
      Type: Integer
      Required: No

Consuming Messages Using Short Polling

When you consume messages from a queue using short polling, Amazon SQS
  samples a subset of its servers (based on a weighted random
  distribution) and returns messages from only those servers. Thus, a
  particular ReceiveMessage request might not return all of your
  messages. However, if you have fewer than 1,000 messages in your
  queue, a subsequent request will return your messages. If you keep
  consuming from your queues, Amazon SQS samples all of its servers, and
  you receive all of your messages.

So we have tested two clients in java using both the older aws sdk and the newer one with the same results. Always only 3 messages back.

Interestingly if instead of running the application externally (on my mighty desktop) you run it as an AWS Lambda you get 10 messages. This lambda test was done using JavaScript by a colleague.

So the question remains why do we only ever get 3 messages per request and seemingly within lambda you can get 10.

Given there is a cost per request is the weighted random distribution based on amazon profit =))

SQS Test Method:

public void SQStart()
{
    AwsBasicCredentials awsCreds = AwsBasicCredentials.create("accessKeyID", "secretKeyID");
    AwsCredentialsProvider creds = StaticCredentialsProvider.create(awsCreds);
    SqsClient sqs = SqsClient.builder().credentialsProvider(creds).region(Region.EU_WEST_1).build();
    GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
            .queueName(QUEUE_NAME)
            .build();
    String queueUrl = sqs.getQueueUrl(getQueueRequest).queueUrl();

    for (int x =1; x < 100; x++) {
        ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .maxNumberOfMessages(10)
                .build();

        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).messages();
        if (messages.size() > 3 ) {
            System.out.println("YEY More than 3 Messages: "+ messages.size());
        }
    }
}

POM.XML:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>SQSTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.10.62</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>

            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sqs</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.720</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</project>


答:
Try this:</p>

```<code>library("dplyr")

# Selects those 3 columns Gets the sum of three columns for each row
medal_count = olympic_df %>% select(medals.gold, medals.silver, medals.bronze) %>% rowSums()

# Filters the original dataset when sum of medals for a row > 10
olympic_df[medal_count>10,"name"] %>% unique # Returns distinct name
</code>```

Title: Using Sum function in R to set a variable from 3 different columns with specified amount

Body:
I am trying to create a character vector that stores the names of countries with 10 or more total medals in R. I am getting back an 'Error: attempt to apply non-function' when running the code.
Here is the code:
biggest_winners=olympic_df$name(sum(olympic_df$medals.gold & olympic_df$medals.silver & olympic_df$medals.bronze >=10))

here is a picture of the first 10 rows with column headers for reference:

Body:
Try this:

library("dplyr")

# Selects those 3 columns Gets the sum of three columns for each row
medal_count = olympic_df %>% select(medals.gold, medals.silver, medals.bronze) %>% rowSums()

# Filters the original dataset when sum of medals for a row > 10
olympic_df[medal_count>10,"name"] %>% unique # Returns distinct name


问:
Using anaconda environment in Atom
I've install Anaconda (Python 3.6) and  tensorflow (python 3.5).  I've managed to get it run both on Spyder and on sublime text 3( by making new build system). Now all the is using Atom( which I'm not used to). So I've trying to "tell" Atom to use python in the following folder: </p>

```<code>C:\users\engine\anaconda3\envs\tensorflow\python.exe
</code>```

<p>without any success, any idea how to do that or what kind of package should I use( I'm using windows so virtualenv)
thanks in advance ! </p>

答:
I had this same issue, and after some exploring, found that this worked well:

There is a file (I'm on macOS Catalina 10.15.3):

~/.atom/packages/platformio-ide-terminal/lib/platformio-ide-terminal.coffee

Look for the autoRunCommand section:

autoRunCommand:

  title: 'Auto Run Command'

  description: 'Command to run on terminal initialization.'

  type: 'string'

  default: ''

If you set the default to:

'export PATH=~/opt/anaconda3/bin:$PATH'

platformio will execute this command every time you start Atom, and it will use the default anaconda python, as specified in the new PATH.

You can then type "conda activate myenvironment" in the platformio terminal and it will work like normal (switch between environments, install packages, etc.). Hope this helps.

Title: Using anaconda environment in Atom

Body:
I've install Anaconda (Python 3.6) and  tensorflow (python 3.5).  I've managed to get it run both on Spyder and on sublime text 3( by making new build system). Now all the is using Atom( which I'm not used to). So I've trying to "tell" Atom to use python in the following folder:

C:\users\engine\anaconda3\envs\tensorflow\python.exe

without any success, any idea how to do that or what kind of package should I use( I'm using windows so virtualenv)
thanks in advance !


问:
Enter blank value in try statements
I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?</p>

```<code>import random
import sys

def main():

  restart = True

  bank_balance = 1000
  player_name = input("Please enter your name: ")
  while (restart):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")

    correct = False
    user_bet=0
    bet = input_bet(user_bet, bank_balance)

    if (user_bet == 0):
      print('Quiting the game')
      break

    win_lose = play_hand(player_name, bet)
    bank_balance+=win_lose

    print(f'Your bank balance: ${bank_balance}')

    play=bet

def input_bet(bet, money):
  correct = False
  while not correct:
    try:
      enough_money = False
      while not enough_money:
        bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
        if (bet > money):
          print('not enough money')
        elif (bet == 0):
          return 0

        elif (bet <= money):
          print(f'Betting ${bet}')
          enough_money=True
          return bet

      correct = True

    except ValueError:
      print('Please enter a number')

def play_hand(name, bet):

  player= []
  dealer= []

  play_again = True

  dealer.append(random.randint(1, 11))

  player.extend([random.randint(1, 11), random.randint(1, 11)])

  print ('The dealer received card of value', *dealer)
  print(name, 'received cards of value', player[0], 'and', player[-1])
  print(f'Dealer total is {sum(dealer)}')
  print(f"{name}'s total is {sum(player)}", '\n')

  stay = False
  bust = False

  while (sum(player) <= 21 and stay == False and play_again == True):
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')

      print(f'Dealer total is {sum(dealer)}')
      print(f"{name}'s cards are", *player)
      print(f"{name}'s total is {sum(player)}", '\n')

    elif (hors == 's'):
      stay=True
      print('stay')

  if (sum(player) > 21 ):
    bust = True
    print('You busted!')
    return -bet

  while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
    dealer.append(random.randint(1, 11))
    print('The dealers cards are', *dealer)
    print('The dealers total is', sum(dealer), '\n')

  if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
    print("The dealer wins!")
    return -bet

  elif (sum(player) <= 21 and sum(player) > sum(dealer)):
    print("You win!")
    return bet

  if (sum(dealer) > 21):
    print ('You win! The dealer busted!')
    return bet

  if (sum(dealer) == sum(player)):
    print('Its a Tie! ')
    return 0

main()
</code>```

答:
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.

```<code>def input_bet(money):
    while True:
        response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
        if bet == "0":
            return 0

        if bet == "":
            bet = "25"
        try:
            bet = int(bet)
        except ValueError:
            print("Please enter a number")
            continue

        if bet > money:
            print("Not enough money")
            continue

        return bet
</code>```

The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.

Title: Enter blank value in try statements

Body:
I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?

import random
import sys

def main():

  restart = True

  bank_balance = 1000
  player_name = input("Please enter your name: ")
  while (restart):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")

    correct = False
    user_bet=0
    bet = input_bet(user_bet, bank_balance)

    if (user_bet == 0):
      print('Quiting the game')
      break

    win_lose = play_hand(player_name, bet)
    bank_balance+=win_lose

    print(f'Your bank balance: ${bank_balance}')

    play=bet

def input_bet(bet, money):
  correct = False
  while not correct:
    try:
      enough_money = False
      while not enough_money:
        bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
        if (bet > money):
          print('not enough money')
        elif (bet == 0):
          return 0

        elif (bet <= money):
          print(f'Betting ${bet}')
          enough_money=True
          return bet

      correct = True

    except ValueError:
      print('Please enter a number')

def play_hand(name, bet):

  player= []
  dealer= []

  play_again = True

  dealer.append(random.randint(1, 11))

  player.extend([random.randint(1, 11), random.randint(1, 11)])

  print ('The dealer received card of value', *dealer)
  print(name, 'received cards of value', player[0], 'and', player[-1])
  print(f'Dealer total is {sum(dealer)}')
  print(f"{name}'s total is {sum(player)}", '\n')

  stay = False
  bust = False

  while (sum(player) <= 21 and stay == False and play_again == True):
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')

      print(f'Dealer total is {sum(dealer)}')
      print(f"{name}'s cards are", *player)
      print(f"{name}'s total is {sum(player)}", '\n')

    elif (hors == 's'):
      stay=True
      print('stay')

  if (sum(player) > 21 ):
    bust = True
    print('You busted!')
    return -bet

  while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
    dealer.append(random.randint(1, 11))
    print('The dealers cards are', *dealer)
    print('The dealers total is', sum(dealer), '\n')

  if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
    print("The dealer wins!")
    return -bet

  elif (sum(player) <= 21 and sum(player) > sum(dealer)):
    print("You win!")
    return bet

  if (sum(dealer) > 21):
    print ('You win! The dealer busted!')
    return bet

  if (sum(dealer) == sum(player)):
    print('Its a Tie! ')
    return 0

main()

Body:
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.

def input_bet(money):
    while True:
        response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
        if bet == "0":
            return 0

        if bet == "":
            bet = "25"
        try:
            bet = int(bet)
        except ValueError:
            print("Please enter a number")
            continue

        if bet > money:
            print("Not enough money")
            continue

        return bet

The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.


问:
Management.Azure.com REST API Call with Odata $expand and $filter | body results not filtering
I am unable to get the desired results using a $expand and $filter in Odata on a REST API GET call. Basically looking to filter results so only properties.status = 'Closed' are returned on the GET API call. So far the expand and filters receive 200 OK but are not honoring the filtering in the body results.

https://management.azure.com/subscriptions/{SUBID}/resourceGroups/{RGNAME}/providers/Microsoft.OperationalInsights/workspaces/{WorkspaceName}/providers/Microsoft.SecurityInsights/Cases?api-version=2019-01-01-preview&$expand=properties($filter=status eq 'Closed')

eventually adding a 2nd filter like:

&$expand=properties($filter=status eq 'Closed' and relatedalertproductnames eq 'Azure Security Center')

答:
I found the following to work as the values were not in an array but an object.

&$filter=(properties/status eq 'Closed')


问:
Android: how to open a Google Map?
I have an activity which extends MapActivity. After running the activity, the Google Map should be shown on the emulator.
How can I do that?</p>

答: for starting mapview then follow this mapview's link</p>

Title: Android: how to open a Google Map?


问:
randomly assign character variables that vary by strata/group in R
I am trying to make a mock employee data set to practice some analyses. I already have a mock data set that has fake employee names, work ids, gender, and ethnicity. I also want to add other variables, such as supervisor status and pay grade. However, male employees are more likely to be supervisors, for instance, than female employees in the actual dataset, so rather than telling R to make 30% of cases supervisor and 70% non-supervisors, I want R to make 20% of female cases  and 30% of male cases supervisors.

I've tried using case_when() or group_by() along with the sample() function, but I can't get it to work.

An ideal solution would be able to be scaled further than just dichotomous variables because pay grade and ethnicity have 5 levels. In addition, if I could scale the solution to account for multiple variables (say, gender and ethnicity), that would be the best.

Here's some fake data with 5 male and 5 female cases. For this case, let's say I want 40% of male cases supervisors (2/5) and only 20% of female cases supervisors (1/5).

```<code>library(tidyverse)
test <- tibble(emp_num = 1:10,
               ethnicity = c("White", "White", "Hispanic", "Black", "Asian", "White", "White", "Hispanic", "Black", "Asian"),
               gender = c("Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female"))
</code>```

Here is how the answer should look with the correct proportions (of course, which employee number is supervisor doesn't matter for this case, just as long as the different proportions by male and female emerge).

```<code>sample_answer <- tibble(emp_num = 1:10,
               ethnicity = c("White", "White", "Hispanic", "Black", "Asian", "White", "White", "Hispanic", "Black", "Asian"),
               gender = c("Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female"),
               sup_status = c("Supervisor", "Supervisor", "Supervisor", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super"))
</code>```

答:
After troubleshooting code I wrote before posting and the answer posted by @Lukas, I found out the issue. The size argument needs to equal the total sample size, and the replace argument needs to be set to TRUE

```<code>test <- test %>% mutate(supervisor = case_when(
         gender == "Male" ~ sample(c("Supervisor", "Non-Super"), nrow(test), replace = TRUE prob=(c(.4, .6))),
         gender == "Female" ~ sample(c("Supervisor", "Non-Super"), nrow(test), replace = TRUE prob=(c(.2, .8))))
</code>```

In this small sample size, you may not find exact breakdowns along these probabilities, but I ran this code on my sample of 5000 and the probabilities are within rounding error.

EDIT: If you want your new variables to vary by multiple groups (say gender and ethnicity, you can do it as you would with any case when. For instance:

```<code>library(tidyverse)
test %>%
  mutate(sup_status = case_when(
    gender == "Female" & ethnicity == "Black" | ethnicity == "Asian" | ethnicity == "Hispanic" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.10, .90)),
    gender == "Female" & ethnicity == "White" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.20, .80)),
    gender == "Male" & ethnicity == "Black" | ethnicity == "Asian" | ethnicity == "Hispanic" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.15, .85)),
    gender == "Male" & ethnicity == "White" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.25, .75)),
  ))
</code>```

Again, with such a small sample dataset, you won't see output with these exact probabilities, but with larger datasets, it will work.

Body:
I am trying to make a mock employee data set to practice some analyses. I already have a mock data set that has fake employee names, work ids, gender, and ethnicity. I also want to add other variables, such as supervisor status and pay grade. However, male employees are more likely to be supervisors, for instance, than female employees in the actual dataset, so rather than telling R to make 30% of cases supervisor and 70% non-supervisors, I want R to make 20% of female cases  and 30% of male cases supervisors.

I've tried using case_when() or group_by() along with the sample() function, but I can't get it to work.

An ideal solution would be able to be scaled further than just dichotomous variables because pay grade and ethnicity have 5 levels. In addition, if I could scale the solution to account for multiple variables (say, gender and ethnicity), that would be the best.

Here's some fake data with 5 male and 5 female cases. For this case, let's say I want 40% of male cases supervisors (2/5) and only 20% of female cases supervisors (1/5).

library(tidyverse)
test <- tibble(emp_num = 1:10,
               ethnicity = c("White", "White", "Hispanic", "Black", "Asian", "White", "White", "Hispanic", "Black", "Asian"),
               gender = c("Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female"))

Here is how the answer should look with the correct proportions (of course, which employee number is supervisor doesn't matter for this case, just as long as the different proportions by male and female emerge).

sample_answer <- tibble(emp_num = 1:10,
               ethnicity = c("White", "White", "Hispanic", "Black", "Asian", "White", "White", "Hispanic", "Black", "Asian"),
               gender = c("Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female"),
               sup_status = c("Supervisor", "Supervisor", "Supervisor", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super", "Non-Super"))

Body:
After troubleshooting code I wrote before posting and the answer posted by @Lukas, I found out the issue. The size argument needs to equal the total sample size, and the replace argument needs to be set to TRUE

test <- test %>% mutate(supervisor = case_when(
         gender == "Male" ~ sample(c("Supervisor", "Non-Super"), nrow(test), replace = TRUE prob=(c(.4, .6))),
         gender == "Female" ~ sample(c("Supervisor", "Non-Super"), nrow(test), replace = TRUE prob=(c(.2, .8))))

In this small sample size, you may not find exact breakdowns along these probabilities, but I ran this code on my sample of 5000 and the probabilities are within rounding error.

EDIT: If you want your new variables to vary by multiple groups (say gender and ethnicity, you can do it as you would with any case when. For instance:

library(tidyverse)
test %>%
  mutate(sup_status = case_when(
    gender == "Female" & ethnicity == "Black" | ethnicity == "Asian" | ethnicity == "Hispanic" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.10, .90)),
    gender == "Female" & ethnicity == "White" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.20, .80)),
    gender == "Male" & ethnicity == "Black" | ethnicity == "Asian" | ethnicity == "Hispanic" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.15, .85)),
    gender == "Male" & ethnicity == "White" ~ sample(c("Supervisor", "Not Supervisor"), nrow(test), replace=TRUE, prob=c(.25, .75)),
  ))

Again, with such a small sample dataset, you won't see output with these exact probabilities, but with larger datasets, it will work.