问:
How to handle cache update after mutation in multiple views?
This is more of a open question but hopefully it won’t get deleted.

I am using react and apollo although the question is more general.

Let’s say I have 3 distinct views in my app all using similar (but not the same) data.
All of them are using separate queries but each of the query uses common operation but with slightly different data returned.

Let’s say I have a mutation somewhere that adds something to data (think of a list of items and a new item being added).

Let’s say after mutation I want to update cache to reflect that change. I am using read/writeQuery to do the update.
With this setup I need to update 3 queries - this becomes a maintenance nightmare.

After some reading I figured I am doing this wrong - I have now created a single query - now I need to only update that single query after mutation and all of my views are updated automatically.
However the problem is that this query now has to download all the data that all 3 views combined need - feels like this is very inefficient, because some of the views will get data they'll never use.

Is there a better way to do it?

Please note that read/writeFragment won't work because they won't update the underlying queries - check this answer for example: https://stackoverflow.com/a/50349323/2874705

Please let me know in comment if you need a more concrete example.

All in all I think in this setup I would just be better with a global state handling and avoid apollo cache all together - however I feel cheated cause apollo promised to solve the state problems :)

EDIT

Here's a concerete example:

Let's say our graphql schema is defined liked this:

```<code>type Post {
    id: ID!
    title: String!
    body: String
    published: Boolean!

}

type Query {
    posts(published: Boolean): [Post!]!
}

type Mutation {
  createDraft(body: String!, title: String!): Post
  publish(id: Int!): Post
}
</code>```

Now, we create 3 queries and 2 mutations on the client

```<code>query PostTitles {
    posts {
        id
        title
    }
}

query Posts {
    posts {
        id
        title
        body
        published
    }
}

query PublishedPosts {
    posts (published: true) {
        id
        title
        body
        published
    }
}

mutation CreateDraftPost ($body: String!, $title: String!) {
    createDraft(body: $body, title: $title) {
        id
        title
        body
        published
    }
}

mutation PublishPost ($id:ID!) {
    publish (id: $id) {
        id
        published
    }
}
</code>```

Just to note createDraft creates a post with the default false published value.

How can use either of those mutations to create or publish a post and have all the 3 cached queries to be updated without using refetchQueries or manualy updating each of the query?
I think the real problem is that each of those queries are stored separately in the apollo in-memory cache.

答:
It sounds like you've looked into and used the update argument that can be passed to mutation functions returned from useMutation. You're probably using proxy.readQuery and proxy.writeQuery to update it (or letting this magic happen in the background). If not, here is the documentation.

Another approach that is similar in concept but finer detail is to use proxy.readFragment and proxy.writeFragment. You can specify a set of properties on a type as being part of a fragment, and update that fragment whenever new data comes in. The nice part is that this fragment can be used within any number of queries, and if you update the fragment, those queries will update.

fragment documentations

Body:
This is more of a open question but hopefully it won’t get deleted.

I am using react and apollo although the question is more general.

Let’s say I have 3 distinct views in my app all using similar (but not the same) data.
All of them are using separate queries but each of the query uses common operation but with slightly different data returned.

Let’s say I have a mutation somewhere that adds something to data (think of a list of items and a new item being added).

Let’s say after mutation I want to update cache to reflect that change. I am using read/writeQuery to do the update.
With this setup I need to update 3 queries - this becomes a maintenance nightmare.

After some reading I figured I am doing this wrong - I have now created a single query - now I need to only update that single query after mutation and all of my views are updated automatically.
However the problem is that this query now has to download all the data that all 3 views combined need - feels like this is very inefficient, because some of the views will get data they'll never use.

Is there a better way to do it?

Please note that read/writeFragment won't work because they won't update the underlying queries - check this answer for example: https://stackoverflow.com/a/50349323/2874705

Please let me know in comment if you need a more concrete example.

All in all I think in this setup I would just be better with a global state handling and avoid apollo cache all together - however I feel cheated cause apollo promised to solve the state problems :)

EDIT

Here's a concerete example:

Let's say our graphql schema is defined liked this:

type Post {
    id: ID!
    title: String!
    body: String
    published: Boolean!

}

type Query {
    posts(published: Boolean): [Post!]!
}

type Mutation {
  createDraft(body: String!, title: String!): Post
  publish(id: Int!): Post
}

Now, we create 3 queries and 2 mutations on the client

query PostTitles {
    posts {
        id
        title
    }
}

query Posts {
    posts {
        id
        title
        body
        published
    }
}

query PublishedPosts {
    posts (published: true) {
        id
        title
        body
        published
    }
}

mutation CreateDraftPost ($body: String!, $title: String!) {
    createDraft(body: $body, title: $title) {
        id
        title
        body
        published
    }
}

mutation PublishPost ($id:ID!) {
    publish (id: $id) {
        id
        published
    }
}

Just to note createDraft creates a post with the default false published value.

How can use either of those mutations to create or publish a post and have all the 3 cached queries to be updated without using refetchQueries or manualy updating each of the query?
I think the real problem is that each of those queries are stored separately in the apollo in-memory cache.


来源: stackexchange

问:
How to see console.log statements in deployed Lambda function

I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

my handler.js contains:

```<code>module.exports.main = async event => {
    console.log('IN HANDLER');

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };
</code>```

my index.js contains a longrunning (45- 60 seconds) puppeteer function (main ) which returns an array of objects:

```<code>async function main(event, context, callback) {
  const chromium = require('chrome-aws-lambda');

 ...................................

 var obj_arr = [];
  var keys = head[0];
  for (let index = 0; index < body.length; index++) {
    var row = body[index];
    var obj = {};
    for (let i = 0; i < keys.length; i++) {
      var k = keys[i];
      obj[k] = row[i];
      console.log(obj);

    }
    obj_arr.push(obj);

  };

  console.log(obj_arr);
  return obj_arr;
</code>```

After uploading my function to lambda using  serverless framework without error. I followed the directions at the bottom of the article about testing the pre provisioned chrome in my layers dashboard. As you can see in the screenshot it appears to be working correctly.

being brand new to this I don't understand the log output:

```<code>START RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3 Version: $LATEST
2020-05-31T19:10:21.280Z    f62dcf47-e2ff-4a96-9807-b34c39f218e3    INFO    SERVERLESS_ENTERPRISE {"c":true,"b":"H4sIAAAAAAAAA7VWbU/cOBD+Kyi6D3fSJms7ifNSIR1aoK1UKsouVe+ADyZxdlMSO9gJL0X732+cZF9ZEJzUL7CZeTyemWf82E+WVPk0F1Zs6ULbbMpFbQ0sncx4yb5zpXNpfMhBYK3zkuualRVYCCLIRr7t4gmOYoxigh0ShP8CTPHbBnCfU4BllKRJ5gU2J1lmeyyidhSiwL52vcSNMoJD7prIjxUHdK2Y0CypzaYDq2KPhWQQ5anPZ9KhtK0rJl7MUlZcMRPiKys7+FpYO2vEIj6UoupJ3oJ2l+OZcrhIXwW1NadNt6cVuw5ClAQuxIcsR1LU/KE2NUAWCX9PU8z6Fo+J5+IsRLYbUNf2QopsljFkezhKSYhpwMNrwD9MljucSVnvY9vnqYcwTgDpRiRKeeZSlvihl0VeSpIo+XDKFDC+j9yMJggSSVOCvYR/GAPLBU/3kTUHdthU72Dhpbb+z9lpmy3V1BQgmqIYWKyqijzZ4JIXBVdmE67u8oSvmesZL5hIhbzvqJ0unCm/A8siwZ0rbMDYJctFn6hsgDE6sBJZVk3N+4rZvXYKVl6nzFq6zhpRd8Ox8jpCpvyndjBxMHXcNTCfdi1ptM2Zrm288p3wUqrHcf7LxMKIeNuuc80Ns0+XltL6EuYsotSn1BtcWjPOqomsWQFmjJChmvZmswqslLoB8kIwwjByJToojjANw/n2TqdcJTAU0MFuT+T4oR+5gb/EmamGbnF1XnXVI6iUBL7nmrnvQZ/1SBbp2BwyK65Vw1ceAfwIGFVxJzt6RxL6CBmtdmh0Lcvx5sD1PhtabW8Tsb5ge/Y2IMdvHYSdq1ah//hyMDkaT7aBB8o4mRIxZBl3WcZLvmPs+6ZN1EUejRczGb8xidfmp0O8MkUdwLT8hq+O2Gbu9/rs/dq9EeLHb9GgrU2+yOlHJZuqp3AInR52nR6+sZMQYVwrzso+hFGkIfKHLh5e9MReURJGDLtpkEQIimchYYTD34S51zjJyHbMI3F3WrA6k6qEiEUumocdkAOVzMD9QJ9RA86OvvYow2EgOIJJ8T3vJeCx4tyc+MAPgBhMn+NGVQPKbV2AapQgSubUX1qf4Uoq/jz7a+8Hl8L8P1Uy4VpLtff3HnF89PHTr0sLtEJXvFUP4iMEn62EwycEa0B/WwVpHQKUGL7MT/1oEL7b2vO0MHYSwqh0IXJ1a4Dz+eA3ZdQ7nmVEvK2MCA42M7oyV/0dDGIvN424gQkSS+vb7q8WO5YNKOjiiLWmXp6MqC6vJK6UVKuj2H4es5b7NcuoKSqV1xu2o4eEV0Y5ulx3eU6gfe1mu5yQR3LTvkcW/rW7/D1PjpoLJjq1kG3kmYQ2YaNLcHmf58ZRfvqZfvNn3yYn9+NDF539g5cLO8D3sNCH09vR4bFOk1l0gkzkqmjgWbqSW9ehThu3NqdjDE8jbfh976sKXjOFbF8z8+6BBT8vrhYct++ci6v5/D/G0CmZFwsAAA==","origin":"sls-agent"}
END RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3
REPORT RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3  Duration: 14.09 ms  Billed Duration: 100 ms Memory Size: 1024 MB    Max Memory Used: 71 MB  Init Duration: 190.72 ms
</code>```

