问:
Restore a PostgreSQL-9.6 database from an old complete dump and/or a up-to-date just base directory and other rescued files
I'm trying to restore/rescue a database from some that I have:

I have all the recent files in PGDATA/base (/var/lib/postgresql/9.6/main/base/), but I have not the complete /var/lib/postgresql/9.6/main/

I have all files from an old backup (and not much different) dump that I restored in a new installation of PostgreSQL-9.6.

I have a lot of rescued files from the hard drive (from ddrescue) and I got thousand of files without a name (having a "#" and then a number instead and in lost+found directory), so, for instance:

I have the pg_class file

I have the pg_clog directory with 0000 file

Edit:

Probably I have the content of pg_xlog, but I don't have the name of the files. I have 5 files sized 16777216 bytes:

```<code>#288294 (date 2019-04-01)
#288287 (date 2019-05-14)
#288293 (date 2019-07-02)
#261307 (date 2019-11-27)
#270185 (date 2020-01-28)
</code>```

Also my old dump is from 2019-04-23, so the first one could
be the same?

So my next step is going to try to read those files with pg_xlogdump
and/or trying to name them with those namefiles (beginning with
00000001000000000000000A by date and put them to the new one pg_xlog directory, that I saw that the system filenaming them, could be?). Also I realized that the last one has the date of the day hard drive crashed, so I have the last one.

The PGDATA/base directory  I rescued from the hard drive (damaged) contains directories 1, 12406, 12407 and 37972 with a lot of files inside. I check with pg_filedump -fi that my updated data is stored on files in directory 37972.

Same (but old) data is stored in files in directory PGDATA/base/16387 in the restored dump.

I tried directly to copy the files from one to other mixing the updated data over the old database but it doesn't work. After solved permission errors I can go in to the "Frankenstein" database in that way:

```<code> postgres@host:~$ postgres --single -P -D /var/lib/postgresql/9.6/main/ dbname
</code>```

And I tried to do something, like reindex, and I get this error:

```<code>PostgreSQL stand-alone backend 9.6.16
backend> reindex system dbname;
ERROR:  could not access status of transaction 136889
DETAIL:  Could not read from file "pg_subtrans/0002" at offset 16384: Success.
CONTEXT:  while checking uniqueness of tuple (1,7) in relation "pg_toast_2619"
STATEMENT:  reindex system dbname;
</code>```

Certainly pg_subtrans/0002 file is part of the "Frankenstein" and not the good one (because I didn't find it yet, not with that name), so I tried: to copied another one that seems similar first and then, to generate 8192 zeroes with dd to that file, in both cases I get the same error (and in case that the file doesn't exist get the DETAIL:  Could not open file "pg_subtrans/0002": No such file or directory.). Anyway I have not idea that what should be that file. Do you think could I get that data from other file? Or could I find the missing file using some tool? So pg_filedump show me empty for the other file in that directory pg_subtrans/0000.

Extra note: I found this useful blog post that talk about restore from just rescued files using pg_filedump, pg_class's file, reindex system and other tools and but is so hard for me to understand how to adapt it to my concrete and easier problem (I think that my problem is easier because I have a dump): https://www.commandprompt.com/blog/recovering_a_lost-and-found_database/

答:
That is doomed. Without the information in pg_xlog and (particularly) pg_clog, you cannot get the information back.

A knowledgeable forensics expert might be able to salvage some of your data, but it is not a straightforward process.

Body:
I'm trying to restore/rescue a database from some that I have:

I have all the recent files in PGDATA/base (/var/lib/postgresql/9.6/main/base/), but I have not the complete /var/lib/postgresql/9.6/main/

I have all files from an old backup (and not much different) dump that I restored in a new installation of PostgreSQL-9.6.

I have a lot of rescued files from the hard drive (from ddrescue) and I got thousand of files without a name (having a "#" and then a number instead and in lost+found directory), so, for instance:

I have the pg_class file

I have the pg_clog directory with 0000 file

Edit:

Probably I have the content of pg_xlog, but I don't have the name of the files. I have 5 files sized 16777216 bytes:

#288294 (date 2019-04-01)
#288287 (date 2019-05-14)
#288293 (date 2019-07-02)
#261307 (date 2019-11-27)
#270185 (date 2020-01-28)

Also my old dump is from 2019-04-23, so the first one could
be the same?

So my next step is going to try to read those files with pg_xlogdump
and/or trying to name them with those namefiles (beginning with
00000001000000000000000A by date and put them to the new one pg_xlog directory, that I saw that the system filenaming them, could be?). Also I realized that the last one has the date of the day hard drive crashed, so I have the last one.

The PGDATA/base directory  I rescued from the hard drive (damaged) contains directories 1, 12406, 12407 and 37972 with a lot of files inside. I check with pg_filedump -fi that my updated data is stored on files in directory 37972.

Same (but old) data is stored in files in directory PGDATA/base/16387 in the restored dump.

I tried directly to copy the files from one to other mixing the updated data over the old database but it doesn't work. After solved permission errors I can go in to the "Frankenstein" database in that way:

 postgres@host:~$ postgres --single -P -D /var/lib/postgresql/9.6/main/ dbname

And I tried to do something, like reindex, and I get this error:

PostgreSQL stand-alone backend 9.6.16
backend> reindex system dbname;
ERROR:  could not access status of transaction 136889
DETAIL:  Could not read from file "pg_subtrans/0002" at offset 16384: Success.
CONTEXT:  while checking uniqueness of tuple (1,7) in relation "pg_toast_2619"
STATEMENT:  reindex system dbname;

Certainly pg_subtrans/0002 file is part of the "Frankenstein" and not the good one (because I didn't find it yet, not with that name), so I tried: to copied another one that seems similar first and then, to generate 8192 zeroes with dd to that file, in both cases I get the same error (and in case that the file doesn't exist get the DETAIL:  Could not open file "pg_subtrans/0002": No such file or directory.). Anyway I have not idea that what should be that file. Do you think could I get that data from other file? Or could I find the missing file using some tool? So pg_filedump show me empty for the other file in that directory pg_subtrans/0000.

Extra note: I found this useful blog post that talk about restore from just rescued files using pg_filedump, pg_class's file, reindex system and other tools and but is so hard for me to understand how to adapt it to my concrete and easier problem (I think that my problem is easier because I have a dump): https://www.commandprompt.com/blog/recovering_a_lost-and-found_database/


来源: stackexchange

问:
Mapping items in an array
Hoping this is a nice easy one, but I just can't see how to do it.

I am wanting to with rego map items in an array to a cleaner version. For example from the data below

```<code>data = [
  {
    "some": "value",
    "another": "mvalue",
    "dont": "want"
  },
  {
    "some": "value1",
    "another": "mvalue1",
    "dont": "want1"
  },
  {
    "some": "value2",
    "another": "mvalue2",
    "dont": "want2"
  }
]
</code>```

I want to turn data into

```<code>result = [
  {
    "some": "value",
    "another": "mvalue"
  },
  {
    "some": "value1",
    "another": "mvalue1"
  },
  {
    "some": "value2",
    "another": "mvalue2"
  }
]
</code>```

The two closest I think I've got is

```<code>result1 = cleaned {
    cleaned := {d |
        d := {
            "some": data[_].some,
            "another": data[_].another
        }
    }
}

result2 = cleaned {
    d := data[_]
    cleaned := {
        "some": p.some,
        "another": p.another
    }
}
</code>```

答:
What about performing a rejection of the key name during the comprehensions?
Probably a more elegant way to do this, but might be helpful.

```<code>package play

reject(key) = result {
    remove := [ "dont", "someotherthing" ]
    result :=  key == remove[_]
}

result = d {
    d := [ obj |
           val := input.data[_];
           obj := { k: v |
                    v := val[k]
                    not reject(k)
                  }
          ]
 }
</code>```

https://play.openpolicyagent.org/p/1A3DNLiNfj

ContentLicense: CC BY-SA 4.0

Title: Mapping items in an array

Body:
Hoping this is a nice easy one, but I just can't see how to do it.

I am wanting to with rego map items in an array to a cleaner version. For example from the data below

data = [
  {
    "some": "value",
    "another": "mvalue",
    "dont": "want"
  },
  {
    "some": "value1",
    "another": "mvalue1",
    "dont": "want1"
  },
  {
    "some": "value2",
    "another": "mvalue2",
    "dont": "want2"
  }
]

I want to turn data into

result = [
  {
    "some": "value",
    "another": "mvalue"
  },
  {
    "some": "value1",
    "another": "mvalue1"
  },
  {
    "some": "value2",
    "another": "mvalue2"
  }
]

The two closest I think I've got is

result1 = cleaned {
    cleaned := {d |
        d := {
            "some": data[_].some,
            "another": data[_].another
        }
    }
}

result2 = cleaned {
    d := data[_]
    cleaned := {
        "some": p.some,
        "another": p.another
    }
}

Body:
What about performing a rejection of the key name during the comprehensions?
Probably a more elegant way to do this, but might be helpful.

package play

reject(key) = result {
    remove := [ "dont", "someotherthing" ]
    result :=  key == remove[_]
}

result = d {
    d := [ obj |
           val := input.data[_];
           obj := { k: v |
                    v := val[k]
                    not reject(k)
                  }
          ]
 }

https://play.openpolicyagent.org/p/1A3DNLiNfj


问:
Collect binary number from user and convert it to decimal in JavaScript
I'm trying to write a script to accept at maximum 8 binary elements, verify if they are indeed binary and show they representation in decimal numbers. I'm stuck in the verification. I'm pretty new at programming and I don't know how to solve this problem.

