问:
Why does the char need to be dereferenced in this instance?
I've been doing some practice with trees in C for my undergraduate courses and I came about on very strange results.

This is the code that didn't output as expected. I have a tree with the root being the struct node * root, and the preorder function prints the data on each node on the tree.

```<code>struct node{
    char data;
    struct node * left;
    struct node * right;
};

struct node* newNode(char data){
    struct node* node = malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void preorder(struct node * root){
    //struct node * start = root;
    struct node * L;
    struct node * R;
    if(root!=NULL){
        printf("%c",root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

int main(){
    struct node * root = newNode("a");
    root->left = newNode("b");
    root->right = newNode("c");
    root->left->left = newNode("d");
    root->left->right = newNode("e");
    root->right->left = newNode("f");
    root->right->right = newNode("g");
    preorder(root);
    return 0;
}
</code>```

I was expecting the output to be "abdecfg", but instead the terminal is outputting a weird result, as such; https://i.imgur.com/LudpUn7.png .
I get the GCC warning "[Warning] assignment makes integer from pointer without a cast", but I don't understand why.
If I use the dereference asterisk on the char inputs, the error stops, and I get the expected output, like this;

```<code>int main(){
    struct node * root = newNode(*"a");
    root->left = newNode(*"b");
    root->right = newNode(*"c");
    root->left->left = newNode(*"d");
    root->left->right = newNode(*"e");
    root->right->left = newNode(*"f");
    root->right->right = newNode(*"g");
    preorder(root);
    return 0;
}
</code>```

Please note that it does not work[1] if I put the dereference asterisk on the newNode input instead.

Thanks in advance for any help.

答:
You're are trying to convert from a string (" ") to a char (' '). A string is a  const char * or a char array, or a bunch of characters. Just switch:

```<code>struct node * root = newNode("a");
</code>```

To

```<code>struct node * root = newNode('a');
</code>```

and so on for all of your constructors.

Body:
I've been doing some practice with trees in C for my undergraduate courses and I came about on very strange results.

This is the code that didn't output as expected. I have a tree with the root being the struct node * root, and the preorder function prints the data on each node on the tree.

struct node{
    char data;
    struct node * left;
    struct node * right;
};