I get a similar log output when I run my deployed function through the api gatewaybut I don't see either the console.log In my function locally I am able to see console.log statements or the returned array of objects which I see when I run locally. How to I see those in my deployed lambda function when I run it?

EDIT:

I've added a screenshot of what I think you are referring to.  I don't see the console logged output I see locally. Can you explain further or am I looking in the wrong place?

EDIT1:

```<code>{ origin: 'sls-agent',
  schemaVersion: '0.0',
  timestamp: '2020-06-03T13:13:52.763Z',
  requestId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3',
  type: 'transaction',
  payload:
   { schemaType: 's-span',
     .....
     tags:
      { schemaType: 's-transaction-function',
        schemaVersion: '0.0',
        timestamp: '2020-06-03T13:13:52.758Z',
        orgId: null,
        applicationName: 'xxxx',
        serviceName: 'xxxxxx',
        stageName: 'dev',
        functionName: 'xxxxx-dev-main',
        timeout: 6,
        computeType: 'aws.lambda',
        computeRuntime: 'aws.lambda.nodejs.12.16.3',
        computeRegion: 'us-east-1',
        computeMemorySize: '1024',
        computeMemoryUsed:
         '{"rss":39337984,"heapTotal":10039296,"heapUsed":6716000,"external":1191688}',
         ......
        eventCustomRequestTime: '03/Jun/2020:13:13:51 +0000',
        eventCustomRequestTimeEpoch: 1591190031809,
        eventCustomHttpPath: '/main/get',
        eventCustomHttpMethod: 'GET',
        eventCustomXTraceId: 'Root=1-5ed7a20f-9a64d880002f1600092ec680',
        eventCustomXForwardedFor: null,
        eventCustomUserAgent:
         'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        errorId: null,
        errorFatal: null,
        errorCulprit: null,
        errorExceptionType: null,
        errorExceptionMessage: null,
        errorExceptionStacktrace: null,
        transactionId: '77fef8cb-3f2c-4f5a-be2c-7fcd51e9ed92',
        tenantId: 'option88',
        appUid: 'mHjdQ5hQ0RY1',
        tenantUid: 'V8lsDgch9M0b',
        pluginVersion: '3.6.11',
        totalSpans: 0,
        traceId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3' },
     logs: {},
     spans: [],
     eventTags: [] } }
</code>```

Edit2:

Edit3:

I changed the handler to :

```<code>'use strict';
var index = require('./index.js');

module.exports.main = async event => {
  var res = await index.main();

  console.log('hello');
  console.log(res);

  console.log('IN HANDLER');
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

};
</code>```

Now seeing error messages.

答:
These are accessible in CloudWatch logs.

If you access in the region you execute the Lambda in it should have a log group of /aws/lambda/functionname.

Then a stream of the save revision

ContentLicense: CC BY-SA 4.0

Body:
I'm getting started trying to write a lambda function with node and puppeteer. I'm using the serverless framework

I've been trying to follow https://codissimo.sinumo.tech/2019/12/27/serverless-puppeteer-with-aws-lambda-layers-and-node-js/ to utilize the provisioned chrome at https://github.com/shelfio/chrome-aws-lambda-layer . My function is working as expected locally.

my handler.js contains:

module.exports.main = async event => {
    console.log('IN HANDLER');

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

my index.js contains a longrunning (45- 60 seconds) puppeteer function (main ) which returns an array of objects:

async function main(event, context, callback) {
  const chromium = require('chrome-aws-lambda');

 ...................................

 var obj_arr = [];
  var keys = head[0];
  for (let index = 0; index < body.length; index++) {
    var row = body[index];
    var obj = {};
    for (let i = 0; i < keys.length; i++) {
      var k = keys[i];
      obj[k] = row[i];
      console.log(obj);

    }
    obj_arr.push(obj);

  };

  console.log(obj_arr);
  return obj_arr;

After uploading my function to lambda using  serverless framework without error. I followed the directions at the bottom of the article about testing the pre provisioned chrome in my layers dashboard. As you can see in the screenshot it appears to be working correctly.

being brand new to this I don't understand the log output:

START RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3 Version: $LATEST
2020-05-31T19:10:21.280Z    f62dcf47-e2ff-4a96-9807-b34c39f218e3    INFO    SERVERLESS_ENTERPRISE {"c":true,"b":"H4sIAAAAAAAAA7VWbU/cOBD+Kyi6D3fSJms7ifNSIR1aoK1UKsouVe+ADyZxdlMSO9gJL0X732+cZF9ZEJzUL7CZeTyemWf82E+WVPk0F1Zs6ULbbMpFbQ0sncx4yb5zpXNpfMhBYK3zkuualRVYCCLIRr7t4gmOYoxigh0ShP8CTPHbBnCfU4BllKRJ5gU2J1lmeyyidhSiwL52vcSNMoJD7prIjxUHdK2Y0CypzaYDq2KPhWQQ5anPZ9KhtK0rJl7MUlZcMRPiKys7+FpYO2vEIj6UoupJ3oJ2l+OZcrhIXwW1NadNt6cVuw5ClAQuxIcsR1LU/KE2NUAWCX9PU8z6Fo+J5+IsRLYbUNf2QopsljFkezhKSYhpwMNrwD9MljucSVnvY9vnqYcwTgDpRiRKeeZSlvihl0VeSpIo+XDKFDC+j9yMJggSSVOCvYR/GAPLBU/3kTUHdthU72Dhpbb+z9lpmy3V1BQgmqIYWKyqijzZ4JIXBVdmE67u8oSvmesZL5hIhbzvqJ0unCm/A8siwZ0rbMDYJctFn6hsgDE6sBJZVk3N+4rZvXYKVl6nzFq6zhpRd8Ox8jpCpvyndjBxMHXcNTCfdi1ptM2Zrm288p3wUqrHcf7LxMKIeNuuc80Ns0+XltL6EuYsotSn1BtcWjPOqomsWQFmjJChmvZmswqslLoB8kIwwjByJToojjANw/n2TqdcJTAU0MFuT+T4oR+5gb/EmamGbnF1XnXVI6iUBL7nmrnvQZ/1SBbp2BwyK65Vw1ceAfwIGFVxJzt6RxL6CBmtdmh0Lcvx5sD1PhtabW8Tsb5ge/Y2IMdvHYSdq1ah//hyMDkaT7aBB8o4mRIxZBl3WcZLvmPs+6ZN1EUejRczGb8xidfmp0O8MkUdwLT8hq+O2Gbu9/rs/dq9EeLHb9GgrU2+yOlHJZuqp3AInR52nR6+sZMQYVwrzso+hFGkIfKHLh5e9MReURJGDLtpkEQIimchYYTD34S51zjJyHbMI3F3WrA6k6qEiEUumocdkAOVzMD9QJ9RA86OvvYow2EgOIJJ8T3vJeCx4tyc+MAPgBhMn+NGVQPKbV2AapQgSubUX1qf4Uoq/jz7a+8Hl8L8P1Uy4VpLtff3HnF89PHTr0sLtEJXvFUP4iMEn62EwycEa0B/WwVpHQKUGL7MT/1oEL7b2vO0MHYSwqh0IXJ1a4Dz+eA3ZdQ7nmVEvK2MCA42M7oyV/0dDGIvN424gQkSS+vb7q8WO5YNKOjiiLWmXp6MqC6vJK6UVKuj2H4es5b7NcuoKSqV1xu2o4eEV0Y5ulx3eU6gfe1mu5yQR3LTvkcW/rW7/D1PjpoLJjq1kG3kmYQ2YaNLcHmf58ZRfvqZfvNn3yYn9+NDF539g5cLO8D3sNCH09vR4bFOk1l0gkzkqmjgWbqSW9ehThu3NqdjDE8jbfh976sKXjOFbF8z8+6BBT8vrhYct++ci6v5/D/G0CmZFwsAAA==","origin":"sls-agent"}
END RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3
REPORT RequestId: f62dcf47-e2ff-4a96-9807-b34c39f218e3  Duration: 14.09 ms  Billed Duration: 100 ms Memory Size: 1024 MB    Max Memory Used: 71 MB  Init Duration: 190.72 ms

I get a similar log output when I run my deployed function through the api gatewaybut I don't see either the console.log In my function locally I am able to see console.log statements or the returned array of objects which I see when I run locally. How to I see those in my deployed lambda function when I run it?

EDIT:

I've added a screenshot of what I think you are referring to.  I don't see the console logged output I see locally. Can you explain further or am I looking in the wrong place?

EDIT1:

{ origin: 'sls-agent',
  schemaVersion: '0.0',
  timestamp: '2020-06-03T13:13:52.763Z',
  requestId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3',
  type: 'transaction',
  payload:
   { schemaType: 's-span',
     .....
     tags:
      { schemaType: 's-transaction-function',
        schemaVersion: '0.0',
        timestamp: '2020-06-03T13:13:52.758Z',
        orgId: null,
        applicationName: 'xxxx',
        serviceName: 'xxxxxx',
        stageName: 'dev',
        functionName: 'xxxxx-dev-main',
        timeout: 6,
        computeType: 'aws.lambda',
        computeRuntime: 'aws.lambda.nodejs.12.16.3',
        computeRegion: 'us-east-1',
        computeMemorySize: '1024',
        computeMemoryUsed:
         '{"rss":39337984,"heapTotal":10039296,"heapUsed":6716000,"external":1191688}',
         ......
        eventCustomRequestTime: '03/Jun/2020:13:13:51 +0000',
        eventCustomRequestTimeEpoch: 1591190031809,
        eventCustomHttpPath: '/main/get',
        eventCustomHttpMethod: 'GET',
        eventCustomXTraceId: 'Root=1-5ed7a20f-9a64d880002f1600092ec680',
        eventCustomXForwardedFor: null,
        eventCustomUserAgent:
         'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
        errorId: null,
        errorFatal: null,
        errorCulprit: null,
        errorExceptionType: null,
        errorExceptionMessage: null,
        errorExceptionStacktrace: null,
        transactionId: '77fef8cb-3f2c-4f5a-be2c-7fcd51e9ed92',
        tenantId: 'option88',
        appUid: 'mHjdQ5hQ0RY1',
        tenantUid: 'V8lsDgch9M0b',
        pluginVersion: '3.6.11',
        totalSpans: 0,
        traceId: 'f4a4cb9b-3e09-46d3-adba-6f14753cdce3' },
     logs: {},
     spans: [],
     eventTags: [] } }

Edit2:

Edit3:

I changed the handler to :

'use strict';
var index = require('./index.js');

module.exports.main = async event => {
  var res = await index.main();

  console.log('hello');
  console.log(res);

  console.log('IN HANDLER');
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'main function executed!',
        input: event,
      },
      null,
      2
    ),
  };

};

