问:
Dataflow fails when I add requirements.txt [Python]
So when I try to run dataflow with the DataflowRunner and include the requirements.txt which looks like this

```<code>google-cloud-storage==1.28.1
pandas==1.0.3
smart-open==2.0.0
</code>```

Every time it fails on this line

```<code>INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://..../beamapp-.../numpy-1.18.2.zip...
Traceback (most recent call last):
File "Database.py", line 107, in <module>
run()
File "Database.py", line 101, in run
| 'Write CSV' >> beam.ParDo(WriteCSVFIle(options.output_bucket,
pandora_options.output_folder))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 503, in __exit__
    self.run().wait_until_finish()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 483, in run
    self._options).run(False)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 496, in run
    return self.runner.run_pipeline(self, self._options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 548, in run_pipeline
    self.dataflow_client.create_job(self.job), self)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 624, in create_job
    self.create_job_description(job)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 680, in create_job_description
    resources = self._stage_resources(job.options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 577, in _stage_resources
    staging_location=google_cloud_options.staging_location)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/portability/stager.py", line 182, in stage_job_resources
    pkg, FileSystems.join(staging_location, os.path.basename(pkg)))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 942, in stage_artifact
    local_path_to_artifact, artifact_name)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 564, in _gcs_file_copy
    self.stage_file(to_folder, to_name, f, total_size=total_size)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 602, in stage_file
    response = self._storage_client.objects.Insert(request, upload=upload)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1156, in Insert
    upload=upload, upload_config=upload_config)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/base_api.py", line 715, in _RunMethod
    http_request, client=self.client)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 908, in InitializeUpload
    return self.StreamInChunks()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1020, in StreamInChunks
    additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 957, in __StreamMedia
    response = send_func(self.stream.tell())
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 943, in CallSendChunk
    start, additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1120, in __SendChunk
    return self.__SendMediaRequest(request, end)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1033, in __SendMediaRequest
    retries=self.num_retries, check_response_func=CheckResponse)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 356, in MakeRequest
    max_retry_wait, total_wait_sec))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 304, in HandleExceptionsAndRebuildHttpConnections
    raise retry_args.exc
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 346, in MakeRequest
    check_response_func=check_response_func)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 396, in _MakeRequestNoRetry
    redirections=redirections, connection_type=connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1991, in request
    cachekey,
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1690, in _request
    content,
httplib2.RedirectMissingLocation: Redirected but the response is missing a Location: header.
</code>```

This is the command I'm running

```<code>python Database.py
--runner DataflowRunner
--project XXX
--staging_location gs://.../staging
--temp_location gs://.../temp
--template_location gs://.../Template
--requirements_file requirements.txt
</code>```

if I remove the --requirements_file requirements.txt it finishes but when I try to run the job it fails because it can't find the packages.

I'm using cloud-storage to list all the files from a bucket so if you have another solution which doesn't involve cloud-storage it would be much appreciated

This is my dataflow-requirements-cache folder. Before cleaning it up I had multiple files with different versions e.g.

```<code>botocore-1.16.16.tar.gz
botocore-1.16.17.tar.gz
botocore-1.16.18.tar.gz
</code>```

After I cleaned it up it looks like this, (it still failed while trying to upload numpy)

```<code>numpy-1.18.4.zip
urllib3-1.25.9.tar.gz
smart_open-2.0.0.tar.gz
six-1.15.0.tar.gz
setuptools-47.1.0.zip
s3transfer-0.3.3.tar.gz
rsa-4.0.tar.gz
requests-2.23.0.tar.gz
pytz-2020.1.tar.gz
python-dateutil-2.8.1.tar.gz
pyasn1-modules-0.2.8.tar.gz
pyasn1-0.4.8.tar.gz
protobuf-3.12.2.tar.gz
pandas-1.0.3.tar.gz
jmespath-0.10.0.tar.gz
idna-2.9.tar.gz
googleapis-common-protos-1.51.0.tar.gz
google-resumable-media-0.5.0.tar.gz
google-cloud-storage-1.28.1.tar.gz
google-cloud-core-1.3.0.tar.gz
google-auth-1.15.0.tar.gz
google-api-core-1.17.0.tar.gz
docutils-0.15.2.tar.gz
chardet-3.0.4.tar.gz
certifi-2020.4.5.1.tar.gz
cachetools-4.1.0.tar.gz
botocore-1.16.18.tar.gz
boto3-1.13.18.tar.gz
boto-2.49.0.tar.gz
</code>```

---- EDIT ----
The full output

```<code>(airflow) afragotsis-mac:pandora_database afragotsis$ python PandoraDatabase.py \
>     --runner DataflowRunner \
>     --project XXX \
>     --staging_location gs://.../dataflow-template/PandoraDatabase/staging \
>     --temp_location gs://.../dataflow-template/PandoraDatabase/temp \
>     --template_location gs://.../dataflow-template/PandoraDatabase/pandoraTemplate \
>     --requirements_file requirements.txt \
>     --save_main_session True
WARNING:apache_beam.options.pipeline_options:--region not set; will default to us-central1. Future releases of Beam will require the user to set --region explicitly, or else have a default set via the gcloud tool. https://cloud.google.com/compute/docs/regions-zones
INFO:apache_beam.internal.gcp.auth:Setting socket default timeout to 60 seconds.
INFO:apache_beam.internal.gcp.auth:socket default timeout is 60.0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pipeline.pb...
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pipeline.pb in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/requirements.txt...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/requirements.txt in 0 seconds.
INFO:apache_beam.runners.portability.stager:Executing command: ['/Users/afragotsis/opt/anaconda3/envs/airflow/bin/python', '-m', 'pip', 'download', '--dest', '/var/folders/zj/dqg766ks0cx663lg7brll7b80000gn/T/dataflow-requirements-cache', '-r', 'requirements.txt', '--exists-action', 'i', '--no-binary', ':all:']
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/rsa-4.0.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/rsa-4.0.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/urllib3-1.25.9.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/urllib3-1.25.9.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/boto3-1.13.19.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/boto3-1.13.19.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pyasn1-modules-0.2.8.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pyasn1-modules-0.2.8.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/numpy-1.18.4.zip...
Traceback (most recent call last):
  File "PandoraDatabase.py", line 125, in <module>
    run()
  File "PandoraDatabase.py", line 119, in run
    | 'Write CSV' >> beam.ParDo(WriteCSVFIle(pandora_options.output_bucket, pandora_options.output_folder))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 503, in __exit__
    self.run().wait_until_finish()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 483, in run
    self._options).run(False)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 496, in run
    return self.runner.run_pipeline(self, self._options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 548, in run_pipeline
    self.dataflow_client.create_job(self.job), self)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 624, in create_job
    self.create_job_description(job)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 680, in create_job_description
    resources = self._stage_resources(job.options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 577, in _stage_resources
    staging_location=google_cloud_options.staging_location)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/portability/stager.py", line 182, in stage_job_resources
    pkg, FileSystems.join(staging_location, os.path.basename(pkg)))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 942, in stage_artifact
    local_path_to_artifact, artifact_name)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 564, in _gcs_file_copy
    self.stage_file(to_folder, to_name, f, total_size=total_size)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 602, in stage_file
    response = self._storage_client.objects.Insert(request, upload=upload)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1156, in Insert
    upload=upload, upload_config=upload_config)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/base_api.py", line 715, in _RunMethod
    http_request, client=self.client)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 908, in InitializeUpload
    return self.StreamInChunks()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1020, in StreamInChunks
    additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 957, in __StreamMedia
    response = send_func(self.stream.tell())
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 943, in CallSendChunk
    start, additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1120, in __SendChunk
    return self.__SendMediaRequest(request, end)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1033, in __SendMediaRequest
    retries=self.num_retries, check_response_func=CheckResponse)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 356, in MakeRequest
    max_retry_wait, total_wait_sec))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 304, in HandleExceptionsAndRebuildHttpConnections
    raise retry_args.exc
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 346, in MakeRequest
    check_response_func=check_response_func)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 396, in _MakeRequestNoRetry
    redirections=redirections, connection_type=connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1991, in request
    cachekey,
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1690, in _request
    content,
httplib2.RedirectMissingLocation: Redirected but the response is missing a Location: header.
</code>```

