问:
Manage Azure vnic in python
i need to attach a specific network security group into a set of vnic present in my azure resource group, how can i do?

usually i use this module:

```<code>import msrestazure
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.compute.models import DiskCreateOption

def get_credentials_sys(sid):
    subscription_id = sid
    credentials = ServicePrincipalCredentials(
        client_id = 'xxxxxxxxxxxxx',
        secret= 'yyyyyyyyyyyyy',
        tenant= 'wwwwwwwwwwww'
    )
    return credentials, subscription_id

def print_item(group):
    """Print a ResourceGroup instance."""
    print("\tName: {}".format(group.name))
    print("\tId: {}".format(group.id))
    print("\tLocation: {}".format(group.location))
    print("\tTags: {}".format(group.tags))
    print_properties(group.properties)

def print_properties(props):
    """Print a ResourceGroup properties instance."""
    if props and props.provisioning_state:
        print("\tProperties:")
        print("\t\tProvisioning State: {}".format(props.provisioning_state))
    print("\n\n")

def main():

    try:
        credentials, subscription_id = get_credentials_sys(SUBSCRIPTION_ID)
    except AuthorizationFailed:
        print("Credential not allowed")

    resource_client = ResourceManagementClient(credentials, subscription_id)
    compute_client = ComputeManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials, subscription_id)

    for item in resource_client.resources.list_by_resource_group(MY_RESOURCE_GROUP):
        if "networkInterfaces" in item.id :
            if "NIC_TO_FILTER" in item.name:
                pass
            else:
                print("I WANT ADD THE NETWORK SECURITY GROUP, HERE")
        else:
            pass

if __name__ == "__main__":
    main()
</code>```

My goal is, filter all vnic present in my resource group, filtering it by name, then i want add it one specific network security group.
Is possible?

答:
Of curse, it's possible. You can get all the NICs in the resource group and get the NSG that you want to associate to the NICs. Then you can filter the NIC with its name in the for loop, associate the NSG and then update it.

I assume you want to associate one NSG to the NICs filtered in the resource group. Then the example code here:

```<code>rg_name = "xxxx"
nsg_name = "xxxx"
nic_list = network_client.network_interfaces.list(rg_name)
nsg = network_client.network_security_groups.get(rg_name, nsg_name)

for nic in nic_list:
  if (nic.name == "xxxx"):             # filter the NICs in your condition
    nic.network_security_group = nsg
    network_client.network_interfaces.create_or_update(resource_group, nic.name, nic)
</code>```

Title: Manage Azure vnic in python

Body:
i need to attach a specific network security group into a set of vnic present in my azure resource group, how can i do?

usually i use this module:

import msrestazure
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.compute.models import DiskCreateOption

def get_credentials_sys(sid):
    subscription_id = sid
    credentials = ServicePrincipalCredentials(
        client_id = 'xxxxxxxxxxxxx',
        secret= 'yyyyyyyyyyyyy',
        tenant= 'wwwwwwwwwwww'
    )
    return credentials, subscription_id

def print_item(group):
    """Print a ResourceGroup instance."""
    print("\tName: {}".format(group.name))
    print("\tId: {}".format(group.id))
    print("\tLocation: {}".format(group.location))
    print("\tTags: {}".format(group.tags))
    print_properties(group.properties)

def print_properties(props):
    """Print a ResourceGroup properties instance."""
    if props and props.provisioning_state:
        print("\tProperties:")
        print("\t\tProvisioning State: {}".format(props.provisioning_state))
    print("\n\n")

def main():

    try:
        credentials, subscription_id = get_credentials_sys(SUBSCRIPTION_ID)
    except AuthorizationFailed:
        print("Credential not allowed")

    resource_client = ResourceManagementClient(credentials, subscription_id)
    compute_client = ComputeManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials, subscription_id)

    for item in resource_client.resources.list_by_resource_group(MY_RESOURCE_GROUP):
        if "networkInterfaces" in item.id :
            if "NIC_TO_FILTER" in item.name:
                pass
            else:
                print("I WANT ADD THE NETWORK SECURITY GROUP, HERE")
        else:
            pass

if __name__ == "__main__":
    main()

My goal is, filter all vnic present in my resource group, filtering it by name, then i want add it one specific network security group.
Is possible?

Body:
Of curse, it's possible. You can get all the NICs in the resource group and get the NSG that you want to associate to the NICs. Then you can filter the NIC with its name in the for loop, associate the NSG and then update it.

I assume you want to associate one NSG to the NICs filtered in the resource group. Then the example code here:

rg_name = "xxxx"
nsg_name = "xxxx"
nic_list = network_client.network_interfaces.list(rg_name)
nsg = network_client.network_security_groups.get(rg_name, nsg_name)

for nic in nic_list:
  if (nic.name == "xxxx"):             # filter the NICs in your condition
    nic.network_security_group = nsg
    network_client.network_interfaces.create_or_update(resource_group, nic.name, nic)


来源: stackexchange

问:
Calculate sum of differences between rows but only if the previous cell is bigger than the current one
I started to get a headache around my problem that I cannot figure out for the love of me.
There are unknown amounts of column if that makes any difference, but basically each row needs to be compared to the previous one and ONLY when the previous value is greater, the difference between them gets added to the sum.

So for example I have this table

```<code>  |  A  |
--|-----|
1 | 100 |
2 |  90 |
3 |  80 |
4 | 100 |
5 |  70 |
6 |  20 |
7 | 100 |
...
</code>```

Expected result: 100, derived from ((100-90) + (90-80) + (100-70) + (70-20))