Now seeing error messages.


问:
itertools.permutations of Pandas dataframe index uses too much memory
I'm trying to make a new Dataframe based on a permutation of another Dataframe.  Here is the original Dataframe.  Price is the index.

```<code>df1
Price     Bid   Ask
1          .01   .05
2          .04   .08
3          .1    .15
.           .      .
130        2.50  3.00
</code>```

The second Dataframe is meant to take the index from df1 and create a Dataframe (df2) with permutations of df1 index based on 4 prices such as in the example output below.

```<code>df2
 #     price1   price2   price 3  price 4
 1       1        2         3       4
 2       1        2         3       5
 3       1        2         3       6
 ..       ..       ..        ..      ..
</code>```

To achieve this, I've been using itertools.permutation, but I'm having memory issues and cannot execute the huge number of permutations.  This is the code I've been using to make the permutations.

```<code>price_combos = list(x for x in itertools.permutations(df1.index, 4))
df2 = pd.DataFrame(price_combos , columns=('price1', 'price2', 'price3', 'price4'))
</code>```

答:
dtypes are probably causing the memory allocation to balloon.

The df1.index is Int64Index

The best thing I found, for your scenario, is to set the dataframe index into a numpy array with an int16 dtype.

The numeric range of int8 is -128 to 128.  Since your index is 0 to 130, int8 will not suffice.

Creating a price_combos variable and then a dataframe, will use twice the amount of memory, so create df2 without the intermediary step.

If you create the dataframe without specifying the dtype, as you're doing, the dtype will be int64

With the following implementation, there will be one object, df2, that will be 2,180,905,112 Bytes

With the original implementation, there would be two int64 objects of 8GB each, for a total of 16GB.

If you're using Jupyter, it has terrible memory management.

Perhaps increasing the the amount of virtual memory / swap file size, will give you the extra buffer needed memory. Virtual memory is Windows, swap file is Linux. It's easy to do, just Google it.

import numpy as np
import pandas a pd
from itertools import permutations

# synthetic data set and create dataframe
np.random.seed(365)
data = {'Price': list(range(1, 131)),
        'Bid': [np.random.randint(1, 10)*0.1 for _ in range(130)]}

df1 = pd.DataFrame(data)
df1['Ask'] = df1.Bid + 0.15
df1.set_index('Price', inplace=True)

# convert the index to an int16 array
values = df1.index.to_numpy(dtype='int16')

# create df2
%%time
df2 = pd.DataFrame(np.array(list(permutations(values, 4))), columns=('price1', 'price2', 'price3', 'price4'))
>>> Wall time: 2min 45s

print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 272613120 entries, 0 to 272613119
Data columns (total 4 columns):
 #   Column  Dtype
---  ------  -----
 0   price1  int16
 1   price2  int16
 2   price3  int16
 3   price4  int16
dtypes: int16(4)
memory usage: 2.0 GB
```

<h3><code>df2.head()</code></h3>

<pre class="lang-py prettyprint-override"><code>   price1  price2  price3  price4
0       1       2       3       4
1       1       2       3       5
2       1       2       3       6
3       1       2       3       7
4       1       2       3       8
</code>```

df2.tail()

           price1  price2  price3  price4