struct node* newNode(char data){
    struct node* node = malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void preorder(struct node * root){
    //struct node * start = root;
    struct node * L;
    struct node * R;
    if(root!=NULL){
        printf("%c",root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

int main(){
    struct node * root = newNode("a");
    root->left = newNode("b");
    root->right = newNode("c");
    root->left->left = newNode("d");
    root->left->right = newNode("e");
    root->right->left = newNode("f");
    root->right->right = newNode("g");
    preorder(root);
    return 0;
}

I was expecting the output to be "abdecfg", but instead the terminal is outputting a weird result, as such; https://i.imgur.com/LudpUn7.png .
I get the GCC warning "[Warning] assignment makes integer from pointer without a cast", but I don't understand why.
If I use the dereference asterisk on the char inputs, the error stops, and I get the expected output, like this;

int main(){
    struct node * root = newNode(*"a");
    root->left = newNode(*"b");
    root->right = newNode(*"c");
    root->left->left = newNode(*"d");
    root->left->right = newNode(*"e");
    root->right->left = newNode(*"f");
    root->right->right = newNode(*"g");
    preorder(root);
    return 0;
}

Please note that it does not work[1] if I put the dereference asterisk on the newNode input instead.

Thanks in advance for any help.

Body:
You're are trying to convert from a string (" ") to a char (' '). A string is a  const char * or a char array, or a bunch of characters. Just switch:

struct node * root = newNode("a");

To

struct node * root = newNode('a');

and so on for all of your constructors.


来源: stackexchange

问:
Aborted connection 10 to db: 'acore_auth' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
My AzerothCore docker-compose fails with the following:

```<code>ac-database_1     | 2019-05-28T16:53:22.645200Z 10 [Note] Aborted connection 10 to db: 'acore_auth' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645268Z 8 [Note] Aborted connection 8 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645271Z 9 [Note] Aborted connection 9 to db: 'acore_auth' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645487Z 4 [Note] Aborted connection 4 to db: 'acore_world' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645273Z 7 [Note] Aborted connection 7 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645549Z 5 [Note] Aborted connection 5 to db: 'acore_world' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645302Z 6 [Note] Aborted connection 6 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)

</code>```

答:
The real error was right before the database logs:

```<code>ac-worldserver_1  | Map file '/azeroth-server/data/maps/0004331.map': does not exist!
</code>```

which means: the datafiles are missing.

As the official guide said, I had to:

Put your data files into the docker/worldserver/data/ folder that is inside azerothcore-wotlk.

ContentLicense: CC BY-SA 4.0

Body:
My AzerothCore docker-compose fails with the following:

ac-database_1     | 2019-05-28T16:53:22.645200Z 10 [Note] Aborted connection 10 to db: 'acore_auth' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645268Z 8 [Note] Aborted connection 8 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645271Z 9 [Note] Aborted connection 9 to db: 'acore_auth' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645487Z 4 [Note] Aborted connection 4 to db: 'acore_world' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645273Z 7 [Note] Aborted connection 7 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645549Z 5 [Note] Aborted connection 5 to db: 'acore_world' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)
ac-database_1     | 2019-05-28T16:53:22.645302Z 6 [Note] Aborted connection 6 to db: 'acore_characters' user: 'root' host: '172.18.0.3' (Got an error reading communication packets)

Body:
The real error was right before the database logs:

ac-worldserver_1  | Map file '/azeroth-server/data/maps/0004331.map': does not exist!

which means: the datafiles are missing.

As the official guide said, I had to:

Put your data files into the docker/worldserver/data/ folder that is inside azerothcore-wotlk.


问:
Trouble scraping the precise values with BeautifulSoup
I'm trying to isolate scrape some Danish election data and I want the names isolated in my output, so I don't get outputs like:

"div class="table-like-cell col-xs-7 col-sm-6 col-md-6 col-lg-8">Jeppe Kofod

I've tried using get_text behind "navn" at the end and select instead of findAll

```<code>from bs4 import BeautifulSoup as soup  # HTML data structure
from urllib.request import urlopen as uReq  # Web client
from urllib.request import Request

# URl to web scrape from.
# in this example we web scrape graphics cards from Newegg.com
page_url =Request("https://www.kmdvalg.dk/ev/2019/e1003A.htm",headers={'User-Agent': 'Mozilla/5.0'})

# opens the connection and downloads html page from url
uClient = uReq(page_url)

# parses html into a soup data structure to traverse html
# as if it were a json data type.
page_soup = soup(uClient.read(), "html.parser")
uClient.close()

# finds each product from the store page
containers = page_soup.findAll("div",{"class": "kmd-personal-votes-list"})

# name the output file to write to local disk
out_filename = "kmd_valg.csv"
# header of csv file to be written
headers = "navn,personlige_stemmer,parti\n"

# opens file, and writes headers
f = open(out_filename, "w")
f.write(headers)
# loops over each product and grabs attributes about
# each product

navn = page_soup.findAll("div", class_="table-like-cell col-xs-7 col-sm-6 col-md-6 col-lg-8")

 # prints the dataset to console
print(navn)
</code>```

I want the names displayed in a list like:

```<code>Jeppe Kofod
Christel Schaldemose
Niels Fuglsang
...
</code>```

答:
You can use css selector with bs4 as shown below</p>

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.kmdvalg.dk/ev/2019/e1003A.htm')
soup = bs(r.content,'lxml')
names = [item.text for item in soup.select('.table-like-cell.col-xs-7')][1:]
print(names)
</code>```

Body:
I'm trying to isolate scrape some Danish election data and I want the names isolated in my output, so I don't get outputs like:

"div class="table-like-cell col-xs-7 col-sm-6 col-md-6 col-lg-8">Jeppe Kofod

I've tried using get_text behind "navn" at the end and select instead of findAll

from bs4 import BeautifulSoup as soup  # HTML data structure
from urllib.request import urlopen as uReq  # Web client
from urllib.request import Request

# URl to web scrape from.
# in this example we web scrape graphics cards from Newegg.com
page_url =Request("https://www.kmdvalg.dk/ev/2019/e1003A.htm",headers={'User-Agent': 'Mozilla/5.0'})

# opens the connection and downloads html page from url
uClient = uReq(page_url)

# parses html into a soup data structure to traverse html
# as if it were a json data type.
page_soup = soup(uClient.read(), "html.parser")
uClient.close()

# finds each product from the store page
containers = page_soup.findAll("div",{"class": "kmd-personal-votes-list"})

# name the output file to write to local disk
out_filename = "kmd_valg.csv"
# header of csv file to be written
headers = "navn,personlige_stemmer,parti\n"

# opens file, and writes headers
f = open(out_filename, "w")
f.write(headers)
# loops over each product and grabs attributes about
# each product

navn = page_soup.findAll("div", class_="table-like-cell col-xs-7 col-sm-6 col-md-6 col-lg-8")

 # prints the dataset to console
print(navn)

I want the names displayed in a list like:

Jeppe Kofod
Christel Schaldemose
Niels Fuglsang
...

Body:
You can use css selector with bs4 as shown below

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.kmdvalg.dk/ev/2019/e1003A.htm')
soup = bs(r.content,'lxml')
names = [item.text for item in soup.select('.table-like-cell.col-xs-7')][1:]
print(names)


问:
Regex - Every spaces without back on line
I would like to accept any spaces with [\s] between to words, but not returns on the line -> [^\n].

I'm using

```<code>([\w\-]+)([\s[^\n]])([\w\-]+)
</code>```

but i doesn't work.

How can I do that?

答:
try the following regex:

```<code>([\w\-]+)([\s^[\n]])([\w\-]+)
</code>```

That should add the "not" you want for new lines.

cheers!

ContentLicense: CC BY-SA 3.0

Body:
I would like to accept any spaces with [\s] between to words, but not returns on the line -> [^\n].

I'm using

([\w\-]+)([\s[^\n]])([\w\-]+)

but i doesn't work.

How can I do that?

Body:
try the following regex:

([\w\-]+)([\s^[\n]])([\w\-]+)

That should add the "not" you want for new lines.

cheers!


问:
Persisting Kinesis messages to S3 in Parquet format
I have Kinesis stream to which my app writes ~10K messages per second, in proto format.

I would like to persist those messages to S3 in parquet format. For easy search afterwards, I need to partition my data by User ID field, which is part of the message.

Currently, I have a lambda function that is triggered by Kinesis event. It receives up to 10K of messages, group them by User ID, and then write those files to S3 in parquet format.

My problem is that the files this lambda function generates are very small, ~200KB, while I would like to create ~200MB files for better query performance (I query those files using AWS Athena).

Naive approach would be to write another lambda function that read those files and merge them (rollup) into a big file, but I feel like I'm missing something and there must be a better way of doing it.

I'm wondering if I should use Spark as described in this question.

答:
Maybe you could use two additional services from AWS:

AWS Kinesis Data Analytics to consume data from Kinesis Stream and generate SQL analysis over your data (group, filter, etc). See more here: https://aws.amazon.com/kinesis/data-analytics/

AWS Kinesis Firehose plugged after Kinesis Data Analytics. With this service, we can create a parquet file on s3 at every X minutes or every Y MB with arrived data. See more here: https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html

A second way to do it is by using Spark Structured Streaming. So you could read from AWS Kinesis Stream, filter not usable data and export to s3 as described here:
https://databricks.com/blog/2017/08/09/apache-sparks-structured-streaming-with-amazon-kinesis-on-databricks.html

P.S.: This example show how to output into a local filesystem, but you can change it to s3 location.


问:
How do I use log4rs' RollingFileAppender to incorporate rolling logging?
I am trying to build a logger based on a rolling policy. Below is the closest I was able to implement:

```<code>let logfile = FileAppender::builder()
    .encoder(Box::new(PatternEncoder::new("{d} {l}::{m}{n}")))
    .build("log/output.log")?;

let config = Config::builder()
    .appender(Appender::builder().build("logfile", Box::new(logfile)))
    .build(Root::builder()
                .appender("logfile")
                .build(LevelFilter::Debug))?;

log4rs::init_config(config)?;
</code>```

This helped me log messages at all levels. However, logging to a file for a long time can be a dangerous proposition. Consequently, I am looking for something which can limit the amount of log data that's preserved. I came across RollingFileAppender, but I am not able to find the proper usage of Policy.

Please guide me through this. I am mostly looking for programmatic configuration.

答:
You can implement it via using RollingFileAppender CompoundPolicy , FixedWindowRoller and SizeTrigger from log4rs crate.

You need to implement the followings in order to create your rolling file logic:

FixedWindowRoller

Specify FixedWindowRoller to roll your log file in a fixed window_size like following:

```<code>let window_size = 3; // log0, log1, log2
let fixed_window_roller =
FixedWindowRoller::builder().build("log{}",window_size).unwrap();
</code>```

SizeTrigger

Specify SizeTrigger to declare the size limit of the file to trigger the Roller like following:

```<code>let size_limit = 5 * 1024; // 5KB as max log file size to roll
let size_trigger = SizeTrigger::new(size_limit);
</code>```

CompoundPolicy

Declare CompoundPolicy to use it in RollingFileAppender like following:

```<code>let compound_policy = CompoundPolicy::new(Box::new(size_trigger),Box::new(fixed_window_roller));
</code>```

Then in your Config, you need to use RollingFileAppender in order to get desired behavior.

let config = Config::builder()
    .appender(
        Appender::builder()
            .filter(Box::new(ThresholdFilter::new(LevelFilter::Debug)))
            .build(
                "logfile",
                Box::new(
                    RollingFileAppender::builder()
                        .encoder(Box::new(PatternEncoder::new("{d} {l}::{m}{n}")))
                        .build("logfile", Box::new(compound_policy))?,
                ),
            ),
    )
    .build(
        Root::builder()
            .appender("logfile")
            .build(LevelFilter::Debug),
    )?;
```
<p>With this implementation, you get a rolling file for the <code>window size 3</code> and the <code>roll size 5KB</code></p>
<hr />
<p>If you want to compress the rolled files you can define this in your roller file extension. Instead of <code>log{}</code>you can specify extension as <code>log{}.gz</code></p>
<p>However, if you want to enable compression with the log files you need to enable this feature in your <code>cargo.toml</code> as following:</p>
```log4rs = { version ="1.0.0", features = ["gzip"] }
```

Note: If you want to have a custom roller and custom trigger for your own purpose, you can implement your own Trigger and Roller from the respective traits

Body:
I am trying to build a logger based on a rolling policy. Below is the closest I was able to implement:

let logfile = FileAppender::builder()
    .encoder(Box::new(PatternEncoder::new("{d} {l}::{m}{n}")))
    .build("log/output.log")?;

let config = Config::builder()
    .appender(Appender::builder().build("logfile", Box::new(logfile)))
    .build(Root::builder()
                .appender("logfile")
                .build(LevelFilter::Debug))?;

log4rs::init_config(config)?;

This helped me log messages at all levels. However, logging to a file for a long time can be a dangerous proposition. Consequently, I am looking for something which can limit the amount of log data that's preserved. I came across RollingFileAppender, but I am not able to find the proper usage of Policy.

Please guide me through this. I am mostly looking for programmatic configuration.

Body:
You can implement it via using RollingFileAppender CompoundPolicy , FixedWindowRoller and SizeTrigger from log4rs crate.

You need to implement the followings in order to create your rolling file logic:

FixedWindowRoller

Specify FixedWindowRoller to roll your log file in a fixed window_size like following:

let window_size = 3; // log0, log1, log2
let fixed_window_roller =
FixedWindowRoller::builder().build("log{}",window_size).unwrap();

SizeTrigger

Specify SizeTrigger to declare the size limit of the file to trigger the Roller like following:

let size_limit = 5 * 1024; // 5KB as max log file size to roll
let size_trigger = SizeTrigger::new(size_limit);

CompoundPolicy

Declare CompoundPolicy to use it in RollingFileAppender like following:

let compound_policy = CompoundPolicy::new(Box::new(size_trigger),Box::new(fixed_window_roller));

Then in your Config, you need to use RollingFileAppender in order to get desired behavior.

let config = Config::builder()
    .appender(
        Appender::builder()
            .filter(Box::new(ThresholdFilter::new(LevelFilter::Debug)))
            .build(
                "logfile",
                Box::new(
                    RollingFileAppender::builder()
                        .encoder(Box::new(PatternEncoder::new("{d} {l}::{m}{n}")))
                        .build("logfile", Box::new(compound_policy))?,
                ),
            ),
    )
    .build(
        Root::builder()
            .appender("logfile")
            .build(LevelFilter::Debug),
    )?;

With this implementation, you get a rolling file for the window size 3 and the roll size 5KB

If you want to compress the rolled files you can define this in your roller file extension. Instead of log{}you can specify extension as log{}.gz

However, if you want to enable compression with the log files you need to enable this feature in your cargo.toml as following:

log4rs = { version ="1.0.0", features = ["gzip"] }

Note: If you want to have a custom roller and custom trigger for your own purpose, you can implement your own Trigger and Roller from the respective traits


问:
Ansible : Execute commands on newly created EC2 instance
I have an Ansible configuration where I am creating an EC2 instance. After the instance is ready, I want to disable periodic apt updates and wait for current update process to finish. Whenever I add the config in yml file, it executes the command on my local system. What am I doing wrong?

yml file:

```<code>---
  - name: Provision an EC2 Instance
    hosts: localhost
    connection: local
    gather_facts: False
    tags: provisioning
 tasks:

      - name: Create New security group with below given name
        local_action:
          module: ec2_group
          name: "{{ security_group }}"
          description: Security Group for Newly Created EC2 Instance
          region: "{{ region }}"
          rules:
            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
          rules_egress:
            - proto: all
              cidr_ip: 0.0.0.0/0

      - name: Launch the new t2 micro EC2 Instance
        local_action: ec2
                      group={{ security_group }}
                      instance_type={{ instance_type}}
                      image={{ image }}
                      wait=true
                      region={{ region }}
                      keypair={{ keypair }}
                      count={{count}}
        register: ec2
</code>```

Now, after this, I wait for ssh to finish and want to pass the following commands on the newly created Ec2 instance :

```<code>- name: Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
  raw: systemctl disable --now {{item}}
  with_items:
    - 'apt-daily.timer'
    - 'apt-daily-upgrade.timer'

- name: Reload systemctl daemon to apply the new changes
  raw: systemctl daemon-reload

- name: Purge autoupdate
  raw: apt -y purge unattended-upgrades

- name: Update apt cache
  raw: apt -y update
</code>```

But adding them as raw is not working, or even adding them as command.

答:
The first section of code you posted is provisioning a new EC2 instance by making calls to the AWS API from your local system:

  - name: Provision an EC2 Instance
    hosts: localhost
    connection: local
    gather_facts: False
...
 - name: Create New security group with below given name
   local_action:
     module: ec2_group
```
<p>Note the <code>local_action</code> section that specifies running an action locally. Also, your target is <code>localhost</code>.</p>
<p>If you then want to then configure the new system, you can add it to a host group and run some configuration steps. For example, add this following the <code>Provision an EC2 Instance</code> step to add the new instance's public IP to a hostgroup called <code>ec2hosts</code>:</p>
<pre class="lang-bash prettyprint-override"><code>   - name: Add instance public IP to host group
     add_host: hostname={{ item.public_ip }} groups=ec2hosts
     loop: "{{ ec2.instances }}"
</code>```

Now you can configure the host by targeting the host group:

- hosts: ec2hosts
  name: configuration play
  user: ec2-user
  gather_facts: true
  tasks:
  - name:  Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
    raw: systemctl disable --now {{item}}
    with_items:
      - 'apt-daily.timer'
      - 'apt-daily-upgrade.timer'

  - name: Reload systemctl daemon to apply the new changes
    raw: systemctl daemon-reload

  - name: Purge autoupdate
    raw: apt -y purge unattended-upgrades

  - name: Update apt cache
    raw: apt -y update
```

To summarize, you first create the instance from your local system, wait for it to boot, add its IP address to a host group, then run additional configuration steps by running ansible against that host group. For this to work, make sure to use an SSH key pair for which the private key has been added to the SSH agent. Also, make sure to launch the EC2 instance in to a public subnet.

Refer to the Ansible Amazon Web Service Guide.

Body:
I have an Ansible configuration where I am creating an EC2 instance. After the instance is ready, I want to disable periodic apt updates and wait for current update process to finish. Whenever I add the config in yml file, it executes the command on my local system. What am I doing wrong?

yml file:

---
  - name: Provision an EC2 Instance
    hosts: localhost
    connection: local
    gather_facts: False
    tags: provisioning
 tasks:

      - name: Create New security group with below given name
        local_action:
          module: ec2_group
          name: "{{ security_group }}"
          description: Security Group for Newly Created EC2 Instance
          region: "{{ region }}"
          rules:
            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
          rules_egress:
            - proto: all
              cidr_ip: 0.0.0.0/0

      - name: Launch the new t2 micro EC2 Instance
        local_action: ec2
                      group={{ security_group }}
                      instance_type={{ instance_type}}
                      image={{ image }}
                      wait=true
                      region={{ region }}
                      keypair={{ keypair }}
                      count={{count}}
        register: ec2

Now, after this, I wait for ssh to finish and want to pass the following commands on the newly created Ec2 instance :

- name: Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
  raw: systemctl disable --now {{item}}
  with_items:
    - 'apt-daily.timer'
    - 'apt-daily-upgrade.timer'

- name: Reload systemctl daemon to apply the new changes
  raw: systemctl daemon-reload

- name: Purge autoupdate
  raw: apt -y purge unattended-upgrades

- name: Update apt cache
  raw: apt -y update

But adding them as raw is not working, or even adding them as command.

Body:
The first section of code you posted is provisioning a new EC2 instance by making calls to the AWS API from your local system:

  - name: Provision an EC2 Instance
    hosts: localhost
    connection: local
    gather_facts: False
...
 - name: Create New security group with below given name
   local_action:
     module: ec2_group

Note the local_action section that specifies running an action locally. Also, your target is localhost.

If you then want to then configure the new system, you can add it to a host group and run some configuration steps. For example, add this following the Provision an EC2 Instance step to add the new instance's public IP to a hostgroup called ec2hosts:

   - name: Add instance public IP to host group
     add_host: hostname={{ item.public_ip }} groups=ec2hosts
     loop: "{{ ec2.instances }}"

Now you can configure the host by targeting the host group:

- hosts: ec2hosts
  name: configuration play
  user: ec2-user
  gather_facts: true
  tasks:
  - name:  Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
    raw: systemctl disable --now {{item}}
    with_items:
      - 'apt-daily.timer'
      - 'apt-daily-upgrade.timer'

  - name: Reload systemctl daemon to apply the new changes
    raw: systemctl daemon-reload

  - name: Purge autoupdate
    raw: apt -y purge unattended-upgrades

  - name: Update apt cache
    raw: apt -y update

To summarize, you first create the instance from your local system, wait for it to boot, add its IP address to a host group, then run additional configuration steps by running ansible against that host group. For this to work, make sure to use an SSH key pair for which the private key has been added to the SSH agent. Also, make sure to launch the EC2 instance in to a public subnet.

Refer to the Ansible Amazon Web Service Guide.


问:
How can I choose the node version when using .nvm to install
In the terminal, using nvm, I would like to run npm install <something> and have npm install the package in the node version that I'm currently using.  Currently, no matter what version I have set using nvm, by default, nvm is installing all packages in node version 9.4.0.

I have ran the command nvm use v10.15.3 which switches me to that current version.  When I run a command npm install -g ionic@latest (or any global command) it always installs it in the version 9.4.0 directory.

My output after running the command...

```<code>.../.nvm/versions/node/v9.4.0/bin/ionic -> .../.nvm/versions/node/v9.4.0/lib/node_modules/ionic/bin/ionic
</code>```

This happens even though I'm currently on 10.15.3 (I would expect to install in the directory v10.15.3 and not v9.4.0

I'm using nvm version 0.34.0.

bash_profile

```<code>export NVM_DIR=~/.nvm
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

source ~/.nvm/nvm.sh
</code>```

答:
You need to change the global version of node installed.

```<code>nvm install node --reinstall-packages-from=node
</code>```

is useful for moving your tools to the new Node.js version.

See usage: https://github.com/creationix/nvm#usage

Body:
In the terminal, using nvm, I would like to run npm install <something> and have npm install the package in the node version that I'm currently using.  Currently, no matter what version I have set using nvm, by default, nvm is installing all packages in node version 9.4.0.

I have ran the command nvm use v10.15.3 which switches me to that current version.  When I run a command npm install -g ionic@latest (or any global command) it always installs it in the version 9.4.0 directory.

My output after running the command...

.../.nvm/versions/node/v9.4.0/bin/ionic -> .../.nvm/versions/node/v9.4.0/lib/node_modules/ionic/bin/ionic

This happens even though I'm currently on 10.15.3 (I would expect to install in the directory v10.15.3 and not v9.4.0

I'm using nvm version 0.34.0.

bash_profile

export NVM_DIR=~/.nvm
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

source ~/.nvm/nvm.sh

Body:
You need to change the global version of node installed.

nvm install node --reinstall-packages-from=node

is useful for moving your tools to the new Node.js version.

See usage: https://github.com/creationix/nvm#usage


问:
Downloading MDB (Access) file from IIS
This question might be better asked over on ServerFault, but since this is related to a programming project, I'll ask here.

Simply put, how do I configure IIS to let me download an Access (.MDB) file the same way it lets me download .HTML, .EXE, etc. files?

I've tried taking MDB out of the mime types, changing the extension to .DAT, telling my local directories to treat .MDB files like binary/octet-stream files, yet nothing works.  I still get a "(401) Unauthorized" access.

What am I doing wrong?

EDIT: Figures that as soon as I ask, I figure it out.  I had not given "Everyone" read permission on the file.  Did that and removed the .MDB Application Mapping, and it wored.

答:
You are not doing anything wrong. IIS is forbidding download of .mdb files. Here are ref's for your use:

http://www.eggheadcafe.com/software/aspnet/29460604/iis-6-wont-serve-mdb-file.aspx

http://www.windowsreference.com/internet-information-services-iis/fix-for-iis-fails-to-download-access-mdb-file-mime-type/

ContentLicense: CC BY-SA 2.5

Title: Downloading MDB (Access) file from IIS


问:
Lambda function not executed in dictionary with "if-else" values
I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

```<code>def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()
</code>```

if we set condition = False, the code will not print b, it will not do anything (it seems)..why?
Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

```<code>dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)
</code>```

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

答:
The code you wrote is equivalent to:

```<code>def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: (a() if condition else lambda: b()),
        'bar': lambda: (c() if condition else lambda: d())
    }.get('foo', lambda: print('not found'))()
</code>```

It means that the code after the first lambda is considered one block of function. What you want is:

```<code>def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': (lambda: a()) if condition else (lambda: b()),
        'bar': (lambda: c()) if condition else (lambda: d())
    }.get('foo', lambda: print('not found'))()