```<code>function verify() {
    var numBin = document.getElementById('bin-input')
    var c = 0
    if (numBin.value == "" || numBin.value.length > 8 || isNaN(numBin) == "True"){
        alert('Write only 8 binary elements!')
    } else (while (numBin.value.length != c){
        if (numBin.length[c] == '0'|| numBin.length[c] == '1'){
            c ++
        } else {
            break
        }
        }){
            alert('Write only 0 and 1')
        }

}
</code>```

This is what I've made so far but the while inside the else if isn't working and I don't know how to fix it. How can I fix this issue?

答:
Here's an example how it could work, if you have any question to specific code lines let me know :)

function verifyAndConvert() {
  let input = document.getElementById('bn').value;
  if (verify(input)) {
    convert(input);
  }
}

function verify(input) {
  var numBin = input;
  var c = 0;
  var binaryFormat = /^[0-1]+$/;
  if (numBin.length > 8 || isNaN(numBin)) {
    alert('Write no more than 8 binary elements!');
  } else if (!numBin.match(binaryFormat)) {
    alert('Write only 0 and 1');
  } else {
    return true;
  }
  return false;
}

function convert(input) {
  alert(parseInt(input, 2));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="fname">Binary Number:</label>
<input type="text" id="bn">
<button onclick="verifyAndConvert()">Verify and Convert</button></code>```

Body:
I'm trying to write a script to accept at maximum 8 binary elements, verify if they are indeed binary and show they representation in decimal numbers. I'm stuck in the verification. I'm pretty new at programming and I don't know how to solve this problem.

function verify() {
    var numBin = document.getElementById('bin-input')
    var c = 0
    if (numBin.value == "" || numBin.value.length > 8 || isNaN(numBin) == "True"){
        alert('Write only 8 binary elements!')
    } else (while (numBin.value.length != c){
        if (numBin.length[c] == '0'|| numBin.length[c] == '1'){
            c ++
        } else {
            break
        }
        }){
            alert('Write only 0 and 1')
        }

}

This is what I've made so far but the while inside the else if isn't working and I don't know how to fix it. How can I fix this issue?

Body:
Here's an example how it could work, if you have any question to specific code lines let me know :)

function verifyAndConvert() {
  let input = document.getElementById('bn').value;
  if (verify(input)) {
    convert(input);
  }
}

function verify(input) {
  var numBin = input;
  var c = 0;
  var binaryFormat = /^[0-1]+$/;
  if (numBin.length > 8 || isNaN(numBin)) {
    alert('Write no more than 8 binary elements!');
  } else if (!numBin.match(binaryFormat)) {
    alert('Write only 0 and 1');
  } else {
    return true;
  }
  return false;
}

function convert(input) {
  alert(parseInt(input, 2));
}

<label for="fname">Binary Number:</label>
<input type="text" id="bn">
<button onclick="verifyAndConvert()">Verify and Convert</button>


问:
How can a team share an eclipse project when their work environment is different?
When sharing a project with team members through version control, it is customary to include the .project in the source under version control.  This makes sure that others on the team get all the dependencies and resources for the project.  But the .project uses full/rooted paths to the resource, and not all members of a team will be working in the same environment.  Even if all the members are on the same platform, the paths can often be in the user's home directory.

For the .classpath file, we can get around this problem by using build path variables.  Each member defines the path to location of dependent libraries on their system, and the .classpath only refers to the variable.

This is a particular concern for Grails project - when we add a plugin, it updates the .project accordingly.

答:
General Approach

As others have mentioned, you should not keep the IDE files in VCS, you should keep an IDE-agnostic description of the project in VCS and generate the IDE-specific project files from them.

Java-Maven Example

Keep the pom.xml file(s) in VCS and generate the Eclipse files by running mvn eclipse:eclipse

Grails Example

A Grails project is described by application.properties and grails-app/conf/BuildConfig.groovy. These files are present in every Grails application. You can generate the Eclipse project descriptions from them by running:

grails integrate-with --eclipse

This command also supports other tools such as IntelliJ and Textmate

ContentLicense: CC BY-SA 3.0


问:
Conditional formatting depending on checkbox
What I want to happen:

Depending on whether a tick box is clicked or not the corresponding cell on the same row should be colored (box unchecked) - so it would look like this:

My best guess was doing the following:

答:
to color a whole row you need to freeze the column with $

```<code>=$G2=FALSE
</code>```

applied to range A2:Z

Body:
to color a whole row you need to freeze the column with $

=$G2=FALSE

applied to range A2:Z


问:
Create adwords BigQuery Transfer with Python bigquery_datatransfer: error 400 Request contains an invalid argument

My step：

Get Authorization code：I use this URL to get auth code

https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?clientId=<id from list data sources>&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/bigquery

Create a service account with Project Owner

Execute sample code：

```<code>def run_quickstart():
    from google.cloud import bigquery_datatransfer_v1
    from google.protobuf.struct_pb2 import Struct

    client = bigquery_datatransfer_v1.DataTransferServiceClient()

    project = <project-id>
    parent = client.location_path(project, 'us')
    params = Struct()
    params.update({
        "customer_id": <customer-id>
    })

    transfer_config = {
        "destination_dataset_id": "test",
        "display_name": "test",
        "data_source_id": "adwords",
        "params": params
    }

    authorization_code = <authorization_code from step 1>
    response = client.create_transfer_config(parent, transfer_config, authorization_code)
    print(response)

if __name__ == '__main__':
    run_quickstart()
</code>```

Expect：Data transfer create
But I got the error：

```<code>Traceback (most recent call last):
  File "/project/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/grpc/_channel.py", line 826, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/project/lib/python3.7/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.INVALID_ARGUMENT
    details = "Request contains an invalid argument."
    debug_error_string = "{"created":"@1581747953.387292000","description":"Error received from peer ipv6:[2404:6800:4012:1::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Request contains an invalid argument.","grpc_status":3}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "app.py", line 49, in <module>
    run_quickstart()
  File "app.py", line 40, in run_quickstart
    parent, transfer_config, authorization_code)
  File "/project/lib/python3.7/site-packages/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py", line 563, in create_transfer_config
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/project/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/project/lib/python3.7/site-packages/google/api_core/retry.py", line 184, in retry_target
    return target()
  File "/project/lib/python3.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Request contains an invalid argument.

</code>```

I couldn't find which step is wrong. Please kind to help me to figure it out.

--- Update 02-19

@mk_sta

I remove authorization_code then the API could create a transfer, but the transfer couldn't work. It will get an error like this screenshot.

I thought the error is caused authorization_code is used to connect to google ads. Is your transfer work fine?

Reference:

https://cloud.google.com/bigquery-transfer/docs/reference/datatransfer/rest/v1/projects.locations.transferConfigs/create

答:
After revising your code snippet, I've noticed some points to mention:

According to the documentation pages BigQuery Data Transfer Service requires initial service account to own bigquery.admin role in order to inherit bigquery.datasets.update permission:

All users that will create transfers must be granted the
  bigquery.admin predefined Cloud IAM role. The bigquery.admin role
  includes the following BigQuery Data Transfer Service permissions:

bigquery.transfers.update

bigquery.transfers.get

Whenever you invoke create_transfer_config function, authorization_code is an optional parameter, that might be skipped, launching the different authentication model for transport configuration, depending on the particular user case.

I've tried to execute the above code using service account key associated with my GCP project:

export GOOGLE_APPLICATION_CREDENTIALS="<some_path>/[FILE_NAME].json"

I've made a few adjustments to the source code in order to get rid of authorization_code in the transfer config:

```<code>def run_quickstart():
    from google.cloud import bigquery_datatransfer_v1
    from google.protobuf.struct_pb2 import Struct

    client = bigquery_datatransfer_v1.DataTransferServiceClient()

    project = <project-id>
    parent = client.location_path(project, 'us')
    params = Struct()
    params.update({
        "customer_id": <customer-id>
    })

    transfer_config = {
        "destination_dataset_id": "test",
        "display_name": "test",
        "data_source_id": "adwords",
        "params": params
    }

    response = client.create_transfer_config(parent, transfer_config)
    print(response)

if __name__ == '__main__':
    run_quickstart()
</code>```

And that worked for me and I've successfully received response body:

```<code>name: "projects/.../..."
destination_dataset_id: "test"
display_name: "test"
update_time {
  seconds: 1582044242
  nanos: 441442000
}
data_source_id: "adwords"
next_run_time {
  seconds: 1581897600
}
params {
  fields {
    key: "customer_id"
    value {
      string_value: "XXXX"
    }
  }
}
user_id: <user_id>
dataset_region: "us"
</code>```

Body:
My step：

Get Authorization code：I use this URL to get auth code

https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?clientId=<id from list data sources>&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/bigquery

Create a service account with Project Owner

Execute sample code：

def run_quickstart():
    from google.cloud import bigquery_datatransfer_v1
    from google.protobuf.struct_pb2 import Struct

    client = bigquery_datatransfer_v1.DataTransferServiceClient()

    project = <project-id>
    parent = client.location_path(project, 'us')
    params = Struct()
    params.update({
        "customer_id": <customer-id>
    })

    transfer_config = {
        "destination_dataset_id": "test",
        "display_name": "test",
        "data_source_id": "adwords",
        "params": params
    }

    authorization_code = <authorization_code from step 1>
    response = client.create_transfer_config(parent, transfer_config, authorization_code)
    print(response)

if __name__ == '__main__':
    run_quickstart()

Expect：Data transfer create
But I got the error：

Traceback (most recent call last):
  File "/project/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/grpc/_channel.py", line 826, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/project/lib/python3.7/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.INVALID_ARGUMENT
    details = "Request contains an invalid argument."
    debug_error_string = "{"created":"@1581747953.387292000","description":"Error received from peer ipv6:[2404:6800:4012:1::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Request contains an invalid argument.","grpc_status":3}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "app.py", line 49, in <module>
    run_quickstart()
  File "app.py", line 40, in run_quickstart
    parent, transfer_config, authorization_code)
  File "/project/lib/python3.7/site-packages/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py", line 563, in create_transfer_config
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/project/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/project/lib/python3.7/site-packages/google/api_core/retry.py", line 184, in retry_target
    return target()
  File "/project/lib/python3.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/project/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Request contains an invalid argument.

I couldn't find which step is wrong. Please kind to help me to figure it out.

--- Update 02-19

@mk_sta

I remove authorization_code then the API could create a transfer, but the transfer couldn't work. It will get an error like this screenshot.

I thought the error is caused authorization_code is used to connect to google ads. Is your transfer work fine?

Reference:

https://cloud.google.com/bigquery-transfer/docs/reference/datatransfer/rest/v1/projects.locations.transferConfigs/create

Body:
After revising your code snippet, I've noticed some points to mention:

According to the documentation pages BigQuery Data Transfer Service requires initial service account to own bigquery.admin role in order to inherit bigquery.datasets.update permission:

All users that will create transfers must be granted the
  bigquery.admin predefined Cloud IAM role. The bigquery.admin role
  includes the following BigQuery Data Transfer Service permissions:

bigquery.transfers.update

bigquery.transfers.get

Whenever you invoke create_transfer_config function, authorization_code is an optional parameter, that might be skipped, launching the different authentication model for transport configuration, depending on the particular user case.

I've tried to execute the above code using service account key associated with my GCP project:

export GOOGLE_APPLICATION_CREDENTIALS="<some_path>/[FILE_NAME].json"

I've made a few adjustments to the source code in order to get rid of authorization_code in the transfer config:

def run_quickstart():
    from google.cloud import bigquery_datatransfer_v1
    from google.protobuf.struct_pb2 import Struct

    client = bigquery_datatransfer_v1.DataTransferServiceClient()

    project = <project-id>
    parent = client.location_path(project, 'us')
    params = Struct()
    params.update({
        "customer_id": <customer-id>
    })

    transfer_config = {
        "destination_dataset_id": "test",
        "display_name": "test",
        "data_source_id": "adwords",
        "params": params
    }

    response = client.create_transfer_config(parent, transfer_config)
    print(response)

if __name__ == '__main__':
    run_quickstart()

And that worked for me and I've successfully received response body:

name: "projects/.../..."
destination_dataset_id: "test"
display_name: "test"
update_time {
  seconds: 1582044242
  nanos: 441442000
}
data_source_id: "adwords"
next_run_time {
  seconds: 1581897600
}
params {
  fields {
    key: "customer_id"
    value {
      string_value: "XXXX"
    }
  }
}
user_id: <user_id>
dataset_region: "us"


问:
How to count the number of cells which contain specific text using Google Sheet Scripts?
How to count the number of cells which contain specific text using Google sheet scripts?

Currently I'am using the following script to count the number of cells which contain specific text, for example cells which contain: 'Complete' or 'Not Complete'.

```<code>function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {
  sheetNames = sheetNames.split(',');
  var count = 0;
  sheetNames.forEach(function(sheetName) {
    var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
    var values = sheet.getRange(range).getValues();
    values.forEach(function(row) {
      row.forEach(function(cell) {
        if (cell.indexOf(text) !== -1 ) count++;
      });
    });
  });
  return count;
};
</code>```

Currently the script counts both cells which contain the text 'Complete' and 'Not Complete' is there a way to modify the script to only count cells which contain the full word 'Complete' instead of also counting cells which contain 'Not Complete' because the cell also contains the keyword: 'Complete'?

Example usage of the current script:

```<code>=COUNT_TEXT_ACROSS_SHEETS("Sheet1", "C1:C1000", "NOT COMPLETE")
</code>```

答:
How about this:</p>

```<code>function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {//text=['Complete','Not Complete']
  var nA=sheetNames.split(',');
  var tA=text.split(',');
  var count = 0;
  var cObj={};
  cObj[tA[0]]=0;
  cObj[tA[1]]=0;
  nA.forEach(function(name) {
    var sh=SpreadsheetApp.getActive().getSheetByName(name);
    var vA = sheet.getRange(range).getValues();
    vA.forEach(function(r) {
      r.forEach(function(c) {
        var idx0=c.indexOf(tA[0]);
        var idx1=c.indexOf(tA[1]);
        if(idx0!=-1 && idx1==-1)cObj[tA[0]]+=1;
        if(idx0!=-1 && idx1!=-1)cObj[tA[1]]+=1
      });
    });
  });
  return Utilities.formatString('Count-%s:%s Count-%s:%s',tA[0],cObj[tA[0]],tA[1],cObj[tA[1]]);
};
</code>```

Body:
How to count the number of cells which contain specific text using Google sheet scripts?

Currently I'am using the following script to count the number of cells which contain specific text, for example cells which contain: 'Complete' or 'Not Complete'.

function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {
  sheetNames = sheetNames.split(',');
  var count = 0;
  sheetNames.forEach(function(sheetName) {
    var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
    var values = sheet.getRange(range).getValues();
    values.forEach(function(row) {
      row.forEach(function(cell) {
        if (cell.indexOf(text) !== -1 ) count++;
      });
    });
  });
  return count;
};

Currently the script counts both cells which contain the text 'Complete' and 'Not Complete' is there a way to modify the script to only count cells which contain the full word 'Complete' instead of also counting cells which contain 'Not Complete' because the cell also contains the keyword: 'Complete'?

Example usage of the current script:

=COUNT_TEXT_ACROSS_SHEETS("Sheet1", "C1:C1000", "NOT COMPLETE")

Body:
How about this:

function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {//text=['Complete','Not Complete']
  var nA=sheetNames.split(',');
  var tA=text.split(',');
  var count = 0;
  var cObj={};
  cObj[tA[0]]=0;
  cObj[tA[1]]=0;
  nA.forEach(function(name) {
    var sh=SpreadsheetApp.getActive().getSheetByName(name);
    var vA = sheet.getRange(range).getValues();
    vA.forEach(function(r) {
      r.forEach(function(c) {
        var idx0=c.indexOf(tA[0]);
        var idx1=c.indexOf(tA[1]);
        if(idx0!=-1 && idx1==-1)cObj[tA[0]]+=1;
        if(idx0!=-1 && idx1!=-1)cObj[tA[1]]+=1
      });
    });
  });
  return Utilities.formatString('Count-%s:%s Count-%s:%s',tA[0],cObj[tA[0]],tA[1],cObj[tA[1]]);
};


问:
How can I subscribe user to a topic for notifications as soon as app starts up?
I am using HTTP POST to send notifications to all users on the app. To do this I have a topic to subscribe to called "global". I want every user to be automatically subscribed to this topic to make sure they get the notifications (assuming they have notifications turned on).

Where in my code should I put the subscription to make sure they will always be subscribed? My fear is that I put it somewhere wrong and they never end up being subscribed. I tried to subscribe at the end of didFinishLaunchingWithOptions but it looks like it is too early to do it here (I guess since user may not have accepted notification prompt yet?).

Currently the subscription is in didRegisterForRemoteNotificationsWithDeviceToken however this does not get called on the first app run so for it to work I have to run the app a second time... Here is my relevant code in AppDelegate:

```<code>import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    FIRApp.configure()

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    return true
}

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("applicationReceivedRemoteMessage")
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
        FIRMessaging.messaging().subscribe(toTopic: "/topics/global")
    }
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
}
</code>```

答:
Subscribe method should be added in this didReceiveRegistrationToken method, so that whenever the token is refreshed, the topic will be subscribed automatically.</p>

```<code>func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