272613115     130     129     128     123
272613116     130     129     128     124
272613117     130     129     128     125
272613118     130     129     128     126
272613119     130     129     128     127
```

Body:
I'm trying to make a new Dataframe based on a permutation of another Dataframe.  Here is the original Dataframe.  Price is the index.

df1
Price     Bid   Ask
1          .01   .05
2          .04   .08
3          .1    .15
.           .      .
130        2.50  3.00

The second Dataframe is meant to take the index from df1 and create a Dataframe (df2) with permutations of df1 index based on 4 prices such as in the example output below.

df2
 #     price1   price2   price 3  price 4
 1       1        2         3       4
 2       1        2         3       5
 3       1        2         3       6
 ..       ..       ..        ..      ..

To achieve this, I've been using itertools.permutation, but I'm having memory issues and cannot execute the huge number of permutations.  This is the code I've been using to make the permutations.

price_combos = list(x for x in itertools.permutations(df1.index, 4))
df2 = pd.DataFrame(price_combos , columns=('price1', 'price2', 'price3', 'price4'))

Body:
dtypes are probably causing the memory allocation to balloon.

The df1.index is Int64Index

The best thing I found, for your scenario, is to set the dataframe index into a numpy array with an int16 dtype.

The numeric range of int8 is -128 to 128.  Since your index is 0 to 130, int8 will not suffice.

Creating a price_combos variable and then a dataframe, will use twice the amount of memory, so create df2 without the intermediary step.

If you create the dataframe without specifying the dtype, as you're doing, the dtype will be int64

With the following implementation, there will be one object, df2, that will be 2,180,905,112 Bytes

With the original implementation, there would be two int64 objects of 8GB each, for a total of 16GB.

If you're using Jupyter, it has terrible memory management.

Perhaps increasing the the amount of virtual memory / swap file size, will give you the extra buffer needed memory. Virtual memory is Windows, swap file is Linux. It's easy to do, just Google it.

import numpy as np
import pandas a pd
from itertools import permutations

# synthetic data set and create dataframe
np.random.seed(365)
data = {'Price': list(range(1, 131)),
        'Bid': [np.random.randint(1, 10)*0.1 for _ in range(130)]}

df1 = pd.DataFrame(data)
df1['Ask'] = df1.Bid + 0.15
df1.set_index('Price', inplace=True)

# convert the index to an int16 array
values = df1.index.to_numpy(dtype='int16')

# create df2
%%time
df2 = pd.DataFrame(np.array(list(permutations(values, 4))), columns=('price1', 'price2', 'price3', 'price4'))
>>> Wall time: 2min 45s

print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 272613120 entries, 0 to 272613119
Data columns (total 4 columns):
 #   Column  Dtype
---  ------  -----
 0   price1  int16
 1   price2  int16
 2   price3  int16
 3   price4  int16
dtypes: int16(4)
memory usage: 2.0 GB

df2.head()

   price1  price2  price3  price4
0       1       2       3       4
1       1       2       3       5
2       1       2       3       6
3       1       2       3       7
4       1       2       3       8

df2.tail()

           price1  price2  price3  price4
272613115     130     129     128     123
272613116     130     129     128     124
272613117     130     129     128     125
272613118     130     129     128     126
272613119     130     129     128     127


问:
SwiftUI - Navigation bar colour change not being applied to status bar
I have the following:

```<code>var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}
</code>```

For the configuration of the nav bar i have:

```<code>struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}
</code>```

But for some reason the top status bar is being left out and the colour is not being applied to it:

How can the red colour also be applied to the status bar above the nav bar, I want it to be the same colour.

I've tried the below, but this fails:

```<code>init() {
    UINavigationBar.appearance().backgroundColor = .red
}
</code>```

答:
EDIT 1:
Checkout my new answer: https://stackoverflow.com/a/62031788/8023700
It has detailed description and screenshot as well.

Try using this modifier as this gives you freedom to change color based on each view.

```<code>struct NavigationBarModifier: ViewModifier {

var backgroundColor: UIColor = .clear

init(backgroundColor: UIColor, tintColor: UIColor = .white) {
    self.backgroundColor = backgroundColor

    let coloredAppearance = UINavigationBarAppearance()
    coloredAppearance.backgroundColor = backgroundColor
    coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
    coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

    UINavigationBar.appearance().standardAppearance = coloredAppearance
    UINavigationBar.appearance().compactAppearance = coloredAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    UINavigationBar.appearance().tintColor = tintColor
}

func body(content: Content) -> some View {
    ZStack{
        content
        VStack {
            GeometryReader { geometry in
                Color(self.backgroundColor)
                    .frame(height: geometry.safeAreaInsets.top)
                    .edgesIgnoringSafeArea(.top)
                Spacer()
            }
        }
    }
}}
</code>```

I used it on below View:

```<code>struct DummyNavigationView: View {
var body: some View {
    NavigationView {
        VStack {
            NavigationLink(destination: Text("Page 2")) {
                Text("Go to detail")
            }
        }
        .navigationBarTitle("Edit Profile", displayMode: .inline)
    }
    .modifier(NavigationBarModifier(backgroundColor: .red, tintColor: .black))
}}
</code>```

Body:
I have the following:

var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}

For the configuration of the nav bar i have:

struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}

But for some reason the top status bar is being left out and the colour is not being applied to it:

How can the red colour also be applied to the status bar above the nav bar, I want it to be the same colour.

I've tried the below, but this fails:

init() {
    UINavigationBar.appearance().backgroundColor = .red
}

Body:
EDIT 1:
Checkout my new answer: https://stackoverflow.com/a/62031788/8023700
It has detailed description and screenshot as well.

Try using this modifier as this gives you freedom to change color based on each view.

struct NavigationBarModifier: ViewModifier {

var backgroundColor: UIColor = .clear

init(backgroundColor: UIColor, tintColor: UIColor = .white) {
    self.backgroundColor = backgroundColor

    let coloredAppearance = UINavigationBarAppearance()
    coloredAppearance.backgroundColor = backgroundColor
    coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
    coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

    UINavigationBar.appearance().standardAppearance = coloredAppearance
    UINavigationBar.appearance().compactAppearance = coloredAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
    UINavigationBar.appearance().tintColor = tintColor
}

func body(content: Content) -> some View {
    ZStack{
        content
        VStack {
            GeometryReader { geometry in
                Color(self.backgroundColor)
                    .frame(height: geometry.safeAreaInsets.top)
                    .edgesIgnoringSafeArea(.top)
                Spacer()
            }
        }
    }
}}

I used it on below View:

struct DummyNavigationView: View {
var body: some View {
    NavigationView {
        VStack {
            NavigationLink(destination: Text("Page 2")) {
                Text("Go to detail")
            }
        }
        .navigationBarTitle("Edit Profile", displayMode: .inline)
    }
    .modifier(NavigationBarModifier(backgroundColor: .red, tintColor: .black))
}}


问:
Let a container use the OpenJDK and libraries of an existing container
I am doing some experiments with my thesis involving the cold start problem that occurs with containers. My test application is a spring boot application that is build on the openjdk image. The first thing I want to try to resolve the problem of cold start, is the following:

Have a container ready, in the container is the openjdk and the libraries that the springboot app uses. I start my other container, using the ipc and networknamespace of the already existing container, and then be able to use the openjdk and the libraries of this container to run the jar file.

I am not exactly sure on how to achieve this? Can i achieve this by using volumes or should i be looking for a completely different approach?

On a another note, if i want x containers to run, i will make sure there are x pre-existing containers running. This is to make sure that every container has its own specific librarycontainer to work with. Would this be okay ?

In short, any way that I can speed up the spring boot application by using a second containers that is connected through ipc/net; would be helpfull to my problem.

答:
So if speed-up application start is your goal i think you would need a different approach here a summary of why i think so:

docker: a container is a running instance of an image, you can see an image as a filesystem (actually is more than that but we are talking about libraries). In a container you have jdk (and i guess your image is based on tomcat). Docker engine has a very well designed cache system so containers starts very quickly, if no changes are made on a container docker only need to retrieve some info from a cache. These containers are isolated and for good reasons (security, modularity and talking about libraries isolation let you have more version of a library in different containers). Volumes do not what you think, they are not designed to share libraries, they let you break isolation to make some things for example you can create a volume for your codebase so you have not to rebuild an image for each change during the programming phase, but usually you won't see them in a production environment (maybe for some config files).

java/spring: spring is a framework based on java, java is based on a jdk and java code runs on a vm. So to run a java program you have to start that vm(no other way to do that) and of course you cannot reduce this startup time. Java environment is very powerfull but this is why a lot of people prefer nodejs expecially for little services, java code is slow in startup (minutes versus seconds). Spring as said before is based on java, servelets and context. Spring application lives in that context, so to run a spring application you have to initialize that context.

You are running a container, on top of that you are running a vm, then you are initializing a spring context and finally you are initializing beans of your application. These steps are sequential for dependencies reasons. You cannot initialize docker,vm and a spring context and run somewhere else your application, for example if you in a spring application add a chainfilter you would need to restart application because you would need to add a servlet to your system. If you want to speed-up the process of startup you would need to change the java vm or make some changes in the spring initialization. In summary you are tryng to deal with this problem at a high level instead of low level.


问:
Trouble passing the correct information from a tableview to a new view controller
Right now I have a program that displays different organizations in a tableview. When an organization is selected, then it displays a screen that passes the name of that specific organization. However, the problem is that when I click on "organization 2" of "section 1" I get the results that would be displayed in "organization 1" of "section 1". How would I fix this so that, when I click "organization 2" of "section 1" it displays the correct information?

Here is my code for the first view controller.

```<code>import UIKit

struct Organizations {
var sectionTitle = String()
var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var searchOrganizations: Organizations?
var selectedRow = 0
var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
]

override func viewDidLoad() {
super.viewDidLoad()

tableView.delegate = self
tableView.dataSource = self
}

extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = organizations[indexPath.section]
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as?    OrganizationsDetailViewController {
     destination.organization = selectedOrganizations
     destination.selectedRow = selectedRow
 }
 }
</code>```

Here is my code for the second view controller.

```<code>import UIKit

class OrganizationsDetailViewController: UIViewController {

@IBOutlet weak var organizationNameLabel: UILabel!

var organization: Organizations? = nil
var selecterRow: Int = 0

override func viewDidLoad() {
super.viewDidLoad()
setupLabel()
}

private func setupLabel() {
    guard let org = self.organization else { return }
    self.organizationNameLabel.text = org.rowTitles[selectedRow]
}
}
</code>```

答:
Modify your didSelectRow to this to fix your mentioned issue:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedOrganizations = searching ? searchArray[indexPath.section] : organizations[indexPath.section]
    selectedRow = indexPath.row
    performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}
```

Body:
Right now I have a program that displays different organizations in a tableview. When an organization is selected, then it displays a screen that passes the name of that specific organization. However, the problem is that when I click on "organization 2" of "section 1" I get the results that would be displayed in "organization 1" of "section 1". How would I fix this so that, when I click "organization 2" of "section 1" it displays the correct information?

Here is my code for the first view controller.

import UIKit

struct Organizations {
var sectionTitle = String()
var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var searchOrganizations: Organizations?
var selectedRow = 0
var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
]

override func viewDidLoad() {
super.viewDidLoad()

tableView.delegate = self
tableView.dataSource = self
}

extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = organizations[indexPath.section]
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as?    OrganizationsDetailViewController {
     destination.organization = selectedOrganizations
     destination.selectedRow = selectedRow
 }
 }

Here is my code for the second view controller.

import UIKit

class OrganizationsDetailViewController: UIViewController {

@IBOutlet weak var organizationNameLabel: UILabel!

var organization: Organizations? = nil
var selecterRow: Int = 0

override func viewDidLoad() {
super.viewDidLoad()
setupLabel()
}

private func setupLabel() {
    guard let org = self.organization else { return }
    self.organizationNameLabel.text = org.rowTitles[selectedRow]
}
}


问:
Container filled with widgets beond hight and width without getting overflowed
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

```<code>Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);
</code>```

Here is the issue that occuring.