</code>```

Body:
I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()

if we set condition = False, the code will not print b, it will not do anything (it seems)..why?
Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

Body:
The code you wrote is equivalent to:

def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': lambda: (a() if condition else lambda: b()),
        'bar': lambda: (c() if condition else lambda: d())
    }.get('foo', lambda: print('not found'))()

It means that the code after the first lambda is considered one block of function. What you want is:

def a():
    print('a')

def b():
    print('b')

def c():
    print('c')

def d():
    print('d')

condition = True

dict = {
        'foo': (lambda: a()) if condition else (lambda: b()),
        'bar': (lambda: c()) if condition else (lambda: d())
    }.get('foo', lambda: print('not found'))()


问:
Error:Unable to start the daemon process.Error occurred during initialization of VM Could not reserve enough space for 1572864KB object heap
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/4.4/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

Invalidate Catches And Restart

Rebuild

Close The Project And Start It Again

答:
Error occurred during initialization of VM Could not reserve enough space for 1572864KB object heap.

To solve This Error You Have To Change Only Heap Size Which Is Define In Gradle.Properties file. You Have To Change The HeapSize To 1024m And Rebuild the Project, If The Error Is Not Solved Then You Have To Close The Project And Rebuild It.

For Video Tutorial See Below Link SOLVED : Unable To Start The Daemon Process In Android Studio


问:
Exporting index table from MySQL database
I am recently working on better indexing concepts. as part of that, I want to know if it is possible to export the index table that mysql generates internally. I want to be able to export the index table in the form of CSV.

I am aware about creating the index in the database with:

```<code>Example : CREATE INDEX index_name ON table_name (column_list)
</code>```

After the index has been made, i am able to see it with:

```<code>SHOW INDEX FROM table_name;
</code>```

In phpmyadmin i am able to see the index table in the structure section.

I am using InnoDB engine and For InnoDB engine, the indexes are stored in the tablespace, along with the table. If innodb_file_per_table option is set, the indexes will be in the table's .ibd file.

so will it be possible to export index table data in a form of csv from .ibd file ?

I want to export the index table that mysql generates internally, in a CSV format.

答:
If you have

```<code>PRIMARY KEY (id),
INDEX(a,b)
</code>```

Then

```<code>SELECT a, b, id INTO outfile ... FROM ... ORDER BY a,b,id
</code>```

will give you the contents of the index.  It will not, however, show you any details of the B+Tree that is the overhead of the INDEX.

The PRIMARY KEY of a InnoDB table is a B+Tree with all the columns in PK order.

The "secondary key" (Unique or not) is a B+Tree with all the columns of the secondary index, plus any other columns from the PK.  It is also sorted.

Prefix indexes (eg, INDEX(foo(7))) are another matter.

FULLTEXT and SPATIAL have their own internal structure, not a straightforward B+Tree.

Body:
I am recently working on better indexing concepts. as part of that, I want to know if it is possible to export the index table that mysql generates internally. I want to be able to export the index table in the form of CSV.

I am aware about creating the index in the database with:

Example : CREATE INDEX index_name ON table_name (column_list)

After the index has been made, i am able to see it with:

SHOW INDEX FROM table_name;

In phpmyadmin i am able to see the index table in the structure section.

I am using InnoDB engine and For InnoDB engine, the indexes are stored in the tablespace, along with the table. If innodb_file_per_table option is set, the indexes will be in the table's .ibd file.

so will it be possible to export index table data in a form of csv from .ibd file ?

I want to export the index table that mysql generates internally, in a CSV format.

Body:
If you have

PRIMARY KEY (id),
INDEX(a,b)

Then

SELECT a, b, id INTO outfile ... FROM ... ORDER BY a,b,id

will give you the contents of the index.  It will not, however, show you any details of the B+Tree that is the overhead of the INDEX.

The PRIMARY KEY of a InnoDB table is a B+Tree with all the columns in PK order.

The "secondary key" (Unique or not) is a B+Tree with all the columns of the secondary index, plus any other columns from the PK.  It is also sorted.

Prefix indexes (eg, INDEX(foo(7))) are another matter.

FULLTEXT and SPATIAL have their own internal structure, not a straightforward B+Tree.


问:
How can I run multiple instances of a Docker image?
I want to to multiple instances/replicas of the same image.

Consider an image workerA which has been build.

```<code>docker build --tag=workerA .
</code>```

I usually run it with

```<code>docker run --net=host -p 18080:8080 -t -i workerA
</code>```

Now I want to run it several replicas of this docker container.I looked into the swarm documentation and create a compose file as

```<code>version: "3"
services:
  web:
    # replace username/repo:tag with your name and image details
    image: workerA:latest
    deploy:
      replicas: 2
      resources:
        limits:
          cpus: "0.5"
          memory: 4G
      restart_policy:
        condition: on-failure
    ports:
      - "18080:8080"
    network_mode: "host"