Messaging.messaging().subscribe(toTopic: "TestTopic"){ error in
            if error == nil{
                print("Subscribed to topic")
            }
            else{
                print("Not Subscribed to topic")
            }
        }
}
</code>```

Body:
I am using HTTP POST to send notifications to all users on the app. To do this I have a topic to subscribe to called "global". I want every user to be automatically subscribed to this topic to make sure they get the notifications (assuming they have notifications turned on).

Where in my code should I put the subscription to make sure they will always be subscribed? My fear is that I put it somewhere wrong and they never end up being subscribed. I tried to subscribe at the end of didFinishLaunchingWithOptions but it looks like it is too early to do it here (I guess since user may not have accepted notification prompt yet?).

Currently the subscription is in didRegisterForRemoteNotificationsWithDeviceToken however this does not get called on the first app run so for it to work I have to run the app a second time... Here is my relevant code in AppDelegate:

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    FIRApp.configure()

    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    return true
}

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("applicationReceivedRemoteMessage")
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
        FIRMessaging.messaging().subscribe(toTopic: "/topics/global")
    }
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
}

Body:
Subscribe method should be added in this didReceiveRegistrationToken method, so that whenever the token is refreshed, the topic will be subscribed automatically.

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

Messaging.messaging().subscribe(toTopic: "TestTopic"){ error in
            if error == nil{
                print("Subscribed to topic")
            }
            else{
                print("Not Subscribed to topic")
            }
        }
}


问:
Find all indices of each letter in a string
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

```<code>a = 'string of letters'
b = [a.index(x) for x in a]
</code>```

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

答:
.index just returns the first occurrence of a character in a string - this has nothing to do with caches. It seems like you just want the list of numbers from 0 until your string length-1:

```<code>b = list(range(len(a)))
</code>```

You do not mention why you need this, but it's pretty rare to need something like this in Python. Note in Python 3 range returns a a special type of it's own representing an immutable sequence of numbers, so you need to explicitly convert it to a list if you do actually need that.

Body:
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

a = 'string of letters'
b = [a.index(x) for x in a]

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

Body:
.index just returns the first occurrence of a character in a string - this has nothing to do with caches. It seems like you just want the list of numbers from 0 until your string length-1:

b = list(range(len(a)))

You do not mention why you need this, but it's pretty rare to need something like this in Python. Note in Python 3 range returns a a special type of it's own representing an immutable sequence of numbers, so you need to explicitly convert it to a list if you do actually need that.


问:
How can I work with swagger yaml file in PhpStorm?
Working with swagger project (openapi: 3.0.0 ) at app.swaggerhub.com
I edit data in yaml format and that raised a questions if there is a way
to work with swagger defintions In PhpStorm 2019.2.3, as it's editor is much better ?

Or some other way more convinient of app.swaggerhub.com ?

Thanks!

答:
There's an OpenAPI editor plugin for IntelliJ IDEs:

https://plugins.jetbrains.com/plugin/12887-openapi-editor


问:
How to insert value into an HTML form using PHP?
I have a form in a file named signup.php like this,

```<code><form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username..."><br><br>
<input type="text" name="mail" placeholder="Email..."><br><br>
<input type="password" name="pwd" placeholder="Password..."><br><br>
<input type="password" name="repeatPwd" placeholder="Repeat Password..."><br><br>
<input type="submit" name="btnSignup" value="Signup">
</form>
</code>```

Then I have this if statement in the signup.inc.php file.

```<code>if (!preg_match("/^[a-zA-z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduid&mail=".$email);
    exit();
}
</code>```

That is if the user enter invalid username, then the user will be route back to the signup page, and I get an error message in the address bar, now I want to get the email from the address bar which the user entered, I make an if statement back in the signup.php file like this,

```<code>if ($_GET['error'] == "invaliduid") {
    echo "Invalid username.";
    $email = $_GET['mail'];
}
</code>```

Now I want to fill the original form

```<code><input type="text" name="mail" placeholder="Email...">
</code>```

And put the email from $_GET['mail'] and put it in the value portion of the form, but I am stuck on how to do this.

The program should work like this, if the user entered proper mail and an invalid username then the user route back to the signup page with the message invalid username, and email field should be populated with the email which he already entered.

答:
This here is working as intended:</p>

```<code><input type="text" name="mail" placeholder="Email..." value="<?php echo(isset($email))?$email:'';?>">
</code>```

Body:
I have a form in a file named signup.php like this,

<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username...">

<input type="text" name="mail" placeholder="Email...">

<input type="password" name="pwd" placeholder="Password...">

<input type="password" name="repeatPwd" placeholder="Repeat Password...">

<input type="submit" name="btnSignup" value="Signup">
</form>

Then I have this if statement in the signup.inc.php file.

if (!preg_match("/^[a-zA-z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduid&mail=".$email);
    exit();
}

That is if the user enter invalid username, then the user will be route back to the signup page, and I get an error message in the address bar, now I want to get the email from the address bar which the user entered, I make an if statement back in the signup.php file like this,

if ($_GET['error'] == "invaliduid") {
    echo "Invalid username.";
    $email = $_GET['mail'];
}

Now I want to fill the original form

<input type="text" name="mail" placeholder="Email...">

And put the email from $_GET['mail'] and put it in the value portion of the form, but I am stuck on how to do this.

The program should work like this, if the user entered proper mail and an invalid username then the user route back to the signup page with the message invalid username, and email field should be populated with the email which he already entered.

Body:
This here is working as intended:

<input type="text" name="mail" placeholder="Email..." value="<?php echo(isset($email))?$email:'';?>">


问:
How to add dtd validation to `xml.etree.cElementTree.iterparse`
I know, that this way of dtd validation before parsing a xml file works:

```<code>    from lxml import etree
    context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