答:
With Dart 2.3 you can use collection if in lists. Since your Padding with the Overflow-Text is within a Column the Padding is part of a list. If the expression inside the if is true, the Padding will be included otherwise not.

```<code>if(!_toogle)
  Padding(
    padding: const EdgeInsets.all(16.0),
    child: Text('I am overflowed'),
  )
</code>```

Here is the link to the documentation: https://dart.dev/guides/language/language-tour#lists
Search for "collection if".

Body:
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);

Here is the issue that occuring.

Body:
With Dart 2.3 you can use collection if in lists. Since your Padding with the Overflow-Text is within a Column the Padding is part of a list. If the expression inside the if is true, the Padding will be included otherwise not.

if(!_toogle)
  Padding(
    padding: const EdgeInsets.all(16.0),
    child: Text('I am overflowed'),
  )

Here is the link to the documentation: https://dart.dev/guides/language/language-tour#lists
Search for "collection if".


问:
How to not write more bytes than are in the buffer in C?
I'm trying to write a simple copy program. It reads test_data.txt in chunks of 100 bytes and copies those bytes to test_dest.txt. I find that the destination file is at least one unit of chunk larger than the source file. How could I adjust it so that just the right number of bytes are copied? Would I need a copy buffer of size 1?
Please not the point is to solve it using low level I/O system calls.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main() {

    int fh  = open("test_data.txt", O_RDONLY);
    int trg = open("test_dest.txt", O_CREAT | O_WRONLY);

    int  BUF_SIZE = 100;
    char inp[BUF_SIZE];

    int read_bytes = read(fh, inp, BUF_SIZE);
    while (read_bytes > 0) {
        write(trg, inp, BUF_SIZE);
        read_bytes = read(fh, inp, BUF_SIZE);
    }

    close(trg);
    close(fh);
    return 0;
}
</code>```

答:
The read function just told you how many bytes it read. You should write that amount of bytes:

```<code>write(trg, inp, read_bytes);
</code>```

On another note, you really should check for failures from the write call as well. And definitely the open calls.

On yet another note, you only really need one call to read:

```<code>ssize_t read_bytes;  // The read function is specified by POSIX to return a ssize_t
while ((read_bytes = read(fh, inp, sizeof inp)) > 0)
{
    write(trg, inp, read_bytes);
}
</code>```

Body:
I'm trying to write a simple copy program. It reads test_data.txt in chunks of 100 bytes and copies those bytes to test_dest.txt. I find that the destination file is at least one unit of chunk larger than the source file. How could I adjust it so that just the right number of bytes are copied? Would I need a copy buffer of size 1?
Please not the point is to solve it using low level I/O system calls.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int main() {

    int fh  = open("test_data.txt", O_RDONLY);
    int trg = open("test_dest.txt", O_CREAT | O_WRONLY);

    int  BUF_SIZE = 100;
    char inp[BUF_SIZE];

    int read_bytes = read(fh, inp, BUF_SIZE);
    while (read_bytes > 0) {
        write(trg, inp, BUF_SIZE);
        read_bytes = read(fh, inp, BUF_SIZE);
    }

    close(trg);
    close(fh);
    return 0;
}

Body:
The read function just told you how many bytes it read. You should write that amount of bytes:

write(trg, inp, read_bytes);

On another note, you really should check for failures from the write call as well. And definitely the open calls.

On yet another note, you only really need one call to read:

ssize_t read_bytes;  // The read function is specified by POSIX to return a ssize_t
while ((read_bytes = read(fh, inp, sizeof inp)) > 0)
{
    write(trg, inp, read_bytes);
}


问:
Replace a character in different elements with the same class in JavaScript?
I have several paragraphs in my page. They all have the same class name. I want to replace a character that is in all of them. I tried something like this:

```<code>  var str = $(".foo").html;
  var res = str.split("　").join("");
  $(".foo").html = res;
</code>```

But I get the error: TypeError: str.split is not a function

I noticed that if I target a single paragraph, with its unique Id, everything works fine. I just cannot do it with several paragraphs at the same time, using their class names.

答: You can use jQuery each function</p>

Body:
I have several paragraphs in my page. They all have the same class name. I want to replace a character that is in all of them. I tried something like this:

  var str = $(".foo").html;
  var res = str.split("　").join("");
  $(".foo").html = res;

But I get the error: TypeError: str.split is not a function

I noticed that if I target a single paragraph, with its unique Id, everything works fine. I just cannot do it with several paragraphs at the same time, using their class names.

Body: You can use jQuery each function


问:
How to force refresh of GrandParent component from grandchild component with React hooks in SPFx
In the main component of a SPFx web part, I have a data load running in a   React.useEffect

```<code>const [jobsGets, setJobsGets] = React.useState(0);

React.useEffect(() => {
   {Some code to get data from SharePoint}
    });
  }, [jobsGets]);
</code>```

So a refresh will happen when the value of "jobsGets" will change, right?

This component calls another component that calls another and the last has an event that should refresh by changing "jobsGets".
If I write a fanction and pass it down the props of each generation's component,

It ends running in the main component forever. So this is not a good solution.
How do I setJobsGets(jobsGets+1); from the grandchild components?

Any hint is welcome.
Thank you

答:
you are likely updating jobs at grandChild with useEffect, that runs on mount and every update. if you pass a second empty array [] param, this update will run only after first render if that's your specific case, avoiding retriggers:

```<code>// at some granchild
useEffect(() => { ...logic here }, [])
</code>```

if useEffect should run after on specific param's update, you pass that param as argument to the array. useEffect will run only on changes for the params dependencies set on [].

```<code>useEffect(() => { ...logic here }, [param])
</code>```

you may also look at useContext for passing down state better at deep tree.

Body:
In the main component of a SPFx web part, I have a data load running in a   React.useEffect

const [jobsGets, setJobsGets] = React.useState(0);

React.useEffect(() => {
   {Some code to get data from SharePoint}
    });
  }, [jobsGets]);

So a refresh will happen when the value of "jobsGets" will change, right?

This component calls another component that calls another and the last has an event that should refresh by changing "jobsGets".
If I write a fanction and pass it down the props of each generation's component,

It ends running in the main component forever. So this is not a good solution.
How do I setJobsGets(jobsGets+1); from the grandchild components?

Any hint is welcome.
Thank you

Body:
you are likely updating jobs at grandChild with useEffect, that runs on mount and every update. if you pass a second empty array [] param, this update will run only after first render if that's your specific case, avoiding retriggers:

// at some granchild
useEffect(() => { ...logic here }, [])

if useEffect should run after on specific param's update, you pass that param as argument to the array. useEffect will run only on changes for the params dependencies set on [].

useEffect(() => { ...logic here }, [param])

you may also look at useContext for passing down state better at deep tree.


问:
How do you pull all records from a paginated WebAPI into a SQL Server database in ASP.NET Core MVC?
My requirement is to pull data from an external api, first call returns only 100 records, but with a header information stating total pages and total records in remote database. I need to pull all this records at once and insert into my database, next call to the api should only pull new records in the remote database.

I am working with ASP.NET Core 3.0 and a SQL Server database.

```<code>    public void GetReservation(int? pageNumber, int? pageSize)
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://www.sitename.com/url");
            MediaTypeWithQualityHeaderValue contentType = new
            MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);
            HttpResponseMessage response = client.GetAsync($"/api/serviceurl?pageNumber=
            {pageNumber}&pageSize={pageSize}").Result;
            string stringData = response.Content.ReadAsStringAsync().Result;
            List<Reservations> data = JsonConvert.DeserializeObject<List<Reservations>>(stringData);

            var headerInfo = response.Headers.GetValues("X-Pagination").First();
            XPaginationObject obj= JsonConvert.DeserializeObject<XPagination>(headerInfo);

           // Insert into database code only enters first 100 page

        }
    }
</code>```

headerinfo contains totalpages, totalrecords, currentpage, hasNext, hasprevious...

答:
It looks to me you're almost there: just run this method in a loop until you have all the records.. But first you need to get the total number of pages.

What I would do is:

1: call the api with pagenumber 1 and size 0 so you receive a header.
2: Get the info from the header and loop over pages until you are done.
3. You will have to write your own logic for only getting the new reservations, for instance, store the last received page and record number so you can skip these the next time.

Does this answer your question?

P.S.: It could very well be possible that your data provider only allows getting 100 rows at a time. If this is the case you will have to loop over 100-record pages until you have received all the pages.

Body:
My requirement is to pull data from an external api, first call returns only 100 records, but with a header information stating total pages and total records in remote database. I need to pull all this records at once and insert into my database, next call to the api should only pull new records in the remote database.

I am working with ASP.NET Core 3.0 and a SQL Server database.

    public void GetReservation(int? pageNumber, int? pageSize)
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://www.sitename.com/url");
            MediaTypeWithQualityHeaderValue contentType = new
            MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);
            HttpResponseMessage response = client.GetAsync($"/api/serviceurl?pageNumber=
            {pageNumber}&pageSize={pageSize}").Result;
            string stringData = response.Content.ReadAsStringAsync().Result;
            List<Reservations> data = JsonConvert.DeserializeObject<List<Reservations>>(stringData);

            var headerInfo = response.Headers.GetValues("X-Pagination").First();
            XPaginationObject obj= JsonConvert.DeserializeObject<XPagination>(headerInfo);

           // Insert into database code only enters first 100 page

        }
    }

headerinfo contains totalpages, totalrecords, currentpage, hasNext, hasprevious...


问:
file payload in google cloud function bucket triggered
I have a question about a Google Cloud functions triggered by an event on a storage bucket (I’m developing it in Python).

I have to read the data of the file just finalized (a PDF file) on the bucket that is triggering the event and I was looking for the file payload on the event object passed to my function (data, context) but it seems there is not payload on that object.

Do I have to use the cloud storage library to get the file from the bucket ? Is there a way to get the payload directly from the context of the triggered function ?

Enrico

答:
From checking the more complete examplein the Firebase documentation, it indeed seems that the payload of the file is not included in the parameters. That make sense, since there's no telling how big the file is that was just finalized, and if that will even fit in the memory of your Functions runtime.

So you'll have to indeed grab the file from the bucket with a separate call, based on the information in the metadata. The full Firebase example grabs the filename and other info from its context/data with:

```<code>exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.
  const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

  ...