</code>```

Usually the worker would connect to host server, grab data and perform a task but the server never receives any request. How can I check what my workerA terminal outputs? I seems I am able to create the replicas

```<code>$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
y0sf30vqaoj1        warokerASwarm_web        replicated          2/2                 workerA:latest    *:18080->8080/tcp
</code>```

but they seem not to be in the same network or preform the way I was used to when a single instances of docker is running.

答:
From the docs

The option network_mode is ignored when deploying a stack in swarm mode with a (version 3) Compose file.

If you're expecting it to behave the same way, as when running a single container, it won't happen.

If there's no specific reason for using version: '3' you may use version:'2' instead.

Or you can let it create its own network, which it does with your current docker-compose file.

If you want to use host network instead, please take note of these limitations (from docs):

In Docker 17.06 and higher, you can also use a host network for a swarm service, by passing --network host to the docker container create command. In this case, control traffic (traffic related to managing the swarm and the service) is still sent across an overlay network, but the individual swarm service containers send data using the Docker daemon’s host network and ports. This creates some extra limitations. For instance, if a service container binds to port 80, only one service container can run on a given swarm node.

Body:
I want to to multiple instances/replicas of the same image.

Consider an image workerA which has been build.

docker build --tag=workerA .

I usually run it with

docker run --net=host -p 18080:8080 -t -i workerA

Now I want to run it several replicas of this docker container.I looked into the swarm documentation and create a compose file as

version: "3"
services:
  web:
    # replace username/repo:tag with your name and image details
    image: workerA:latest
    deploy:
      replicas: 2
      resources:
        limits:
          cpus: "0.5"
          memory: 4G
      restart_policy:
        condition: on-failure
    ports:
      - "18080:8080"
    network_mode: "host"

Usually the worker would connect to host server, grab data and perform a task but the server never receives any request. How can I check what my workerA terminal outputs? I seems I am able to create the replicas

$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
y0sf30vqaoj1        warokerASwarm_web        replicated          2/2                 workerA:latest    *:18080->8080/tcp

but they seem not to be in the same network or preform the way I was used to when a single instances of docker is running.


问:
Mapping values to different values in list
The problem is to map a particular list in order to accumulate the time. A single change in digit accounts for 1 ms . However the clock resets after number 255.

```<code>list_val = [ 253 ,1,15,27,45,63,120,140,195,210,225,243,2,5,1]
</code>```

The output should be like

```<code>new_list = [ 1 ,3,17,29,47,65,122,142,197,212,227,245,257,260,510].
</code>```

Here is what I have tried

```<code>new_list = []
for i in range(len(list_val)):
      if i == 0:
          new_list.append(1)
      elif list_val[i-1] < list_val[i] :
          new_list[i] =new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
      elif list_val[i-1] > list_val[i] :
          new_list[i] = new_list.append(255 - list_val[i-1] + new_list[i-1])
      else: #list_val[i-1] == list_val[i]:
          new_list[i] = new_list.append(255 + list_val[i-1] + new_list[i-1])