</code>```

But how do I get this to work for the xml.etree.cElementTree.iterparse?

```<code>    from xml.etree.cElementTree import iterparse
    context = iterparse(PATH_TO_XML, ???, events=("start", "end"))
</code>```

答:
cElementTree is not part of lxml.
According to the cElementTree website, DTD Validation is not available to cElementTree.</p>

Body:
I know, that this way of dtd validation before parsing a xml file works:

    from lxml import etree
    context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))

But how do I get this to work for the xml.etree.cElementTree.iterparse?

    from xml.etree.cElementTree import iterparse
    context = iterparse(PATH_TO_XML, ???, events=("start", "end"))


问:
net::ERR_CERT_COMMON_NAME_INVALID when using multiple server_name in nginx
I'm using nginx container to access different services provided by other containers.
i have an app hosted on app-something.domain.com with an ssl certificates all is well but my problem is when i want to add an alias, app.domain.com. the one who did it before me had done something like this

```<code>server {
    listen                  80;
    listen                  [::]:80;
    server_name             app-something.domain.com app.domain.com;
}

server {
    listen                  443 ssl;
    listen                  [::]:443 ssl;
    server_name             app-something.domain.com app.domain.com;
    ssl_certificate         certificate/path;
    ssl_certificate_key     certificate/key/path;

    location / {
        resolver            ip valid=30s;
        set                 $backend "http://app-url:port";
        proxy_pass          $backend;
    }
}
</code>```

when i do the same, i get an ssl error because app.domain.com uses the certificate of another domain.
the certificate is a multi domain certificate and it has been generated using acme.sh with the following command:

```<code>acme.sh --home home/path/ -w webroot/path --issue -d app-something.domain.com -d app.domain.com
</code>```

i'd like to understand how to make an alias for the subdomain, the fact that i'm getting different result than people who did it before me by doing the very same thing as them is confusing me.

thanks for helping me.

答: Left it aside for a while since not urgent came back to it after a month the cert has been renewed and it runs fine even though deleting the cert and generating a new one did not work</p>

Body:
I'm using nginx container to access different services provided by other containers.
i have an app hosted on app-something.domain.com with an ssl certificates all is well but my problem is when i want to add an alias, app.domain.com. the one who did it before me had done something like this

server {
    listen                  80;
    listen                  [::]:80;
    server_name             app-something.domain.com app.domain.com;
}

server {
    listen                  443 ssl;
    listen                  [::]:443 ssl;
    server_name             app-something.domain.com app.domain.com;
    ssl_certificate         certificate/path;
    ssl_certificate_key     certificate/key/path;

    location / {
        resolver            ip valid=30s;
        set                 $backend "http://app-url:port";
        proxy_pass          $backend;
    }
}

when i do the same, i get an ssl error because app.domain.com uses the certificate of another domain.
the certificate is a multi domain certificate and it has been generated using acme.sh with the following command:

acme.sh --home home/path/ -w webroot/path --issue -d app-something.domain.com -d app.domain.com

i'd like to understand how to make an alias for the subdomain, the fact that i'm getting different result than people who did it before me by doing the very same thing as them is confusing me.

thanks for helping me.


问:
Get input value and pass it to route in same blade file Laravel 5.7
I want to pass selected value from dropdown to be passed throw routing from the same blade file

Here is my blade code :

```<code><div class="form-group col-md-2">
    <label>@lang('site.son')</label>

    @if(Auth::user()->shortsign == '--')
    <select class="select2-size-lg form-control border-primary" style="width: 100%;" name="sign">
        @foreach ($users as $user)
        <option value="{{ $user->shortsign }}">{{ $user->shortsign }}</option>
        @endforeach
    </select>
    @else
    <select class="select2-size-lg form-control border-primary" style="width: 100%;" name="sign" readonly>
        <option value="{{ Auth::user()->shortsign }}">{{ Auth::user()->shortsign }}</option>
    </select>
    @endif

</div>

<div class="form-actions right">
    <a href="{{  url('/salereports/report/' . $user->shortsign) }}" class="btn btn-outline-dark btn-min-width box-shadow-2 mr-1 mb-1"><i class="la la-search" aria-hidden="true"></i> @lang('site.search')</a>
</div>
</code>```

Now the code iam using pass the last value from database not selected value

答:
you can try this by giving id to your anchor tag    </p>

```<code><script type="text/javascript">
   $('.select2-size-lg').change(function () {
    var id = $(this).val();
    document.getElementById("abc").href="{{  url('/salereports/report/' . id) }}";
});
</script>
</code>```

Body:
I want to pass selected value from dropdown to be passed throw routing from the same blade file

Here is my blade code :

    @lang('site.son')

    @if(Auth::user()->shortsign == '--')
    <select class="select2-size-lg form-control border-primary" style="width: 100%;" name="sign">
        @foreach ($users as $user)
        <option value="{{ $user->shortsign }}">{{ $user->shortsign }}</option>
        @endforeach
    </select>
    @else
    <select class="select2-size-lg form-control border-primary" style="width: 100%;" name="sign" readonly>
        <option value="{{ Auth::user()->shortsign }}">{{ Auth::user()->shortsign }}</option>
    </select>
    @endif

    shortsign) }}" class="btn btn-outline-dark btn-min-width box-shadow-2 mr-1 mb-1"> @lang('site.search')

Now the code iam using pass the last value from database not selected value

Body:
you can try this by giving id to your anchor tag

<script type="text/javascript">
   $('.select2-size-lg').change(function () {
    var id = $(this).val();
    document.getElementById("abc").href="{{  url('/salereports/report/' . id) }}";
});
</script>


答:
One approach could be to build a dictionary, iterating over the distinct letters in the string and using re.finditer to obtain the index of all occurrences in the string. So going step by step:

```<code>import re
a = 'string of letters'
</code>```

We can find the unique letters in the string by taking a set:

```<code>letters = set(a.replace(' ',''))
# {'e', 'f', 'g', 'i', 'l', 'n', 'o', 'r', 's', 't'}
</code>```

Then we could use a dictionary comprehension to build the dictionary, in which the the values are a list generated by iterating over all match instances returned by re.finditer:

```<code>{w: [m.start() for m in re.finditer(w, a)] for w in letters}

{'i': [3],
 'o': [7],
 'f': [8],
 'l': [10],
 'g': [5],
 'e': [11, 14],
 't': [1, 12, 13],
 's': [0, 16],
 'n': [4],
 'r': [2, 15]}