</code>```

I'll see if I can find a more complete example. But I'd expect it to work similarly on raw Google Cloud Functions, which Firebase wraps, even when using Python.

Update: from looking at this Storage/Function/PubSub documentation that the Python binding is apparently based on, it looks like the the path should be available as data['resource'] or as data['name'].

Body:
From checking the more complete examplein the Firebase documentation, it indeed seems that the payload of the file is not included in the parameters. That make sense, since there's no telling how big the file is that was just finalized, and if that will even fit in the memory of your Functions runtime.

So you'll have to indeed grab the file from the bucket with a separate call, based on the information in the metadata. The full Firebase example grabs the filename and other info from its context/data with:

exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.
  const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

  ...

I'll see if I can find a more complete example. But I'd expect it to work similarly on raw Google Cloud Functions, which Firebase wraps, even when using Python.

Update: from looking at this Storage/Function/PubSub documentation that the Python binding is apparently based on, it looks like the the path should be available as data['resource'] or as data['name'].


问:
Pandas ignores start date of a DataFrame
I am new to python and programming in general. I'm trying to import the historical data from multiple stocks. These are imported by Yahoo Finance and are expected to cover the last 20 years. For some unknown reason, Python ignores my start date and only imports data from the previous 10 years. If I import the data of the shares individually, there are no problems. Do you know what the problem might be? BTW python only uses 30% of RAM.

assets=['EXX6.DE','GLD','SC0J.DE','EEM','BRK-B','SBUX','BABA','DIS','MSFT','ABBV','MUV2.DE','NNW.F','V']
pf_data=pd.DataFrame()
for a in assets:
    pf_data[a]=wb.DataReader(a,data_source='yahoo',start='2000-1-1') ['Adj Close']
My code in jupyter

答:
This should do the trick. I would recommend in the future (to make it easier for us to help you) to add the code as copyable text as well.

I believe that all you have left to do is to add the rest of the columns to assets.

This problem has been solved by looking directly at the documentation of  the function you send in your picture, wb.DataReader as well as reading the documentation of the function it uses (get_data_yahoo).

```<code>import pandas_datareader as dr
assets = ['EXX6.DE', 'GLD', 'SC0J.DE', 'EEM']
df = dr.data.get_data_yahoo(assets, start='1/1/2000', end='5/5/2020')
print(df)
</code>```

Body:
This should do the trick. I would recommend in the future (to make it easier for us to help you) to add the code as copyable text as well.

I believe that all you have left to do is to add the rest of the columns to assets.

This problem has been solved by looking directly at the documentation of  the function you send in your picture, wb.DataReader as well as reading the documentation of the function it uses (get_data_yahoo).

import pandas_datareader as dr
assets = ['EXX6.DE', 'GLD', 'SC0J.DE', 'EEM']
df = dr.data.get_data_yahoo(assets, start='1/1/2000', end='5/5/2020')
print(df)


问:
CSS Center Navbar Elements
I know that this is probably asked many times already. I just want to center all items of my navbar vertically. I tried to set vertical-align: center; in my headercss tag.
I probably miss something:

```<code><header>
            <nav class="navbar">

                <div class="branding">
                    <a href="index.html"> <img src="pic/branding.png" alt="branding"></a>
                </div>

                <div class="navbar-links">
                    <ul>
                        <li><a href="de/login.html">Login</a> </li>
                    </ul>
                </div>

                <div class="searchbox-container">
                    <input class="searchbar" type="text" placeholder="Search...">
                    <button class="search-button" type="submit"><img src="pic/searchicon.png" height="25px" width="25px" alt="search"></button>
                </div>

            </nav>

        </header>
</code>```

css:

```<code>*{
    margin: 0;
    padding: 0;
    text-decoration: none;
    list-style: none;
}

body{
    font-family: sans-serif;
}

/* Navbar stuff */
header{
    background-color: #424242/*#80aaff*/;
    height: 60px;
}

.navbar{
    width: 80%;
    margin: auto;
}

.branding{
    float: left;
}

.navbar-links{
    float: right;
}

.navbar-links ul{
    list-style: none;
}

.navbar-links ul li a{
    text-decoration: none;
    text-transform: uppercase;
    color: white;
}
</code>```

答:
* {
  margin: 0;
  padding: 0;
  text-decoration: none;
  list-style: none;
}

body {
  font-family: sans-serif;
}

/* Navbar stuff */

header {
  background-color: #424242/*#80aaff*/
  ;
  height: 60px;
  display: flex;
  align-items: center;
}

.navbar {
  width: 80%;
  margin: auto;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

.branding {
  margin-right:
}

.navbar-links {
  margin-left: auto;
}

.navbar-links ul {
  list-style: none;
}

.navbar-links ul li a {
  text-decoration: none;
  text-transform: uppercase;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav class="navbar">
    <div class="branding">
       <img src="pic/branding.png" alt="branding">
    </div>
    <div class="navbar-links">
      <ul>
        <li>Login </li>
      </ul>
      <div>
        <div class="searchbox-container">
          <input class="searchbar" type="text" placeholder="Search...">
          <button class="search-button" type="submit"><img src="pic/searchicon.png" height="25px" width="25px" alt="search"></button>
        </div>
      </div>
    </div>
  </nav>
</header></code>```

Title: CSS Center Navbar Elements

Body:
I know that this is probably asked many times already. I just want to center all items of my navbar vertically. I tried to set vertical-align: center; in my headercss tag.
I probably miss something:

Login

                    <input class="searchbar" type="text" placeholder="Search...">
                    <button class="search-button" type="submit"></button>

css:

*{
    margin: 0;
    padding: 0;
    text-decoration: none;
    list-style: none;
}

body{
    font-family: sans-serif;
}

/* Navbar stuff */
header{
    background-color: #424242/*#80aaff*/;
    height: 60px;
}

.navbar{
    width: 80%;
    margin: auto;
}

.branding{
    float: left;
}

.navbar-links{
    float: right;
}

.navbar-links ul{
    list-style: none;
}

.navbar-links ul li a{
    text-decoration: none;
    text-transform: uppercase;
    color: white;
}

Body:
* {
  margin: 0;
  padding: 0;
  text-decoration: none;
  list-style: none;
}

body {
  font-family: sans-serif;
}

/* Navbar stuff */

header {
  background-color: #424242/*#80aaff*/
  ;
  height: 60px;
  display: flex;
  align-items: center;
}