the full path of the dataflow-requirements-cache

```<code>/private/var/folders/zj/dqg766ks0cx663lg7brll7b80000gn/T/dataflow-requirements-cache
</code>```

it always fails when it tries to upload numpy

答:
A quick search turns up this related question: GCloud Upload httplib2.RedirectMissingLocation: Redirected but the response is missing a Location: header

You may be affected by https://github.com/googleapis/google-api-python-client/issues/803. A workaround appears to be to adjust the httplib2 version.

Body:
So when I try to run dataflow with the DataflowRunner and include the requirements.txt which looks like this

google-cloud-storage==1.28.1
pandas==1.0.3
smart-open==2.0.0

Every time it fails on this line

INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://..../beamapp-.../numpy-1.18.2.zip...
Traceback (most recent call last):
File "Database.py", line 107, in <module>
run()
File "Database.py", line 101, in run
| 'Write CSV' >> beam.ParDo(WriteCSVFIle(options.output_bucket,
pandora_options.output_folder))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 503, in __exit__
    self.run().wait_until_finish()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 483, in run
    self._options).run(False)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 496, in run
    return self.runner.run_pipeline(self, self._options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 548, in run_pipeline
    self.dataflow_client.create_job(self.job), self)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 624, in create_job
    self.create_job_description(job)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 680, in create_job_description
    resources = self._stage_resources(job.options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 577, in _stage_resources
    staging_location=google_cloud_options.staging_location)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/portability/stager.py", line 182, in stage_job_resources
    pkg, FileSystems.join(staging_location, os.path.basename(pkg)))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 942, in stage_artifact
    local_path_to_artifact, artifact_name)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 564, in _gcs_file_copy
    self.stage_file(to_folder, to_name, f, total_size=total_size)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 602, in stage_file
    response = self._storage_client.objects.Insert(request, upload=upload)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1156, in Insert
    upload=upload, upload_config=upload_config)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/base_api.py", line 715, in _RunMethod
    http_request, client=self.client)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 908, in InitializeUpload
    return self.StreamInChunks()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1020, in StreamInChunks
    additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 957, in __StreamMedia
    response = send_func(self.stream.tell())
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 943, in CallSendChunk
    start, additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1120, in __SendChunk
    return self.__SendMediaRequest(request, end)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1033, in __SendMediaRequest
    retries=self.num_retries, check_response_func=CheckResponse)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 356, in MakeRequest
    max_retry_wait, total_wait_sec))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 304, in HandleExceptionsAndRebuildHttpConnections
    raise retry_args.exc
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 346, in MakeRequest
    check_response_func=check_response_func)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 396, in _MakeRequestNoRetry
    redirections=redirections, connection_type=connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1991, in request
    cachekey,
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1690, in _request
    content,
httplib2.RedirectMissingLocation: Redirected but the response is missing a Location: header.

This is the command I'm running

python Database.py
--runner DataflowRunner
--project XXX
--staging_location gs://.../staging
--temp_location gs://.../temp
--template_location gs://.../Template
--requirements_file requirements.txt

if I remove the --requirements_file requirements.txt it finishes but when I try to run the job it fails because it can't find the packages.

I'm using cloud-storage to list all the files from a bucket so if you have another solution which doesn't involve cloud-storage it would be much appreciated

This is my dataflow-requirements-cache folder. Before cleaning it up I had multiple files with different versions e.g.

botocore-1.16.16.tar.gz
botocore-1.16.17.tar.gz
botocore-1.16.18.tar.gz

After I cleaned it up it looks like this, (it still failed while trying to upload numpy)

numpy-1.18.4.zip
urllib3-1.25.9.tar.gz
smart_open-2.0.0.tar.gz
six-1.15.0.tar.gz
setuptools-47.1.0.zip
s3transfer-0.3.3.tar.gz
rsa-4.0.tar.gz
requests-2.23.0.tar.gz
pytz-2020.1.tar.gz
python-dateutil-2.8.1.tar.gz
pyasn1-modules-0.2.8.tar.gz
pyasn1-0.4.8.tar.gz
protobuf-3.12.2.tar.gz
pandas-1.0.3.tar.gz
jmespath-0.10.0.tar.gz
idna-2.9.tar.gz
googleapis-common-protos-1.51.0.tar.gz
google-resumable-media-0.5.0.tar.gz
google-cloud-storage-1.28.1.tar.gz
google-cloud-core-1.3.0.tar.gz
google-auth-1.15.0.tar.gz
google-api-core-1.17.0.tar.gz
docutils-0.15.2.tar.gz
chardet-3.0.4.tar.gz
certifi-2020.4.5.1.tar.gz
cachetools-4.1.0.tar.gz
botocore-1.16.18.tar.gz
boto3-1.13.18.tar.gz
boto-2.49.0.tar.gz

---- EDIT ----
The full output

(airflow) afragotsis-mac:pandora_database afragotsis$ python PandoraDatabase.py \
>     --runner DataflowRunner \
>     --project XXX \
>     --staging_location gs://.../dataflow-template/PandoraDatabase/staging \
>     --temp_location gs://.../dataflow-template/PandoraDatabase/temp \
>     --template_location gs://.../dataflow-template/PandoraDatabase/pandoraTemplate \
>     --requirements_file requirements.txt \
>     --save_main_session True
WARNING:apache_beam.options.pipeline_options:--region not set; will default to us-central1. Future releases of Beam will require the user to set --region explicitly, or else have a default set via the gcloud tool. https://cloud.google.com/compute/docs/regions-zones
INFO:apache_beam.internal.gcp.auth:Setting socket default timeout to 60 seconds.
INFO:apache_beam.internal.gcp.auth:socket default timeout is 60.0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pipeline.pb...
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pipeline.pb in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/requirements.txt...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/requirements.txt in 0 seconds.
INFO:apache_beam.runners.portability.stager:Executing command: ['/Users/afragotsis/opt/anaconda3/envs/airflow/bin/python', '-m', 'pip', 'download', '--dest', '/var/folders/zj/dqg766ks0cx663lg7brll7b80000gn/T/dataflow-requirements-cache', '-r', 'requirements.txt', '--exists-action', 'i', '--no-binary', ':all:']
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/rsa-4.0.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/rsa-4.0.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/urllib3-1.25.9.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/urllib3-1.25.9.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/boto3-1.13.19.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/boto3-1.13.19.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pyasn1-modules-0.2.8.tar.gz...
INFO:apache_beam.runners.dataflow.internal.apiclient:Completed GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/pyasn1-modules-0.2.8.tar.gz in 0 seconds.
INFO:apache_beam.runners.dataflow.internal.apiclient:Starting GCS upload to gs://.../dataflow-template/PandoraDatabase/staging/beamapp-afragotsis-0529200636-871276.1590782796.871390/numpy-1.18.4.zip...
Traceback (most recent call last):
  File "PandoraDatabase.py", line 125, in <module>
    run()
  File "PandoraDatabase.py", line 119, in run
    | 'Write CSV' >> beam.ParDo(WriteCSVFIle(pandora_options.output_bucket, pandora_options.output_folder))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 503, in __exit__
    self.run().wait_until_finish()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 483, in run
    self._options).run(False)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/pipeline.py", line 496, in run
    return self.runner.run_pipeline(self, self._options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 548, in run_pipeline
    self.dataflow_client.create_job(self.job), self)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 624, in create_job
    self.create_job_description(job)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 680, in create_job_description
    resources = self._stage_resources(job.options)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 577, in _stage_resources
    staging_location=google_cloud_options.staging_location)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/portability/stager.py", line 182, in stage_job_resources
    pkg, FileSystems.join(staging_location, os.path.basename(pkg)))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 942, in stage_artifact
    local_path_to_artifact, artifact_name)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/utils/retry.py", line 234, in wrapper
    return fun(*args, **kwargs)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 564, in _gcs_file_copy
    self.stage_file(to_folder, to_name, f, total_size=total_size)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 602, in stage_file
    response = self._storage_client.objects.Insert(request, upload=upload)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apache_beam/io/gcp/internal/clients/storage/storage_v1_client.py", line 1156, in Insert
    upload=upload, upload_config=upload_config)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/base_api.py", line 715, in _RunMethod
    http_request, client=self.client)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 908, in InitializeUpload
    return self.StreamInChunks()
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1020, in StreamInChunks
    additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 957, in __StreamMedia
    response = send_func(self.stream.tell())
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 943, in CallSendChunk
    start, additional_headers=additional_headers)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1120, in __SendChunk
    return self.__SendMediaRequest(request, end)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/transfer.py", line 1033, in __SendMediaRequest
    retries=self.num_retries, check_response_func=CheckResponse)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 356, in MakeRequest
    max_retry_wait, total_wait_sec))
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 304, in HandleExceptionsAndRebuildHttpConnections
    raise retry_args.exc
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 346, in MakeRequest
    check_response_func=check_response_func)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/apitools/base/py/http_wrapper.py", line 396, in _MakeRequestNoRetry
    redirections=redirections, connection_type=connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/oauth2client/transport.py", line 169, in new_request
    redirections, connection_type)
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1991, in request
    cachekey,
  File "/Users/afragotsis/opt/anaconda3/envs/airflow/lib/python3.7/site-packages/httplib2/__init__.py", line 1690, in _request
    content,