</code>```

Title: Find all indices of each letter in a string

Body:
One approach could be to build a dictionary, iterating over the distinct letters in the string and using re.finditer to obtain the index of all occurrences in the string. So going step by step:

import re
a = 'string of letters'

We can find the unique letters in the string by taking a set:

letters = set(a.replace(' ',''))
# {'e', 'f', 'g', 'i', 'l', 'n', 'o', 'r', 's', 't'}

Then we could use a dictionary comprehension to build the dictionary, in which the the values are a list generated by iterating over all match instances returned by re.finditer:

{w: [m.start() for m in re.finditer(w, a)] for w in letters}

{'i': [3],
 'o': [7],
 'f': [8],
 'l': [10],
 'g': [5],
 'e': [11, 14],
 't': [1, 12, 13],
 's': [0, 16],
 'n': [4],
 'r': [2, 15]}


问:
How can I implement a boolean tag search in SQL?
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?

Is there a good "standard" solution for this?

答:
It depends on how you're storing tags in the database, but you probably want the IN operator:

```<code>SELECT tag FROM myTags WHERE tag IN ('p1','p2',...)
SELECT tag FROM myTags WHERE tag NOT IN ('p1','p2',...)
</code>```

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
It depends on how you're storing tags in the database, but you probably want the IN operator:

SELECT tag FROM myTags WHERE tag IN ('p1','p2',...)
SELECT tag FROM myTags WHERE tag NOT IN ('p1','p2',...)

OwnerDisplayName: Jason Cohen


问:
Couchdb map/reduce to return the first in a stream, then order by time
I have a couchdb which holds a series of events.  Each event has an owner, an id, a time it occured and a message (plus a bunch of other stuff which doesn't matter for this exercise).  I'd like a list of events which occured recently ordered by time.  I looked through this question CouchDB - filter latest log per logged instance from a list and tried using it with the comparison in the reducer flipped to keep the first message (using the form where I have a complex key).

Unfortunately it doesn't quite seem to do what want.

Here's my map function

```<code>function(doc) {
  var owner, id;
  if (doc.owner
      && doc.stream_id
      && doc.message
      && doc.receipt_time)
    {
      emit([doc.owner,doc.stream_id,doc.receipt_time],
           { owner: doc.owner,
             stream_id: doc.stream_id,
             timestamp: doc.receipt_time,
             message: doc.message
           });
    }
}
</code>```

and my reduce function

```<code>function(keys, values) {
  var challenger, winner = null;
  for (var a = 0; a < values.length; a++) {
      challenger = values[a];
      if (! winner) {
        winner = challenger;
      } else {
        if (winner.owner !== challenger.owner
            && winner.trace_id !== challenger.trace_id ) {
          return null;
        } else if (challenger.timestamp < winner.timestamp) {
          winner = challenger;
        }
      }
    }
  return winner;
}
</code>```

Then I invoke with ?descending=true&group=true&group_level=2 to get the first message from each stream, however, it doesn't seem to be ordered by time, but by owner and stream_id, like this

```<code>{"rows":[
  {"key":["sam","a"],
   "value":
     {"owner":"sam","stream_id":"a","timestamp":1303754236482,"message":"foo"}
  },
  {"key":["sam","b"],
   "value":
     {"owner":"sam","stream_id":"b","timestamp":1303752578476,"message":"bar"}
  },
  {"key":["jim","j1"],
   "value":
     {"owner":"jim","stream_id":"j1","timestamp":1303625378839,"message":"stuff"}
  },
  {"key":["bob","loblaw"],
   "value":
     {"owner":"bob","stream_id":"loblaw","timestamp":1303328396532,"message":"more stuff"}
  },
  {"key":["anthony","foo"],
   "value":
     {"owner":"anthony","stream_id":"foo","timestamp":1303769699444,"message":"even more"}
  }
]}
</code>```

(Notice the final entry actually is the most recent in time).

So what I'd like is for the final view to be what it is now but ordered by time.  Is there a way to do this?

答:
Store stream_created_at timestamp in every message. So for the first message you take current time. For every next message in the stream you copy it from the previous one (create a view to get stream_created_at_by_stream_id for this).

Then create view that emits:

```<code>[doc.owner,doc.stream_created_at, doc.stream_id, doc.receipt_time]
</code>```

That will group messages from the same stream together while preserving time ordering. stream.id will ensure that messages from different streams don't mix up when two streams are created at the same time. And receipt_time will order the messages in the stream by time.

So in the end you will get Facebook like conversations. And you don't need any reduce function at all.

Body:
I have a couchdb which holds a series of events.  Each event has an owner, an id, a time it occured and a message (plus a bunch of other stuff which doesn't matter for this exercise).  I'd like a list of events which occured recently ordered by time.  I looked through this question CouchDB - filter latest log per logged instance from a list and tried using it with the comparison in the reducer flipped to keep the first message (using the form where I have a complex key).

Unfortunately it doesn't quite seem to do what want.

Here's my map function

function(doc) {
  var owner, id;
  if (doc.owner
      && doc.stream_id
      && doc.message
      && doc.receipt_time)
    {
      emit([doc.owner,doc.stream_id,doc.receipt_time],
           { owner: doc.owner,
             stream_id: doc.stream_id,
             timestamp: doc.receipt_time,
             message: doc.message
           });
    }
}

and my reduce function

function(keys, values) {
  var challenger, winner = null;
  for (var a = 0; a < values.length; a++) {
      challenger = values[a];
      if (! winner) {
        winner = challenger;
      } else {
        if (winner.owner !== challenger.owner
            && winner.trace_id !== challenger.trace_id ) {
          return null;
        } else if (challenger.timestamp < winner.timestamp) {
          winner = challenger;
        }
      }
    }
  return winner;
}

Then I invoke with ?descending=true&group=true&group_level=2 to get the first message from each stream, however, it doesn't seem to be ordered by time, but by owner and stream_id, like this

{"rows":[
  {"key":["sam","a"],
   "value":
     {"owner":"sam","stream_id":"a","timestamp":1303754236482,"message":"foo"}
  },
  {"key":["sam","b"],
   "value":
     {"owner":"sam","stream_id":"b","timestamp":1303752578476,"message":"bar"}
  },
  {"key":["jim","j1"],
   "value":
     {"owner":"jim","stream_id":"j1","timestamp":1303625378839,"message":"stuff"}
  },
  {"key":["bob","loblaw"],
   "value":
     {"owner":"bob","stream_id":"loblaw","timestamp":1303328396532,"message":"more stuff"}
  },
  {"key":["anthony","foo"],
   "value":
     {"owner":"anthony","stream_id":"foo","timestamp":1303769699444,"message":"even more"}
  }
]}

(Notice the final entry actually is the most recent in time).

So what I'd like is for the final view to be what it is now but ordered by time.  Is there a way to do this?

Body:
Store stream_created_at timestamp in every message. So for the first message you take current time. For every next message in the stream you copy it from the previous one (create a view to get stream_created_at_by_stream_id for this).

Then create view that emits:

[doc.owner,doc.stream_created_at, doc.stream_id, doc.receipt_time]

That will group messages from the same stream together while preserving time ordering. stream.id will ensure that messages from different streams don't mix up when two streams are created at the same time. And receipt_time will order the messages in the stream by time.

So in the end you will get Facebook like conversations. And you don't need any reduce function at all.


答:
Use TextFinder class.

Sample script:

```<code>/**
 * @customfunction
 * @return count of given text in spreadsheet
 * @param {string} text text to search
 * @param {boolean} mec whether to match entire cell
 * @param {boolean} mc whether to match case
 */
function COUNT_SS(text = 'NOT COMPLETE', mec = true, mc = true) {
  return SpreadsheetApp.getActive()
    .createTextFinder(text)
    .matchEntireCell(mec)
    .matchCase(mc)
    .findAll()
    .length;
}
</code>```

Usage:

```<code>=COUNT_SS()
</code>```

Title: How to count the number of cells which contain specific text using Google Sheet Scripts?

Body:
Use TextFinder class.

Sample script:

/**
 * @customfunction
 * @return count of given text in spreadsheet
 * @param {string} text text to search
 * @param {boolean} mec whether to match entire cell
 * @param {boolean} mc whether to match case
 */
function COUNT_SS(text = 'NOT COMPLETE', mec = true, mc = true) {
  return SpreadsheetApp.getActive()
    .createTextFinder(text)
    .matchEntireCell(mec)
    .matchCase(mc)
    .findAll()
    .length;
}

Usage:

=COUNT_SS()


问:
Enable special permissions by default on xiaomi mi phone
I need to open the app when getting the push notification. It is working fine in all devices except in MI devices. I came out with the solution to enable the specific permissions of MI phone. It is working when they are enabled manually but how to enable all three permissions shown in images below programmatically.

答:
```<code>Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
intent.setClassName("com.miui.securitycenter",
"com.miui.permcenter.permissions.PermissionsEditorActivity");
intent.putExtra("extra_pkgname", getPackageName());
startActivity(intent);
</code>```


问:
Php7.4 preload with opcache enabled fpm error
I'm currently using nginx, php7.4-fpm (php7.4.2) and symfony5.

I tried to enable php7.4 preload feature I'm getting fpm error.

*1 recv() failed (104: Connection reset by peer) while reading response header from upstream, client

php.ini:
opcache.preload=/var/www/domain/var/cache/prod/App_KernelProdContainer.preload.php
opcache.preload_user=ubuntu

Any suggestions what could be wrong?

答:
I had the same issue with php7.4.2, symfony 5 and nginx and after some research, here what I found:

https://github.com/symfony/symfony/pull/34910#issuecomment-578761190

https://ezplatform.com/blog/php-7.4-opcache-preloading-benchmark

It seems to be a bug with opcache.preload_user parameter which is mandatory :)

I suggest you to comment opcache.preload and opcache.preload_user and wait for php7.4.3.

Hope it helps


答:
Sounds like you're trying to get a list of the indeces of each input char as
an output. So, for s, you would get [0, 16], or something along those lines.

So for each input char, you would add its position to the right list.

Storing the results in a dict seems like a good approach, so, something like:

```<code>def index_dict(stringy):
    d = {}
    for index, char in enumerate(stringy):
        if char not in d:
            d[char] = []
        d[char].append(index)
    return d