.navbar {
  width: 80%;
  margin: auto;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

.branding {
  margin-right:
}

.navbar-links {
  margin-left: auto;
}

.navbar-links ul {
  list-style: none;
}

.navbar-links ul li a {
  text-decoration: none;
  text-transform: uppercase;
  color: white;
}

<header>
  <nav class="navbar">
    <div class="branding">
      <a href="index.html"> <img src="pic/branding.png" alt="branding"></a>
    </div>
    <div class="navbar-links">
      <ul>
        <li><a href="de/login.html">Login</a> </li>
      </ul>
      <div>
        <div class="searchbox-container">
          <input class="searchbar" type="text" placeholder="Search...">
          <button class="search-button" type="submit"><img src="pic/searchicon.png" height="25px" width="25px" alt="search"></button>
        </div>
      </div>
    </div>
  </nav>
</header>


问:
How to properly use TypeScript types with a Styled Component canvas on React
I am creating a React component on Gatsby using TypeScript and have defined a canvas Styled Component this way:

```<code>const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;
</code>```

And to use it I am assigning types to it this way:

```<code>const canvas: HTMLCanvasElement = Background,
  context = Background.getContext('2d');
</code>```

But I am getting this error with the canvas type:

```<code>Type 'String & StyledComponentBase<"canvas", any, {}, never> & NonReactStatics<never, {}>' is missing the following properties from type 'HTMLCanvasElement': height, width, getContext, toBlob, and 238 more.
</code>```

I am also getting an error on the .getContext() method:

```<code>This expression is not callable.
Type 'never' has no call signatures.
</code>```

I have been searching for a solution but can not find a proper one for this specific problem.
Could someone please explain to me the best way to use Styled Component canvas with TypeScript?

答:
The Background is a React.Component (i.e. a function that creates a virtual element) rather than an HTMLCanvasElement. Not only does the function need to be called for it to even return anything remotely like an HTMLCanvasElement, but you also need access to the underlying DOM element to make it work. I do have a suggestion that you might be able to try, though.

```<code>import { useRef, useEffect } from 'react';

const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;

const ComponentUsingTheCanvas = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const context = canvasRef.current.getContext('2d');
    // Do stuff with your canvas context here
  });
  return (
    <Background ref={canvasRef} />
  );
}
</code>```

One note, I didn't type anything because TypeScript can do that automatically most of the time.

By the way, why use a styled component when you can just style inline? styled-components is only really useful if you do something with the props.

Body:
I am creating a React component on Gatsby using TypeScript and have defined a canvas Styled Component this way:

const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;

And to use it I am assigning types to it this way:

const canvas: HTMLCanvasElement = Background,
  context = Background.getContext('2d');

But I am getting this error with the canvas type:

Type 'String & StyledComponentBase<"canvas", any, {}, never> & NonReactStatics<never, {}>' is missing the following properties from type 'HTMLCanvasElement': height, width, getContext, toBlob, and 238 more.

I am also getting an error on the .getContext() method:

This expression is not callable.
Type 'never' has no call signatures.

I have been searching for a solution but can not find a proper one for this specific problem.
Could someone please explain to me the best way to use Styled Component canvas with TypeScript?

Body:
The Background is a React.Component (i.e. a function that creates a virtual element) rather than an HTMLCanvasElement. Not only does the function need to be called for it to even return anything remotely like an HTMLCanvasElement, but you also need access to the underlying DOM element to make it work. I do have a suggestion that you might be able to try, though.

import { useRef, useEffect } from 'react';

const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;

const ComponentUsingTheCanvas = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const context = canvasRef.current.getContext('2d');
    // Do stuff with your canvas context here
  });
  return (
    <Background ref={canvasRef} />
  );
}

One note, I didn't type anything because TypeScript can do that automatically most of the time.

By the way, why use a styled component when you can just style inline? styled-components is only really useful if you do something with the props.


问:
Deploying to Heroku: ImportError:Couldn't import Django
When I want to deploy my code to Heroku using
git push heroku master
I have ImportError:Couldn't import Django.
So I try python manage.py runserver to see what is going on and it shows this in the terminal.
Full description of ImportError:Couldn't import Django.
Before I tab all the process for deploying my code to Heroku,python manage.py runserver works well (the system gives me a link to open my Web page).

Here is my requirements.txt
requirements.txt

答:
Usually, when you deploy a python app to Heroku, you must have a requirements.txt file. I had this same error and when I added all of my dependencies to a requirements.txt file, it all worked. Best way to do this is if you are running on a virtual environment is </p>

```<code>pip freeze > requirements.txt
</code>```

Body:
Usually, when you deploy a python app to Heroku, you must have a requirements.txt file. I had this same error and when I added all of my dependencies to a requirements.txt file, it all worked. Best way to do this is if you are running on a virtual environment is

pip freeze > requirements.txt


问:
C compiler not noticing errors and correcting code itself
So I am a beginner in C and I have been following a book Primer Plus 6th edition.
While I was running my program I noticed something really strange, compiler is not working as it is supposed to, for example

```<code>int main(){
    one_three();
    getchar();
    return 0;
}

void one_three(void){
    printf("one\n");
    two();
    printf("three");
}

void two(void){
    printf("two\n");

}

</code>```

this is my code, there are many errors as no function prototype declarations and not including header files, but some how the output is produced only by giving warnings, i dont think this should happen
NOTE I HAVE INTENTIONALLY REMOVED FUNCTION PROTOTYPE DECLARTAIONS AND INCLUDING HEADER FILES

output is :

```<code>review1.c: In function 'main':
review1.c:2:5: warning: implicit declaration of function 'one_three' [-Wimplicit-function-declaration]
    2 |     one_three();
      |     ^~~~~~~~~
review1.c:3:5: warning: implicit declaration of function 'getchar' [-Wimplicit-function-declaration]
    3 |     getchar();
      |     ^~~~~~~
review1.c:1:1: note: 'getchar' is defined in header '<stdio.h>'; did you forget to '#include <stdio.h>'?
  +++ |+#include <stdio.h>
    1 | int main(){
review1.c: At top level:
review1.c:7:6: warning: conflicting types for 'one_three'
    7 | void one_three(void){
      |      ^~~~~~~~~
review1.c:2:5: note: previous implicit declaration of 'one_three' was here
    2 |     one_three();
      |     ^~~~~~~~~
review1.c: In function 'one_three':
review1.c:8:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    8 |     printf("one\n");
      |     ^~~~~~
review1.c:8:5: warning: incompatible implicit declaration of built-in function 'printf'
review1.c:8:5: note: include '<stdio.h>' or provide a declaration of 'printf'
review1.c:9:5: warning: implicit declaration of function 'two' [-Wimplicit-function-declaration]
    9 |     two();
      |     ^~~
review1.c: At top level:
review1.c:13:6: warning: conflicting types for 'two'
   13 | void two(void){
      |      ^~~
review1.c:9:5: note: previous implicit declaration of 'two' was here
    9 |     two();
      |     ^~~
review1.c: In function 'two':
review1.c:14:5: warning: incompatible implicit declaration of built-in function 'printf'
   14 |     printf("two\n");
      |     ^~~~~~
review1.c:14:5: note: include '<stdio.h>' or provide a declaration of 'printf'
one
two
three

</code>```

those last three lines "one" two three is the output
Please help, i am using this compiler

I expect it to output errors when it has to and not add stuff itself, so that i could learn by my mistakes
using visual studio code with extensions : C/C++ by microsoft, Code runner

答:
Earlier pre-standard versions of C had the concept of a default type given to objects if they weren't explicitly given a type.  Functions, if not declared, were implicitly typed as:

```<code>int func();
</code>```

So a function without a prototype was assumed to return int and take an unspecified number of arguments.  Because old code was written with this in mind, many compilers are backward compatible and compile old code such as this, but issues warnings when these old constructs are used.

In your particular case, you're able to get away with the implicit function declarations of the functions you define because the functions have void return type and no attempt is made to use the return value of these functions.  For the getchar and printf functions, their return type is int so they can work with the implicit declaration.

Body:
So I am a beginner in C and I have been following a book Primer Plus 6th edition.
While I was running my program I noticed something really strange, compiler is not working as it is supposed to, for example

int main(){
    one_three();
    getchar();
    return 0;
}

void one_three(void){
    printf("one\n");
    two();
    printf("three");
}

void two(void){
    printf("two\n");

}

this is my code, there are many errors as no function prototype declarations and not including header files, but some how the output is produced only by giving warnings, i dont think this should happen
NOTE I HAVE INTENTIONALLY REMOVED FUNCTION PROTOTYPE DECLARTAIONS AND INCLUDING HEADER FILES

output is :

review1.c: In function 'main':
review1.c:2:5: warning: implicit declaration of function 'one_three' [-Wimplicit-function-declaration]
    2 |     one_three();
      |     ^~~~~~~~~
review1.c:3:5: warning: implicit declaration of function 'getchar' [-Wimplicit-function-declaration]
    3 |     getchar();
      |     ^~~~~~~