</code>```

The following is the error
unsupported operand type(s) for +: 'int' and 'NoneType'

答:
There are some errors in your syntax.

Calling the append method will add an element to the original list but it returns None. So you need to adjust your code as follows.

```<code>new_list = []
for i in range(len(list_val)):
    if i == 0:
        new_list.append(1)
    elif list_val[i-1] < list_val[i] :
        new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
        # you can replace new_list[i-1] with new_list[-1] if you choose to
    elif list_val[i-1] > list_val[i] :
        new_list.append(255 - list_val[i-1] + new_list[i-1])
    else:
        new_list.append(255 + list_val[i-1] + new_list[i-1])
</code>```

The result is

```<code>new_list = [1, 3, 17, 29, 47, 65, 122, 142, 197, 212, 227, 245, 257, 260, 510]
</code>```

Body:
The problem is to map a particular list in order to accumulate the time. A single change in digit accounts for 1 ms . However the clock resets after number 255.

list_val = [ 253 ,1,15,27,45,63,120,140,195,210,225,243,2,5,1]

The output should be like

new_list = [ 1 ,3,17,29,47,65,122,142,197,212,227,245,257,260,510].

Here is what I have tried

new_list = []
for i in range(len(list_val)):
      if i == 0:
          new_list.append(1)
      elif list_val[i-1] < list_val[i] :
          new_list[i] =new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
      elif list_val[i-1] > list_val[i] :
          new_list[i] = new_list.append(255 - list_val[i-1] + new_list[i-1])
      else: #list_val[i-1] == list_val[i]:
          new_list[i] = new_list.append(255 + list_val[i-1] + new_list[i-1])

The following is the error
unsupported operand type(s) for +: 'int' and 'NoneType'

Body:
There are some errors in your syntax.

Calling the append method will add an element to the original list but it returns None. So you need to adjust your code as follows.

new_list = []
for i in range(len(list_val)):
    if i == 0:
        new_list.append(1)
    elif list_val[i-1] < list_val[i] :
        new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
        # you can replace new_list[i-1] with new_list[-1] if you choose to
    elif list_val[i-1] > list_val[i] :
        new_list.append(255 - list_val[i-1] + new_list[i-1])
    else:
        new_list.append(255 + list_val[i-1] + new_list[i-1])

The result is

new_list = [1, 3, 17, 29, 47, 65, 122, 142, 197, 212, 227, 245, 257, 260, 510]


问:
Docker build is failing with No module named pip._vendor for airflow 1.10.0 and python 2.7
I have a docker image with python 2.7. I am trying to install airflow in the image, but during the pip installation of the airflow dependencies I am getting the below issues.

Dockerfile:-

```<code>FROM python:2.7-slim
...
...
# Install Airflow and Celery
COPY pip_airflow.txt /pip_airflow.txt
RUN pip install --no-cache-dir -r /pip_airflow.txt
</code>```

Below is my pip_airflow.txt file.

```<code>apache-airflow[all]==1.10.0
celery[redis]>=4.2.1,<4.3.0
flower>=0.7.3,<1.0
kombu>=4.2.0,<5.0
</code>```

Logs:- The failure is when the pip install for airflow is happening from the dockerfile.

```<code>Collecting pendulum==1.4.4 (from apache-airflow[all]==1.10.0->-r /pip_airflow.txt (line 1))
    Downloading https://files.pythonhosted.org/packages/85/a5/9fc15751f9725923b170ad37d6c61031fc9e941bafd5288ca6ee51233284/pendulum-1.4.4.tar.gz (74kB)
    Installing build dependencies: started
    Installing build dependencies: finished with status 'done'
    Getting requirements to build wheel: started
    Getting requirements to build wheel: finished with status 'error'
    Complete output from command /usr/local/bin/python /usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py get_requires_for_build_wheel /tmp/tmpnYnATX:
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 207, in <module>
        main()
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 197, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 54, in get_requires_for_build_wheel
        return hook(config_settings)
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 130, in get_requires_for_build_wheel
        return self._get_build_requires(config_settings, requirements=['wheel'])
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 112, in _get_build_requires
        self.run_setup()
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 126, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 47, in <module>
        from build import *
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/build.py", line 7, in <module>
        from pip._vendor import pytoml
    ImportError: No module named pip._vendor
</code>```

答:
Update pip, e.g. pip install pip===19.0.2.
In my case it worked.

Body:
I have a docker image with python 2.7. I am trying to install airflow in the image, but during the pip installation of the airflow dependencies I am getting the below issues.

Dockerfile:-

FROM python:2.7-slim
...
...
# Install Airflow and Celery
COPY pip_airflow.txt /pip_airflow.txt
RUN pip install --no-cache-dir -r /pip_airflow.txt

Below is my pip_airflow.txt file.

apache-airflow[all]==1.10.0
celery[redis]>=4.2.1,<4.3.0
flower>=0.7.3,<1.0
kombu>=4.2.0,<5.0

Logs:- The failure is when the pip install for airflow is happening from the dockerfile.

Collecting pendulum==1.4.4 (from apache-airflow[all]==1.10.0->-r /pip_airflow.txt (line 1))
    Downloading https://files.pythonhosted.org/packages/85/a5/9fc15751f9725923b170ad37d6c61031fc9e941bafd5288ca6ee51233284/pendulum-1.4.4.tar.gz (74kB)
    Installing build dependencies: started
    Installing build dependencies: finished with status 'done'
    Getting requirements to build wheel: started
    Getting requirements to build wheel: finished with status 'error'
    Complete output from command /usr/local/bin/python /usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py get_requires_for_build_wheel /tmp/tmpnYnATX:
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 207, in <module>
        main()
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 197, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 54, in get_requires_for_build_wheel
        return hook(config_settings)
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 130, in get_requires_for_build_wheel
        return self._get_build_requires(config_settings, requirements=['wheel'])
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 112, in _get_build_requires
        self.run_setup()
      File "/tmp/pip-build-env-OXncUe/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 126, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 47, in <module>
        from build import *
      File "/usr/local/lib/python2.7/site-packages/pip/_vendor/pep517/build.py", line 7, in <module>
        from pip._vendor import pytoml
    ImportError: No module named pip._vendor


问:
Is there a concise way to check if an int variable is equal to a series of ints? | C#
Rather than something like this:

```<code>switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}
</code>```

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

答:
You could try:

```<code>List<int> ints = new List<int> {2, 5, 11, 15};
if (ints.Contains(id))
{
}
</code>```

Though it might be slower than doing the switch.

However, it does have the advantage that (assuming that you initialise the list from data) you can use this to check on any list of integer values and aren't constrained to hard coded values.

Body:
Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

Body:
You could try:

List<int> ints = new List<int> {2, 5, 11, 15};
if (ints.Contains(id))
{
}

Though it might be slower than doing the switch.

However, it does have the advantage that (assuming that you initialise the list from data) you can use this to check on any list of integer values and aren't constrained to hard coded values.


问:
npm ERR! Unexpected end of JSON input while parsing near '...npmjs.org/prelude-ls/'
Trying to run:

```<code>npm install @angular-devkit/build-angular
</code>```

Getting below while installing

npm ERR! Unexpected end of JSON input while parsing near '...npmjs.org/prelude-ls/'

Please help

答:
I got the same proplem. Try with below command. It's worked for me.

```<code>**npm cache clean --force**
</code>```

Or else you can try removing all the files that were listed below problem will solve.

```<code>> For Windows : go to C:\Users\username\AppData\Roaming\npm-cache
> Delete all files and install angular again.
</code>```

Body:
Trying to run:

npm install @angular-devkit/build-angular

Getting below while installing

npm ERR! Unexpected end of JSON input while parsing near '...npmjs.org/prelude-ls/'

Please help

Body:
I got the same proplem. Try with below command. It's worked for me.

**npm cache clean --force**

Or else you can try removing all the files that were listed below problem will solve.

> For Windows : go to C:\Users\username\AppData\Roaming\npm-cache
> Delete all files and install angular again.


问:
tf.estimator.export.build_raw_serving_input_receiver_fn problem
I have a problem about exporting a savedmodel from an estimator of Tensorflow. My tensorflow program is using an estimator to do the CNN function, where the input is a 2D image. This is my code for the saving part.

```<code>            def serving_input_rec_fn():
                serving_features = {'images': tf.placeholder(shape=[None, self.num_input[0], self.num_input[1]], dtype=tf.float32)}
                return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)

            self.model.export_savedmodel(export_dir, serving_input_rec_fn,
                                         strip_default_attrs=True)