</code>```

The index() method always finds the first occurrence. You need to find all occurrences. So, the above func will give you a dict with all the keys matching the chars of your input string, and then the value for each key is a list of indeces where that char is found.

Body:
Sounds like you're trying to get a list of the indeces of each input char as
an output. So, for s, you would get [0, 16], or something along those lines.

So for each input char, you would add its position to the right list.

Storing the results in a dict seems like a good approach, so, something like:

def index_dict(stringy):
    d = {}
    for index, char in enumerate(stringy):
        if char not in d:
            d[char] = []
        d[char].append(index)
    return d

The index() method always finds the first occurrence. You need to find all occurrences. So, the above func will give you a dict with all the keys matching the chars of your input string, and then the value for each key is a list of indeces where that char is found.


问:
Google Mock and Catch.hpp Integration
I really like catch.hpp for testing (https://github.com/philsquared/Catch). I like its BDD style and its REQUIRE statements, its version of asserts. However, catch does not come with a mocking framework.

The project I'm working on has GMock and GTest but we've used catch for a few projects as well. I'd like to use GMock with catch.

I found 2 conflicts in the catch.hpp and gtests header files for the macros FAIL and SUCCEED. Since I'm not using the TDD style but instead the BDD style I commented them out, I checked that they weren't referenced anywhere else in catch.hpp.

Problem: Using EXPECT_CALL() doesn't return anything or have callbacks to know if the EXPECT passed. I want to do something like:

```<code>REQUIRE_NOTHROW(EXPECT_CALL(obj_a, an_a_method()).Times(::testing::AtLeast(1)));
</code>```

Question: How can I get a callback if EXPECT_CALL fails (or a return value)

答:
I created a small example how to integrate GMock with Catch2.

https://github.com/matepek/catch2-with-gmock

Hope it helps someone.

Disclaimer: It is not bulletproof. Feel free to contribute and improve.

Title: Google Mock and Catch.hpp Integration

Body:
I really like catch.hpp for testing (https://github.com/philsquared/Catch). I like its BDD style and its REQUIRE statements, its version of asserts. However, catch does not come with a mocking framework.

The project I'm working on has GMock and GTest but we've used catch for a few projects as well. I'd like to use GMock with catch.

I found 2 conflicts in the catch.hpp and gtests header files for the macros FAIL and SUCCEED. Since I'm not using the TDD style but instead the BDD style I commented them out, I checked that they weren't referenced anywhere else in catch.hpp.

Problem: Using EXPECT_CALL() doesn't return anything or have callbacks to know if the EXPECT passed. I want to do something like:

REQUIRE_NOTHROW(EXPECT_CALL(obj_a, an_a_method()).Times(::testing::AtLeast(1)));

Question: How can I get a callback if EXPECT_CALL fails (or a return value)


问:
Applying multiple value thresholds to a dataframe in python
I am working with a data frame in python. I want to apply a threshold to the data. I want all S4 values >0.6 and <1. Please advice on how I could implement this and isolate all threshold entries. Please take into consideration that some of the data entries have a blank S4 value ie the data frame contains blank entries.

答:
All you need to do is:

data[(data['Total_S4_Sig1'] > 0.6) & (data['Total_S4_Sig1'] < 1.0)]
```

<p>However, I believe the column 'Total_S4_Sig1' is in <code>str</code>. You would need to convert it to <code>float</code> for the above command to work. To do that:</p>

<pre class="lang-py prettyprint-override"><code>data['Total_S4_Sig1'] = pd.to_numeric(data['Total_S4_Sig1'], errors='coerce')
</code>```

The above command will convert blanks to NaN as well.

Body:
All you need to do is:

data[(data['Total_S4_Sig1'] > 0.6) & (data['Total_S4_Sig1'] < 1.0)]

However, I believe the column 'Total_S4_Sig1' is in str. You would need to convert it to float for the above command to work. To do that:

data['Total_S4_Sig1'] = pd.to_numeric(data['Total_S4_Sig1'], errors='coerce')

The above command will convert blanks to NaN as well.


问:
How to declare a variable and increment it in Django templates
How to initialize a numerical variable in Django templates.

```<code>{% with i=1 %}
    {% for cont in data %}

    {% if i|divisibleby:3 %}
         {{ forloop.i }}
    <!-- HTML -->

    {% elif i|divisibleby:2 %}
         {{ forloop.i }}
    <!-- HTML -->

    {% else %}
         {{ forloop.i }}
    <!-- HTML -->

    {% endif %}
   {% endfor %}
</code>```

Getting this error due to {% with i=1 %}

```<code>TemplateSyntaxError at /tools-dash/

Unclosed tag on line 21: 'with'. Looking for one of: endwith.
</code>```

The variable i is not being incremented by each {{ forloop.i }}. For each row in DB I get the same template in else part. How this can be changed to alternative ones.

答:
There's no need to create a new variable. You can use your normal for loop, and check if forloop.counter is divisible by 3 or 2. Like so:

{% for cont in data %}

    {% if forloop.counter|divisibleby:3 %}
        {{ forloop.counter }}

    {% elif forloop.counter|divisibleby:2 %}
        {{ forloop.counter }}

    {% else %}
        {{ forloop.counter }}

    {% endif %}

{% endfor %}
```

Body:
How to initialize a numerical variable in Django templates.

{% with i=1 %}
    {% for cont in data %}

    {% if i|divisibleby:3 %}
         {{ forloop.i }}

    {% elif i|divisibleby:2 %}
         {{ forloop.i }}

    {% else %}
         {{ forloop.i }}

    {% endif %}
   {% endfor %}

Getting this error due to {% with i=1 %}

TemplateSyntaxError at /tools-dash/

Unclosed tag on line 21: 'with'. Looking for one of: endwith.

The variable i is not being incremented by each {{ forloop.i }}. For each row in DB I get the same template in else part. How this can be changed to alternative ones.

Body:
There's no need to create a new variable. You can use your normal for loop, and check if forloop.counter is divisible by 3 or 2. Like so:

{% for cont in data %}

    {% if forloop.counter|divisibleby:3 %}
        {{ forloop.counter }}
        <!-- HTML -->

    {% elif forloop.counter|divisibleby:2 %}
        {{ forloop.counter }}
        <!-- HTML -->

    {% else %}
        {{ forloop.counter }}
        <!-- HTML -->

    {% endif %}

{% endfor %}


问:
Get .Net Core 3.1 single-file executable version number
I have a .Net Core application that has been published as a single file executable.  When I run any of the following code from within Visual Studio, I get the expected result:

```<code>Assembly.GetAssembly(typeof(Installer)).GetName().Version.ToString();
Assembly.GetEntryAssembly().GetName().Version.ToString();
Assembly.GetExecutingAssembly().GetName().Version.ToString();
</code>```

But when the above code is run within the published application (in production) it always returns "0.0.0.0"

答:
Have you tried this? I created a new project and it seemed to work.

Assuming you're using Visual Studio 2019.

Right-click project -> Add -> New Item -> Assembly Information File

You will then have a AssemblyInfo.cs file with the assembly version in

You then need to ignore the generated assembly version so you need to add GenerateAssemblyInfo with false to your .csproj.

Right-click project -> Edit Project File -> Add GenerateAssemblyInfo element like below:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
   <PropertyGroup>
      <TargetFramework>netcoreapp3.1</TargetFramework>
      <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
   </PropertyGroup>
</Project>
</code>```

Body:
I have a .Net Core application that has been published as a single file executable.  When I run any of the following code from within Visual Studio, I get the expected result:

Assembly.GetAssembly(typeof(Installer)).GetName().Version.ToString();
Assembly.GetEntryAssembly().GetName().Version.ToString();
Assembly.GetExecutingAssembly().GetName().Version.ToString();

But when the above code is run within the published application (in production) it always returns "0.0.0.0"

Body:
Have you tried this? I created a new project and it seemed to work.

Assuming you're using Visual Studio 2019.

Right-click project -> Add -> New Item -> Assembly Information File

You will then have a AssemblyInfo.cs file with the assembly version in

You then need to ignore the generated assembly version so you need to add GenerateAssemblyInfo with false to your .csproj.

Right-click project -> Edit Project File -> Add GenerateAssemblyInfo element like below:

<Project Sdk="Microsoft.NET.Sdk.Web">
   <PropertyGroup>
      <TargetFramework>netcoreapp3.1</TargetFramework>
      <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
   </PropertyGroup>
</Project>


问:
How to fix this- error: Invalid use of className::className?
Getting the error: invalid use of className::className.

Was trying to make a timeStamp class which represented a time of a day, it stores seconds, minutes, hours in specific variables. Ran into an error in line #13 on main function, the error reads: invalid use of timeStamp::timeStamp what did i do wrong?
There's a header file where all the methods are declared.

The source file cpp:

```<code>    #include "timeStamp.h"
#include <iostream>
using namespace std;

timeStamp::timeStamp()
{
    Hour = 0;
    Minute = 0;
    Second =0;
}
timeStamp::timeStamp(int h, int m, int s){

Hour = h;
Minute = m;
Second = s;

}
int timeStamp::getHour(){

return Hour;
}

int timeStamp::getMinute(){
return Minute;
}
int timeStamp::getSecond(){
return Second;
}