httplib2.RedirectMissingLocation: Redirected but the response is missing a Location: header.

the full path of the dataflow-requirements-cache

/private/var/folders/zj/dqg766ks0cx663lg7brll7b80000gn/T/dataflow-requirements-cache

it always fails when it tries to upload numpy


来源: stackexchange

问:
If bitwise OR operator is used twice between two number. How will that work?
```<code>#include <stdio.h>
int main()
{
    int a = 60; // 0011 1100
    int b = 13; // 0000 1101
    int c = 0;
    c = a || b;
    printf("%d",c);
    return 0;
}
</code>```

The output for my code is 1. Can anyone explain how that worked?

答:
In this statement

```<code> c = a || b; // 0011 1101
</code>```

there is used the logical OR operator || that yields 1 if either of operands is unequal to 0.

From the C Standard (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare
  unequal to 0; otherwise, it yields 0. The result has type int.

The bitwise inclusive OR operator | is written like

```<code> c = a | b; // 0011 1101
</code>```

If you will write like

```<code> c = a | | b;
</code>```

with a blank between the symbols '|' then the compiler will issue an error. You may not use such a way any binary operator because such an operator expects operands on the left and the right sides of the operator.

Of course, if you will write for example like

```<code>c = a + + b;
</code>```

then there is the first operator + is the binary plus and the second operator +  is the unary plus operator. That is there is no two consecutive binary operators +.

You should not mix logical operators || and && with bitwise operators | and &.

ContentLicense: CC BY-SA 4.0

Body:
#include <stdio.h>
int main()
{
    int a = 60; // 0011 1100
    int b = 13; // 0000 1101
    int c = 0;
    c = a || b;
    printf("%d",c);
    return 0;
}

The output for my code is 1. Can anyone explain how that worked?

Body:
In this statement

 c = a || b; // 0011 1101

there is used the logical OR operator || that yields 1 if either of operands is unequal to 0.

From the C Standard (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare
  unequal to 0; otherwise, it yields 0. The result has type int.

The bitwise inclusive OR operator | is written like

 c = a | b; // 0011 1101

If you will write like

 c = a | | b;

with a blank between the symbols '|' then the compiler will issue an error. You may not use such a way any binary operator because such an operator expects operands on the left and the right sides of the operator.

Of course, if you will write for example like

c = a + + b;

then there is the first operator + is the binary plus and the second operator +  is the unary plus operator. That is there is no two consecutive binary operators +.

You should not mix logical operators || and && with bitwise operators | and &.


问:
Using JavaScript's Document.write() to create a HTML link
I have an URL stored in a variable (var URL).

I thought this would work:

```<code>document.write("<a href='"+url+"'>LINK</a>");

</code>```

But it isn't! Any solution??

This is exactly what I'm trying to do:

```<code>         <script>

          var url2="https://wa.me/(phonenumber)/?text=";
          var url3="<data:post.title/>";
          var url4=url2+url3;
          var url5="<a href='"+url4+"'>ORDER VIA WHATSAPP</a>";
          document.write(url5);

              </script>
</code>```

(EDIT: IT'S WORKING NOW. SOLVED!)

答:
use    document.write have
it is not Good beacuse it delete all the contents inside the calling element
so use innerHTML or insertAdjacentHTML instead or create the link like this

```<code> let a = document.createElement('a');
 a.href = '#';
</code>```

Body:
I have an URL stored in a variable (var URL).

I thought this would work:

document.write("LINK");

But it isn't! Any solution??

This is exactly what I'm trying to do:

(EDIT: IT'S WORKING NOW. SOLVED!)

Body:
use    document.write have
it is not Good beacuse it delete all the contents inside the calling element
so use innerHTML or insertAdjacentHTML instead or create the link like this

 let a = document.createElement('a');
 a.href = '#';


问:
Pymongo query on datetime key returns mongo query operator and huge int
I am writing this query;

```<code>end = dt.datetime.today()
start = end - dt.timedelta(7)

query = collection.find({'date' : {'$gt': start, '$lt' : end}},
                       {'_id' : 1, 'name' : 1, 'date_created' : 1})
docs = json.loads(dumps(query))
</code>```

I am querying using pymongo on a datetime object and converting from bytes to json using bson. What I get back is a document that instead of having a datetime object, it looks like this;

```<code>{'_id' : 0, 'name' : 'Brand CN Homepage (Desktop)', 'date' : {'$date' : 1590537600000}}
</code>```

When I try to convert that huge integer, I get;

```<code>OverflowError: Python int too large to convert to C long
</code>```

the date key, value should look like this;

```<code>{'date' : datetime.datetime(2020, 4, 3, 0, 0)}
</code>```

Is there a way I can get back a datetime object and not a massive integer?

答:
'date' : {'$date' : 1590537600000}

This is an extended json representation of a timestamp, documented here. To load extended json, use json_util rather than the standard library json module.

Body:
I am writing this query;

end = dt.datetime.today()
start = end - dt.timedelta(7)

query = collection.find({'date' : {'$gt': start, '$lt' : end}},
                       {'_id' : 1, 'name' : 1, 'date_created' : 1})
docs = json.loads(dumps(query))

I am querying using pymongo on a datetime object and converting from bytes to json using bson. What I get back is a document that instead of having a datetime object, it looks like this;

{'_id' : 0, 'name' : 'Brand CN Homepage (Desktop)', 'date' : {'$date' : 1590537600000}}

When I try to convert that huge integer, I get;

OverflowError: Python int too large to convert to C long

the date key, value should look like this;

{'date' : datetime.datetime(2020, 4, 3, 0, 0)}

Is there a way I can get back a datetime object and not a massive integer?


问:
Duplicate Nodes with different input
Background info.  I'm writing an XSL file to take an XML sent to the server by an analytical instrument and translate that file into an XML file accepted by our LIMS system.

Here is a Simple XML file coming from the instrument:

```<code><dataRoot>
<dataRow>
<a0>2020-05-29 10:48:09 UTC-4</a0>
<a1>MSA - Conc.(Bench)</a1>
<a2>WHC202005270038</a2>
<a3>00251832</a3>
<a4>1.15966</a4>
<a5>MSA</a5>
<a6>101.067</a6>
</dataRow>
</dataRoot>
</code>```

Here is what I have so far for the XSL File:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0"/>

<xsl:template match="/dataRoot">

<INBOUND>
    <xsl:call-template name="A"/>
    <xsl:copy-of select="A" />
</INBOUND>

</xsl:template>

<xsl:template match="/dataRow" name="A">
    <xsl:for-each select="dataRow">
            <xsl:variable name="sSampleID" select="normalize-space(a2)" />
            <xsl:variable name="sSubmitter">AutoT_EQ00004</xsl:variable>
            <xsl:variable name="sEnteredBy">EQ00004</xsl:variable>
            <!-- Use a variable for OWNER, so that only one spot needs changing if a different value is desired -->
            <xsl:variable name="sOwner">WHC</xsl:variable>
                <xsl:variable name="sParameter" select="normalize-space(a5)" />
                <xsl:variable name="sParamName"> <!-- Parameter names mapping for import to LIMS-->
                <xsl:call-template name="ConvertPaName">
                    <xsl:with-param name="sPaName" select="$sParameter" />
                </xsl:call-template>
                </xsl:variable>
                <xsl:variable name="sResult" select="normalize-space(a6)" />
                <xsl:for-each select="$sParamName">

                                <INBOX_SAMPLE>
                                    <EVENT>1</EVENT>
                                    <SAMPLE_ID><xsl:value-of select="$sSampleID"/></SAMPLE_ID>
                                    <SUBMITTER><xsl:value-of select="$sSubmitter" /></SUBMITTER>
                                    <ENTERED_BY><xsl:value-of select="$sEnteredBy" /></ENTERED_BY>
                                    <OWNER><xsl:value-of select="$sOwner" /></OWNER>
                                    <PARAMETER_NAME><xsl:value-of select="$sParamName"/></PARAMETER_NAME>
                                    <SRESULT><xsl:value-of select="$sResult"/></SRESULT>
                                </INBOX_SAMPLE>
                </xsl:for-each>
    </xsl:for-each>
</xsl:template>

<!-- Convert PaNames as needed, and skip processing certain values that are not actual Parameters (ie: 'Application') -->
<xsl:template name="ConvertPaName">
    <xsl:param name="sPaName" />
    <xsl:choose>
        <xsl:when test="$sPaName='MSA'">MSA - Conc.(Bench)</xsl:when>
        <xsl:when test="$sPaName='MSA'">Free MSA</xsl:when>
        <xsl:otherwise>Halt_Import</xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Here is the output of current translation:

```<code><INBOUND>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>MSA - Conc.(Bench)</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
</INBOUND>
</code>```

What I need to do is to duplicate this node for both parameter names:

```<code><xsl:when test="$sPaName='MSA'">MSA - Conc.(Bench)</xsl:when>
<xsl:when test="$sPaName='MSA'">Free MSA</xsl:when>
</code>```

So that my output becomes:

```<code><INBOUND>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>MSA - Conc.(Bench)</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>Free MSA</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
</INBOUND>
</code>```

This is because instrument sends one parameter name like "MSA" but in our LIMS we have it under either "Free MSA" or "MSA - Conc.(Bench)" and I need to be able to provide the result for both possible parameter names and LIMS will insert the one that it find a match for.

Thank you so much in advanced :)

答:
Add parm elements to template.

```<code><xsl:template name="ConvertPaName">
    <xsl:param name="sPaName" />
    <xsl:choose>
        <xsl:when test="$sPaName='MSA'">
          <parm>MSA - Conc.(Bench)</parm>
          <parm>Free MSA</parm>
        </xsl:when>
        <xsl:otherwise>
          <parm>Halt_Import</parm>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

Call your template

```<code><xsl:variable name="sParamName">
  <xsl:call-template name="ConvertPaName">
    <xsl:with-param name="sPaName" select="$sParameter" />
   </xsl:call-template>
</xsl:variable>
</code>```

Convert to node set:  (However you do it.  You currently don't have the msxml namespace set up.)

```<code><xsl:variable name="sParamNameList" select="msxml:node-set($sParamName)">
</code>```

Then use the parm list in your for-each loop.

```<code><xsl:for-each select="$sParamNameList/parm">
</code>```

Title: Duplicate Nodes with different input

Body:
Background info.  I'm writing an XSL file to take an XML sent to the server by an analytical instrument and translate that file into an XML file accepted by our LIMS system.

Here is a Simple XML file coming from the instrument:

<dataRoot>
<dataRow>
<a0>2020-05-29 10:48:09 UTC-4</a0>
<a1>MSA - Conc.(Bench)</a1>
<a2>WHC202005270038</a2>
<a3>00251832</a3>
<a4>1.15966</a4>
<a5>MSA</a5>
<a6>101.067</a6>
</dataRow>
</dataRoot>

Here is what I have so far for the XSL File:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0"/>

<xsl:template match="/dataRoot">

<INBOUND>
    <xsl:call-template name="A"/>
    <xsl:copy-of select="A" />
</INBOUND>

</xsl:template>

<xsl:template match="/dataRow" name="A">
    <xsl:for-each select="dataRow">
            <xsl:variable name="sSampleID" select="normalize-space(a2)" />
            <xsl:variable name="sSubmitter">AutoT_EQ00004</xsl:variable>
            <xsl:variable name="sEnteredBy">EQ00004</xsl:variable>

            <xsl:variable name="sOwner">WHC</xsl:variable>
                <xsl:variable name="sParameter" select="normalize-space(a5)" />
                <xsl:variable name="sParamName">
                <xsl:call-template name="ConvertPaName">
                    <xsl:with-param name="sPaName" select="$sParameter" />
                </xsl:call-template>
                </xsl:variable>
                <xsl:variable name="sResult" select="normalize-space(a6)" />
                <xsl:for-each select="$sParamName">

                                <INBOX_SAMPLE>
                                    <EVENT>1</EVENT>
                                    <SAMPLE_ID><xsl:value-of select="$sSampleID"/></SAMPLE_ID>
                                    <SUBMITTER><xsl:value-of select="$sSubmitter" /></SUBMITTER>
                                    <ENTERED_BY><xsl:value-of select="$sEnteredBy" /></ENTERED_BY>
                                    <OWNER><xsl:value-of select="$sOwner" /></OWNER>
                                    <PARAMETER_NAME><xsl:value-of select="$sParamName"/></PARAMETER_NAME>
                                    <SRESULT><xsl:value-of select="$sResult"/></SRESULT>
                                </INBOX_SAMPLE>
                </xsl:for-each>
    </xsl:for-each>
</xsl:template>

<xsl:template name="ConvertPaName">
    <xsl:param name="sPaName" />
    <xsl:choose>
        <xsl:when test="$sPaName='MSA'">MSA - Conc.(Bench)</xsl:when>
        <xsl:when test="$sPaName='MSA'">Free MSA</xsl:when>
        <xsl:otherwise>Halt_Import</xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

Here is the output of current translation:

<INBOUND>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>MSA - Conc.(Bench)</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
</INBOUND>

What I need to do is to duplicate this node for both parameter names:

<xsl:when test="$sPaName='MSA'">MSA - Conc.(Bench)</xsl:when>
<xsl:when test="$sPaName='MSA'">Free MSA</xsl:when>

So that my output becomes:

<INBOUND>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>MSA - Conc.(Bench)</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
   <INBOX_SAMPLE>
      <EVENT>1</EVENT>
      <SAMPLE_ID>WHC202005270038</SAMPLE_ID>
      <SUBMITTER>AutoT_EQ00004</SUBMITTER>
      <ENTERED_BY>EQ00004</ENTERED_BY>
      <OWNER>WHC</OWNER>
      <PARAMETER_NAME>Free MSA</PARAMETER_NAME>
      <SRESULT>101.067</SRESULT>
   </INBOX_SAMPLE>
</INBOUND>

This is because instrument sends one parameter name like "MSA" but in our LIMS we have it under either "Free MSA" or "MSA - Conc.(Bench)" and I need to be able to provide the result for both possible parameter names and LIMS will insert the one that it find a match for.

Thank you so much in advanced :)

Body:
Add parm elements to template.

<xsl:template name="ConvertPaName">
    <xsl:param name="sPaName" />
    <xsl:choose>
        <xsl:when test="$sPaName='MSA'">
          <parm>MSA - Conc.(Bench)</parm>
          <parm>Free MSA</parm>
        </xsl:when>
        <xsl:otherwise>
          <parm>Halt_Import</parm>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Call your template

<xsl:variable name="sParamName">
  <xsl:call-template name="ConvertPaName">
    <xsl:with-param name="sPaName" select="$sParameter" />
   </xsl:call-template>
</xsl:variable>

Convert to node set:  (However you do it.  You currently don't have the msxml namespace set up.)

<xsl:variable name="sParamNameList" select="msxml:node-set($sParamName)">

Then use the parm list in your for-each loop.

<xsl:for-each select="$sParamNameList/parm">


问:
Google Sheet Script - onChange
Please help with Google onChange function Sheet Script.
I only want to log onChange for one sheet "Attendance" the change on this sheet is then logged in "Sheet5"
When there is a change in "Attendance" column C, then copy the value of column B into "Sheet5" and add the current date and time. Here is some code I tried, but do not know how to change it.</p>

```<code>function createSpreadsheetOpenTrigger() {

   ScriptApp.newTrigger('onChange')
    .forSpreadsheet('ID to go here')
   .onChange()
   .create();

    }

function onChange(e) {

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet5");
  const lastRow = sheet.getLastRow();

  sheet.getRange(lastRow + 1,1,1,4).setValues([
    [e.changeType,
      e.source.getSheetName(),
      e.source.getActiveSheet().getActiveRange().getValue(),
     new Date()]
    ]);
   }
</code>```

答:
Try this:

```<code>function onEdit(e) {
  const sh=e.range.getSheet();
  if(sh.getName()=='Attendance' && e.range.columnStart==3 && e.range.rowStart>'Your header row') {
    e.source.getSheetByName("Sheet5").appendRow([e.range.offset(0,-1).getValue(),new Date()]);
  }
}
</code>```

onedit event obj

Title: Google Sheet Script - onChange

Body:
Please help with Google onChange function Sheet Script.
I only want to log onChange for one sheet "Attendance" the change on this sheet is then logged in "Sheet5"
When there is a change in "Attendance" column C, then copy the value of column B into "Sheet5" and add the current date and time. Here is some code I tried, but do not know how to change it.

function createSpreadsheetOpenTrigger() {

   ScriptApp.newTrigger('onChange')
    .forSpreadsheet('ID to go here')
   .onChange()
   .create();

    }

function onChange(e) {

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet5");
  const lastRow = sheet.getLastRow();

  sheet.getRange(lastRow + 1,1,1,4).setValues([
    [e.changeType,
      e.source.getSheetName(),
      e.source.getActiveSheet().getActiveRange().getValue(),
     new Date()]
    ]);
   }

Body:
Try this:

function onEdit(e) {
  const sh=e.range.getSheet();
  if(sh.getName()=='Attendance' && e.range.columnStart==3 && e.range.rowStart>'Your header row') {
    e.source.getSheetByName("Sheet5").appendRow([e.range.offset(0,-1).getValue(),new Date()]);
  }
}

onedit event obj


问:
I get a "Type mismatch: inferred type is String but Editable! was expected" I used this same code down below and it works?
```<code>override fun update(message: String) {
    var text = textViewInstructions.text.toString()

    val timer = object : CountDownTimer(3000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            textViewInstructions.setText(newText)
            textViewInstructions.setSelection(textViewInstructions.text.length)
        }

        override fun onFinish() {
            textViewInstructions.text = ""  // this line here ??
        }
    }
    timer.start()
}
</code>```

答:
In this case of EditText, You need to use

```<code>textViewInstructions.setText("")
</code>```

Read more here

Body:
In this case of EditText, You need to use

textViewInstructions.setText("")

Read more here


问:
Jackson deserialization to concrete polymorphic class
I have following Jackson annotated classes (Kotlin)

```<code>@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes(
    value = [
        JsonSubTypes.Type(value = Child1::class, name = "child1"),
        JsonSubTypes.Type(value = Child2::class, name = "child2")
    ]
)
sealed class Parent

class Child1: Parent()
class Child2: Parent()
</code>```

I try to deserialize JSON that does not contain type property but I provide concrete class so it should not matter

```<code>// Kotlin extension method provides type in runtime
mapper.readValue<Child1>(json)
</code>```

I get Missing type id when trying to resolve subtype of ... anyway. Is there a way how to tell Jackson to use the type provided in the deserialization and not to try find it from the type property?

答:
There’s
 a default implementation class to use for deserialization via defaultImpl:

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = Child1.class)
</code>```

From the Javadoc:

Optional property that can be used to specify default implementation
  class to use for deserialization if type identifier is either not
  present, or can not be mapped to a registered type (which can occur
  for ids, but not when specifying explicit class to use). Property has
  no effect on choice of type id used for serialization; it is only used
  in deciding what to do for otherwise unmappable cases.

Body:
I have following Jackson annotated classes (Kotlin)

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes(
    value = [
        JsonSubTypes.Type(value = Child1::class, name = "child1"),
        JsonSubTypes.Type(value = Child2::class, name = "child2")
    ]
)
sealed class Parent

class Child1: Parent()
class Child2: Parent()

I try to deserialize JSON that does not contain type property but I provide concrete class so it should not matter

// Kotlin extension method provides type in runtime
mapper.readValue<Child1>(json)

I get Missing type id when trying to resolve subtype of ... anyway. Is there a way how to tell Jackson to use the type provided in the deserialization and not to try find it from the type property?

Body:
There’s
 a default implementation class to use for deserialization via defaultImpl:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = Child1.class)

From the Javadoc:

Optional property that can be used to specify default implementation
  class to use for deserialization if type identifier is either not
  present, or can not be mapped to a registered type (which can occur
  for ids, but not when specifying explicit class to use). Property has
  no effect on choice of type id used for serialization; it is only used
  in deciding what to do for otherwise unmappable cases.


问:
Server 2012 Event log forwarding
I am having issues getting the Event logs to forward to my collector server.  I have followed various articles on how to set this up and, enabled winrm on the source and wecutil on the collector.  I ensured the collector was in the Event Log Readers Group, and the windows firewall rules were enabled, however the firewall is not enabled.  I have set up the subscription properly with collector initiated and machine account for the user account, however No events show up in the "Forwarded Events" log, and the runtime status fails with the following error:

Error - Last retry time: 10/12/2016 8:55:12 AM. Code (0x80338095): The connectivity test from the push subscription source to the client failed. This can happen if the client machine initiating the push subscription is unreachable from the server machine where the event source is located. Possible reasons include firewall or some other network boundary. Modify subscription to use Pull based subscription.   Next retry time: 10/12/2016 9:00:12 AM.

I haven't found much on the web to troubleshoot this.  Are there any steps I can take to determine the issue, or am I missing something simple?  One technet article talked about a hotfix for 2008 servers, mine are all 2012.  Could it be GPO related?

答: I just changed the Event Delivery Optimization back to Normal, then ran the command wecutil gr <Subscription name> and it looked like it worked.

ContentLicense: CC BY-SA 3.0

Title: Server 2012 Event log forwarding


问:
error while building signed apk how can i solve this?
I'm a new at android studio today finished a project trying to build signed apk but getting error
I really tried hard to find reson but failing badly

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.
> Could not resolve all task dependencies for configuration ':app:lintClassPath'.
   > Could not resolve com.android.tools.lint:lint-gradle:26.6.3.
     Required by:
         project :app
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
</code>```

and the app build section is given below, i don't know who to solve this, please give answer
also mention reason so that i can learn form it app build section is given below:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.example.covid_19"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }}}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.leo.simplearcloader:simplearcloader:1.0.+'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
</code>```

答:
this happen because your android studio use gradle on mode offline.
please see this solutions : No Cached Version Gradle Plugin Available for offline mode</p>

Body:
I'm a new at android studio today finished a project trying to build signed apk but getting error
I really tried hard to find reson but failing badly

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.
> Could not resolve all task dependencies for configuration ':app:lintClassPath'.
   > Could not resolve com.android.tools.lint:lint-gradle:26.6.3.
     Required by:
         project :app
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.
      > No cached version of com.android.tools.lint:lint-gradle:26.6.3 available for offline mode.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

and the app build section is given below, i don't know who to solve this, please give answer
also mention reason so that i can learn form it app build section is given below:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.example.covid_19"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }}}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.github.blackfizz:eazegraph:1.2.5l@aar'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.leo.simplearcloader:simplearcloader:1.0.+'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}


问:
@JsonView annotation not working
I am trying to deserialize several fields from my object in Spring using the @JsonView annotation. However, I add the annotation to my method, instead of deserializing the specified field, it returns an empty object.

Here is my POJO:

```<code>@Entity
data class Album(
        @JsonView(View.AlbumSummary::class)
        val title: String,

        @JsonView(View.AlbumSummary::class)
        @ManyToMany
        val artists: List<Account>,

        val dateReleased: LocalDate,

        val genre: String = GENRE_NA,

        @OneToMany(mappedBy = "album")
        val songs: List<Song> = ArrayList(),

        val description: String = ""
)
</code>```

And also, the method that implements the @JsonView annotation:

```<code>@JsonView(View.AlbumSummary::class)
@RequestMapping("/home-recommendations/{userId}")
fun getHomeRecommendations(@PathVariable userId: String): List<Recommendation> {

    val recommendations = ArrayList<Recommendation>()

    val user = accountRepository.findById(userId).get()
    val followingArtists = user.following.filter {
        it.following.isArtist
    }
    val suggestedArtists = followingArtists.shuffled().take(Random().nextInt(11) + 10)

    for (i in 0 until suggestedArtists.size) {

        val suggestedArtist = suggestedArtists[i].following

        val recommendedAlbums = suggestedArtist.albums.shuffled().take(Random().nextInt(6) + 10)

        recommendations.add(Recommendation("Because you listened to ${suggestedArtist.fullName}", Recommendation.TYPE_ALBUM, albums = recommendedAlbums))

    }

    return recommendations

}
</code>```

Edit: My gradle configuration:

```<code>buildscript {
    ext {
        kotlinVersion = '1.2.50'
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'kotlin-jpa'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.aceinteract'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('org.springframework.boot:spring-boot-starter-mustache')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.fasterxml.jackson.module:jackson-module-kotlin')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    compile("org.jetbrains.kotlin:kotlin-reflect")
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
}
</code>```

I can provide more code if needed. Thanks in advance.

P.S. The same code works perfectly when the @JsonView annotation is removed from the method

Also, I'm using IntelliJ Idea

答: I had this same problem, and the JsonView only worked after I moved the fields out of the constructor and into the class body. You wouldn't use a data class in this case, but you can still delegate equals hashcode toString to a private inner data class.</p>

Title: @JsonView annotation not working

Body:
I am trying to deserialize several fields from my object in Spring using the @JsonView annotation. However, I add the annotation to my method, instead of deserializing the specified field, it returns an empty object.

Here is my POJO:

@Entity
data class Album(
        @JsonView(View.AlbumSummary::class)
        val title: String,

        @JsonView(View.AlbumSummary::class)
        @ManyToMany
        val artists: List<Account>,

        val dateReleased: LocalDate,

        val genre: String = GENRE_NA,

        @OneToMany(mappedBy = "album")
        val songs: List<Song> = ArrayList(),

        val description: String = ""
)

And also, the method that implements the @JsonView annotation:

@JsonView(View.AlbumSummary::class)
@RequestMapping("/home-recommendations/{userId}")
fun getHomeRecommendations(@PathVariable userId: String): List<Recommendation> {

    val recommendations = ArrayList<Recommendation>()

    val user = accountRepository.findById(userId).get()
    val followingArtists = user.following.filter {
        it.following.isArtist
    }
    val suggestedArtists = followingArtists.shuffled().take(Random().nextInt(11) + 10)

    for (i in 0 until suggestedArtists.size) {

        val suggestedArtist = suggestedArtists[i].following

        val recommendedAlbums = suggestedArtist.albums.shuffled().take(Random().nextInt(6) + 10)

        recommendations.add(Recommendation("Because you listened to ${suggestedArtist.fullName}", Recommendation.TYPE_ALBUM, albums = recommendedAlbums))

    }

    return recommendations

}

Edit: My gradle configuration:

buildscript {
    ext {
        kotlinVersion = '1.2.50'
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'kotlin-jpa'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.aceinteract'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('org.springframework.boot:spring-boot-starter-mustache')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.fasterxml.jackson.module:jackson-module-kotlin')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    compile("org.jetbrains.kotlin:kotlin-reflect")
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
}

I can provide more code if needed. Thanks in advance.

P.S. The same code works perfectly when the @JsonView annotation is removed from the method

Also, I'm using IntelliJ Idea


问:
What's the difference between aws-amplify-react and @aws-amplify/ui-react?
I saw many docs and places saying to use aws-amplify-react but here on the docs to get start with react I saw this package @aws-amplify/ui-react to use the module withAuthentication (which aws-amplify-react also has)

What's the difference between them? When should I use aws-amplify-react and when should I use @aws-amplify/ui-react ?

答:
It looks like aws-amplify-react is the legacy package name and it was changed to @aws-amplify/ui-react in the current version.

So to answer which to use, use @aws-amplify/ui-react as mentioned in the migration section of the documentation. The documentation is possibly not up to date everywhere.

They have a migration section in the repository README.md file as well:

For aws-amplify-react's Authenticator Component, you will need to
  import the styles within your app:

```<code>import '@aws-amplify/ui/dist/style.css';
</code>```

But even that file isn't completely up to date since it still refers to the legacy version in the installation section.

It looks like the documentation update is currently in progress, though you could ask for more guidance on the documentation repository.

Body:
It looks like aws-amplify-react is the legacy package name and it was changed to @aws-amplify/ui-react in the current version.

So to answer which to use, use @aws-amplify/ui-react as mentioned in the migration section of the documentation. The documentation is possibly not up to date everywhere.

They have a migration section in the repository README.md file as well:

For aws-amplify-react's Authenticator Component, you will need to
  import the styles within your app:

import '@aws-amplify/ui/dist/style.css';

But even that file isn't completely up to date since it still refers to the legacy version in the installation section.

It looks like the documentation update is currently in progress, though you could ask for more guidance on the documentation repository.


问:
MongoDb Node js Real Time notifications with change streams
In my web application i have followers and notifications. The problem is how to get to the list of users and report changes of some document like changed price, or user created one more property etc.. So i can use change streams to watch for changes inside collection.

```<code>Property.watch().
on('change', async data => {
  let prop = await Property.findById(data.documentKey._id);
  let user = await Follow.findOne({userId: prop.user._id});

  // After that find all followers then
  user.followers.forEach(foll => {
    await Notification.create({
      ...
    })
  })
});

</code>```

This code looks crazy to me, I mean even with some validations etc.. this is again overkill.

Maybe better approach is some logic inside controller, but how i can first return response to user after he successfully created or updated document and then run some function where i can find all users on followers list and create notifications for them ?

What you guys think ? There is not much examples and solutions for notification system, is there any resource that can be helpful

答: Change streams support filtering and other functionality.</p>

Body:
In my web application i have followers and notifications. The problem is how to get to the list of users and report changes of some document like changed price, or user created one more property etc.. So i can use change streams to watch for changes inside collection.

Property.watch().
on('change', async data => {
  let prop = await Property.findById(data.documentKey._id);
  let user = await Follow.findOne({userId: prop.user._id});

  // After that find all followers then
  user.followers.forEach(foll => {
    await Notification.create({
      ...
    })
  })
});

This code looks crazy to me, I mean even with some validations etc.. this is again overkill.

Maybe better approach is some logic inside controller, but how i can first return response to user after he successfully created or updated document and then run some function where i can find all users on followers list and create notifications for them ?

What you guys think ? There is not much examples and solutions for notification system, is there any resource that can be helpful


问:
Tooltip display on top without affecting the height and width of container
On click on the image, number displays as tooltip message for 4 seconds and disappears. This is working as expected. But while displaying the tooltip, the div height and width got changed. How can we display the tool tip on top of the image without affecting the height/width of the grid-container

I haved added a demo here:

https://codesandbox.io/s/amazing-ellis-2h3pd?file=/src/components/Home.js

答:
First Solution

You can set position: absolute and apply necessary margins to make it appear on top of the image

```<code>{phoneTooltip === id && (
  <div style={{position: 'absolute', marginLeft: '100px', zIndex: 1, marginTop: '-50px'}}
    className="tooltip_PhoneNumber_home" key={phonenumber}>
      {phonenumber}
</div>
)}
</code>```

Second Solution

Refactor jsx so tooltip is always on top of image but with visibility: hidden, opacity: 0 and click action makes it visible.

```<code><span className="phoneNumber_home">
  <div style={{opacity: phoneTooltip === id ? 1 : 0}} className="tooltip_PhoneNumber_home" key={phonenumber}>
    {phonenumber}
  </div>
  <img
    src="https://homepages.cae.wisc.edu/~ece533/images/tulips.png"
    alt={"phoneTooltip.show"}
    key={id}
    name="phoneNumberhomeicon"
    onClick={displayPhoneToolTip(id)}/>
</span>
</code>```

Body:
First Solution

You can set position: absolute and apply necessary margins to make it appear on top of the image

{phoneTooltip === id && (
  <div style={{position: 'absolute', marginLeft: '100px', zIndex: 1, marginTop: '-50px'}}
    className="tooltip_PhoneNumber_home" key={phonenumber}>
      {phonenumber}
</div>
)}

Second Solution

Refactor jsx so tooltip is always on top of image but with visibility: hidden, opacity: 0 and click action makes it visible.

<span className="phoneNumber_home">
  <div style={{opacity: phoneTooltip === id ? 1 : 0}} className="tooltip_PhoneNumber_home" key={phonenumber}>
    {phonenumber}
  </div>
  <img
    src="https://homepages.cae.wisc.edu/~ece533/images/tulips.png"
    alt={"phoneTooltip.show"}
    key={id}
    name="phoneNumberhomeicon"
    onClick={displayPhoneToolTip(id)}/>
</span>


问:
Laravel one to many grab only one object from the collection
I have two models, a Phrase model and a Translations model. One phrase can have many translations. In my phrase model I have the following relation:

```<code>public function translations()
{
    return $this->hasMany(Translation::class);
}
</code>```

On one of my pages I want to show only the translations based on a certain language. For example, there are 10 phrases I want to show, including their translations. I have 5 translations for each phrase in the database. Using a whereHas I return only the 10 phrases including their respective translations. So far so good. My whereHas:

```<code>$phrases = Phrase::with('translations')->whereHas('translations', function ($query) {
    return $query->where('lang', 'en');
})->get();
</code>```

This returns a collection of phrases with each one relation, to the translated version. On my show page I cannot simply do this:

```<code>@foreach($phrases as $phrase)
    {{ $phrase->name }} // The actual Phrase name
    {{ $phrase->translation->name }} // The translated version of the phrase
@endforeach
</code>```

First of all, because the relation translation does not exist here: $phrase->translation, and second of all, the translations are a collection as well.

So my question is, if you understand what I am trying to achieve, is something like the foreach I posted possible in some simple way?

PS. I know I could simply convert my original collection to an array but that is not what I want.

答:
I suggest you using a seperate hasOne relation to fetch one translation from your database which you can constrain further in your query.

Phrase model

```<code>class Phrase
{
    public function translation()
    {
        return $this->hasOne(Translation::class);
    }
}
</code>```

Controller

```<code>$phrases = Phrase::with([
    'translation' => function ($query) {
        $query->where('lang', 'en');
    },
])->get();
</code>```

This should yield the expected result but is untested.

Body:
I have two models, a Phrase model and a Translations model. One phrase can have many translations. In my phrase model I have the following relation:

public function translations()
{
    return $this->hasMany(Translation::class);
}

On one of my pages I want to show only the translations based on a certain language. For example, there are 10 phrases I want to show, including their translations. I have 5 translations for each phrase in the database. Using a whereHas I return only the 10 phrases including their respective translations. So far so good. My whereHas:

$phrases = Phrase::with('translations')->whereHas('translations', function ($query) {
    return $query->where('lang', 'en');
})->get();

This returns a collection of phrases with each one relation, to the translated version. On my show page I cannot simply do this:

@foreach($phrases as $phrase)
    {{ $phrase->name }} // The actual Phrase name
    {{ $phrase->translation->name }} // The translated version of the phrase
@endforeach

First of all, because the relation translation does not exist here: $phrase->translation, and second of all, the translations are a collection as well.

So my question is, if you understand what I am trying to achieve, is something like the foreach I posted possible in some simple way?

PS. I know I could simply convert my original collection to an array but that is not what I want.

Body:
I suggest you using a seperate hasOne relation to fetch one translation from your database which you can constrain further in your query.

Phrase model

class Phrase
{
    public function translation()
    {
        return $this->hasOne(Translation::class);
    }
}

Controller

$phrases = Phrase::with([
    'translation' => function ($query) {
        $query->where('lang', 'en');
    },
])->get();

This should yield the expected result but is untested.


问:
Remove emojis and @users from a list in Python and punctuation, NLP problem, and my emoji function does not work
I wrote the code below. My sentence is part of Twitter. I want to remove all emojis from my list, but my emoji function does not work. Why?

And also I want to remove users. Users start from the beginning of a sentence, but sometimes it keeps users and sometimes it removes users. Also my punctuation does not work and I commented it. How can I fix that?

```<code>import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

  # Remove emoji
    emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags=re.UNICODE)

    string = emoji_pattern.sub(r'', input_string) # No emoji

    # Normalize to lowercase
    string = input_string.lower()

    # Spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # In case the string is empty
    if not string_split:
        return ''

    # Remove user

    # Assuming user is the first word and contains an @
    if '@' in string_split[0]:
        del string_split[0]

    # Join back to string
    string = ' '.join(string_split)

    # Remove # and @
    for punc in '":!@#':
       string = string.replace(punc, '')

    # Remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # Removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#Punctuation

   # string = [''.join(w for w in string.split() if w not in string.punctuation) for w in string]

    # return string

#list = ['@cosmetic_candy I think a lot of people just enjoy being a pain in the ass on there',

 'Best get ready sunbed and dinner with nana today :)',

 '@hardlyin70 thats awesome!',

 'Loving this weather',

 '“@danny_boy_37: Just seen an absolute idiot in shorts! Be serious!” Desperado gentleman',

 '@SamanthaOrmerod trying to resist a hardcore rave haha! Resisting towns a doddle! Posh dance floor should wear them in quite easy xx',

 '59 days until @Beyonce!!! Wooo @jfracassini #cannotwait',

 'That was the dumbest tweet I ever seen',

 'Oh what to do on this fine sunny day?',

 '@Brooke_C_X hows the fish ? Hope they r ok. Xx',

 '@Jbowe_ ',

 'Or this @louise_munchi',

 '@guy_clifton your diary is undoubtedly busier than mine, but feel free to check ',

 'Willy⚽']

list_sanitized = [sanitize(string) for string in list]

list_sanitized[:50]

</code>```

答:
I'm drawing on some other SO answers here:

removing textual emojis: https://stackoverflow.com/a/61758471/42346

removing graphical emojis: https://stackoverflow.com/a/50602709/42346

This will also remove any Twitter username wherever it appears in the string.

```<code>import emoji
import spacy
import stop_words

nlp = spacy.load('en_core_web_sm')

stopwords = [w.lower() for w in stop_words.get_stop_words('en')]

emoticon_string = r"""
    (?:
      [<>]?
      [:;=8]                     # eyes
      [\-o\*\']?                 # optional nose
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
      |
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
      [\-o\*\']?                 # optional nose
      [:;=8]                     # eyes
      [<>]?
    )"""

def give_emoji_free_text(text):
    return emoji.get_emoji_regexp().sub(r'', text)

def sanitize(string):
    """ Sanitize one string """

    # remove graphical emoji
    string = give_emoji_free_text(string)

    # remove textual emoji
    string = re.sub(emoticon_string,'',string)

    # normalize to lowercase
    string = string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    # join back to string
    string = ' '.join(string_split)

    # remove user
    # assuming user has @ in front
    string = re.sub(r"""(?:@[\w_]+)""",'',string)

    #remove # and @
    for punc in '":!@#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stopwords])

    return string
</code>```

Body:
I wrote the code below. My sentence is part of Twitter. I want to remove all emojis from my list, but my emoji function does not work. Why?

And also I want to remove users. Users start from the beginning of a sentence, but sometimes it keeps users and sometimes it removes users. Also my punctuation does not work and I commented it. How can I fix that?

import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

  # Remove emoji
    emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags=re.UNICODE)

    string = emoji_pattern.sub(r'', input_string) # No emoji

    # Normalize to lowercase
    string = input_string.lower()

    # Spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # In case the string is empty
    if not string_split:
        return ''

    # Remove user

    # Assuming user is the first word and contains an @
    if '@' in string_split[0]:
        del string_split[0]

    # Join back to string
    string = ' '.join(string_split)

    # Remove # and @
    for punc in '":!@#':
       string = string.replace(punc, '')

    # Remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # Removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#Punctuation

   # string = [''.join(w for w in string.split() if w not in string.punctuation) for w in string]

    # return string