</code>```

But when I ran export_savedmodel function, it produced the following error:

```<code>AttributeError: 'function' object has no attribute 'features'
</code>```

When I checked the code, I actually provided the serving_features here. Could any one help me solve this problem?

答:
In serving_input_rec_fn() change:

```<code>def serving_input_rec_fn():
   ...
   return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)
</code>```

to:

```<code>def serving_input_rec_fn():
   ...
   return tf.estimator.export.build_raw_serving_input_receiver_fn(serving_features)
</code>```

As of documentation (here), build_raw_serving_input_receiver_fn function does not have a features argument

Body:
I have a problem about exporting a savedmodel from an estimator of Tensorflow. My tensorflow program is using an estimator to do the CNN function, where the input is a 2D image. This is my code for the saving part.

            def serving_input_rec_fn():
                serving_features = {'images': tf.placeholder(shape=[None, self.num_input[0], self.num_input[1]], dtype=tf.float32)}
                return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)

            self.model.export_savedmodel(export_dir, serving_input_rec_fn,
                                         strip_default_attrs=True)

But when I ran export_savedmodel function, it produced the following error:

AttributeError: 'function' object has no attribute 'features'

When I checked the code, I actually provided the serving_features here. Could any one help me solve this problem?

Body:
In serving_input_rec_fn() change:

def serving_input_rec_fn():
   ...
   return tf.estimator.export.build_raw_serving_input_receiver_fn(features=serving_features)

to:

def serving_input_rec_fn():
   ...
   return tf.estimator.export.build_raw_serving_input_receiver_fn(serving_features)

As of documentation (here), build_raw_serving_input_receiver_fn function does not have a features argument


问:
How to? Listen for Location Setting being turned ON (Android App)
So I've spent the past few weeks working on my Android App and looking into the best way of implementing what I need to do, but still can't quite get it right.. Any/all help is greatly appreciated, as I am still getting the hang of things..

Task:

(Assuming the "Location"/GPS Setting is currently off), I need to have my App constantly be listening for the "Location" Setting to be turned ON.. At this point, simply start an Activity.

Ideas:

These are all the different ways I think it could possibly work:

LocationListener using "onProviderEnabled"

GpsStatusListener using "onGpsStatusChanged" with "GPS_EVENT_STARTED"

GpsProvider requiresSatellite (to determine if it starts), or somehow use the GpsProvider's "AVAILABLE" Constant/int

SettingInjectorService using "ACTION_SERVICE_INTENT" (and/or) "ACTION_INJECTED_SETTING_CHANGED" with "onGetEnabled" or "isEnabled"

Settings.Secure using "LOCATION_MODE" != "LOCATION_MODE_OFF"

a ContentObserver/ContentResolver

Intent getAction (...)

An "if/else" of some kind

Questions:

Any kind of advice or answers for any of the following questions are very much appreciated..

Which of the Ideas above would be the best way of accomplishing the Task? The simpler the better, but most importantly it needs to be listening at all times, and respond instantly when the Location Setting is turned On.

For whichever one of the Ideas  above works best, how would I implement it? (For example, would I need a BroadcastListener? or a Service? and how would it all piece together?

I truly appreciate any advice or help that you can provide me with.. I'm still getting the hang of all this, but confident enough to do it, and eager to   publish my first App.. So thank you, it means a lot and will greatly help me along.

EDIT:

OK So here's what I've got so far...

Heres my Receiver:

MyReceiver.Java

```<code>public class MyReceiver extends BroadcastReceiver {

    private final static String TAG = "LocationProviderChanged";

    boolean isGpsEnabled;
    boolean isNetworkEnabled;

    public MyReceiver() {
    // EMPTY

    // MyReceiver Close Bracket
    }

    // START OF onReceive
    @Override
    public void onReceive(Context context, Intent intent) {

        // PRIMARY RECEIVER
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {

            Log.i(TAG, "Location Providers Changed");

            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Toast.makeText(context, "GPS Enabled: " + isGpsEnabled + " Network Location Enabled: " + isNetworkEnabled, Toast.LENGTH_LONG).show();

            // START DIALOG ACTIVITY
            if (isGpsEnabled || isNetworkEnabled) {
                Intent runDialogActivity = new Intent(context, DialogActivity.class);
                context.startActivity(runDialogActivity);

            }

        }

        // BOOT COMPLETED (REPLICA OF PRIMARY RECEIVER CODE FOR WHEN BOOT_COMPLETED)
        if (intent.getAction().matches("android.intent.action.BOOT_COMPLETED")) {

            Log.i(TAG, "Location Providers Changed Boot");

            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Toast.makeText(context, "GPS Enabled Boot: " + isGpsEnabled + " Network Location Enabled Boot: " + isNetworkEnabled, Toast.LENGTH_LONG).show();

            // START DIALOG ACTIVITY
            if (isGpsEnabled || isNetworkEnabled) {
                Intent runDialogActivity = new Intent(context, DialogActivity.class);
                context.startActivity(runDialogActivity);

            }

        }

    // onReceive CLOSE BRACKET
    }

// CLOSE OF FULL CLASS
}
</code>```

And heres what the Manifest looks like:

Manifest.XML

```<code><?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ender.projects.receivertest">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".DialogActivity">
        </activity>

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />

                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

    </application>