bool timeStamp::operator!=(timeStamp t){

    if (Second ==t.Second && Minute ==t.Minute && Hour ==t.Hour)
        return true;
    else
        return false;

}

void timeStamp::Print()
{
    std:: cout<<"Hour:"<<Hour<<"\nMinute:"<<Minute<<"\nSecond:"<<Second<<std::endl;
}
</code>```

Main:

```<code>#include <iostream>
#include "timeStamp.cpp"

using namespace std;

int main()
{
    timeStamp obj1, obj2;
    int h,m,s;

        cout<<"Give hour minute and second:";
        cin>>h>>m>>s;
        obj1.timeStamp(h,m,s); //error
        cout<<"Give H M S";
        cin>>h>>m>>s;
        obj2.timeStamp(h,m,s);

        bool isEqual = obj1 ! = obj2;
        cout<<isEqual<<endl;

}
</code>```

答:
That is not how you construct objects.

You have to give constructor arguments at the point of definition.

You can't call the constructor like a function later.

```<code>int main()
{
    int h,m,s;

    cout<<"Give hour minute and second:";
    cin>>h>>m>>s;
    timeStamp obj1(h,m,s);

    cout<<"Give H M S";
    cin>>h>>m>>s;
    timeStamp obj2(h,m,s);

    bool isEqual = obj1 ! = obj2;
    cout<<isEqual<<endl;
}
</code>```

I'm sure that your book goes into more detail about this.

Body:
Getting the error: invalid use of className::className.

Was trying to make a timeStamp class which represented a time of a day, it stores seconds, minutes, hours in specific variables. Ran into an error in line #13 on main function, the error reads: invalid use of timeStamp::timeStamp what did i do wrong?
There's a header file where all the methods are declared.

The source file cpp:

    #include "timeStamp.h"
#include <iostream>
using namespace std;

timeStamp::timeStamp()
{
    Hour = 0;
    Minute = 0;
    Second =0;
}
timeStamp::timeStamp(int h, int m, int s){

Hour = h;
Minute = m;
Second = s;

}
int timeStamp::getHour(){

return Hour;
}

int timeStamp::getMinute(){
return Minute;
}
int timeStamp::getSecond(){
return Second;
}

bool timeStamp::operator!=(timeStamp t){

    if (Second ==t.Second && Minute ==t.Minute && Hour ==t.Hour)
        return true;
    else
        return false;

}

void timeStamp::Print()
{
    std:: cout<<"Hour:"<<Hour<<"\nMinute:"<<Minute<<"\nSecond:"<<Second<<std::endl;
}

Main:

#include <iostream>
#include "timeStamp.cpp"

using namespace std;

int main()
{
    timeStamp obj1, obj2;
    int h,m,s;

        cout<<"Give hour minute and second:";
        cin>>h>>m>>s;
        obj1.timeStamp(h,m,s); //error
        cout<<"Give H M S";
        cin>>h>>m>>s;
        obj2.timeStamp(h,m,s);

        bool isEqual = obj1 ! = obj2;
        cout<<isEqual<<endl;

}

Body:
That is not how you construct objects.

You have to give constructor arguments at the point of definition.

You can't call the constructor like a function later.

int main()
{
    int h,m,s;

    cout<<"Give hour minute and second:";
    cin>>h>>m>>s;
    timeStamp obj1(h,m,s);

    cout<<"Give H M S";
    cin>>h>>m>>s;
    timeStamp obj2(h,m,s);

    bool isEqual = obj1 ! = obj2;
    cout<<isEqual<<endl;
}

I'm sure that your book goes into more detail about this.


问:
name 'item' is not defined
I have taken what was once a class project and turned it into something more usable for work. My program is designed as an inventory system. I have currently ensured that my program can export data to a text file, and import that data at request if the program is ever closed. I cannot edit the data after import unless I add new data to the list first, or add new data to the list then import.

I think the reason why it isn't working is because the data imported from the list doesn't have a logical position yet until new data is added.

```<code>class Inventory:
    def __init__(self):
        self.item = ""
        self.amount = 0
        self.asset_tag = 0
        self.notes = ""

    def add_inventory(self):
        self.item = input("Enter item: ")
        self.amount = int(input("How many? "))
        self.asset_tag = int(input("Enter Asset Tag if available. Enter 0 if not tagged. "))
        self.notes = input("Please add any additional information: ")
    def __str__(self):
        return('Item: %s Amount: %d Asset Tag: %d Notes: %s' %
               (self.item, self.amount, self.asset_tag, self.notes))

inventory_list = []

def edit(inventory_list):
    pos = int(input('Enter the position of the item you would like to edit: '))
    new_inventory = item.add_inventory()
    new_inventory = item.__str__()
    inventory_list[pos-1] = new_inventory
    print('Inventory has been updated. If the amount is now 0 please notify.')

while True:
    print("""
    1. Add new inventory.
    2. Remove item from inventory.
    3. View inventory.
    4. Update current inventory.
    5. Export inventory to file.
    6. Import Inventory file
    7. Quit
    """)
    ans = input('What would you like to do? ')
    if ans == "1":
        item = Inventory()
        item.add_inventory()
        inventory_list.append(item.__str__())
    elif ans == "2":
        for i in inventory_list:
            inventory_list.pop(int(input('Enter position of item to remove: ')))
            print('Inventory item removed successfully!')
    elif ans == "3":
        print('\n'.join(map(str, inventory_list)))
    elif ans == "4":
        edit(inventory_list)
    elif ans == "5":
        f = open('Inventory_List.txt', 'w')
        for ele in inventory_list:
            f.write(ele+'\n')
        f.close()
    elif ans == "6":
        with open('Inventory_List.txt') as f:
            data = f.read().splitlines()
            print(data)
            inventory_list.extend(data)
    elif ans == "7":
        break
    else:
        print('Invalid entry, try again.')```

```

答: item is not defined in the function edit before it gets utilized.</p>

Title: name 'item' is not defined

Body:
I have taken what was once a class project and turned it into something more usable for work. My program is designed as an inventory system. I have currently ensured that my program can export data to a text file, and import that data at request if the program is ever closed. I cannot edit the data after import unless I add new data to the list first, or add new data to the list then import.

I think the reason why it isn't working is because the data imported from the list doesn't have a logical position yet until new data is added.

class Inventory:
    def __init__(self):
        self.item = ""
        self.amount = 0
        self.asset_tag = 0
        self.notes = ""

    def add_inventory(self):
        self.item = input("Enter item: ")
        self.amount = int(input("How many? "))
        self.asset_tag = int(input("Enter Asset Tag if available. Enter 0 if not tagged. "))
        self.notes = input("Please add any additional information: ")
    def __str__(self):
        return('Item: %s Amount: %d Asset Tag: %d Notes: %s' %
               (self.item, self.amount, self.asset_tag, self.notes))

inventory_list = []

def edit(inventory_list):
    pos = int(input('Enter the position of the item you would like to edit: '))
    new_inventory = item.add_inventory()
    new_inventory = item.__str__()
    inventory_list[pos-1] = new_inventory
    print('Inventory has been updated. If the amount is now 0 please notify.')

while True:
    print("""
    1. Add new inventory.
    2. Remove item from inventory.
    3. View inventory.
    4. Update current inventory.
    5. Export inventory to file.
    6. Import Inventory file
    7. Quit
    """)
    ans = input('What would you like to do? ')
    if ans == "1":
        item = Inventory()
        item.add_inventory()
        inventory_list.append(item.__str__())
    elif ans == "2":
        for i in inventory_list:
            inventory_list.pop(int(input('Enter position of item to remove: ')))
            print('Inventory item removed successfully!')
    elif ans == "3":
        print('\n'.join(map(str, inventory_list)))
    elif ans == "4":
        edit(inventory_list)
    elif ans == "5":
        f = open('Inventory_List.txt', 'w')
        for ele in inventory_list:
            f.write(ele+'\n')
        f.close()
    elif ans == "6":
        with open('Inventory_List.txt') as f:
            data = f.read().splitlines()
            print(data)
            inventory_list.extend(data)
    elif ans == "7":
        break
    else:
        print('Invalid entry, try again.')```


问:
issues with the in statement using a subquery
Issues with this statement

```<code>    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )
</code>```

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

答:
You're over complicating things. This is a simple INNER JOIN solution. You don't need a CASE statement, just an OR in the WHERE clause.

```<code>SELECT
    t1.*
FROM table t1
INNER JOIN Tabl1 t2 ON t1.ID = t2.ID
WHERE (t2.changes = 40 AND t2.UserID = 121)
    OR t2.changes <> 40
</code>```

Body:
Issues with this statement

    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

Body:
You're over complicating things. This is a simple INNER JOIN solution. You don't need a CASE statement, just an OR in the WHERE clause.

SELECT
    t1.*
FROM table t1
INNER JOIN Tabl1 t2 ON t1.ID = t2.ID
WHERE (t2.changes = 40 AND t2.UserID = 121)
    OR t2.changes <> 40


问:
How to update loggingService of container.v1.cluster with deployment-manager
I want to set the loggingService field of an existing container.v1.cluster through deployment-manager.
I have the following config

```<code>resources:
- name: px-cluster-1
  type: container.v1.cluster
  properties:
    zone: europe-west1-b
    cluster:
      description: "dev cluster"
      initialClusterVersion: "1.13"
      nodePools:
        - name: cluster-pool
          config:
            machineType: "n1-standard-1"
            oauthScopes:
            - https://www.googleapis.com/auth/compute
            - https://www.googleapis.com/auth/devstorage.read_only
            - https://www.googleapis.com/auth/logging.write
            - https://www.googleapis.com/auth/monitoring
          management:
            autoUpgrade: true
            autoRepair: true
          initialNodeCount: 1
          autoscaling:
            enabled: true
            minNodeCount: 3
            maxNodeCount: 10
      ipAllocationPolicy:
        useIpAliases: true
      loggingService: "logging.googleapis.com/kubernetes"
      masterAuthorizedNetworksConfig:
        enabled: false
      locations:
        - "europe-west1-b"
        - "europe-west1-c"