#list = ['@cosmetic_candy I think a lot of people just enjoy being a pain in the ass on there',

 'Best get ready sunbed and dinner with nana today :)',

 '@hardlyin70 thats awesome!',

 'Loving this weather',

 '“@danny_boy_37: Just seen an absolute idiot in shorts! Be serious!” Desperado gentleman',

 '@SamanthaOrmerod trying to resist a hardcore rave haha! Resisting towns a doddle! Posh dance floor should wear them in quite easy xx',

 '59 days until @Beyonce!!! Wooo @jfracassini #cannotwait',

 'That was the dumbest tweet I ever seen',

 'Oh what to do on this fine sunny day?',

 '@Brooke_C_X hows the fish ? Hope they r ok. Xx',

 '@Jbowe_ ',

 'Or this @louise_munchi',

 '@guy_clifton your diary is undoubtedly busier than mine, but feel free to check ',

 'Willy⚽']

list_sanitized = [sanitize(string) for string in list]

list_sanitized[:50]

Body:
I'm drawing on some other SO answers here:

removing textual emojis: https://stackoverflow.com/a/61758471/42346

removing graphical emojis: https://stackoverflow.com/a/50602709/42346

This will also remove any Twitter username wherever it appears in the string.

import emoji
import spacy
import stop_words