</manifest>
</code>```

Aside from these files, I have the following files:

MainActivity.Java and DialogActivity.Java, both with Layout files,

activity_main.xml and activity_dialog.xml to match with them.

So if I understand correctly, when the user downloads the App and opens it, my MainActivity.Java and corresponding layout will launch. But I am only going to use this simply as a preferences screen. So once they open the App for the first time, the Broadcast Receiver should automatically start listening for the LOCATION setting to be turned on, correct? I also want the Broadcast Listener to remain listening, even after it receives the initial Broadcast (so that my onReceive still fires if they turn the LOCATION setting off, and then later they turn it ON again..

So (A) How does my code look thus far?

and (B) To accomplish what I just described, what would need to be added?

and (C) Running it throws this error when I turn the LOCATION setting ON.

..How can I fix it?:

java.lang.RuntimeException: Unable to start receiver com.bryce.projects.servicesthreadsetc.MyReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Thanks again for all the help!

答:
LocationListeners's onProvideEnabled() method will work instantly. When you call this remember if you are doing LocationManager.removeUpdates() in between onProviderEnabled() won't work.

And this is pretty much simple when you are reading locations from Location API's of Android. You don't need the broadcast receivers listening and communication further

But when you are using FusedLocationProviderClient from google API and if you use LocationListener's onProviderEnabled and onProviderDisabled methods you will be having two services running in parallel, checking for the provider changes. So using BroadcastReceiver is better

Body:
So I've spent the past few weeks working on my Android App and looking into the best way of implementing what I need to do, but still can't quite get it right.. Any/all help is greatly appreciated, as I am still getting the hang of things..

Task:

(Assuming the "Location"/GPS Setting is currently off), I need to have my App constantly be listening for the "Location" Setting to be turned ON.. At this point, simply start an Activity.

Ideas:

These are all the different ways I think it could possibly work:

LocationListener using "onProviderEnabled"

GpsStatusListener using "onGpsStatusChanged" with "GPS_EVENT_STARTED"

GpsProvider requiresSatellite (to determine if it starts), or somehow use the GpsProvider's "AVAILABLE" Constant/int

SettingInjectorService using "ACTION_SERVICE_INTENT" (and/or) "ACTION_INJECTED_SETTING_CHANGED" with "onGetEnabled" or "isEnabled"

Settings.Secure using "LOCATION_MODE" != "LOCATION_MODE_OFF"

a ContentObserver/ContentResolver

Intent getAction (...)

An "if/else" of some kind

Questions:

Any kind of advice or answers for any of the following questions are very much appreciated..

Which of the Ideas above would be the best way of accomplishing the Task? The simpler the better, but most importantly it needs to be listening at all times, and respond instantly when the Location Setting is turned On.

For whichever one of the Ideas  above works best, how would I implement it? (For example, would I need a BroadcastListener? or a Service? and how would it all piece together?

I truly appreciate any advice or help that you can provide me with.. I'm still getting the hang of all this, but confident enough to do it, and eager to   publish my first App.. So thank you, it means a lot and will greatly help me along.

EDIT:

OK So here's what I've got so far...

Heres my Receiver:

MyReceiver.Java

public class MyReceiver extends BroadcastReceiver {

    private final static String TAG = "LocationProviderChanged";

    boolean isGpsEnabled;
    boolean isNetworkEnabled;

    public MyReceiver() {
    // EMPTY

    // MyReceiver Close Bracket
    }

    // START OF onReceive
    @Override
    public void onReceive(Context context, Intent intent) {

        // PRIMARY RECEIVER
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {

            Log.i(TAG, "Location Providers Changed");

            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Toast.makeText(context, "GPS Enabled: " + isGpsEnabled + " Network Location Enabled: " + isNetworkEnabled, Toast.LENGTH_LONG).show();

            // START DIALOG ACTIVITY
            if (isGpsEnabled || isNetworkEnabled) {
                Intent runDialogActivity = new Intent(context, DialogActivity.class);
                context.startActivity(runDialogActivity);

            }

        }

        // BOOT COMPLETED (REPLICA OF PRIMARY RECEIVER CODE FOR WHEN BOOT_COMPLETED)
        if (intent.getAction().matches("android.intent.action.BOOT_COMPLETED")) {

            Log.i(TAG, "Location Providers Changed Boot");

            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Toast.makeText(context, "GPS Enabled Boot: " + isGpsEnabled + " Network Location Enabled Boot: " + isNetworkEnabled, Toast.LENGTH_LONG).show();

            // START DIALOG ACTIVITY
            if (isGpsEnabled || isNetworkEnabled) {
                Intent runDialogActivity = new Intent(context, DialogActivity.class);
                context.startActivity(runDialogActivity);

            }

        }

    // onReceive CLOSE BRACKET
    }

// CLOSE OF FULL CLASS
}

And heres what the Manifest looks like:

Manifest.XML

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ender.projects.receivertest">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".DialogActivity">
        </activity>

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />

                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Aside from these files, I have the following files:

MainActivity.Java and DialogActivity.Java, both with Layout files,

activity_main.xml and activity_dialog.xml to match with them.

So if I understand correctly, when the user downloads the App and opens it, my MainActivity.Java and corresponding layout will launch. But I am only going to use this simply as a preferences screen. So once they open the App for the first time, the Broadcast Receiver should automatically start listening for the LOCATION setting to be turned on, correct? I also want the Broadcast Listener to remain listening, even after it receives the initial Broadcast (so that my onReceive still fires if they turn the LOCATION setting off, and then later they turn it ON again..

So (A) How does my code look thus far?

and (B) To accomplish what I just described, what would need to be added?

and (C) Running it throws this error when I turn the LOCATION setting ON.

..How can I fix it?:

java.lang.RuntimeException: Unable to start receiver com.bryce.projects.servicesthreadsetc.MyReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Thanks again for all the help!


问:
Need to extract all links from script tag HTML Python
Basically i need to parse all src="" links from all

Unfortunately, bs4 cannot do that. Any ideas how can i achieve this?

答:
I would condense and use script[src] to ensure script has src attribute

```<code>import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://example.com').content
soup = bs(r, 'lxml') # 'html.parser' if lxml not installed
srcs = [item['src'] for item in soup.select('script[src]')]
</code>```

Body:
I would condense and use script[src] to ensure script has src attribute

import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://example.com').content
soup = bs(r, 'lxml') # 'html.parser' if lxml not installed
srcs = [item['src'] for item in soup.select('script[src]')]


问:
Running Python code in Visual Studio - installing pip not working
Im trying to connect Linkedin to my Python.
and Im trying to run these in Visual Studio

For the below line,

$ pip install python-linkedin

it keeps throwing syntax error, not reading that $pip correctly.

I followed few videos and posts on Stackoverflow, and they suggested to click on "View" -> "Tools" -> Python environments, but I can`t find this "Tool" and Python environments from View option

Is there any alternative solutions to this?

Screenshot is my Visual Studio setting, if it helps..
VS setup

答:
You need to install Python support for VS to work with python.

https://learn.microsoft.com/en-us/visualstudio/python/installing-python-support-in-visual-studio?view=vs-2019

Once you do that you should be able to see the python environment tab. It would look like this:

Another potential issue is that pip for python3.x is usually installed as pip3.x, not pip, so if you are using python 3x, you would need to change your settings.json accordingly.


问:
Change tab colour based on cell value, runtime error
On each tab of my workbook, cell I1 calculates Print if the tab should be printed (meets criteria)

I am trying to code each tab to look at I1 and change tab colour if I1 = "Print". All of the codes that I am trying end up resulting in a Runtime error 1004.

Can anyone see what is wrong with my code?

EDIT 1: The error is thrown up at

                .Color = RGB(255, 255, 102)

EDIT 2: I have switched to Calculate from Change. Thanks for that.

EDIT 3: I have two module codes in the same book which password protect/unprotect all tabs. Could this be interfering?

```<code>Sub protect_all_sheets()
top:
pass = InputBox("password?")
repass = InputBox("Verify Password")
If Not (pass = repass) Then
MsgBox "you made a boo boo"
GoTo top
End If
 For i = 1 To Worksheets.Count
 If Worksheets(i).ProtectContents = True Then GoTo oops
 Next
 For Each s In ActiveWorkbook.Worksheets
 s.Protect Password:=pass
 Next
 Exit Sub
 oops: MsgBox "I think you have some sheets that are already protected. Please unprotect all sheets then running this Macro."
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    MyVal = Range("I1").Text

    With ActiveSheet.Tab
        Select Case MyVal
            Case "Print"
                .Color = RGB(255, 255, 102)
            Case Else
                .ColorIndex = xlColorIndexNone
        End Select
    End With
End Sub
</code>```

答:
Worksheet_Change isn't triggered by calculations: you need Worksheet_Calculate

```<code>Private Sub Worksheet_Calculate()
    Me.tab.color = IIf(Me.Range("I1").value="Print",vbRed,vbWhite)
End Sub
</code>```

Body:
On each tab of my workbook, cell I1 calculates Print if the tab should be printed (meets criteria)

I am trying to code each tab to look at I1 and change tab colour if I1 = "Print". All of the codes that I am trying end up resulting in a Runtime error 1004.

Can anyone see what is wrong with my code?

EDIT 1: The error is thrown up at

                .Color = RGB(255, 255, 102)

EDIT 2: I have switched to Calculate from Change. Thanks for that.

EDIT 3: I have two module codes in the same book which password protect/unprotect all tabs. Could this be interfering?

Sub protect_all_sheets()
top:
pass = InputBox("password?")
repass = InputBox("Verify Password")
If Not (pass = repass) Then
MsgBox "you made a boo boo"
GoTo top
End If
 For i = 1 To Worksheets.Count
 If Worksheets(i).ProtectContents = True Then GoTo oops
 Next
 For Each s In ActiveWorkbook.Worksheets
 s.Protect Password:=pass
 Next
 Exit Sub
 oops: MsgBox "I think you have some sheets that are already protected. Please unprotect all sheets then running this Macro."
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    MyVal = Range("I1").Text

    With ActiveSheet.Tab
        Select Case MyVal
            Case "Print"
                .Color = RGB(255, 255, 102)
            Case Else
                .ColorIndex = xlColorIndexNone
        End Select
    End With
End Sub

Body:
Worksheet_Change isn't triggered by calculations: you need Worksheet_Calculate

Private Sub Worksheet_Calculate()
    Me.tab.color = IIf(Me.Range("I1").value="Print",vbRed,vbWhite)
End Sub


问:
Take tail of variadic template parameters
Given this type:

```<code>template<typename ...As>
struct Base {};
</code>```

I need to implement a function

```<code>template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}
</code>```

which returns an instance of B using the tail of type parameter list from index i.

For example,

```<code>Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert
</code>```

I know how to get the type at index i :

```<code>template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at<i - 1, Ts...>::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};
</code>```

but I can't get a working version for the entire problem.

答:
And now, for something completely different...

Just for fun I propose a C++14 solution that doesn't use recursion but the power of std::tuple_cat().

```<code>#include <tuple>
#include <type_traits>

template <typename...>
struct Base
 { };

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I <= J), bool> = true>
constexpr std::tuple<Base<A>> Tail_helper3 ();

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I > J), bool> = true>
constexpr std::tuple<> Tail_helper3 ();

template <typename ... As>
constexpr Base<As...> Tail_helper2 (std::tuple<Base<As>...> const &);

template <std::size_t I, typename ... As, std::size_t ... Is>
constexpr auto Tail_helper1 (std::index_sequence<Is...> const &)
   -> decltype( Tail_helper2(std::tuple_cat(Tail_helper3<I, Is, As>()...)) );

template <std::size_t I, typename ... As>
constexpr auto Tail ()
   -> decltype( Tail_helper1<I, As...>(std::index_sequence_for<As...>{}) )
 {
   static_assert(I < sizeof...(As), "index out of range");

   return {};
 }

int main ()
 {
   static_assert( std::is_same_v<Base<int, double, int>,
                                 decltype(Tail<0u, int, double, int>())> );

   static_assert( std::is_same_v<Base<double, int>,
                                 decltype(Tail<1u, int, double, int>())> );

   static_assert( std::is_same_v<Base<int>,
                                 decltype(Tail<2u, int, double, int>())> );

   // Tail<3u, int, double, int>(); compilation error!
 }
</code>```