I have spent a whole day browsing every single excel tutorial page and cannot find a single helpful answer. Please help :(

答:
Formula for Cell B2: (pull down through the rows).

```<code>=IF(A1>B1;A1-B1;0)+B1
</code>```

Logic: If previous value is larger than current value, add the difference to the total.

ContentLicense: CC BY-SA 4.0

Body:
I started to get a headache around my problem that I cannot figure out for the love of me.
There are unknown amounts of column if that makes any difference, but basically each row needs to be compared to the previous one and ONLY when the previous value is greater, the difference between them gets added to the sum.

So for example I have this table

  |  A  |
--|-----|
1 | 100 |
2 |  90 |
3 |  80 |
4 | 100 |
5 |  70 |
6 |  20 |
7 | 100 |
...

Expected result: 100, derived from ((100-90) + (90-80) + (100-70) + (70-20))

I have spent a whole day browsing every single excel tutorial page and cannot find a single helpful answer. Please help :(

Body:
Formula for Cell B2: (pull down through the rows).

=IF(A1>B1;A1-B1;0)+B1

Logic: If previous value is larger than current value, add the difference to the total.


答:
Try eliminating all non-printable characters:</p>

```<code>$empId = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', trim($empId));
</code>```

Title: Same key takes two array index - PHP

Body:
"0012" has the same key but takes two array index, can't find the issue. Is there any encoding issues?

File content-

0012 2020-01-27 18:45:00
0012 2020-01-28 09:15:00
0012 2020-02-05 18:15:00
0012 2020-02-13 19:15:00
0012 2020-02-15 09:30:00
0012 2020-02-15 15:30:00
0118 2020-02-09 10:20:00
0118 2020-02-09 20:15:00
0118 2020-02-10 10:25:00
0118 2020-02-10 20:15:00
0118 2020-02-12 19:40:00
0118 2020-02-13 20:15:00
0118 2020-02-16 00:20:00
0118 2020-02-16 08:10:00
0036 2020-02-11 18:10:00
0036 2020-02-12 22:15:00
0036 2020-02-16 19:30:00
0036 2020-02-17 09:00:00
0036 2020-02-17 20:30:00
0036 2020-02-18 09:00:00
0323 2020-01-16 09:25:00
0323 2020-01-16 22:30:00
0323 2020-01-17 18:20:00

Scripts-

$filename = 'file.txt';

$array = explode("\n", file_get_contents($filename));
$array = array_filter($array);
$empArr = array();
foreach($array as $line){
    list($empId, $date, $time) = explode(" ", $line);
    $empId = (string) trim($empId);

    $empArr[$empId][] = $date . ' ' .$time;
}

echo "
";
print_r($empArr);
echo "
";

Output-

Array
(
    [0012] => Array
        (
            [0] => 2020-01-27 18:45:00
        )

    [0012] => Array
        (
            [0] => 2020-01-28 09:15:00
            [1] => 2020-02-05 18:15:00
            [2] => 2020-02-13 19:15:00
            [3] => 2020-02-15 09:30:00
            [4] => 2020-02-15 15:30:00
        )

    [0118] => Array
        (
            [0] => 2020-02-09 10:20:00
            [1] => 2020-02-09 20:15:00
            [2] => 2020-02-10 10:25:00
            [3] => 2020-02-10 20:15:00
            [4] => 2020-02-12 19:40:00
            [5] => 2020-02-13 20:15:00
            [6] => 2020-02-16 00:20:00
            [7] => 2020-02-16 08:10:00
        )

    [0036] => Array
        (
            [0] => 2020-02-11 18:10:00
            [1] => 2020-02-12 22:15:00
            [2] => 2020-02-16 19:30:00
            [3] => 2020-02-17 09:00:00
            [4] => 2020-02-17 20:30:00
            [5] => 2020-02-18 09:00:00
        )

    [0323] => Array
        (
            [0] => 2020-01-16 09:25:00
            [1] => 2020-01-16 22:30:00
            [2] => 2020-01-17 18:20:00
        )

    [] => Array
        (
            [0] =>
        )

)

Body:
Try eliminating all non-printable characters:

$empId = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', trim($empId));


问:
See resulting tsconfig when using { "extends": ... }
I'm using WebStorm with my Angular project, so I have a lot of different tsconfig files (tsconfig.json, tsconfig.lib.json, tsconfig.lib.prod.json and tsconfig.spec.json).

Now most of the configuration is only in tsconfig.json, while all other extend this config. But there are also some cases, where a config is in multiple extended files and I'm wondering if they can be moved to the main file.

Is there a way to see the full tsconfig.lib.json, with the extended options?

AFAIK: Visual Studio had this option for its web.config files.

答:
You can use the --showConfig CLI argument to get the extended config file  as output.

Rather than actually execute a build with the other input options and config files, show the final implied config file in the output.

Example:

```<code>tsc -p path/to/tsconfig.lib.json --showConfig
</code>```

Body:
You can use the --showConfig CLI argument to get the extended config file  as output.

Rather than actually execute a build with the other input options and config files, show the final implied config file in the output.

Example:

tsc -p path/to/tsconfig.lib.json --showConfig


问:
Moment - Difference between two EPOCH dates
I have two dates in EPOCH value.

Open : 1579269496000

Close : 1579270005225

I want to get display different between two dates.
So difference = Close - Open = <ddd> Days <hh> Hours <mm> Mins <ss> Sec.

I'm using Moment.js to convert the date but I don't see to substract EPOCH date using that.

var c = new Date(close);
var o = new Date(open);

var seconds =enter code here (c.getTime() - o.getTime()) / 1000;

var ms = moment(close,"DD/MM/YYYY HH:mm:ss").diff(moment(open,"DD/MM/YYYY HH:mm:ss"));

```

答:
Hope this solves your concern.
First convert epoch value to the value supported by momentJS. Then you could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.

```<code>var moment = require("moment");

var a = "1582113418";
var b = "1582113444";

var aa = moment.unix(a); // converted value
var bb = moment.unix(b); // converted value

var days = bb.diff(aa, "days");
aa.add(days, "years");

var hours = bb.diff(aa, "hour");
aa.add(hours, "hours");

var seconds = bb.diff(aa, "seconds");

console.log(days + " days " + hours + " hours " + seconds + " seconds");

</code>```

Working sandbox: https://codesandbox.io/s/adoring-shamir-0yuxq

Body:
Hope this solves your concern.
First convert epoch value to the value supported by momentJS. Then you could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.

var moment = require("moment");

var a = "1582113418";
var b = "1582113444";

var aa = moment.unix(a); // converted value
var bb = moment.unix(b); // converted value

var days = bb.diff(aa, "days");
aa.add(days, "years");

var hours = bb.diff(aa, "hour");
aa.add(hours, "hours");

var seconds = bb.diff(aa, "seconds");

console.log(days + " days " + hours + " hours " + seconds + " seconds");

Working sandbox: https://codesandbox.io/s/adoring-shamir-0yuxq


问:
How to get specific information from a complex JSON format file C#
I am trying to attain a List of all "methodname"  "fullname" and property[] values from a complex JSON file, I have tried to implement a basic model to read the top layer but everything returns as null;

```<code>public class TestRun
{
    public string @id { get; set; }
    public string @name { get; set; }
    public string @fullname { get; set; }
    public string testcasecount { get; set; }
    public TestSuite[] TestSuite { get; set; }
}

public class TestSuite
{

}

public class ScriptModel
{
    public TestRun[] TestRun { get; set; }

}
</code>```

JSON looks like so; From the root level there are a large amount of nested "test-suites" and "test-fixtures"

```<code>            "test-suite": {
                "@type": "TestSuite",
                "@id": "0-1030",
                "@name": "Example__Exampledll",
                "@fullname": "Example",
                "@runstate": "Runnable",
                "@testcasecount": "24",
                "test-suite": {
                    "@type": "TestSuite",
                    "@id": "0-1031",
                    "@name": "Features",
                    "@fullname": "Payments_Regression.Features",
                    "@runstate": "Runnable",
                    "@testcasecount": "24",
                    "test-suite": [
                        {
                            "@type": "TestSuite",
                            "@id": "0-1033",
                            "@name": "PRE",
                            "@fullname": "Payments_Regression.Features",
                            "@runstate": "Runnable",
                            "@testcasecount": "16",
                            "test-suite": [
                                {
                                    "@type": "TestFixture",
                                    "@id": "0-1015",
                                    "@name": "Outwards",
                                    "@fullname": "Example_Outwards",
                                    "@classname": "Example_Dll_Example_Outwards",
                                    "@runstate": "Runnable",
                                    "@testcasecount": "8",
                                    "properties": {
                                        "property": [
                                            {
                                                "@name": "Description",
                                                "@value": "Smoke"
                                            },
                                            {
                                                "@name": "Category",
                                                "@value": "PREPRODUCTION"
                                            },
                                            {
                                                "@name": "Category",
                                                "@value": "Payment"
                                            }
                                        ]
                                    },
                                    "test-case": [
                                        {
                                            "@id": "0-1017",
                                            "@name": "TestCaseNameIWantToCapture",
                                            "@fullname": "fullnameexample",
                                            "@methodname": "MethodNameToCapture",
                                            "@classname": "ClassNametoCapture",
                                            "@runstate": "Runnable",
                                            "@seed": "1767458888",
                                            "properties": {
                                                "property": {
                                                    "@name": "Description",
                                                    "@value": "PropertyValueiWouldLikeToCapture."
                                                }
                                            }
                                        },
</code>```

答:
You use special symbol @ it don't change name of variable, this symbol sometimes use for use keywords like variable names var @object = "sample"

You need to use JsonProperty attribute

```<code>public class TestRun
{
    [JsonProperty("@id")]
    public string Id { get; set; }

    [JsonProperty("@name")]
    public string Name { get; set; }

    [JsonProperty("@fullname")]
    public string FullName { get; set; }

    [JsonProperty("@testcasecount")]
    public string TestCaseCount { get; set; }

    [JsonProperty("test-suite")]
    public TestSuite[] TestSuite { get; set; }
}
</code>```

Body:
I am trying to attain a List of all "methodname"  "fullname" and property[] values from a complex JSON file, I have tried to implement a basic model to read the top layer but everything returns as null;

public class TestRun
{
    public string @id { get; set; }
    public string @name { get; set; }
    public string @fullname { get; set; }
    public string testcasecount { get; set; }
    public TestSuite[] TestSuite { get; set; }
}

public class TestSuite
{

}

public class ScriptModel
{
    public TestRun[] TestRun { get; set; }

}

JSON looks like so; From the root level there are a large amount of nested "test-suites" and "test-fixtures"

            "test-suite": {
                "@type": "TestSuite",
                "@id": "0-1030",
                "@name": "Example__Exampledll",
                "@fullname": "Example",
                "@runstate": "Runnable",
                "@testcasecount": "24",
                "test-suite": {
                    "@type": "TestSuite",
                    "@id": "0-1031",
                    "@name": "Features",
                    "@fullname": "Payments_Regression.Features",
                    "@runstate": "Runnable",
                    "@testcasecount": "24",
                    "test-suite": [
                        {
                            "@type": "TestSuite",
                            "@id": "0-1033",
                            "@name": "PRE",
                            "@fullname": "Payments_Regression.Features",
                            "@runstate": "Runnable",
                            "@testcasecount": "16",
                            "test-suite": [
                                {
                                    "@type": "TestFixture",
                                    "@id": "0-1015",
                                    "@name": "Outwards",
                                    "@fullname": "Example_Outwards",
                                    "@classname": "Example_Dll_Example_Outwards",
                                    "@runstate": "Runnable",
                                    "@testcasecount": "8",
                                    "properties": {
                                        "property": [
                                            {
                                                "@name": "Description",
                                                "@value": "Smoke"
                                            },
                                            {
                                                "@name": "Category",
                                                "@value": "PREPRODUCTION"
                                            },
                                            {
                                                "@name": "Category",
                                                "@value": "Payment"
                                            }
                                        ]
                                    },
                                    "test-case": [
                                        {
                                            "@id": "0-1017",
                                            "@name": "TestCaseNameIWantToCapture",
                                            "@fullname": "fullnameexample",
                                            "@methodname": "MethodNameToCapture",
                                            "@classname": "ClassNametoCapture",
                                            "@runstate": "Runnable",
                                            "@seed": "1767458888",
                                            "properties": {
                                                "property": {
                                                    "@name": "Description",
                                                    "@value": "PropertyValueiWouldLikeToCapture."
                                                }
                                            }
                                        },

Body:
You use special symbol @ it don't change name of variable, this symbol sometimes use for use keywords like variable names var @object = "sample"

You need to use JsonProperty attribute

public class TestRun
{
    [JsonProperty("@id")]
    public string Id { get; set; }

    [JsonProperty("@name")]
    public string Name { get; set; }

    [JsonProperty("@fullname")]
    public string FullName { get; set; }

    [JsonProperty("@testcasecount")]
    public string TestCaseCount { get; set; }

    [JsonProperty("test-suite")]
    public TestSuite[] TestSuite { get; set; }
}


问:
cert-manager could not genere cloud-robotics certificate
I have issue with the cert manager which prevents me from synchronizing the robot with the cloud cluster.

It seems that it is due to a certificate error some way I can solve it.

the logs of cert manager:

```<code>1 controller.go:200] cert-manager/controller/orders "msg"="re-queuing item  due to error processing" "error"="error creating new order: acme: urn:ietf:params:acme:error:rateLimited: Error creating new order :: too many certificates already issued for exact set of domains: www.endpoints.guminator.cloud.goog: see https://letsencrypt.org/docs/rate-limits/" "key"="default/cloud-robotics-2181866887"
</code>```

答:
This is hitting the "Duplicate Certificate limit of 5 per week" mentioned at https://letsencrypt.org/docs/rate-limits/. https://tools.letsdebug.net/cert-search?m=domain&q=www.endpoints.guminator.cloud.goog&d=168 shows when the certificates were created.

For a short-term resolution: I'd hope it will start working again in the next days, since the first certificates were issued on the 12th.

For a long-term resolution: Have you done anything that would cause this, for example deleting and recreating the cluster multiple times? If you need to do this regularly, you have two options:

Back up the certificate

https://cert-manager.readthedocs.io/en/release-0.9/tasks/backup-restore-crds.html suggests the following approach for backing up and restoring the configuration:

```<code>kubectl get -o yaml \
   issuer,clusterissuer,certificates,orders,challenges > cert-manager-backup.yaml
kubectl get -o yaml secret letsencrypt-prod > cert-manager-secret-backup.yaml
</code>```

Then, to restore after recreating the cluster:

```<code>kubectl apply -f cert-manager-secret-backup.yaml
</code>```

Caveat: I have not tested this approach.

Use the Staging environment

https://letsencrypt.org/docs/staging-environment/ states that the staging environment allows 30,000 duplicate certs per week. You'd need to:

edit src/app_charts/base/cloud/cert-manager-issuers.yaml to refer to https://acme-staging-v02.api.letsencrypt.org/directory

configure the clients to trust the staging CA: https://letsencrypt.org/certs/fakeleintermediatex1.pem

Body:
I have issue with the cert manager which prevents me from synchronizing the robot with the cloud cluster.

It seems that it is due to a certificate error some way I can solve it.

the logs of cert manager:

1 controller.go:200] cert-manager/controller/orders "msg"="re-queuing item  due to error processing" "error"="error creating new order: acme: urn:ietf:params:acme:error:rateLimited: Error creating new order :: too many certificates already issued for exact set of domains: www.endpoints.guminator.cloud.goog: see https://letsencrypt.org/docs/rate-limits/" "key"="default/cloud-robotics-2181866887"

Body:
This is hitting the "Duplicate Certificate limit of 5 per week" mentioned at https://letsencrypt.org/docs/rate-limits/. https://tools.letsdebug.net/cert-search?m=domain&q=www.endpoints.guminator.cloud.goog&d=168 shows when the certificates were created.

For a short-term resolution: I'd hope it will start working again in the next days, since the first certificates were issued on the 12th.

For a long-term resolution: Have you done anything that would cause this, for example deleting and recreating the cluster multiple times? If you need to do this regularly, you have two options:

Back up the certificate

https://cert-manager.readthedocs.io/en/release-0.9/tasks/backup-restore-crds.html suggests the following approach for backing up and restoring the configuration:

kubectl get -o yaml \
   issuer,clusterissuer,certificates,orders,challenges > cert-manager-backup.yaml
kubectl get -o yaml secret letsencrypt-prod > cert-manager-secret-backup.yaml

Then, to restore after recreating the cluster:

kubectl apply -f cert-manager-secret-backup.yaml

Caveat: I have not tested this approach.

Use the Staging environment

https://letsencrypt.org/docs/staging-environment/ states that the staging environment allows 30,000 duplicate certs per week. You'd need to:

edit src/app_charts/base/cloud/cert-manager-issuers.yaml to refer to https://acme-staging-v02.api.letsencrypt.org/directory

configure the clients to trust the staging CA: https://letsencrypt.org/certs/fakeleintermediatex1.pem


问:
React Router V4 - Can't get URL params in props
I'm trying to create simple React-Redux-Router V4 app. The route to one of my components makes use of the url param. In my Route components, I've been passing in the render prop, which is an anonymous function that returns a component. Like so:

<Route key="post" path="/post/:id" render={() => <Post/>} />

I use this prop as opposed to the component prop:

<Route key="post" path="/post/:id" component={Post} />

Because I'm not able to props into the rendered component using the component prop. The issue is, with the component prop, you can make use of props.match.params.name, which will contain the exact param I need. This is not available when using the render component.

I can use window.location.href but it feels dirty.

Thanks!

答:
You need to import this first

```<code>import { withRouter } from 'react-router-dom';
</code>```

After that at the end export the component like this. 'User' is a class component name

```<code>export default (withRouter(User));
</code>```

Now, If you will print the value you will get a response.

```<code>constructor(props) {
        super(props);
        console.log('Props', this.props);
    }
</code>```

Happy Coding

ContentLicense: CC BY-SA 3.0

Body:
You need to import this first

import { withRouter } from 'react-router-dom';

After that at the end export the component like this. 'User' is a class component name

export default (withRouter(User));

Now, If you will print the value you will get a response.

constructor(props) {
        super(props);
        console.log('Props', this.props);
    }

Happy Coding


问:
curl from Write_http plugin of collectd is not working
I am trying to enable to Write_http plugin in collectd for Splunk, the problem is when I try to curl externally

```<code>curl http://10.xx.xxx.x:8088/services/collector/raw  -H "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792" -d {"test":"value"}
</code>```

It works. But when I do the same in
 collectd plugin

```<code><Plugin write_http>
<Node "node-http-1">
URL "http://10.xx.xxx.x:8088/services/collector/raw?channel=2c396ad4-f518-416f-83cd-e37596228792"
Header "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792"
Format "JSON"
Metrics true
StoreRates true
</code>```

I get

```<code>[error] write_http plugin: curl_easy_perform failed with status 56: Recv failure: Connection reset by peer
</code>```

is it because of the curl version of collectd?

答:
Just check the port in global settings in http data inputs in splunk.
It must be 8080 by default. Change the port in collect.conf accordingly in write_http plugin.

Hope it works for you!

Body:
I am trying to enable to Write_http plugin in collectd for Splunk, the problem is when I try to curl externally

curl http://10.xx.xxx.x:8088/services/collector/raw  -H "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792" -d {"test":"value"}

It works. But when I do the same in
 collectd plugin

<Plugin write_http>
<Node "node-http-1">
URL "http://10.xx.xxx.x:8088/services/collector/raw?channel=2c396ad4-f518-416f-83cd-e37596228792"
Header "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792"
Format "JSON"
Metrics true
StoreRates true

I get

[error] write_http plugin: curl_easy_perform failed with status 56: Recv failure: Connection reset by peer

is it because of the curl version of collectd?


问:
Find which element of list is a key in a dictionary and what is it's value
I have a dictionary:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
</code>```

and a list:

```<code>labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']
</code>```

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

```<code>class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])
</code>```

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

答:
Using a list comprehension:

>>> [classes_dictionary[k] for k in labels_list if k in classes_dictionary]
['Speech']
```

<p>If only one match is expected, you can use <code>next</code> with a generator expression to stop searching once it's found:</p>

<pre class="lang-py prettyprint-override"><code>>>> next(classes_dictionary[k] for k in labels_list if k in classes_dictionary)
'Speech'
</code>```

Body:
I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

Body:
Using a list comprehension:

>>> [classes_dictionary[k] for k in labels_list if k in classes_dictionary]
['Speech']

If only one match is expected, you can use next with a generator expression to stop searching once it's found:

>>> next(classes_dictionary[k] for k in labels_list if k in classes_dictionary)
'Speech'


问:
Compare the colnames within two lists of data.frames?
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

```<code>> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7
</code>```

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

```<code>$A
  b
1 3
$B
  e
1 1
$C
  f
1 6
</code>```

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

```<code>## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]
</code>```

答:
With purrr:

```<code>map2(.x = list1,
     .y = list2,
     ~ .x[setdiff(names(.x), names(.y))])

$A
  b
1 3

$B
  e
1 1

$C
  f
1 6
</code>```

Body:
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

$A
  b
1 3
$B
  e
1 1
$C
  f
1 6

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]

Body:
With purrr:

map2(.x = list1,
     .y = list2,
     ~ .x[setdiff(names(.x), names(.y))])

$A
  b
1 3

$B
  e
1 1

$C
  f
1 6


问:
Hero section with CSS slideshow, positioning for heading and normal flow?
I'm trying to create a Hero/Jumbotron with a slideshow using CSS animations. However, what I've got so far disrupts the normal flow.

Anything I add after the slideshow is located on top/under, and removing the position: absolute  of the .pic-wrapper section makes it so that the .pic-wrapper takes up the entire body.

What I need is for the hero section to have a title centered and then for the rest of the site to follow as normally. Any help?

HTML

```<code><section class="pic-wrapper">
    <h1>Slideshow Heading, should be on top of slideshow</h1>
    <figure class="pic-1" style="background-image: url(https://images.pexels.com/photos/258109/pexels-photo-258109.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-2" style="background-image: url(https://images.pexels.com/photos/206359/pexels-photo-206359.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-3" style="background-image: url(https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-4" style="background-image: url(https://images.pexels.com/photos/1166209/pexels-photo-1166209.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
</section>
<section>
<h2>New Section, this currently ends up under the slideshow</h2>
</section>
</code>```

CSS

```<code>.pic-wrapper {
        position: absolute;
        width: 100%;
        min-height: 50vh;
        /* overflow: hidden; */
        }

        figure {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;

        /*animation*/
        animation: slideShow 24s linear infinite 0s;
        -o-animation: slideShow 24s linear infinite 0s;
        -moz-animation: slideShow 24s linear infinite 0s;
        -webkit-animation: slideShow 24s linear infinite 0s;
        }

        .pic-1 {
        opacity: 1;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-2 {
        animation-delay: 6s;
        -o-animation-delay: 6s;
        -moz--animation-delay: 6s;
        -webkit-animation-delay: 6s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-3 {
        animation-delay: 12s;
        -o-animation-delay: 12s;
        -moz--animation-delay: 12s;
        -webkit-animation-delay: 12s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-4 {
        animation-delay: 18s;
        -o-animation-delay: 18s;
        -moz--animation-delay: 18s;
        -webkit-animation-delay: 18s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }
        /* keyframes*/

        @keyframes
        slideShow {  0% {
        opacity: 0;
        transform:scale(1);
        -ms-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        transform:scale(1.1);
        -ms-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        transform:scale(1);
        -ms-transformm:scale(1);
        }
        }
        @-o-keyframes
        slideShow {  0% {
        opacity: 0;
        -o-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -o-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -o-transformm:scale(1);
        }
        }
        @-moz-keyframes
        slideShow {  0% {
        opacity: 0;
        -moz-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -moz-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -moz-transformm:scale(1);
        }
        }
        @-webkit-keyframes
        slideShow {  0% {
        opacity: 0;
        -webkit-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -webkit-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -webkit-transformm:scale(1);
        }
        }
</code>```

Codepen link

答:
I think you should simply change the position setting of .pic-wrapper to relative, which puts it into the flow. I see no reason for the absolute setting.

Plus you should add a height setting, not just min-height. You could either use height instead  of min-height or use height: 50vh and a fixed px value for `min-height

Body:
I'm trying to create a Hero/Jumbotron with a slideshow using CSS animations. However, what I've got so far disrupts the normal flow.

Anything I add after the slideshow is located on top/under, and removing the position: absolute  of the .pic-wrapper section makes it so that the .pic-wrapper takes up the entire body.

What I need is for the hero section to have a title centered and then for the rest of the site to follow as normally. Any help?

HTML

Slideshow Heading, should be on top of slideshow

New Section, this currently ends up under the slideshow

CSS

.pic-wrapper {
        position: absolute;
        width: 100%;
        min-height: 50vh;
        /* overflow: hidden; */
        }

        figure {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;

        /*animation*/
        animation: slideShow 24s linear infinite 0s;
        -o-animation: slideShow 24s linear infinite 0s;
        -moz-animation: slideShow 24s linear infinite 0s;
        -webkit-animation: slideShow 24s linear infinite 0s;
        }

        .pic-1 {
        opacity: 1;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-2 {
        animation-delay: 6s;
        -o-animation-delay: 6s;
        -moz--animation-delay: 6s;
        -webkit-animation-delay: 6s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-3 {
        animation-delay: 12s;
        -o-animation-delay: 12s;
        -moz--animation-delay: 12s;
        -webkit-animation-delay: 12s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-4 {
        animation-delay: 18s;
        -o-animation-delay: 18s;
        -moz--animation-delay: 18s;
        -webkit-animation-delay: 18s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }
        /* keyframes*/

        @keyframes
        slideShow {  0% {
        opacity: 0;
        transform:scale(1);
        -ms-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        transform:scale(1.1);
        -ms-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        transform:scale(1);
        -ms-transformm:scale(1);
        }
        }
        @-o-keyframes
        slideShow {  0% {
        opacity: 0;
        -o-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -o-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -o-transformm:scale(1);
        }
        }
        @-moz-keyframes
        slideShow {  0% {
        opacity: 0;
        -moz-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -moz-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -moz-transformm:scale(1);
        }
        }
        @-webkit-keyframes
        slideShow {  0% {
        opacity: 0;
        -webkit-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -webkit-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -webkit-transformm:scale(1);
        }
        }

Codepen link


问:
how to split a string value that contains characters and numbers
I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

答:
Simple STL approach:</p>

```<code>#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::vector<std::string> parts;

    const char digits[] = "0123456789";

    std::string::size_type from=0, to=std::string::npos;

    do
    {
        from = s.find_first_of(digits, from);
        if (std::string::npos != from)
            from = s.find_first_not_of(digits, from);

        if (std::string::npos != from)
        {
            to = s.find_first_of(digits, from);
            if (std::string::npos == to)
                parts.push_back(s.substr(from));
            else
                parts.push_back(s.substr(from, to-from));

            from = to; // could be npos
        }

    } while (std::string::npos != from);

    for (int i=0; i<parts.size(); i++)
       std::cout << i << ":\t" << parts[i] << std::endl;

    return 0;
}
</code>```

Body:
Simple STL approach:

#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::vector<std::string> parts;

    const char digits[] = "0123456789";

    std::string::size_type from=0, to=std::string::npos;

    do
    {
        from = s.find_first_of(digits, from);
        if (std::string::npos != from)
            from = s.find_first_not_of(digits, from);

        if (std::string::npos != from)
        {
            to = s.find_first_of(digits, from);
            if (std::string::npos == to)
                parts.push_back(s.substr(from));
            else
                parts.push_back(s.substr(from, to-from));

            from = to; // could be npos
        }

    } while (std::string::npos != from);

    for (int i=0; i<parts.size(); i++)
       std::cout << i << ":\t" << parts[i] << std::endl;

    return 0;
}


问:
How to disable button in nav component
I have a nav component where you can navigate back en for. But on a certain condition I want to disable the navigation buttons. So I try it like this:

```<code>
<app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [disabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

</code>```

and this is the component:

```<code>export class EcheqProgressNavComponent implements OnInit {
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();

  constructor() {}

  ngOnInit() {}
}
</code>```

But I get an error like this:

```<code>
Can't bind to 'disabled' since it isn't a known property of 'app-echeq-progress-nav'.

</code>```

So what I have to fix?

Thank you

Oke, I try it like this:

```<code><div class="echeq-progress-nav">
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"

  >
    <span class="fa fa-caret-left"></span>
  </button>
  <div class="echeq-progress-pages">Vraag {{ currentPage }} / {{ totalPages }}</div>
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"
  >
    <span class="fa fa-caret-right"></span>
  </button>
</div>
</code>```

I have it like this:

```<code>  <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

but here :

```<code> <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

I dont have directly access with status

答:
You should add a Input decorator in child's component.ts (echeq-progress-nav)

```<code>@Input() isBtnDisabled = false; // by default not disabled.
</code>```

and bind this input to the relative button in the child-component's template:

```<code><div class="echeq-progress-nav">
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="isBtnDisabled">
    <span class="fa fa-caret-left"></span>
  </button>
  <div class="echeq-progress-pages">Vraag {{ currentPage }} / {{ totalPages }}</div>
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="isBtnDisabled">
    <span class="fa fa-caret-right"></span>
  </button>
</div>
</code>```

And in Parent Component, pass value to child-component.

```<code><app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [isBtnDisabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>
</code>```

Title: How to disable button in nav component

Body:
I have a nav component where you can navigate back en for. But on a certain condition I want to disable the navigation buttons. So I try it like this:

<app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [disabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

and this is the component:

export class EcheqProgressNavComponent implements OnInit {
  @Input() currentPage: number;
  @Input() totalPages: number;
  @Input() conditionals: { isFirst?: boolean; sending?: boolean };

  @Output() previous = new EventEmitter<void>();
  @Output() next = new EventEmitter<void>();

  constructor() {}

  ngOnInit() {}
}

But I get an error like this:

Can't bind to 'disabled' since it isn't a known property of 'app-echeq-progress-nav'.

So what I have to fix?

Thank you

Oke, I try it like this:

  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"

  >

  </button>

Vraag {{ currentPage }} / {{ totalPages }}

  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="status === EcheqSubmissionStatus.EXPIRED"
  >

  </button>

I have it like this:

  <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

but here :

 <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>

I dont have directly access with status

Body:
You should add a Input decorator in child's component.ts (echeq-progress-nav)

@Input() isBtnDisabled = false; // by default not disabled.

and bind this input to the relative button in the child-component's template:

<div class="echeq-progress-nav">
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-back"
    (click)="previous.emit()"
    [ngClass]="{ disabled: conditionals && (conditionals.isFirst || conditionals.sending) }"
    [disabled]="isBtnDisabled">
    <span class="fa fa-caret-left"></span>
  </button>
  <div class="echeq-progress-pages">Vraag {{ currentPage }} / {{ totalPages }}</div>
  <button
    type="button"
    class="echeq-progress-button echeq-progress-button-forward"
    (click)="next.emit()"
    [ngClass]="{ disabled: conditionals && conditionals.sending }"
    [disabled]="isBtnDisabled">
    <span class="fa fa-caret-right"></span>
  </button>
</div>

And in Parent Component, pass value to child-component.

<app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"
      [isBtnDisabled]="status === EcheqSubmissionStatus.EXPIRED"
      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"

    ></app-echeq-progress-nav>


问:
Reading a text file up to a certain character
Here's my dilemma. I have a file, and wish to read in all characters up until the program hits a '#', and ignore everything on that line after the '#'. For example

0 4001232 0        #comment, discard

This is frustrating, as it feels like there is  a very simple solution. Thanks!

答:
```<code>filePointer = fopen("person.txt", "r");

do
{
    read = fgetc(filePointer);
    //stop when '#' read or when file ends
    if (feof(filePointer) || read == '#')
    {
        break;
    }
    printf("%c", read);
} while (1);

fclose(filePointer);
</code>```

also you better check if file opened succesfully

```<code>if (filePointer == NULL)
{
    printf("person.txt file failed to open.");
}
else
{
    file operations
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
filePointer = fopen("person.txt", "r");

do
{
    read = fgetc(filePointer);
    //stop when '#' read or when file ends
    if (feof(filePointer) || read == '#')
    {
        break;
    }
    printf("%c", read);
} while (1);

fclose(filePointer);

also you better check if file opened succesfully

if (filePointer == NULL)
{
    printf("person.txt file failed to open.");
}
else
{
    file operations
}


问:
Include a JS variable inside "<%: %>"
I want to include the variable "count" inside the '<%:Givenome[count]%>' code.

HTML code

```<code><table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
</table>
<br>

<button type="button" onclick="myFunction()">Try it</button>
<script>
    function myFunction() {
        var count;
        for (count = 0; count < <%=Givenome.Count()%>; count++)
        {
            var table = document.getElementById("myTable");
            var row = table.insertRow(0);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = "<%:Givenome[count]%>";
            cell2.innerHTML = "NEW CELL2";
        }
    }
</script>
</code>```

This is my C# Code, where I create my string array.

```<code>public string[] Givenome { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    string[] answers = new string[10] { "Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y" };

    Givenome = answers;
}
</code>```

答:
you should convert your c# array into javascript readable formate using

```<code>var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.Givenome)%>;
</code>```

then you can iterate through javascript object

```<code>for (var x = 0; x < array.length; x++)
{
     var table = document.getElementById("myTable");
     var row = table.insertRow(0);
     var cell1 = row.insertCell(0);
     var cell2 = row.insertCell(1);
     cell1.innerHTML = array[x];
     cell2.innerHTML = "NEW CELL2";
}
</code>```

Title: Include a JS variable inside "<%: %>"

Body:
I want to include the variable "count" inside the '<%:Givenome[count]%>' code.

HTML code

    Row1 cell1
    Row1 cell2

<button type="button" onclick="myFunction()">Try it</button>

This is my C# Code, where I create my string array.

public string[] Givenome { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    string[] answers = new string[10] { "Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y" };

    Givenome = answers;
}

Body:
you should convert your c# array into javascript readable formate using

var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.Givenome)%>;

then you can iterate through javascript object

for (var x = 0; x < array.length; x++)
{
     var table = document.getElementById("myTable");
     var row = table.insertRow(0);
     var cell1 = row.insertCell(0);
     var cell2 = row.insertCell(1);
     cell1.innerHTML = array[x];
     cell2.innerHTML = "NEW CELL2";
}


问:
404 error for category permalinks in subfolder multisite
I have a multisite WordPress 3.1, using subdirectories to separate the individual sites.
For some reason category permalinks don't work, I get 404 errors for every category page. The same goes for tag pages.

I have tried resetting .htaccess file to the default one mentioned here: http://codex.wordpress.org/Create_A_Network#.htaccess_and_Mod_Rewrite

I have tried changing the theme to Wordpress default, same error.

I deactivated all plugins, same error.

I use permalinks /%year%/%monthnum%/%day%/%postname%/ and default category and tag base.
Note: If I change permalink to default, IT WORKS! But I don't want the http://site/?p=123 links.

答: same problem here. for some reason you have to reset the permalinks per blog again. what helped me is:, login as admin, chmod the .htaccess, goto permalinks, choose and save the permalink structure and chmod the .htaccess to the default. full article @ http://www.squidoo.com/wordpress-not-found-error-fix.  on wordpress i found this article: http://wordpress.org/support/topic/post-title-links-do-not-work-404-problem-page-not-found. hope it helps you.</p>


问:
How to find the first undefined array element in javascript, to fill it?
If entries are being added and removed in an array (not pushed/popped) what is the optimal way to scan and find the first undefined element, so that it can be set with a new value?</p>

答:
Today I've got the same question, so here's my take on it.

It all depends on your specific problem. My problem was this:

I have an array instances[], with objects in it;

Methods of some of these are registered as callbacks elsewhere;

Sometimes I do need to remove some instance from an array;

Sometimes I need to add new instance;

The problem is that I can't just splice an array, because it'll invalidate all my callback registrations. Well, I can just leave them in the array and forget, adding new elements at the end. But it's.... bad. It's leaking memory.

So I came with an idea of making "holes" in an array in place of removed elements, and then re-using these holes for new elements.

Thus the question "how to find undefined elements in an array?".

Someone here suggested using array.indexOf(undefined) - unfortunately that won't work... for some reason.

But, if it's okay in your case to use null or 0 instead, then it will work.

Here's an example:

```<code>var A = [1,1,1,1, , ,0,0,null,1,1];
A.indexOf(undefined);   // output: -1 (doesn't work)
A.indexOf(0);           // output: 6
A.indexOf(null);        // output: 8
</code>```

Hope this'll be useful.

Body:
Today I've got the same question, so here's my take on it.

It all depends on your specific problem. My problem was this:

I have an array instances[], with objects in it;

Methods of some of these are registered as callbacks elsewhere;

Sometimes I do need to remove some instance from an array;

Sometimes I need to add new instance;

The problem is that I can't just splice an array, because it'll invalidate all my callback registrations. Well, I can just leave them in the array and forget, adding new elements at the end. But it's.... bad. It's leaking memory.

So I came with an idea of making "holes" in an array in place of removed elements, and then re-using these holes for new elements.

Thus the question "how to find undefined elements in an array?".

Someone here suggested using array.indexOf(undefined) - unfortunately that won't work... for some reason.

But, if it's okay in your case to use null or 0 instead, then it will work.

Here's an example:

var A = [1,1,1,1, , ,0,0,null,1,1];
A.indexOf(undefined);   // output: -1 (doesn't work)
A.indexOf(0);           // output: 6
A.indexOf(null);        // output: 8

Hope this'll be useful.


问:
Adding an arrow function to input field results an error
Here is a React class I'm working on:

```<code>import React from 'react';

export default class ExpenseForm extends React.Component {
    state = {
        title: ''
    };

    onTitleChange = (e) => {
        const title = e.target.value;
        this.setState(() => ({title}));
    };

    render() {
        return (
            <div>
                <form>
                    <input
                        type='text'
                        placeholder='title'
                        value={this.state.title}
                        onChange={(e) => this.setState(() => ({title: e.target.value}))}
                        required autoFocus/>
                    <textarea placeholder='Add a note for your expense'/>
                    <input type='number' placeholder='amount' required/>
                    <input type='submit' value='Add Expense'/>
                </form>
            </div>
        );
    }
}
</code>```

This throws an error Uncaught TypeError: Cannot read property 'value' of null when executing onChange.

But when I restructure inner js of onChange into a separate function onTitleChange and calling that function: onChange={this.onTitleChange}, it works perfectly. What could be the reason behind this behavior?

答:
I would guess, that your parameter e is not known in the inner arrow function.
You could write it like this:</p>

```<code><input
  type='text'
  placeholder='title'
  value={this.state.title}
  onChange={e => this.setState({ title: e.target.value })}
  required
  autoFocus
/>
</code>```

Body:
Here is a React class I'm working on:

import React from 'react';

export default class ExpenseForm extends React.Component {
    state = {
        title: ''
    };

    onTitleChange = (e) => {
        const title = e.target.value;
        this.setState(() => ({title}));
    };

    render() {
        return (

                <form>
                    <input
                        type='text'
                        placeholder='title'
                        value={this.state.title}
                        onChange={(e) => this.setState(() => ({title: e.target.value}))}
                        required autoFocus/>
                    <textarea placeholder='Add a note for your expense'/>
                    <input type='number' placeholder='amount' required/>
                    <input type='submit' value='Add Expense'/>
                </form>

        );
    }
}

This throws an error Uncaught TypeError: Cannot read property 'value' of null when executing onChange.

But when I restructure inner js of onChange into a separate function onTitleChange and calling that function: onChange={this.onTitleChange}, it works perfectly. What could be the reason behind this behavior?

Body:
I would guess, that your parameter e is not known in the inner arrow function.
You could write it like this:

<input
  type='text'
  placeholder='title'
  value={this.state.title}
  onChange={e => this.setState({ title: e.target.value })}
  required
  autoFocus
/>


问:
javascript regex help
I have this complex question from my customer, I can't find a answer on it so now I will try to ask you guys.

The quest is the following:

I think that one rule might be: Dots
  which appears immediately after a
  number, not counted as sentences. This
  means that sentence present in the
  "8. marts"and "2.567" is not counted as
  word dots. In return, each word dots
  may be overlooked (if now a sentence
  ends with a number: "Vi kommer kl. 8")
  but it's probably after all not quite
  as often.

Another might be: If there is one
  character (a letter or number)
  immediately after a sentence is not a
  phrase sentence. That would make that
  we avoided counting the sentence
  present in the "f.eks.", "bl.a."
  and "cand.mag.".

I hope I can be helped here.

My code:

```<code><script>
function word_count(field, count) {

    var wordsNumberOverSeven = 0;
    var wordsNumber = 0

    var contentText = $(\'#lix_word_count\').val();
    contentText = contentText.replace(\'?\', \'.\');
    contentText = contentText.replace(\'!\', \'.\');
    contentText = contentText.replace(\',\', \'\');
    contentText = contentText.replace(\';\', \'\');
    contentText = contentText.replace(\':\', \'\');
    contentText = contentText.replace(\'\n\', \' \').replace(/^\s+|\s+$/g,\'\').replace(/\s\s+/g,\' \');

    var matchDots = contentText.split(\'.\').length-1;
    var match = contentText.split(\' \');

    $.each(match, function(){
        if ( this.length > 0 )
            wordsNumber += 1;

        if ( this.length >= 7 )
        {
            wordsNumberOverSeven += 1;
        }

    });

    var lixMatWords = wordsNumber / matchDots;
    var lixMatLongWords = ( wordsNumberOverSeven * 100 ) / wordsNumber;

    var lixMatch = Math.round(( lixMatWords + lixMatLongWords ) *100)/100;
    var lixType = \'\';

    if ( lixMatch <= 24 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget let at læse.\';
    else if ( lixMatch <= 34 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er let at læse\';
    else if ( lixMatch <= 44 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten ligger i midterområdet.\';
    else if ( lixMatch <= 54 )
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er svær at læse.\';
    else
        lixType = \'Lixen i din tekst er \'+ lixMatch +\', dvs. at teksten er meget svær at læse.\';

    /** alert(lixType +\'\nDots: \'+ matchDots +\'\nWords: \'+ wordsNumber +\'\nLangeord: \'+ wordsNumberOverSeven); **/
    alert(lixType);
}
</script>
</code>```

答:
If you want to split sentences based on that rule, then something like

```<code>mySentences.match(/(?:[^.0-9]|[0-9]+\.?|\.[a-z0-9])+(?:\.|$)/ig)
</code>```

should do it.

You'll have to expand a-z to include accented characters in your language, but that should do it.

It produces the following for your input text.

```<code>["I think that one rule might be: Dots which appears immediately after a number, not counted as sentences.",
 " This means that sentence present in the \"8. marts\"and \"2.567\" is not counted as word dots.",
 " In return, each word dots may be overlooked (if now a sentence ends with a number: \"Vi kommer kl.",
 " 8\") but it's probably after all not quite as often.",
 "\n\nAnother might be: If there is one character (a letter or number) immediately after a sentence is not a phrase sentence.",
 " That would make that we avoided counting the sentence present in the \"f.eks.",
 "\", \"bl.a.","\" and \"cand.mag.",
 "\"."]
</code>```

so obviously it has trouble with dots that appear inside quoted sections.  You could fix that up by walking and rejoining as long as a sentence ends inside a quoted section.

```<code>// Given mySentences defined above, walk counting quote characters.
// You could modify the regexp below if your language tends to use
// a different quoting style, e.g. French-style angle quotes.
for (var i = 0; i < mySentences.length - 1; ++i) {
  var quotes = mySentences[i].match(/["\u201c\u201d]/g);
  // If there are an odd number of quotes, combine the next sentence
  // into this one.
  if (quotes && quotes.length % 2) {
    // In English, it is common to end the quoted section after the
    // closing punctuator: Say "hello."
    var next =  mySentences[i + 1];
    if (/^["\u201c\u201d]/.test(next)) {
      mySentences[i] += next.substring(0, 1);
      mySentences[i + 1] = next.substring(1);
    } else {
      mySentences[i] += next;
      mySentences.splice(i, 1);
      --i;  // See if there's more to combine into this sentence.
    }
  }
}
</code>```

This kind of stuff is pretty brittle though.  If you want to know how it's done by people who specialize in this kind of thing, search for "natural language segmentation."

Title: javascript regex help

Body:
If you want to split sentences based on that rule, then something like

mySentences.match(/(?:[^.0-9]|[0-9]+\.?|\.[a-z0-9])+(?:\.|$)/ig)

should do it.

You'll have to expand a-z to include accented characters in your language, but that should do it.

It produces the following for your input text.

["I think that one rule might be: Dots which appears immediately after a number, not counted as sentences.",
 " This means that sentence present in the \"8. marts\"and \"2.567\" is not counted as word dots.",
 " In return, each word dots may be overlooked (if now a sentence ends with a number: \"Vi kommer kl.",
 " 8\") but it's probably after all not quite as often.",
 "\n\nAnother might be: If there is one character (a letter or number) immediately after a sentence is not a phrase sentence.",
 " That would make that we avoided counting the sentence present in the \"f.eks.",
 "\", \"bl.a.","\" and \"cand.mag.",
 "\"."]

so obviously it has trouble with dots that appear inside quoted sections.  You could fix that up by walking and rejoining as long as a sentence ends inside a quoted section.

// Given mySentences defined above, walk counting quote characters.
// You could modify the regexp below if your language tends to use
// a different quoting style, e.g. French-style angle quotes.
for (var i = 0; i < mySentences.length - 1; ++i) {
  var quotes = mySentences[i].match(/["\u201c\u201d]/g);
  // If there are an odd number of quotes, combine the next sentence
  // into this one.
  if (quotes && quotes.length % 2) {
    // In English, it is common to end the quoted section after the
    // closing punctuator: Say "hello."
    var next =  mySentences[i + 1];
    if (/^["\u201c\u201d]/.test(next)) {
      mySentences[i] += next.substring(0, 1);
      mySentences[i + 1] = next.substring(1);
    } else {
      mySentences[i] += next;
      mySentences.splice(i, 1);
      --i;  // See if there's more to combine into this sentence.
    }
  }
}

This kind of stuff is pretty brittle though.  If you want to know how it's done by people who specialize in this kind of thing, search for "natural language segmentation."


问:
Error in opening a CSV file with specifying row.name using R
I have a big df (CSV format) that looks like:

```<code>miRNAs <- c('mmu_mir-1-3p','mmu_mir-1-5p','mmu-mir-6-5p','mmu-mir-6-3p')
cca <- c('12854','5489','54485','2563')
ccb <- c('124','589','5465','25893')
taa <- c('12854','589','5645','763')
df <- data.frame(miRNAs,cca,ccb,taa)
</code>```

and I want to use this df in DESeq2 analyses. I made this df unique by using unique(df) and tried to open using countData <- as.matrix(read.csv(file="df.csv", row.name="miRNAs", sep = ",")) but it gives this error

Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
    duplicate 'row.names' are not allowed

Since I made the df unique I don't know why this error keeps popping up. Basically why I want to read my df in that way is that I want to get the list of my column headers (except the first column) when I type colnames(df). Because I need to do FALSE TRUE test to see if match these are matching with row names of another file called phenotype.csv all(rownames(phenotype) == colnames(countData))

答:
In the row.name="miRNAs" argument you are not accessing the respective column, but are using a length one character vector. That then gets recycled and that's why you get the error. Import without the row.names argument and if you really want that variable as row names instead of a column, then do that after the import:

df <- data.frame(
  miRNAs = c('mmu_mir-1-3p','mmu_mir-1-5p','mmu-mir-6-5p','mmu-mir-6-3p'),
  cca = c('12854','5489','54485','2563'),
  ccb = c('124','589','5465','25893'),
  taa = c('12854','589','5645','763')
  )

rownames(df) <- df$miRNAs
df$miRNAs <- NULL
df
#>                cca   ccb   taa
#> mmu_mir-1-3p 12854   124 12854
#> mmu_mir-1-5p  5489   589   589
#> mmu-mir-6-5p 54485  5465  5645
#> mmu-mir-6-3p  2563 25893   763
```

Created on 2020-02-19 by the reprex package (v0.3.0)

Body:
I have a big df (CSV format) that looks like:

miRNAs <- c('mmu_mir-1-3p','mmu_mir-1-5p','mmu-mir-6-5p','mmu-mir-6-3p')
cca <- c('12854','5489','54485','2563')
ccb <- c('124','589','5465','25893')
taa <- c('12854','589','5645','763')
df <- data.frame(miRNAs,cca,ccb,taa)

and I want to use this df in DESeq2 analyses. I made this df unique by using unique(df) and tried to open using countData <- as.matrix(read.csv(file="df.csv", row.name="miRNAs", sep = ",")) but it gives this error

Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
    duplicate 'row.names' are not allowed

Since I made the df unique I don't know why this error keeps popping up. Basically why I want to read my df in that way is that I want to get the list of my column headers (except the first column) when I type colnames(df). Because I need to do FALSE TRUE test to see if match these are matching with row names of another file called phenotype.csv all(rownames(phenotype) == colnames(countData))

Body:
In the row.name="miRNAs" argument you are not accessing the respective column, but are using a length one character vector. That then gets recycled and that's why you get the error. Import without the row.names argument and if you really want that variable as row names instead of a column, then do that after the import:

df <- data.frame(
  miRNAs = c('mmu_mir-1-3p','mmu_mir-1-5p','mmu-mir-6-5p','mmu-mir-6-3p'),
  cca = c('12854','5489','54485','2563'),
  ccb = c('124','589','5465','25893'),
  taa = c('12854','589','5645','763')
  )

rownames(df) <- df$miRNAs
df$miRNAs <- NULL
df
#>                cca   ccb   taa
#> mmu_mir-1-3p 12854   124 12854
#> mmu_mir-1-5p  5489   589   589
#> mmu-mir-6-5p 54485  5465  5645
#> mmu-mir-6-3p  2563 25893   763

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
Is there a way to see all Google Sheets that link/depend on another one?
I know what I'm doing is not good, and we're working on changing it for the better, but in the meantime I need to make do with what I have...

I have a rather large Google Sheet that more or less is acting as a DB. It's fed data from GForms and then that data is used on a number of other sheets for various purposes (e.g. reporting, selective info sharing to certain groups, etc.) mostly through querys and importranges.

The editing of the main sheet is restricted to only a handful of people, including myself. One of the others has made some changes (deleting some columns) that are going to break any queries or imports because the importrange won't catch the column changes and auto-update the range.

The changes made are actually good and worth keeping, so I don't want to revert them.

Is there a way for me to easily find out all of the sheets that use the main one so that I can update the affected formulas? In updating, I'll also need to find a way to avoid this happening again (I think I can do this by setting the range references using address? But that's future me's problem...)

Thanks in advance!

答:
To find dependencies between sheets in different documents (or even the same document) use the following script to search for references to a given doc id (eg within IMPORTRANGE) eg:</p>

```<code>FindFormulae("1XgTuET_dJKP-i4JppvQQFI047-ZKP-i4o4bhE-K1lF-o")

</code>```

```<code>
function FindFormulae(keyword) {
// searches all google docs for formulae containing the given keyword
// outputs to sheet "output"
// may take a while if you have a lot of docs, and could timeout (5 minutes)
// if timeout just run the script again, it skips any docs already checked
// to cancel script execution go to https://script.google.com/home/executions
// Feb 2020 www.enex.net

var sheetOut= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("output");

docsAlreadyChecked = sheetOut.getRange(1,1,sheetOut.getLastRow(),1).getValues();

var files = DriveApp.getFiles();
while (files.hasNext()) {  // loop thru files
  var file = files.next();
  if (file.getMimeType() != "application/vnd.google-apps.spreadsheet") continue;  // only process spreadsheets
  docURL =file.getUrl();
  docName =file.getName();
  //Logger.log('Starting.. ' + docName + '\n' + docURL + '\n');

  //DaysSinceUpdate = (new Date() - file.getLastUpdated())/(1000 * 60 * 60 * 24)
  //if ( DaysSinceUpdate > 90 ) continue;  // skip if file hasn't been updated for more than 7 days

  if (docsAlreadyChecked.toString().indexOf(docName)>0) continue;  // skip if already done    // note this needs fixing as will fail if one doc is substring of another

  var ssIn = SpreadsheetApp.openByUrl(docURL); // open doc

  for (var i = 0; i < ssIn.getNumSheets(); i++) {  //loop thru sheets in doc
    sheetname = ssIn.getSheets()[i].getName();
    //sheetid = ssIn.getSheets()[i].getSheetId();
    if (ssIn.getSheets()[i].getMaxRows()==0) continue; //skip if no rows (eg if it's a chart)
    ListFormulae(docURL, sheetname, keyword);
  } // end for loop thru sheets

  //strHyperlink = "=hyperlink(\"" + docURL + "#gid=" + ssIn.getSheets()[i].getSheetId() + "\", \"" + docName + "\")";
  strHyperlink = "=hyperlink(\"" + docURL  + "\", \"" + docName + "\")";
  sheetOut.appendRow([strHyperlink, '', '', 'finished search ' + new Date() ]);

} // end while loop thru files

}

function ListFormulae(docURL, sheetname, keyword) {

var ssIn = SpreadsheetApp.openByUrl(docURL);
var sheetIn = ssIn.getSheetByName(sheetname);
//var sheetIn = ssIn.getSheetId(sheetid);
//var sheetname = ssIn.getSheetName();
var sheetOut= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("output");
LastRow = sheetIn.getLastRow();
LastColumn = sheetIn.getLastColumn();
if (LastRow==0 && LastColumn==0)  return;  // nothing in sheet

var range = sheetIn.getRange(1, 1,LastRow , LastColumn);
var formulas = range.getFormulas();
for (var i in formulas) {
  for (var j in formulas[i]) {
    if (formulas[i][j]=="") continue;  // skip if no formula
    if (formulas[i][j].search(keyword) == -1) continue;  //skip if keyword not found
    strHyperlink = "=hyperlink(\"" + docURL + "#gid=" + sheetIn.getSheetId() + "\", \"" + ssIn.getName() + "\")";

    rownum = parseInt(i)+1;
    colnum = parseInt(j)+1;

    sheetOut.appendRow([strHyperlink, sheetname, 'R' + rownum + 'C' + colnum, "'" + formulas[i][j]]);
  }
}
}
</code>```

Body:
To find dependencies between sheets in different documents (or even the same document) use the following script to search for references to a given doc id (eg within IMPORTRANGE) eg:

FindFormulae("1XgTuET_dJKP-i4JppvQQFI047-ZKP-i4o4bhE-K1lF-o")

function FindFormulae(keyword) {
// searches all google docs for formulae containing the given keyword
// outputs to sheet "output"
// may take a while if you have a lot of docs, and could timeout (5 minutes)
// if timeout just run the script again, it skips any docs already checked
// to cancel script execution go to https://script.google.com/home/executions
// Feb 2020 www.enex.net

var sheetOut= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("output");

docsAlreadyChecked = sheetOut.getRange(1,1,sheetOut.getLastRow(),1).getValues();

var files = DriveApp.getFiles();
while (files.hasNext()) {  // loop thru files
  var file = files.next();
  if (file.getMimeType() != "application/vnd.google-apps.spreadsheet") continue;  // only process spreadsheets
  docURL =file.getUrl();
  docName =file.getName();
  //Logger.log('Starting.. ' + docName + '\n' + docURL + '\n');

  //DaysSinceUpdate = (new Date() - file.getLastUpdated())/(1000 * 60 * 60 * 24)
  //if ( DaysSinceUpdate > 90 ) continue;  // skip if file hasn't been updated for more than 7 days

  if (docsAlreadyChecked.toString().indexOf(docName)>0) continue;  // skip if already done    // note this needs fixing as will fail if one doc is substring of another

  var ssIn = SpreadsheetApp.openByUrl(docURL); // open doc

  for (var i = 0; i < ssIn.getNumSheets(); i++) {  //loop thru sheets in doc
    sheetname = ssIn.getSheets()[i].getName();
    //sheetid = ssIn.getSheets()[i].getSheetId();
    if (ssIn.getSheets()[i].getMaxRows()==0) continue; //skip if no rows (eg if it's a chart)
    ListFormulae(docURL, sheetname, keyword);
  } // end for loop thru sheets

  //strHyperlink = "=hyperlink(\"" + docURL + "#gid=" + ssIn.getSheets()[i].getSheetId() + "\", \"" + docName + "\")";
  strHyperlink = "=hyperlink(\"" + docURL  + "\", \"" + docName + "\")";
  sheetOut.appendRow([strHyperlink, '', '', 'finished search ' + new Date() ]);

} // end while loop thru files

}

function ListFormulae(docURL, sheetname, keyword) {

var ssIn = SpreadsheetApp.openByUrl(docURL);
var sheetIn = ssIn.getSheetByName(sheetname);
//var sheetIn = ssIn.getSheetId(sheetid);
//var sheetname = ssIn.getSheetName();
var sheetOut= SpreadsheetApp.getActiveSpreadsheet().getSheetByName("output");
LastRow = sheetIn.getLastRow();
LastColumn = sheetIn.getLastColumn();
if (LastRow==0 && LastColumn==0)  return;  // nothing in sheet

var range = sheetIn.getRange(1, 1,LastRow , LastColumn);
var formulas = range.getFormulas();
for (var i in formulas) {
  for (var j in formulas[i]) {
    if (formulas[i][j]=="") continue;  // skip if no formula
    if (formulas[i][j].search(keyword) == -1) continue;  //skip if keyword not found
    strHyperlink = "=hyperlink(\"" + docURL + "#gid=" + sheetIn.getSheetId() + "\", \"" + ssIn.getName() + "\")";

    rownum = parseInt(i)+1;
    colnum = parseInt(j)+1;

    sheetOut.appendRow([strHyperlink, sheetname, 'R' + rownum + 'C' + colnum, "'" + formulas[i][j]]);
  }
}
}


问:
How to make autofill into add/remove field dynamically using jquery?
I am doing a program using laravel. I use add/remove field with jquery. The first field grab the data from database to list out the person's name.

```<code>     <div class="container table-responsive col-lg-10">
          <form method="post" id="dynamic_form">
            <span id="result"></span>
             <table class="table table-hover table-responsive table-bordered" id="user_table">
           <thead>
            <tr>
                <td class="text-center col-lg-3">Nama</th>
                <td class="text-center col-lg-2">No Personal</th>
                <td class="text-center col-lg-1">Jabatan</th>
                <td class="text-center col-lg-1">Telefon</th>
                <td class="text-center col-lg-1">Ext</th>
                <td class="text-center col-lg-1">Action</th>
            </tr>
           </thead>
           <tbody>

           </tbody>
           <tfoot>
            <tr>
              <td colspan="2" align="right"> </td>
              <td></td>
            </tr>
           </tfoot>
       </table>
    </div>
    <script>
      $(document).ready(function(){

      var count = 1;

      dynamic_field(count);

      function dynamic_field(number)
      {
      html = '<tr>';
     html += '<td><select id="nama" name="nama[]" class="form-control"><option value="">--Pilih--</option><?php foreach($staff as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
    html += '<td><input type="text" name="no_personal[]" class="form-control" /></td>';
    html += '<td><input type="text" name="jabatan[]" class="form-control" /></td>';
    html += '<td><input type="text" name="telefon[]" class="form-control" /></td>';
    html += '<td><input type="text" name="ext[]" class="form-control" /></td>';
    if(number > 1)
    {
        html += '<td class="text-center"><button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button></td></tr>';
        $('tbody').append(html);
    }
    else
    {
        html += '<td class="text-center"><button type="button" name="add" id="add" class="btn btn-success">Tambah Pegawai</button></td></tr>';
        $('tbody').html(html);
    }
}

   $(document).on('change', '.nama', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_staff/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#no_personal').val(data.Nobadan);
                $('#jabatan').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#no_personal').empty();
      $('#jabatan').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
  });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

});
</script>
</code>```

I had edited the js code:

```<code>    function dynamic_field(number)
 {
  html = '<tr>';
     html += '<td><select id="nama_'+ count +'" name="nama[]" class="form-control"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
    html += '<td><input id="nb_'+ count +'" type="text" name="no_badan[]" class="form-control"  value="nb_'+ count +'" /></td>';
    html += '<td><input id="sek_'+ count +'" type="text" name="seksyen[]" class="form-control" /></td>';
    html += '<td><input id="tel_'+ count +'" type="text" name="telefon[]" class="form-control" /></td>';
    html += '<td><input id="ext_'+ count +'" type="text" name="ext[]" class="form-control" /></td>';
    if(number > 1)
    {
        html += '<td class="text-center"><button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button></td></tr>';
        $('tbody').append(html);
    }
    else
    {
        html += '<td class="text-center"><button type="button" name="add" id="add" class="btn btn-success">Tambah</button></td></tr>';
        $('tbody').html(html);
    }
 }

 $(document).on('change', '.nama_'+ count +'', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_sta/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#nb_'+ count +'').val(data.Nobadan);
                $('#seksyen').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#nb_'+ count +'').empty();
      $('#seksyen').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

  $(document).on('click', '#add', function(){
   count++;
   dynamic_field(count);
 });

  $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
  });

  });
 </script>
</code>```

When the first field（staff name）selected，the information  about no_personal, jabatan, telefon and ext will be filled automatically into the field. The information grabbed using this ajax url:

```<code> url : 'add_demo/get_staff/'+staffID,
</code>```

The controller for that is:

```<code>$data = staffs::where('staffID', $staffID)
            ->select('staffs.No_pers', 'staffs.JabID', 'staffs.notel', 'staffs.ext')
            ->first();

return json_encode($data);
</code>```

I can list out the staff name in the selection box. But when I selected the staff name, the information is not filled into the fields.

The field had been given an id like this:

```<code> html += '<td><input id="nb_'+ count++ +'" type="text" name="no_badan[]" class="form-control" /></td>';
</code>```

How to improvised the code? I tried to put id in the added fields, but it gives error of same id name for added fields.

答:
Suggestion:

Please check the id, its not unique.

Use the proper count to increment the ID

Body:
I am doing a program using laravel. I use add/remove field with jquery. The first field grab the data from database to list out the person's name.

          <form method="post" id="dynamic_form">

                Nama
                No Personal
                Jabatan
                Telefon
                Ext
                Action

I had edited the js code:

    function dynamic_field(number)
 {
  html = '
';
     html += '<select id="nama_'+ count +'" name="nama[]" class="form-control"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select>	';
    html += '<input id="nb_'+ count +'" type="text" name="no_badan[]" class="form-control"  value="nb_'+ count +'" />	';
    html += '<input id="sek_'+ count +'" type="text" name="seksyen[]" class="form-control" />	';
    html += '<input id="tel_'+ count +'" type="text" name="telefon[]" class="form-control" />	';
    html += '<input id="ext_'+ count +'" type="text" name="ext[]" class="form-control" />	';
    if(number > 1)
    {
        html += '<button type="button" name="remove" id="" class="btn btn-danger remove">Batal</button>
';
        $('tbody').append(html);
    }
    else
    {
        html += '<button type="button" name="add" id="add" class="btn btn-success">Tambah</button>
';
        $('tbody').html(html);
    }
 }

 $(document).on('change', '.nama_'+ count +'', function(){
    var staffID = jQuery(this).val();
    if(staffID)
    {
      jQuery.ajax({
          url : 'add_demo/get_sta/'+staffID,
          type : "GET",
          dataType : "json",
          success:function(data)
          {
            console.log(data);
                $('#nb_'+ count +'').val(data.Nobadan);
                $('#seksyen').val(data.SectionID);
                $('#telefon').val(data.notelttp);
                $('#ext').val(data.ext);
          }
      });
    }
    else
    {
      $('#nb_'+ count +'').empty();
      $('#seksyen').empty();
      $('#telefon').empty();
      $('#ext').empty();
    }
  });

  $(document).on('click', '#add', function(){
   count++;
   dynamic_field(count);
 });

  $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
  });

  });
 </script>

When the first field（staff name）selected，the information  about no_personal, jabatan, telefon and ext will be filled automatically into the field. The information grabbed using this ajax url:

 url : 'add_demo/get_staff/'+staffID,

The controller for that is:

$data = staffs::where('staffID', $staffID)
            ->select('staffs.No_pers', 'staffs.JabID', 'staffs.notel', 'staffs.ext')
            ->first();

return json_encode($data);

I can list out the staff name in the selection box. But when I selected the staff name, the information is not filled into the fields.

The field had been given an id like this:

 html += '<input id="nb_'+ count++ +'" type="text" name="no_badan[]" class="form-control" />	';

How to improvised the code? I tried to put id in the added fields, but it gives error of same id name for added fields.