review1.c:1:1: note: 'getchar' is defined in header '<stdio.h>'; did you forget to '#include <stdio.h>'?
  +++ |+#include <stdio.h>
    1 | int main(){
review1.c: At top level:
review1.c:7:6: warning: conflicting types for 'one_three'
    7 | void one_three(void){
      |      ^~~~~~~~~
review1.c:2:5: note: previous implicit declaration of 'one_three' was here
    2 |     one_three();
      |     ^~~~~~~~~
review1.c: In function 'one_three':
review1.c:8:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    8 |     printf("one\n");
      |     ^~~~~~
review1.c:8:5: warning: incompatible implicit declaration of built-in function 'printf'
review1.c:8:5: note: include '<stdio.h>' or provide a declaration of 'printf'
review1.c:9:5: warning: implicit declaration of function 'two' [-Wimplicit-function-declaration]
    9 |     two();
      |     ^~~
review1.c: At top level:
review1.c:13:6: warning: conflicting types for 'two'
   13 | void two(void){
      |      ^~~
review1.c:9:5: note: previous implicit declaration of 'two' was here
    9 |     two();
      |     ^~~
review1.c: In function 'two':
review1.c:14:5: warning: incompatible implicit declaration of built-in function 'printf'
   14 |     printf("two\n");
      |     ^~~~~~
review1.c:14:5: note: include '<stdio.h>' or provide a declaration of 'printf'
one
two
three

those last three lines "one" two three is the output
Please help, i am using this compiler

I expect it to output errors when it has to and not add stuff itself, so that i could learn by my mistakes
using visual studio code with extensions : C/C++ by microsoft, Code runner

Body:
Earlier pre-standard versions of C had the concept of a default type given to objects if they weren't explicitly given a type.  Functions, if not declared, were implicitly typed as:

int func();

So a function without a prototype was assumed to return int and take an unspecified number of arguments.  Because old code was written with this in mind, many compilers are backward compatible and compile old code such as this, but issues warnings when these old constructs are used.

In your particular case, you're able to get away with the implicit function declarations of the functions you define because the functions have void return type and no attempt is made to use the return value of these functions.  For the getchar and printf functions, their return type is int so they can work with the implicit declaration.


问:
What is wrong with my JAVA Swing code when I try to access Excel file?
I'm trying to make "Life Scheduler" with JAVA Swing, and I am trying to use Excel for database. (I can't use SQL for database cause I don't really know about it)

But it seems that my program corrupts excel file that I tried to use.

When I press "addSchedulebutton", I intended to add String "This is a test Data" at cell (0, 0). But it seems my program corrupts excel file while adding the string. After I press the button, I cannot open excel file with error message "It seems this excel file is corrupted..."

```<code>addSchedulebutton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sheet1");
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("This is a test Data");

            try {
                FileOutputStream fileoutputstream = new FileOutputStream("C:/Users/jihlo/Desktop/ScheduleData.xlsx");
                workbook.write(fileoutputstream);
                fileoutputstream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
</code>```

Above is the code that I made. Can someone find problem in my code?

答:
HSSF is designed to work with the  Excel '97(-2007) file format (.xls). You are trying to save a .xlsx file(Excel 2007 OOXML). You can try saving as ".xls" or change the program to use the XSSF classes.

I suggest changing the output to .xls. It is a quick way to see if the implementation is really the problem.

Body:
I'm trying to make "Life Scheduler" with JAVA Swing, and I am trying to use Excel for database. (I can't use SQL for database cause I don't really know about it)

But it seems that my program corrupts excel file that I tried to use.

When I press "addSchedulebutton", I intended to add String "This is a test Data" at cell (0, 0). But it seems my program corrupts excel file while adding the string. After I press the button, I cannot open excel file with error message "It seems this excel file is corrupted..."

addSchedulebutton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sheet1");
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("This is a test Data");

            try {
                FileOutputStream fileoutputstream = new FileOutputStream("C:/Users/jihlo/Desktop/ScheduleData.xlsx");
                workbook.write(fileoutputstream);
                fileoutputstream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

Above is the code that I made. Can someone find problem in my code?


答:
Your code is not standard C11. Check by reading the standard n1570, and read before the Modern C book.

Your code is more or less POSIX, and certainly compiles on most Linux distributions, e.g. Debian or Ubuntu (you want to install their build-essentials metapackage).

Please read the documentation of open(2), read(2), write(2), every syscalls(2) you are using, and of errno(3).

Notice that each of the functions you are calling can fail, and your code should test for the failure case. Also be aware that a write (or a read) could be partial in some cases, and this is documented.

Recommendation:

with a recent GCC -the usual C compiler on most Linux distributions, compile with all warnings and debug info, so gcc -Wall -Wextra -g.

Read Advanced Linux Programming and How to debug small programs

Learn to use the GDB debugger.

Read about build automation tools, such as GNU make (a very common tool on most Linux systems) or ninja.

Be aware of strace(1). You might use it on cp(1), or study the source code of GNU coreutils (providing cp).

Remember that most Linux distributions are mostly made of open source software.

You are allowed to study their source code.

I even believe that you should study their source code, at least for inspiration !

I'm trying to write a simple copy program. It reads test_data.txt in chunks of 100 bytes and copies those bytes to test_dest.txt

If performance matters, the chunk size of 100 bytes is really too small in practice. I would recommend a power of two bigger than 4Kbytes (the usual page size on x86-64).

Title: How to not write more bytes than are in the buffer in C?


问:
Java Regex - multiple urls match in one output string
I have this string:

```<code>jwplayer("vplayer").setup({sources:[{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4",label:"720p"},{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4",label:"360p"}],image:"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg"
</code>```

I want to get only the two urls i.e. the ones after file:.
The desired output string should be like:

```<code>https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4, https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4
</code>```

How can I get this in java?

I have tried this regex: "file:\"(.*?)\"", but I got only the first url even that I've put matcher.find() inside a while loop.

Edit:
This regex works fine also the one in the @azro answer. My problem was that some code inside the while loop throws an error and stops the loop after one iteration (thanks to @pafau_k).
Sorry for the inconvenience..

答:
To get the urls a simple regex like this file:"(https.*?)" would work, the *? means a few as possible, to stop at first quote after

```<code>String content = "jwplayer(\"vplayer\").setup({sources:[{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4\",label:\"720p\"},{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4\",label:\"360p\"}],image:\"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg\"";

Matcher m = Pattern.compile("file:\"(http.*?)\"").matcher(content);
while(m.find())
    System.out.println(m.group(1));
</code>```

Stream version to collect at same time

```<code>String res = Pattern.compile("file:\"(http.*?)\"")
                    .matcher(content)
                    .results()
                    .map(r -> r.group(1))
                    .collect(Collectors.joining(" "));

System.out.println(res); // https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4 https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4
</code>```

Body:
I have this string:

jwplayer("vplayer").setup({sources:[{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4",label:"720p"},{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4",label:"360p"}],image:"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg"

I want to get only the two urls i.e. the ones after file:.
The desired output string should be like:

https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4, https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4

How can I get this in java?

I have tried this regex: "file:\"(.*?)\"", but I got only the first url even that I've put matcher.find() inside a while loop.

Edit:
This regex works fine also the one in the @azro answer. My problem was that some code inside the while loop throws an error and stops the loop after one iteration (thanks to @pafau_k).
Sorry for the inconvenience..

Body:
To get the urls a simple regex like this file:"(https.*?)" would work, the *? means a few as possible, to stop at first quote after

String content = "jwplayer(\"vplayer\").setup({sources:[{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4\",label:\"720p\"},{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4\",label:\"360p\"}],image:\"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg\"";

Matcher m = Pattern.compile("file:\"(http.*?)\"").matcher(content);
while(m.find())
    System.out.println(m.group(1));

Stream version to collect at same time

String res = Pattern.compile("file:\"(http.*?)\"")
                    .matcher(content)
                    .results()
                    .map(r -> r.group(1))
                    .collect(Collectors.joining(" "));

System.out.println(res); // https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4 https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4


问:
How to change status bar color using AnnotatedRegion?
I want to change color of status bar using AnnotatedRegion, I got the below code from this answer but it is having no effect on status bar color.

```<code>AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Annotated Region'),
        ),
        body: Center(
          child:
              Text('Status Bar!'),
        ),
      ),
    )
</code>```

To quickly get started with this code, you can use this Github repository.

答:
If you check the code of the Appbar you will see it uses it's own AnnotatedRegion

```<code>final SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark
      ? SystemUiOverlayStyle.light
      : SystemUiOverlayStyle.dark;

return Semantics(
      container: true,
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: overlayStyle,
        child: Material(
          color: widget.backgroundColor
            ?? appBarTheme.color
            ?? theme.primaryColor,
          elevation: widget.elevation
            ?? appBarTheme.elevation
            ?? _defaultElevation,
          shape: widget.shape,
          child: Semantics(
            explicitChildNodes: true,
            child: appBar,
          ),
        ),
      ),
    );
</code>```

to override the effect of the Appbar you will need to wrap your scaffold with a SafeArea, then you will see the change of your own AnnotatedRegion

```<code>return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
      child: SafeArea(
        child: Scaffold(
          primary: false,
          appBar: AppBar(
            title: Text('Annotated Region'),
          ),
          body: Center(
            child: Text('Status Bar!'),
          ),
        )
      )
    );
</code>```

Body:
I want to change color of status bar using AnnotatedRegion, I got the below code from this answer but it is having no effect on status bar color.

AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Annotated Region'),
        ),
        body: Center(
          child:
              Text('Status Bar!'),
        ),
      ),
    )

To quickly get started with this code, you can use this Github repository.

Body:
If you check the code of the Appbar you will see it uses it's own AnnotatedRegion

final SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark
      ? SystemUiOverlayStyle.light
      : SystemUiOverlayStyle.dark;

return Semantics(
      container: true,
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: overlayStyle,
        child: Material(
          color: widget.backgroundColor
            ?? appBarTheme.color
            ?? theme.primaryColor,
          elevation: widget.elevation
            ?? appBarTheme.elevation
            ?? _defaultElevation,
          shape: widget.shape,
          child: Semantics(
            explicitChildNodes: true,
            child: appBar,
          ),
        ),
      ),
    );

to override the effect of the Appbar you will need to wrap your scaffold with a SafeArea, then you will see the change of your own AnnotatedRegion

return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light.copyWith(statusBarColor: Colors.white),
      child: SafeArea(
        child: Scaffold(
          primary: false,
          appBar: AppBar(
            title: Text('Annotated Region'),
          ),
          body: Center(
            child: Text('Status Bar!'),
          ),
        )
      )
    );