nlp = spacy.load('en_core_web_sm')

stopwords = [w.lower() for w in stop_words.get_stop_words('en')]

emoticon_string = r"""
    (?:
      [<>]?
      [:;=8]                     # eyes
      [\-o\*\']?                 # optional nose
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
      |
      [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
      [\-o\*\']?                 # optional nose
      [:;=8]                     # eyes
      [<>]?
    )"""

def give_emoji_free_text(text):
    return emoji.get_emoji_regexp().sub(r'', text)

def sanitize(string):
    """ Sanitize one string """

    # remove graphical emoji
    string = give_emoji_free_text(string)

    # remove textual emoji
    string = re.sub(emoticon_string,'',string)

    # normalize to lowercase
    string = string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    # join back to string
    string = ' '.join(string_split)

    # remove user
    # assuming user has @ in front
    string = re.sub(r"""(?:@[\w_]+)""",'',string)

    #remove # and @
    for punc in '":!@#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stopwords])

    return string


问:
accessing sqlite file in android
I have a sqlite file. I want to use it in my application.
Can anyone share proper example as how I can do that.

I was not sure if .sqlite file can be used so I have also made .db file.

答:
Check the answer on this links for sample code:

SQLite Database "context" passed to adapter

Database not copying from assets

adding your own SQLite database to an android application