</code>```

When I try to run gcloud deployment-manager deployments update ..., I get the following error

```<code>ERROR: (gcloud.deployment-manager.deployments.update) Error in Operation [operation-1582040492957-59edb819a5f3c-7155f798-5ba37285]: errors:
- code: NO_METHOD_TO_UPDATE_FIELD
  message: No method found to update field 'cluster' on resource 'px-cluster-1' of
    type 'container.v1.cluster'. The resource may need to be recreated with the new
    field.
</code>```

The same succeeds if I remove loggingService.

Is there a way to update loggingService using deployment-manager without deleting the cluster?

答:
The error NO_METHOD_TO_UPDATE_FIELD is due to updating "initialClusterVersion" when you issued the update call to GKE. This field is only used on creation of the cluster, and the type definition doesn't currently allow for it to be updated later. So that should remain static at the original value and will have no effect on the deployment moving forward or try to delete/comment that line.

Even when the previous entry is true, there is also no method to update the logging service, actually Deployment Manager doesn't have many update methods, so, try using the gcloud command to update the cluster directly, keep in mind that you have to use the monitoring service together with the logging service, so, the commando would look like:

gcloud container clusters update px-cluster-1 --logging-service=logging.googleapis.com/kubernetes --monitoring-service=monitoring.googleapis.com/kubernetes --zone=europe-west1-b

Body:
I want to set the loggingService field of an existing container.v1.cluster through deployment-manager.
I have the following config

resources:
- name: px-cluster-1
  type: container.v1.cluster
  properties:
    zone: europe-west1-b
    cluster:
      description: "dev cluster"
      initialClusterVersion: "1.13"
      nodePools:
        - name: cluster-pool
          config:
            machineType: "n1-standard-1"
            oauthScopes:
            - https://www.googleapis.com/auth/compute
            - https://www.googleapis.com/auth/devstorage.read_only
            - https://www.googleapis.com/auth/logging.write
            - https://www.googleapis.com/auth/monitoring
          management:
            autoUpgrade: true
            autoRepair: true
          initialNodeCount: 1
          autoscaling:
            enabled: true
            minNodeCount: 3
            maxNodeCount: 10
      ipAllocationPolicy:
        useIpAliases: true
      loggingService: "logging.googleapis.com/kubernetes"
      masterAuthorizedNetworksConfig:
        enabled: false
      locations:
        - "europe-west1-b"
        - "europe-west1-c"

When I try to run gcloud deployment-manager deployments update ..., I get the following error

ERROR: (gcloud.deployment-manager.deployments.update) Error in Operation [operation-1582040492957-59edb819a5f3c-7155f798-5ba37285]: errors:
- code: NO_METHOD_TO_UPDATE_FIELD
  message: No method found to update field 'cluster' on resource 'px-cluster-1' of
    type 'container.v1.cluster'. The resource may need to be recreated with the new
    field.

The same succeeds if I remove loggingService.

Is there a way to update loggingService using deployment-manager without deleting the cluster?


问:
Excel VBA - Convert existing image in cell to comment picture
I'm trying to use VBA in Excel to convert a bunch of pictures in a column (one per cell) to a pop up comment image instead so that the sheet is more easily readable.
I can find the image I need by iterating through the shapes, and I can set this as an object; but I can't seem to use that onject to populate the comment field. It seems to be looking for a true file path instead.

I don't particularly want to have to save each image and then reload it, seems kind of pointless.

```<code> For Each Pic In ActiveSheet.Shapes
    If Pic.TopLeftCell.Address = ActiveCell.Address Then
      If Pic.Type = msoPicture Then
        Pic.Select
        Application.ActiveCell.AddComment.Shape.Fill.UserPicture **(ActiveSheet.Shapes(Pic.name))** 'if I use a path here its okay
        'SelectPictureAtActiveCell = name
        Exit For
      End If
    End If
   Next
</code>```

any thoughts?

CJ

答:
I think you want to show one image if you select a specific cell then

See

Making shapes invisible/visible in excel through VBA

with

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Macro1
End Sub
</code>```

You can make images hide and show  using
ActiveSheet.Shapes("ImageName").Visible = False or True

for example when you click on cell A1 first image is hidden else all images are visible

```<code>Sub Macro1()

Dim shp As Shape

If ActiveCell.Address = "$A$1" Then
For Each shp In ActiveSheet.Shapes
ActiveSheet.Shapes(1).Visible = False
' or you can use image name as
'ActiveSheet.Shapes("ImageName").Visible = False
'shp.Visible = False
Next
Else
For Each shp In ActiveSheet.Shapes
shp.Visible = True
Next
End If
End Sub
</code>```

Body:
I'm trying to use VBA in Excel to convert a bunch of pictures in a column (one per cell) to a pop up comment image instead so that the sheet is more easily readable.
I can find the image I need by iterating through the shapes, and I can set this as an object; but I can't seem to use that onject to populate the comment field. It seems to be looking for a true file path instead.

I don't particularly want to have to save each image and then reload it, seems kind of pointless.

 For Each Pic In ActiveSheet.Shapes
    If Pic.TopLeftCell.Address = ActiveCell.Address Then
      If Pic.Type = msoPicture Then
        Pic.Select
        Application.ActiveCell.AddComment.Shape.Fill.UserPicture **(ActiveSheet.Shapes(Pic.name))** 'if I use a path here its okay
        'SelectPictureAtActiveCell = name
        Exit For
      End If
    End If
   Next

any thoughts?

CJ

Body:
I think you want to show one image if you select a specific cell then

See

Making shapes invisible/visible in excel through VBA

with

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Macro1
End Sub

You can make images hide and show  using
ActiveSheet.Shapes("ImageName").Visible = False or True

for example when you click on cell A1 first image is hidden else all images are visible

Sub Macro1()

Dim shp As Shape

If ActiveCell.Address = "$A$1" Then
For Each shp In ActiveSheet.Shapes
ActiveSheet.Shapes(1).Visible = False
' or you can use image name as
'ActiveSheet.Shapes("ImageName").Visible = False
'shp.Visible = False
Next
Else
For Each shp In ActiveSheet.Shapes
shp.Visible = True
Next
End If
End Sub


问:
Django does not store password in database
When i print my password from view it shows non in my command prompt
i am using only password1 in forms.py
i put pass2=none

Models.py:-

```<code>class Profile(models.Model):
            user = models.OneToOneField(User, on_delete=models.CASCADE)
            bio = models.TextField(max_length=500, blank=True)
            location = models.CharField(max_length=30, blank=True)
            birth_date = models.DateField(null=True, blank=True)
            gender = models.CharField(max_length=10,blank=True)

            def __str__(self):
                return self.fullname
</code>```

Forms.py:-

```<code>class UserForm(forms.ModelForm):
            username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'}))
            password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'}))
            email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'}))
    password2=None

            class Meta:
                model=User
                fields=['username','password1','email']

        class ProfileForm(forms.ModelForm):
            fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'}))
            class Meta:
                model=Profile
                fields=['fullname']
</code>```

views.py:-

```<code>def register(request):
        if request.method =='POST':
            form = UserForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if form.is_valid() and profile_form.is_valid():
                user=form.save()
                profile=profile_form.save(commit=False)
                profile.user=user
                profile.save()
                username= form.cleaned_data.get('username')
                password= form.cleaned_data.get('password')
                print(username)
                print(password)
                messages.success(request,f'account created for {{ username }}')
                return redirect('home')
        else:
            form = UserForm()
            profile_form = ProfileForm()
        context={'form':form , 'profile_form':profile_form}
        return render(request, 'users/register.html',context)
</code>```

**When i print my password in viws it shows None.also i am using only password1 **

答:
The problem is your UserForm.

It is requiring the fields: ['username','password1','email']
from the User model, as if they existed.

The User model does NOT have a field called "password1". It does have a "password" field.

So if you change the fields in your UserForm Meta class to ['username','password','email'] and change the UserForm "password1" field as well it will work.

Now when you save the valid form, it will actually pass a field ("password") to the User model which it needs in order to generate your hashed password.

Body:
When i print my password from view it shows non in my command prompt
i am using only password1 in forms.py
i put pass2=none

Models.py:-

class Profile(models.Model):
            user = models.OneToOneField(User, on_delete=models.CASCADE)
            bio = models.TextField(max_length=500, blank=True)
            location = models.CharField(max_length=30, blank=True)
            birth_date = models.DateField(null=True, blank=True)
            gender = models.CharField(max_length=10,blank=True)

            def __str__(self):
                return self.fullname

Forms.py:-

class UserForm(forms.ModelForm):
            username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'}))
            password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'}))
            email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'}))
    password2=None

            class Meta:
                model=User
                fields=['username','password1','email']

        class ProfileForm(forms.ModelForm):
            fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'}))
            class Meta:
                model=Profile
                fields=['fullname']

views.py:-

def register(request):
        if request.method =='POST':
            form = UserForm(request.POST)
            profile_form = ProfileForm(request.POST)
            if form.is_valid() and profile_form.is_valid():
                user=form.save()
                profile=profile_form.save(commit=False)
                profile.user=user
                profile.save()
                username= form.cleaned_data.get('username')
                password= form.cleaned_data.get('password')
                print(username)
                print(password)
                messages.success(request,f'account created for {{ username }}')
                return redirect('home')
        else:
            form = UserForm()
            profile_form = ProfileForm()
        context={'form':form , 'profile_form':profile_form}
        return render(request, 'users/register.html',context)

**When i print my password in viws it shows None.also i am using only password1 **