Body:
Given this type:

template<typename ...As>
struct Base {};

I need to implement a function

template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}

which returns an instance of B using the tail of type parameter list from index i.

For example,

Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert

I know how to get the type at index i :

template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};

but I can't get a working version for the entire problem.

Body:
And now, for something completely different...

Just for fun I propose a C++14 solution that doesn't use recursion but the power of std::tuple_cat().

#include <tuple>
#include <type_traits>

template <typename...>
struct Base
 { };

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I <= J), bool> = true>
constexpr std::tuple<Base<A>> Tail_helper3 ();

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I > J), bool> = true>
constexpr std::tuple<> Tail_helper3 ();

template <typename ... As>
constexpr Base<As...> Tail_helper2 (std::tuple<Base<As>...> const &);

template <std::size_t I, typename ... As, std::size_t ... Is>
constexpr auto Tail_helper1 (std::index_sequence<Is...> const &)
   -> decltype( Tail_helper2(std::tuple_cat(Tail_helper3<I, Is, As>()...)) );

template <std::size_t I, typename ... As>
constexpr auto Tail ()
   -> decltype( Tail_helper1<I, As...>(std::index_sequence_for<As...>{}) )
 {
   static_assert(I < sizeof...(As), "index out of range");

   return {};
 }

int main ()
 {
   static_assert( std::is_same_v<Base<int, double, int>,
                                 decltype(Tail<0u, int, double, int>())> );

   static_assert( std::is_same_v<Base<double, int>,
                                 decltype(Tail<1u, int, double, int>())> );

   static_assert( std::is_same_v<Base<int>,
                                 decltype(Tail<2u, int, double, int>())> );

   // Tail<3u, int, double, int>(); compilation error!
 }


问:
How to use Angular interfaces from another module for validation and intellisense
I have a series of UI widget components in a one module in an Angular 5 application.  An separate application module uses those widgets and needs to provide a configuration object for each one.  While creating the configuration object in my editor (VS Code), I'd like the editor to validate the configuration object as well as provide intellisense.

Ideally, I'd like to define an interface for each widget in its component.ts file - it's easy to update both the component and the interface at the same time that way.  Alternatively, I could have a single file of interfaces.

I understand that interfaces aren't used at compile time.  I just want them to be available when I'm setting up a configuration object in my application module.  What is the best way to do this?

Option A: Namespaces

Based on this article I've been looking at namespaces.  I like the idea of adding to a single Config namespace from multiple files.  However, I've seen several opinions like this answer on SO that say namespaces are bad.

Because I believe that namespaces are a TS thing, not an Angular thing, I've tried this:

config.namespace.ts (Currently a single file - once that works I'll try to distribute it to multiple files.)

```<code>export namespace Config {
    export interface Breadcrumbs {
      responsive: boolean;
      links: BreadcrumbLink[];
    }
    interface BreadcrumbLink {
      label: string;
      link?: string;
    }
}
</code>```

app-config.service.ts

```<code>/// <reference path="/path/to/config.namespace.ts" />

@Injectable()
export class AppConfigService {
  config: any = {};
  constructor() { }

  configureWidgets() {
    const breadcrumbWidget: Config.Breadcrumbs = {
      'responsive': true,
      'links': [
        { 'label': 'Home', 'link': 'http://...' },
        { 'label': 'Main Section', 'link': 'http://...' },
        { 'label': 'Current Page' },
      ]
    };
    this.config.breadcrumbs = breadcrumbWidget;
</code>```

Unfortunately, it's not pulling the Config namespace to use in the editor.

Option B: .d.ts file

I'm new to this concept, but it looks like it's defining types that the package.json then pulls in and makes generally available.  This might work, but it means that I couldn't keep the interfaces in each widget's file, right where they're the most useful.  Also, most of the articles about .d.ts files assume that you're setting up typings for a package, which isn't the case here.

Option C: Import each interface directly

import { Breadcrumbs } from './path/to/config.namespace.ts'

This works, but it doesn't feel right.  This will lead to a long set of interface imports and specific paths if I keep each interface with it's widget.component.ts file.  Also, I believe that imports are mainly for pulling in other functionality that you're going to use in the application, not just for convenience in the IDE?

答:
I ended up going with a version of Option C, but using a barrel file to simplify the importing.  Each widget's component.ts file includes an interface to use when configuring it.  The barrel file then re-exports all of them:

```<code>export { Breadcrumbs } from './path/to/component';
export { Button } from './path/to/component';
export { DialogButton } from './path/to/component';
</code>```

Then, in the service that sets up the configuration for each widget, I import everything from the barrel file with:

```<code>import * as Config from '../../path/to/barrel/widget-interfaces.index';
</code>```

Finally, when I create an configuration object for a new widget, I declare the interface needed:

```<code>    const app_breadcrumbs: Config.Breadcrumbs = {
      responsive: true,
      links: [
        { label: 'Home', link: '//www.homeurl.com/index.html' },
        { label: 'Main Section', link: '//www.homeurl.com/main-section/main.html' },
        { label: 'Current Page' }
      ]
    };
</code>```

I'm using VS code, and it suggests keys as I start typing and validates that the types and object shapes are correct.

Body:
I have a series of UI widget components in a one module in an Angular 5 application.  An separate application module uses those widgets and needs to provide a configuration object for each one.  While creating the configuration object in my editor (VS Code), I'd like the editor to validate the configuration object as well as provide intellisense.

Ideally, I'd like to define an interface for each widget in its component.ts file - it's easy to update both the component and the interface at the same time that way.  Alternatively, I could have a single file of interfaces.

I understand that interfaces aren't used at compile time.  I just want them to be available when I'm setting up a configuration object in my application module.  What is the best way to do this?

Option A: Namespaces

Based on this article I've been looking at namespaces.  I like the idea of adding to a single Config namespace from multiple files.  However, I've seen several opinions like this answer on SO that say namespaces are bad.

Because I believe that namespaces are a TS thing, not an Angular thing, I've tried this:

config.namespace.ts (Currently a single file - once that works I'll try to distribute it to multiple files.)

export namespace Config {
    export interface Breadcrumbs {
      responsive: boolean;
      links: BreadcrumbLink[];
    }
    interface BreadcrumbLink {
      label: string;
      link?: string;
    }
}

app-config.service.ts

/// <reference path="/path/to/config.namespace.ts" />

@Injectable()
export class AppConfigService {
  config: any = {};
  constructor() { }

  configureWidgets() {
    const breadcrumbWidget: Config.Breadcrumbs = {
      'responsive': true,
      'links': [
        { 'label': 'Home', 'link': 'http://...' },
        { 'label': 'Main Section', 'link': 'http://...' },
        { 'label': 'Current Page' },
      ]
    };
    this.config.breadcrumbs = breadcrumbWidget;

Unfortunately, it's not pulling the Config namespace to use in the editor.

Option B: .d.ts file

I'm new to this concept, but it looks like it's defining types that the package.json then pulls in and makes generally available.  This might work, but it means that I couldn't keep the interfaces in each widget's file, right where they're the most useful.  Also, most of the articles about .d.ts files assume that you're setting up typings for a package, which isn't the case here.

Option C: Import each interface directly

import { Breadcrumbs } from './path/to/config.namespace.ts'

This works, but it doesn't feel right.  This will lead to a long set of interface imports and specific paths if I keep each interface with it's widget.component.ts file.  Also, I believe that imports are mainly for pulling in other functionality that you're going to use in the application, not just for convenience in the IDE?

Body:
I ended up going with a version of Option C, but using a barrel file to simplify the importing.  Each widget's component.ts file includes an interface to use when configuring it.  The barrel file then re-exports all of them:

export { Breadcrumbs } from './path/to/component';
export { Button } from './path/to/component';
export { DialogButton } from './path/to/component';

Then, in the service that sets up the configuration for each widget, I import everything from the barrel file with:

import * as Config from '../../path/to/barrel/widget-interfaces.index';

Finally, when I create an configuration object for a new widget, I declare the interface needed:

    const app_breadcrumbs: Config.Breadcrumbs = {
      responsive: true,
      links: [
        { label: 'Home', link: '//www.homeurl.com/index.html' },
        { label: 'Main Section', link: '//www.homeurl.com/main-section/main.html' },
        { label: 'Current Page' }
      ]
    };

I'm using VS code, and it suggests keys as I start typing and validates that the types and object shapes are correct.