Title: accessing sqlite file in android


问:
How does exshuffle works in cloze questions (package `exams`)?
I would like to understand how does exsuffle works on cloze questions. Does it work with various schoice questions with a different number of possible answers?

I expect to have the possible answers shuffled when presenting the exercises in Moodle. With the observed behavior, the order is always the same.

答:
```<code>```
options[[1]] <- sample(paste0(c(correct_answer, possible_answers[!possible_answers %in% correct_answer])))
solutions[[1]] <- options[[1]]==correct_answer
```
</code>```


问:
Python - split data in list when we detect symbol ('|')
I wouldlike to split my list when I detect this '|'
Something like this :</p>

```<code>list A = ['abc', 'bcd', 'cde', '|', 'iojfsdifdosj', 'iojsdfiosjf', '|', 'jhuh']

out :
['abc,bcd,cde', 'iojfsdifdosj,iojsdfiosjf']
</code>```

答:
Simple solution would be to concatenate list_A into a single string and then split it by pipes.

str_list_A = ",".join(list_A)
out = str_list_A.split(",|,")
```

Body:
I wouldlike to split my list when I detect this '|'
Something like this :

list A = ['abc', 'bcd', 'cde', '|', 'iojfsdifdosj', 'iojsdfiosjf', '|', 'jhuh']

out :
['abc,bcd,cde', 'iojfsdifdosj,iojsdfiosjf']


问:
On the First guess nothing is being registered even if i get it right
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

```<code>import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))

guess_limit = 5
guess_counter = 1
out_of_guesses = False

print("You have", str(guess_limit - guess_counter), "tries left")

while not out_of_guesses:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        exit(0)

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")

    # exit clause
    if guess_limit == guess_counter:
        out_of_guesses = True

print("Game over, sorry")
</code>```

And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!

As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)

答:
You do not check if guess == Magic_number after reading input on line 4.
Like this

```<code>import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))

if guess == Magic_number:
    print ("You won")
    exit(0)
</code>```

You don't need all those variables, check this.

```<code>import random
Magic_number = random.randrange(1, 100)
print(Magic_number)

guess_limit = 5
guess_counter = 0

while True:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        exit(0)

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print(f"You have {guess_limit - guess_counter} tries left")

    if guess_counter == guess_limit:
        print("Game over, sorry")
        exit(0)
</code>```

Body:
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))

guess_limit = 5
guess_counter = 1
out_of_guesses = False

print("You have", str(guess_limit - guess_counter), "tries left")

while not out_of_guesses:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        exit(0)

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")

    # exit clause
    if guess_limit == guess_counter:
        out_of_guesses = True

print("Game over, sorry")

And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!

As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)

Body:
You do not check if guess == Magic_number after reading input on line 4.
Like this

import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))

if guess == Magic_number:
    print ("You won")
    exit(0)

You don't need all those variables, check this.

import random
Magic_number = random.randrange(1, 100)
print(Magic_number)

guess_limit = 5
guess_counter = 0

while True:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        exit(0)

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print(f"You have {guess_limit - guess_counter} tries left")

    if guess_counter == guess_limit:
        print("Game over, sorry")
        exit(0)