问:
I am getting a warning regarding an infinite update loop in a component render. What part of my code is causing this?
In my application I have a list of documents that I display in a table, each document has a specific type, which is specified in json file as enum values.
I can already display all the documents without any problems, but now I have tried to create an input where the user can choose from the list of enum values, and when doing so only the documents with the selected enum type will be shown in the table.
This does sorta work, but the problem is that I have somehow created an infinite update loop, which causes the application to randomly stop working.

This is the template. I am using a custom made template component, but that is not related to the issue.

<template>

            {{ folderName }}

            {{
                search ?
                  $t('documentCountFiltered', {filtered: filteredDocuments.length, count: documents.length}) :
                  $tc('documentCount', documents.length)
              }}

          <template v-if="!inherited && mode !== 'READ_ONLY'">

              {{ $t('uploadFiles') }}

              <input type="file" multiple @change="selectFiles">

              <template slot="button-content">
                 {{ $t('createDocument') }}
              </template>

                {{ $t('companyTemplates') }}

                {{ template.name }}

               0">
               0" id="dropdown-header-inheritedDocuments">
                {{ $t('formBuilderTemplates') }}

                {{ template.name }}

               0" id="dropdown-header-globalDocuments">
                {{ $t('globalTemplates') }}

                {{ template.name }}

          </template>

        <w-b-form-select v-model="filteredDocumentType">

          <template>
            -- {{ $t('selectDocumentByType') }} --
          </template>

          ({{ $t('all') }})

          <option v-for="documentType in availableDocumentTypes" :key="documentType" :value="documentType">
            {{ $t('model.document.types.' + documentType) }}
          </option>

        </w-b-form-select>

        <common-table
          :fields="fields"
          :items="filteredDocuments"
          primary-key="id"
          sort-by="creationDateTime"
          sort-desc
        >
          <template slot="head(select)">
            <check-all-checkbox :list="filteredDocuments" @change="handleTag(documents, $event)" property="selected"/>
          </template>
          <template slot="cell(select)" slot-scope="data">
            <w-b-form-checkbox v-model="data.item.selected" v-if="data.item.selected != null"
                               @change="handleTag([data.item], $event)" data-test-id="check-box"/>
          </template>
          <template slot="cell(name)" slot-scope="data">

                   {{ $t('showDocument') }}

                   {{
                      $t('download')
                    }}

          </template>
        </common-table>

</template>```
</div>
</div>
</p>
<p>My script</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  import CheckAllCheckbox from '@/components/CheckAllCheckbox';
  import CommonTable from '@/components/common/CommonTable';
  import CommonInput from '@/components/common/CommonInput';
  import {applianceService} from '@/services/appliance';
  import PDFJSViewer from '@/components/PDFJSViewer';
  import axios from '@/config/axios';
  import {documentService} from '@/services/document';
  import documentTypes from '@/models/document/type';
  import {propertyFacilityService} from '@/services/property-facility';
  import CommonCollapsible from '@/components/common/CommonCollapsible';

  export default {
    props: {
      documents: Array,
      documentOwnerType: String,
      companyTemplates: Array,
      companyFormBuilderTemplates: Array,
      globalTemplates: Array,
      inherited: Boolean,
      startCollapsed: {
        type: Boolean,
        default: false
      },
      mode: String,
      search: String,
      applianceId: String,
      propertyFacilityId: String,
      noteId:String
    },
    components: {
      CheckAllCheckbox,
      CommonTable,
      CommonCollapsible,
      CommonInput,
      PDFJSViewer
    },
    data() {
      return {
        documentTypes,
        showCollapse: true,
        filteredDocumentType: null

      };
    },
    computed: {
      filteredDocuments() {
        console.log(this.filteredDocumentType)
        console.log(this.documents)
        if (this.filteredDocumentType === null || this.filteredDocumentType === 'all') {
          return (this.documents ?? []).filter(document =>
            (document.name.toUpperCase().includes(this.search.toUpperCase()) ||
              this.$t(`model.document.types.${document.type}`).toUpperCase().includes(this.search.toUpperCase())))
        }
        else {
          return (this.documents ?? []).filter(document =>
            (document.name.toUpperCase().includes(this.search.toUpperCase()) ||
              this.$t(`model.document.types.${document.type}`).toUpperCase().includes(this.search.toUpperCase())) &&
            document.type === this.filteredDocumentType)
        }
      },
      folderName() {
        if (this.inherited) {
          return this.$t('sharedDocuments');
        } else if (this.documentOwnerType === 'COMPANY') {
          return this.$t('companyDocuments');
        } else {
          return this.$t('documents');
        }
      },
      availableDocumentTypes() {
        return this.documentTypes.sort((a, b) => this.getDocumentTypeText(a).localeCompare(this.getDocumentTypeText(b)));
      },
      fields() {
        return [
          {
            key: 'select',
            thStyle: 'width: 1%'
          },
          {
            key: 'name',
            label: this.$t('name'),
            sortable: true
          },
          {
            key: 'inherited',
            label: this.$t('inherited'),
            formatter: inherited => this.$t(inherited ? 'yes' : 'no'),
            sortable: true,
            hide: this.inherited
          },
          {
            key: 'sharedOnTC',
            label: this.$t('sharedOnTC'),
            formatter: sharedOnTC => this.$t(sharedOnTC ? 'yes' : 'no'),
            sortable: true,
            hide: this.sharedOnTC
          },
          {
            key: 'type',
            label: this.$t('type'),
            formatter: type => this.$t('model.document.types.' + type),
            sortable: true,
            sortByFormatted: true
          },
          {
            key: 'tags',
            label: this.$t('tags'),
            formatter: tags => tags.join(', '),
            sortable: true,
            sortByFormatted: true
          },
          {
            key: 'signed',
            label: this.$t('signed'),
            formatter: sharedOnTC => this.$t(sharedOnTC ? 'yes' : 'no'),
            sortable: true,
            sortByFormatted: true
          },
          {
            key: 'creationDateTime',
            label: this.$t('created'),
            sortable: true,
            template: {type: 'date', format: 'L LT'}
          },
          {
            key: 'changedDateTime',
            label: this.$t('changed'),
            sortable: true,
            template: {type: 'date', format: 'L LT'}
          },
          {
            key: 'actions',
            hide: this.inherited || this.mode === 'READ_ONLY',
            template: {
              type: 'actions',
              cell: [
                {
                  icon: 'fa-edit',
                  tooltip: this.$t('edit'),
                  if: this.mode !== 'RESTRICTED',
                  disabled: data => data.item.uploading || !data.item.documentTemplateId || data.item.signed,
                  action: data => this.emitDocumentEditTemplateSelectEvent(data.item)
                },
                {
                  icon: 'fa-cog',
                  tooltip: this.$t('documentSettings'),
                  disabled: data => data.item.uploading,
                  action: data => this.emitDocumentEditSelectEvent(data.item)
                },
                {
                  icon: 'fa-trash',
                  variant: 'outline-danger',
                  disabled: data => data.item.uploading,
                  action: data => this.emitDocumentDeleteSelectEvent(data.item)
                }
              ]
            }
          }
        ].filter(field => !field.hide);
      }
    },
    methods: {
      getDocumentTypeText(type) {
        return this.$t(`model.document.types.${type}`);
      },
      selectFiles(event) {
        this.emitFileUploadEvent(event.target.files);
        event.target.value = '';
      },
      onDropEvent(event) {
        this.emitFileUploadEvent(event.dataTransfer.files);
      },
      downloadFile(document) {
        documentService.downloadDocument(document.id)
          .catch(error => {
            console.error(error);
          });
      },
      viewFile(document) {
        documentService.getPublicDownloadToken(document.id).then(result => {
          let fileName = `${axios.defaults.baseURL}/file/public/${result.data}/download`;

          this.$refs['pdf-viewer'].show(fileName);
        }).catch(error => {
          console.error(error);
        });
      },
      emitGlobalDocumentCreateSelectEvent(template) {
        this.$emit('document-global-create-select', template);
      },
      emitDocumentCreateSelectEvent(template) {
        this.$emit('document-create-select', template);
      },
      emitWordDocumentCreateSelectEvent(template) {
        this.$emit('document-word-create-select', template);
      },
      emitDocumentEditSelectEvent(document) {
        documentService.getDocument(document.id).then(result => {
          document = result.data;
          this.$emit('document-edit-select', document);
        });
      },
      emitDocumentEditTemplateSelectEvent(document) {
        this.$emit('document-edit-template-select', document);
      },
      emitDocumentDeleteSelectEvent(document) {
        this.$emit('document-delete-select', document);
      },
      emitFileUploadEvent(files) {
        if (files && files.length) {
          this.$emit('file-upload', [...files]);
        }
      },
      handleTag(documents, selected) {
        if (this.applianceId) {
          applianceService.updateDocuments(this.applianceId, {
            documentIds: documents.map(doc => doc.id), selected: selected
          }).then(({data: documents}) => {
            documents.forEach(doc => {
              this.documents.splice(this.documents.findIndex(d => d.id === doc.id), 1,
                Object.assign(doc, {selected: selected}));
            });
          });
        }
        if (this.propertyFacilityId) {
          propertyFacilityService.updateDocuments(this.propertyFacilityId, {
            documentIds: documents.map(doc => doc.id), selected: selected
          }).then(({data: documents}) => {
            documents.forEach(doc => {
              this.documents.splice(this.documents.findIndex(d => d.id === doc.id), 1,
                Object.assign(doc, {selected: selected}));
            });
          });

        }
      }
    },
    created() {
      this.showCollapse = !this.startCollapsed;
    }
  };
</script></code>```

Body:
In my application I have a list of documents that I display in a table, each document has a specific type, which is specified in json file as enum values.
I can already display all the documents without any problems, but now I have tried to create an input where the user can choose from the list of enum values, and when doing so only the documents with the selected enum type will be shown in the table.
This does sorta work, but the problem is that I have somehow created an infinite update loop, which causes the application to randomly stop working.

This is the template. I am using a custom made template component, but that is not related to the issue.

<template>

            {{ folderName }}

            {{
                search ?
                  $t('documentCountFiltered', {filtered: filteredDocuments.length, count: documents.length}) :
                  $tc('documentCount', documents.length)
              }}

          <template v-if="!inherited && mode !== 'READ_ONLY'">

              {{ $t('uploadFiles') }}

              <input type="file" multiple @change="selectFiles">

              <template slot="button-content">
                 {{ $t('createDocument') }}
              </template>

                {{ $t('companyTemplates') }}

                {{ template.name }}

               0">
               0" id="dropdown-header-inheritedDocuments">
                {{ $t('formBuilderTemplates') }}

                {{ template.name }}

               0" id="dropdown-header-globalDocuments">
                {{ $t('globalTemplates') }}

                {{ template.name }}

          </template>

        <w-b-form-select v-model="filteredDocumentType">

          <template>
            -- {{ $t('selectDocumentByType') }} --
          </template>

          ({{ $t('all') }})

          <option v-for="documentType in availableDocumentTypes" :key="documentType" :value="documentType">
            {{ $t('model.document.types.' + documentType) }}
          </option>

        </w-b-form-select>

        <common-table
          :fields="fields"
          :items="filteredDocuments"
          primary-key="id"
          sort-by="creationDateTime"
          sort-desc
        >
          <template slot="head(select)">
            <check-all-checkbox :list="filteredDocuments" @change="handleTag(documents, $event)" property="selected"/>
          </template>
          <template slot="cell(select)" slot-scope="data">
            <w-b-form-checkbox v-model="data.item.selected" v-if="data.item.selected != null"
                               @change="handleTag([data.item], $event)" data-test-id="check-box"/>
          </template>
          <template slot="cell(name)" slot-scope="data">

                   {{ $t('showDocument') }}

                   {{
                      $t('download')
                    }}

          </template>
        </common-table>

</template>

My script


来源: stackexchange

问:
Creating and matching the user created in Laravel in firebase
I have a Laravel 8 project. Users are applying to be a creator from another web project, and we approve these applications from the project I am currently having problems with. In other words, the project we are talking about is an admin panel. Let me tell you what I want to do now. We approve the applications coming here with the create button in the admin panel and create the creator. However, this creator does not currently occur on Firebase. I also want this creator to be rendered in Firebase as well. I did some research and found something like Firebase Admin SDK for PHP. As far as I understand, I can perform this operation with the help of this SDK.

Then I went and wrote my codes to the create function inside the CreatorController, where the content of this Create Button is written. Here is my code that I wrote.

CreatorController.php-create function

```<code>    public function create(Request $request){
        $application = null;
        $subscriber = null;
        if($request->application_id!=null){
            $application = CreatorApplicationForm::findorfail($request->application_id);
            $subscriber = User::where([['email','=',$application->email],['role_id','=',4]])->get()->first();
        }
        return view('admin.creators.create',['application' => $application,'subscriber' => $subscriber]);

            if(isset($_POST['create-btn'])){

                $displayName = $_POST['name'];
                $email = $_POST['email'];

                $userProperties = [
                    'displayName' => $displayName,
                    'email' => $email,
                ];

                $createdUser = $auth->createUser($userProperties);

            }
    }
</code>```

I wrote the last if block in the function, the previous ones were already written.

Later, when I showed this to a friend, he said it wouldn't work for me. He said you wrote it in classical PHP form and told me to adapt it to Laravel. Also, I guess I need to sync the newly created user to the subscribers in the first if block.

Frankly, I'm a little confused. How can I solve this problem?

ContentLicense: CC BY-SA 4.0

Body:
I have a Laravel 8 project. Users are applying to be a creator from another web project, and we approve these applications from the project I am currently having problems with. In other words, the project we are talking about is an admin panel. Let me tell you what I want to do now. We approve the applications coming here with the create button in the admin panel and create the creator. However, this creator does not currently occur on Firebase. I also want this creator to be rendered in Firebase as well. I did some research and found something like Firebase Admin SDK for PHP. As far as I understand, I can perform this operation with the help of this SDK.

Then I went and wrote my codes to the create function inside the CreatorController, where the content of this Create Button is written. Here is my code that I wrote.

CreatorController.php-create function

    public function create(Request $request){
        $application = null;
        $subscriber = null;
        if($request->application_id!=null){
            $application = CreatorApplicationForm::findorfail($request->application_id);
            $subscriber = User::where([['email','=',$application->email],['role_id','=',4]])->get()->first();
        }
        return view('admin.creators.create',['application' => $application,'subscriber' => $subscriber]);

            if(isset($_POST['create-btn'])){

                $displayName = $_POST['name'];
                $email = $_POST['email'];

                $userProperties = [
                    'displayName' => $displayName,
                    'email' => $email,
                ];

                $createdUser = $auth->createUser($userProperties);

            }
    }

I wrote the last if block in the function, the previous ones were already written.

Later, when I showed this to a friend, he said it wouldn't work for me. He said you wrote it in classical PHP form and told me to adapt it to Laravel. Also, I guess I need to sync the newly created user to the subscribers in the first if block.

Frankly, I'm a little confused. How can I solve this problem?


问:
Pass a generic type to Json.encodetostring()
I'm trying to do something from a guide I found online, which is passing a generic type variable to the Json function encodeToString(), I do not want to use a reified type, but it does not work for me...

Here is my sample code:

fun <G> encodetojson(toConvert: G){
    converted = Json.encodeToString(toConvert)
    return converted
}
```

From the above code I get a type mismatch error.

How I might fix this?

Body:
I'm trying to do something from a guide I found online, which is passing a generic type variable to the Json function encodeToString(), I do not want to use a reified type, but it does not work for me...

Here is my sample code:

fun <G> encodetojson(toConvert: G){
    converted = Json.encodeToString(toConvert)
    return converted
}

From the above code I get a type mismatch error.

How I might fix this?


问:
Maintainable Excel Spreadsheet
i have 2 excel spreadsheet. page 1 is a questionnaire and page 2 is a requirements page. so to break it down even further, users will answer the questionnaire by ticking on checkboxes next to the column of the question. each question will result in a different requirement being shown on the requirements page. my question is, what would be a better way to reference the required rows to be shown other than just referencing their row number.

so lets say, ive decided to add a new question and name it Question 5 - Show Requirement 5, everything after the index 5 will have to increase by 1, in turn, my macros that reference to the row number after index 5 will all have to increase by 1. so what would be a better way in getting this done?

Title: Maintainable Excel Spreadsheet


问:
Actice and idle connection count for Redis in java
I use Lettuce to connect to Redis in a Springboot environment. I've set up a LettuceConnectionFactory with a GenericObjectPoolConfig config object. In the GenericObjectPoolConfig i've set the maximum total connections, the max idle connections, the min idle connections and the maximum wait for connections.
I would like to monitor the connections to redis with micrometer. Is there any way to get the active and idle connection count for redis?

I've fount a similar question: Spring data Redis. How to know number of Active, Idle Connection?. But they are using jedis as a redis client.


问:
Design API to update a document with a field containing list. Add & Remove in single request
I have an API which should update a document. Document contains a list, to which items can be added and removed in the same request. How should I model my client.

Example:

Student

```<code>{
  id: 1,
  name: Bob,
  languages: [English, French, Korean]
}
</code>```

Now I am designing /updateStudent API.

How should I model my UpdateStudentRequest which removes a language and adds another language.

Option1:

Replace existing languages with the languages from UpdateStudentRequest.

Request:

```<code>updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .withLanguages(Arrays.asList("English", "French", "German"))
                         .build();
client.updateStudent(updateStudentRequest);
</code>```

Downside: Users should know what are the existing languages in order to update them.

Option2:

Provide add and remove lists in the UpdateStudentRequest.

Request:

```<code>updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .addLanguages(Arrays.asList("German"))
                         .removeLanguages(Arrays.asList("Korean"));
                         .build();
client.updateStudent(updateStudentRequest);
</code>```

Downside: Users need to write additional code.

Option3:

Have both add and remove lists in the same request

Request:

```<code>List<String> addLanguages = Arrays.asList("German");
List<String> removeLanguages = Arrays.asList("Korean");

updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .withLanguages(addLanguages, removeLanguages);
                         .build();
client.updateStudent(updateStudentRequest);
</code>```

Downside: Confusion, mistakes like replacing add with remove is common.

What is the best practice when designing REST APIs like this.

Body:
I have an API which should update a document. Document contains a list, to which items can be added and removed in the same request. How should I model my client.

Example:

Student

{
  id: 1,
  name: Bob,
  languages: [English, French, Korean]
}

Now I am designing /updateStudent API.

How should I model my UpdateStudentRequest which removes a language and adds another language.

Option1:

Replace existing languages with the languages from UpdateStudentRequest.

Request:

updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .withLanguages(Arrays.asList("English", "French", "German"))
                         .build();
client.updateStudent(updateStudentRequest);

Downside: Users should know what are the existing languages in order to update them.

Option2:

Provide add and remove lists in the UpdateStudentRequest.

Request:

updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .addLanguages(Arrays.asList("German"))
                         .removeLanguages(Arrays.asList("Korean"));
                         .build();
client.updateStudent(updateStudentRequest);

Downside: Users need to write additional code.

Option3:

Have both add and remove lists in the same request

Request:

List<String> addLanguages = Arrays.asList("German");
List<String> removeLanguages = Arrays.asList("Korean");

updateStudentRequest = updateStudentRequestBuilder.withId(1)
                         .withLanguages(addLanguages, removeLanguages);
                         .build();
client.updateStudent(updateStudentRequest);

Downside: Confusion, mistakes like replacing add with remove is common.

What is the best practice when designing REST APIs like this.


问:
How to install a specific version of Swoole in WHM
I would like to install SWOOLE on WHM and I want to download a specific version (4.8.1)

But I can't only download the latest version, which is 5.0.1, and I want to download 4.8.1.

Is there any way to install it...

I tried the download from Module Installers, but it did not work


问:
Current User Apache Kylin
Why "select current_user" in Apache Kylin always return 'sa'
How to get real user connected and queried kylin?

I tried docker image Kylin v 4.0.1. No matter who is Authorized - "select current_user" always return 'sa'

Title: Current User Apache Kylin


问:
Error 502 when get topics with google apis iid
I tray to get all topic in specific token(fcm).

https://iid.googleapis.com/iid/info/{token}?details=true

that's response an error 502.

response

But if I not use details=true it work fine.

is that api deprecated?


问:
Python Watchdog with linux Rsync gives modified event for new files that are created in target directory
I have a python script that uses watchdog for performing some actions on any file creation and modification event in the target directory (say target-dir). This target-dir is kept in sync with a remote directory (say source-dir) using linux's Rsync feature. When Rsync copies the file from source-dir to target-dir, i believe it should trigger a CREATED event. But for some files i am receiving CREATED event and for some i am receiving MODIFIED event.

Can anyone explain me if this behaviour is expected or if I am missing something?


问:
Using 2 Node.js express server on same machine exposing only one
I have a backend service for a business application, this service is a Node.js express server that is running on a proprietary machine. (database access, business logic, ...)

I have a second Node.js app that i need to use from my backend server without exposing it. This second service can be used via CLI but also gives me the opportunity to start it as a server an use it via REST API.

What should i do to call the second service from the main service?

I thought about calling the service using the CLI with Node.js child process but i am concerned about security issues, is there a way to start and call the second server from the main one without exposing it?


问:
GAN generator for image size 224X224
i want to generate synthetic image of size 224x224 using gan generator. but i dont understand how to design dcgan generator specific image size using 2d transpose convolution. kindly help

TensorFlow Gan code for DCGAN I tried

Title: GAN generator for image size 224X224


问:
Jenkins pipeline making docker image using img, throwing `nsenter: USER is unset: Inappropriate ioctl for device`
Im trying build the docker image using img, im able to install the img in jenkins, but when i try to make the image using make file showing

nsenter: USER is unset: Inappropriate ioctl for device

Below is the cmd to install the img

```<code> sudo apt-get update -y \\
                        && sudo apt-get install -y uidmap \\
                        && echo "Downloading img" \\
                        && curl -fSL "https://github.com/genuinetools/img/releases/download/v0.5.11/img-linux-amd64" -o "/usr/local/bin/img" \\
                        && echo "cc9bf08794353ef57b400d32cd1065765253166b0a09fba360d927cfbd158088  /usr/local/bin/img" | sha256sum -c - \\
                        && chmod a+x "/usr/local/bin/img"
</code>```

Body:
Im trying build the docker image using img, im able to install the img in jenkins, but when i try to make the image using make file showing

nsenter: USER is unset: Inappropriate ioctl for device

Below is the cmd to install the img

 sudo apt-get update -y \\
                        && sudo apt-get install -y uidmap \\
                        && echo "Downloading img" \\
                        && curl -fSL "https://github.com/genuinetools/img/releases/download/v0.5.11/img-linux-amd64" -o "/usr/local/bin/img" \\
                        && echo "cc9bf08794353ef57b400d32cd1065765253166b0a09fba360d927cfbd158088  /usr/local/bin/img" | sha256sum -c - \\
                        && chmod a+x "/usr/local/bin/img"


问:
Sonar-scala and default scala not working together
I am currently using SonarQube 8.9 LTS
I have tried to install sonar-scala https://github.com/sonar-scala/sonar-scala in extensions/plugins folder, but I am facing error like as below:

```<code>java.lang.IllegalStateException: There are two languages declared with the same key 'scala' declared by the plugins 'scala' and 'sonarscala'. Please uninstall one of the conflicting plugins.
</code>```

Could someone who worked with sonar scala confirm, is there no way I can keep both default scala rules and sonar scala work together in parallel? uninstalling existing sonarway scala is a risk for me

Body:
I am currently using SonarQube 8.9 LTS
I have tried to install sonar-scala https://github.com/sonar-scala/sonar-scala in extensions/plugins folder, but I am facing error like as below:

java.lang.IllegalStateException: There are two languages declared with the same key 'scala' declared by the plugins 'scala' and 'sonarscala'. Please uninstall one of the conflicting plugins.

Could someone who worked with sonar scala confirm, is there no way I can keep both default scala rules and sonar scala work together in parallel? uninstalling existing sonarway scala is a risk for me


问:
WebPush data is null
im busy with Webpush to WebRTC application and need some help understanding the way some of it fits together.

After looking at the RFC: https://www.rfc-editor.org/rfc/rfc8599#section-12
I see that in Section 12 :

```<code>   The value of the 'pn-provider' URI parameter is "webpush".
   The value of the 'pn-param' URI parameter MUST NOT be used.
   The value of the 'pn-prid' URI parameter is the push subscription
   URI.
</code>```

So, in my app.js I have implemented this something like this:

```<code>var pubKey = urlBase64ToUint8Array(<publicKey>)
var o = { userVisibleOnly: true, applicationServerKey: pubKey }
swg.pushManager.subscribe(o).then(function(sub){
    var contact-params = {
        "pn-provider" : "webpush"
        "pn-prid" : sub.endpoint
     }
    // apply contact-params, and register
}
</code>```

So as we can see above, the RFC specifies, 'pn-provider' and 'pn-prid' are to be used with your register. The pushManager.subscribe() provides me with this information, great... so far so good.

I have a Pubic key  that I use above (with is corresponding private key  that I have not used yet).

Now on the server my PHP code from here: https://github.com/web-push-libs/web-push-php
specifies a sample like the following:

```<code>$prid = $_GET['prid'];
$payload = '{ "text" : "Incoming Call !!" }';

$auth = array(
    'VAPID' => array(
        'subject' => $vapidSubject,
        'publicKey' => $publicKey, // Same as in app.js
        'privateKey' => $privateKey,
    )
);

$subscription = Subscription::create(
    array(
        'endpoint' => $prid,
        'contentEncoding' => 'aesgcm'
    )
);

$webPush = new WebPush($auth);
$report = $webPush -> sendOneNotification($subscription, $payload);
</code>```

The above php code works!... but, the payload (event.data) is null.

If I test with: https://web-push-codelab.glitch.me/ and give it the full subscription, with (the exact string of the sub from the app.js) it also works (as expected).

The same thing for my PHP code - If I add the keys:

```<code>$subscription = Subscription::create(
    array(
        'endpoint' => $prid,
        'keys' => [
            'p256dh' => '<sub.keys.p256dh>',
            'auth' => '<sub.keys.auth>'
        ],
        'contentEncoding' => 'aesgcm'
    )
);
</code>```

Then it work fine, and my payload is delivered.

So you can see, the problem is that the Push RFC says I only need to store 1 piece of information (endpoint), then have 1 common piece of information (public key) and 1 private piece of information (private key).

But in order for the the push code to work it needs 3 pieces of information, the endpoint, p256dh, auth, and then the public key and private key. (The p256dh and auth is of corse different with each endpoint.)

I think i'm missing something here, can someone help me understand this?

Title: WebPush data is null

Body:
im busy with Webpush to WebRTC application and need some help understanding the way some of it fits together.

After looking at the RFC: https://www.rfc-editor.org/rfc/rfc8599#section-12
I see that in Section 12 :

   The value of the 'pn-provider' URI parameter is "webpush".
   The value of the 'pn-param' URI parameter MUST NOT be used.
   The value of the 'pn-prid' URI parameter is the push subscription
   URI.

So, in my app.js I have implemented this something like this:

var pubKey = urlBase64ToUint8Array(<publicKey>)
var o = { userVisibleOnly: true, applicationServerKey: pubKey }
swg.pushManager.subscribe(o).then(function(sub){
    var contact-params = {
        "pn-provider" : "webpush"
        "pn-prid" : sub.endpoint
     }
    // apply contact-params, and register
}

So as we can see above, the RFC specifies, 'pn-provider' and 'pn-prid' are to be used with your register. The pushManager.subscribe() provides me with this information, great... so far so good.

I have a Pubic key  that I use above (with is corresponding private key  that I have not used yet).

Now on the server my PHP code from here: https://github.com/web-push-libs/web-push-php
specifies a sample like the following:

$prid = $_GET['prid'];
$payload = '{ "text" : "Incoming Call !!" }';

$auth = array(
    'VAPID' => array(
        'subject' => $vapidSubject,
        'publicKey' => $publicKey, // Same as in app.js
        'privateKey' => $privateKey,
    )
);

$subscription = Subscription::create(
    array(
        'endpoint' => $prid,
        'contentEncoding' => 'aesgcm'
    )
);

$webPush = new WebPush($auth);
$report = $webPush -> sendOneNotification($subscription, $payload);

The above php code works!... but, the payload (event.data) is null.

If I test with: https://web-push-codelab.glitch.me/ and give it the full subscription, with (the exact string of the sub from the app.js) it also works (as expected).

The same thing for my PHP code - If I add the keys:

$subscription = Subscription::create(
    array(
        'endpoint' => $prid,
        'keys' => [
            'p256dh' => '',
            'auth' => ''
        ],
        'contentEncoding' => 'aesgcm'
    )
);

Then it work fine, and my payload is delivered.

So you can see, the problem is that the Push RFC says I only need to store 1 piece of information (endpoint), then have 1 common piece of information (public key) and 1 private piece of information (private key).

But in order for the the push code to work it needs 3 pieces of information, the endpoint, p256dh, auth, and then the public key and private key. (The p256dh and auth is of corse different with each endpoint.)

I think i'm missing something here, can someone help me understand this?


问:
Double width and double height font in a JTextPane
I have the same question asked by Alex Ghilas here (https://stackoverflow.com/questions/66421996/how-to-put-double-width-and-double-height-characters-in-a-jtextpane#new-answer). I have tried the solution based on the AffineTransform proposed by user1324109, but it in my case it does not work for all the font sizes.

Here is a snippet of code that shows what I mean:

```<code>import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;

public class Test {

    static JTextPane textPane = new JTextPane();

    private static void displayText(String s, Font font) throws Exception {

        displayTextLine(s, font, 1.0, 1.0); // normal (48 characters)
        displayTextLine(s, font, 1.0, 2.0); // double height  (48 characters)
        displayTextLine(s.substring(0, 24), font, 2.0, 1.0); // double width (24 characters)
        displayTextLine(s.substring(0, 24), font, 2.0, 2.0); // double height and width (24 characters)

        displayTextLine("================================================", font, 1.0, 1.0);
    }

    private static void displayTextLine(String s, Font font, double scaleX, double scaleY) throws Exception {
        AffineTransform at = new AffineTransform();
        at.scale(scaleX, scaleY);
        Canvas c = new Canvas();
        Font renderFont = font.deriveFont(font.getStyle(), at);
        FontMetrics fm = c.getFontMetrics(renderFont);
        BufferedImage img = new BufferedImage(fm.stringWidth(s), fm.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setFont(renderFont);
        g.setColor(Color.black);
        g.drawString(s, 0, fm.getHeight() - fm.getDescent());
        textPane.insertIcon(new ImageIcon(img));
        Document doc = textPane.getDocument();
        doc.insertString(doc.getLength(), "\n", null);
    }

    public static void main(String args[]) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("Test");
                Container container = frame.getContentPane();
                container.add(new JScrollPane(textPane));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(600, 300);
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);

                for (int size = 10; size <= 26; size += 2) {
                    try {
                        displayText("ABCDEFGHIJKLMNOabcdefghxijklmnopqrstu01234567890",
                        new Font(Font.MONOSPACED, Font.PLAIN, size));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
</code>```

The test code print 4 line of text (normal, double height, double width and double height and width) with increasing font sizes. The normal and double height text is composed by 48 characters and the double width and double height and width text is composed by 24 characters, so I was expecting the same width in pixel for all the 4 string messages, for each font size.

The output shown by the above snippet is the following:

output produced by the above code snippet

Only at font size 10, 12, 18 and 20 the result is what I was expecting. The same is true for other font sizes. It seems there is a pattern: two sizes are OK, the next two not, the next two again are OK, and so on...

I have tried with different JRE version (1.6, 1.8 and 19), but the effect is always the same.

Someone has a clue about which could be the reason or I'm doing something wrong?

Body:
I have the same question asked by Alex Ghilas here (https://stackoverflow.com/questions/66421996/how-to-put-double-width-and-double-height-characters-in-a-jtextpane#new-answer). I have tried the solution based on the AffineTransform proposed by user1324109, but it in my case it does not work for all the font sizes.

Here is a snippet of code that shows what I mean:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;

public class Test {

    static JTextPane textPane = new JTextPane();

    private static void displayText(String s, Font font) throws Exception {

        displayTextLine(s, font, 1.0, 1.0); // normal (48 characters)
        displayTextLine(s, font, 1.0, 2.0); // double height  (48 characters)
        displayTextLine(s.substring(0, 24), font, 2.0, 1.0); // double width (24 characters)
        displayTextLine(s.substring(0, 24), font, 2.0, 2.0); // double height and width (24 characters)

        displayTextLine("================================================", font, 1.0, 1.0);
    }

    private static void displayTextLine(String s, Font font, double scaleX, double scaleY) throws Exception {
        AffineTransform at = new AffineTransform();
        at.scale(scaleX, scaleY);
        Canvas c = new Canvas();
        Font renderFont = font.deriveFont(font.getStyle(), at);
        FontMetrics fm = c.getFontMetrics(renderFont);
        BufferedImage img = new BufferedImage(fm.stringWidth(s), fm.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setFont(renderFont);
        g.setColor(Color.black);
        g.drawString(s, 0, fm.getHeight() - fm.getDescent());
        textPane.insertIcon(new ImageIcon(img));
        Document doc = textPane.getDocument();
        doc.insertString(doc.getLength(), "\n", null);
    }

    public static void main(String args[]) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("Test");
                Container container = frame.getContentPane();
                container.add(new JScrollPane(textPane));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(600, 300);
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);

                for (int size = 10; size <= 26; size += 2) {
                    try {
                        displayText("ABCDEFGHIJKLMNOabcdefghxijklmnopqrstu01234567890",
                        new Font(Font.MONOSPACED, Font.PLAIN, size));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

The test code print 4 line of text (normal, double height, double width and double height and width) with increasing font sizes. The normal and double height text is composed by 48 characters and the double width and double height and width text is composed by 24 characters, so I was expecting the same width in pixel for all the 4 string messages, for each font size.

The output shown by the above snippet is the following:

output produced by the above code snippet

Only at font size 10, 12, 18 and 20 the result is what I was expecting. The same is true for other font sizes. It seems there is a pattern: two sizes are OK, the next two not, the next two again are OK, and so on...

I have tried with different JRE version (1.6, 1.8 and 19), but the effect is always the same.

Someone has a clue about which could be the reason or I'm doing something wrong?


问:
.NET Web API Response DateTime format
Could someone assist me on this one. I am trying to make an API function where there is a response of an object the object has DateTime fields inside of it. When debugging the object itself has the correct datetime format (I set the intended datetime format globally) as follows:

```<code>var ci = new CultureInfo("en-US");
ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
ci.DateTimeFormat.ShortTimePattern = "HH:mm:ss";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss";
ci.DateTimeFormat.FullDateTimePattern = Constants.DateTimeFormat;

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(ci),
    SupportedCultures = new List<CultureInfo> { ci },
    SupportedUICultures = new List<CultureInfo> { ci }
});
</code>```

But after it is returned

```<code>return Ok(new FileResponseModel
            {
                File = file

            });
</code>```

it formats to nonsensical format that I never have set (that also includes letter T in the middle). Any advice how to set the format for the response would be great (I am testing the response with swagger and postman).

Title: .NET Web API Response DateTime format

Body:
Could someone assist me on this one. I am trying to make an API function where there is a response of an object the object has DateTime fields inside of it. When debugging the object itself has the correct datetime format (I set the intended datetime format globally) as follows:

var ci = new CultureInfo("en-US");
ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
ci.DateTimeFormat.ShortTimePattern = "HH:mm:ss";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss";
ci.DateTimeFormat.FullDateTimePattern = Constants.DateTimeFormat;

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(ci),
    SupportedCultures = new List<CultureInfo> { ci },
    SupportedUICultures = new List<CultureInfo> { ci }
});

But after it is returned

return Ok(new FileResponseModel
            {
                File = file

            });

it formats to nonsensical format that I never have set (that also includes letter T in the middle). Any advice how to set the format for the response would be great (I am testing the response with swagger and postman).


问:
accept xml as request body in asp.net 6 rest api
I need to accept xml as request body

Here is my controller

```<code>[HttpPost]
        [Route("UpdateLeaveBalance")]
        [ProducesResponseType(typeof(RootLeaveBalanceDto), (int)HttpStatusCode.OK)]
        public async Task<IActionResult> CreateOrUpdate([FromBody] RootLeaveBalanceDto model)
        {
            var result = await _leaveBalanceService.SetLeaveBalance(model);

            return OkResult(result);
        }
</code>```

here is the program.cs

```<code> services.AddControllersWithViews(options =>
    {
        options.Filters.Add(typeof(GlobalModelStateValidatorAttribute));
    }).AddXmlDataContractSerializerFormatters();
</code>```

I tried using this code i gave but when i set debuger i got no data but the post request gives 200

Body:
I need to accept xml as request body

Here is my controller

[HttpPost]
        [Route("UpdateLeaveBalance")]
        [ProducesResponseType(typeof(RootLeaveBalanceDto), (int)HttpStatusCode.OK)]
        public async Task<IActionResult> CreateOrUpdate([FromBody] RootLeaveBalanceDto model)
        {
            var result = await _leaveBalanceService.SetLeaveBalance(model);

            return OkResult(result);
        }

here is the program.cs

 services.AddControllersWithViews(options =>
    {
        options.Filters.Add(typeof(GlobalModelStateValidatorAttribute));
    }).AddXmlDataContractSerializerFormatters();

I tried using this code i gave but when i set debuger i got no data but the post request gives 200


问:
get changed context value after component re renders inside helper function
Intention:
I have a component called "ABC", and I am calling a helper function in a different file called "initTimer". Inside "initTimer" function I intend to change the context value using "setResendExpTime" function, and get the changed state value accessible from "authState".

Problem:
I am able to change the context value using "setResendExpTime", ABC component does rerender but my intention was to get a new state value inside "initTimer", after setting the context value failed. I keep on getting old context values. Is there any way I can pass the changed context value?

note: Inside the helper function, I am not able to use useContext hook so I am passing it as params.

I have this code inside my component:

```<code>file: ABC.js component:

const ABC = () => {
  const { authState, setResendExpTime } = useContext(AuthContext);

  const onNextPress = async () => {
      initTimer(authState, setResendExpTime);
  }

  // "setResendExpTime" called from inside of initTimer rerenders this component, and we have a new "authState" value here but not inside "initTimer"... maybe coz initTimer has already been called with the previous state value.
}
</code>```
```<code>file: helper.js

export const initTimer = (authState, setResendExpTime) => {

  console.log("auth val is", authState);
  // when initTImer is called authState is {name: "", lname: ""}

  setResendExpTime({
    name: "hello",
    lname: "world"
  });

  // problem: now I want to access the changed "authState" inside this function and carry out the rest of the function call. I also wish to run setResendExpTime again and again and get changed "authState".

</code>```

Body:
Intention:
I have a component called "ABC", and I am calling a helper function in a different file called "initTimer". Inside "initTimer" function I intend to change the context value using "setResendExpTime" function, and get the changed state value accessible from "authState".

Problem:
I am able to change the context value using "setResendExpTime", ABC component does rerender but my intention was to get a new state value inside "initTimer", after setting the context value failed. I keep on getting old context values. Is there any way I can pass the changed context value?

note: Inside the helper function, I am not able to use useContext hook so I am passing it as params.

I have this code inside my component:

file: ABC.js component:

const ABC = () => {
  const { authState, setResendExpTime } = useContext(AuthContext);

  const onNextPress = async () => {
      initTimer(authState, setResendExpTime);
  }

  // "setResendExpTime" called from inside of initTimer rerenders this component, and we have a new "authState" value here but not inside "initTimer"... maybe coz initTimer has already been called with the previous state value.
}

file: helper.js

export const initTimer = (authState, setResendExpTime) => {

  console.log("auth val is", authState);
  // when initTImer is called authState is {name: "", lname: ""}

  setResendExpTime({
    name: "hello",
    lname: "world"
  });

  // problem: now I want to access the changed "authState" inside this function and carry out the rest of the function call. I also wish to run setResendExpTime again and again and get changed "authState".


问:
PredicateBuilder null check not added to query
I have a situation where I want to query an accounts table. I want all accounts except accounts where ParentId != null as default.

I have tried the following with the predicate builder, but it does not take effect in the sql query. Any idea how to add the whereClause.And(a => a.ParentId != null); check when using the LinqKit PredicateBuilder?

```<code> var whereClause = PredicateBuilder.New<VAccount>(true);

 whereClause = whereClause.And(a => a.ParentId != null); // Not added to query

 if (dto.OrganisationId != 0)
    whereClause = whereClause.Or(a => a.OrganisationId == dto.OrganisationId);

 // Other search inputs added etc..
</code>```

Body:
I have a situation where I want to query an accounts table. I want all accounts except accounts where ParentId != null as default.

I have tried the following with the predicate builder, but it does not take effect in the sql query. Any idea how to add the whereClause.And(a => a.ParentId != null); check when using the LinqKit PredicateBuilder?

 var whereClause = PredicateBuilder.New<VAccount>(true);

 whereClause = whereClause.And(a => a.ParentId != null); // Not added to query

 if (dto.OrganisationId != 0)
    whereClause = whereClause.Or(a => a.OrganisationId == dto.OrganisationId);

 // Other search inputs added etc..


问:
Prisma client won't run on Raspbian 64 bit
As I understand Prisma should have binaries which support Raspbian 64 bit. However whenever I try to run any Prisma commands (npx prisma db push for example) I still get

%Error: Not Found https://binaries.prisma.sh/all_commits/d6e67a83f971b175a593ccc12e15c4a757f93ffe/linux-arm-openssl-1.1.x/prisma-fmt.gz

If I run uname -m it returns aarch64.


问:
i have put refferal id in form input feild which is present in url
I have created a referral link in my angular project which has carry a referral id when I copy that link and search on browser I want that referral number in the input field of the form on that page. Can anyone tell me the solution

i had with save this referal link in variable and display in interpolation but in form field referal link is not showing


问:
Django Rest Framework adding import in settings.py causes 403 error
I have a Django Rest Framework application with custom render and parse classes, set in settings.py:

```<code>REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
    ),
}
</code>```

And at this point everything works fine.

But if I add import statement in settings.py like this:

```<code>from djangorestframework_camel_case.render import CamelCaseJSONRenderer
REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
    ),
}
</code>```

I start to get 403 error.
Why is that? How may I fix it?

Just in case it somehow matters my installed apps:

```<code>INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.postgres",
    "django.contrib.sessions",
    "django.contrib.staticfiles",
    "corsheaders",
    "django_filters",

    "rest_framework",

    "my_porject.my_app",
]
</code>```

Body:
I have a Django Rest Framework application with custom render and parse classes, set in settings.py:

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
    ),
}

And at this point everything works fine.

But if I add import statement in settings.py like this:

from djangorestframework_camel_case.render import CamelCaseJSONRenderer
REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "djangorestframework_camel_case.render.CamelCaseJSONRenderer",
        "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "djangorestframework_camel_case.parser.CamelCaseFormParser",
        "djangorestframework_camel_case.parser.CamelCaseMultiPartParser",
        "djangorestframework_camel_case.parser.CamelCaseJSONParser",
    ),
}

I start to get 403 error.
Why is that? How may I fix it?

Just in case it somehow matters my installed apps:

INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.postgres",
    "django.contrib.sessions",
    "django.contrib.staticfiles",
    "corsheaders",
    "django_filters",

    "rest_framework",

    "my_porject.my_app",
]


问:
Getting Status : 415 while making POST Request using fetch
I am trying to make POST request using fetch. I am actually following docs example. Docs Provided curl example to make POST request

```<code>curl -X POST https://example.com/upload/01
 -d "api_key=948324jkl3h45h"
 -d "@path/filename.mp4"
 -H "Content-Type: application/x-www-form-urlencoded"
</code>```

There is .mp4 file in my dir. I wrote a simple script to make POST request using fetch. Here is my code.

```<code>const filePath = path.join(__dirname , "/video/video.mp4");
const fileData = fs.createReadStream(filePath);
fetch(url, {
        body: `api_key=${API_KEY}&${fileData}`,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST"
      }).then(result => {
        console.log(result)
      })
</code>```

When I make POST request I am getting this error.

```<code>Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https:/example.com/upload/01',
    status: 415,
    statusText: 'Unsupported Media Type',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}
</code>```

I read file using fs.createReadStream. Is that actually right? If there is something wrong, please point me out. I thought some of my file system getting wrong while reading mp4. I wish someone can help me.

Thank youu.

Body:
I am trying to make POST request using fetch. I am actually following docs example. Docs Provided curl example to make POST request

curl -X POST https://example.com/upload/01
 -d "api_key=948324jkl3h45h"
 -d "@path/filename.mp4"
 -H "Content-Type: application/x-www-form-urlencoded"

There is .mp4 file in my dir. I wrote a simple script to make POST request using fetch. Here is my code.

const filePath = path.join(__dirname , "/video/video.mp4");
const fileData = fs.createReadStream(filePath);
fetch(url, {
        body: `api_key=${API_KEY}&${fileData}`,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST"
      }).then(result => {
        console.log(result)
      })

When I make POST request I am getting this error.

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https:/example.com/upload/01',
    status: 415,
    statusText: 'Unsupported Media Type',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

I read file using fs.createReadStream. Is that actually right? If there is something wrong, please point me out. I thought some of my file system getting wrong while reading mp4. I wish someone can help me.

Thank youu.


问:
How to make a C++ STACK container iterable?
Can we write a myStack class that will be implemented in terms of std::stack so that it offers all of its member functions plus an additional feature: iterators?

I tried some options, but they seem to me not quite optimal.


问:
I want to generate all table creation statements through information_schema
I want to read the information_schema to generate a table creation statement through the tables inside, and then send it to bigquery to realize the table creation, but I know what kind of solution can realize my idea

currently looking for some solutions


问:
GORM v2 Many to Many does not create new record in join table
Two structs Thread & Interest have a many to many relationship with each other. According to the documentation this is how both structs looks like:

```<code>type Thread struct {
    ID        uuid.UUID `gorm:"primaryKey" json:"threadId"`
    Title     string    `gorm:"not null" json:"title"`
    Body      string    `gorm:"not null" json:"body"`
    CreatedAt time.Time
    UpdatedAt time.Time

    // Foreign keys
    UserID uuid.UUID `json:"userId"`

    // Has many association
    Comments []Comment `json:"comments"`

    // many to many associations
    Interests     []Interest `gorm:"many2many:thread_interests;" json:"interests"`
    UsersLiked    []User     `gorm:"many2many:post_likes;" json:"usersLiked"`
    UsersDisliked []User     `gorm:"many2many:post_dislikes;" json:"usersDisliked"`
}

type Interest struct {
    ID        uuid.UUID `gorm:"primaryKey" json:"interestId"`
    Name      string    `json:"name"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`

    // Many to many associations
    UserProfiles []UserProfile `gorm:"many2many:user_interests;" json:"userProfiles"`
    Threads      []Thread      `gorm:"many2many:thread_interests;" json:"threads"`
}
</code>```

Since it is many to many between both structs I created another struct to act as join table named ThreadInterest. The code:

```<code>type ThreadInterest struct {
    ThreadID   uuid.UUID `gorm:"primaryKey;"`
    InterestID uuid.UUID `gorm:"primaryKey;"`
    CreatedAt  time.Time
    UpdatedAt  time.Time
}
</code>```

The problem is that whenever I create a new thread with the corresponding interests it creates the thread record but no new record is created in the join table ThreadInterest. I tried reading the documentation and searching online but I can't find a solution. I hope you guys could help me on this.

UPDATE:
Here is how I create the thread

handler:

```<code>func HandleCreateThread(context *gin.Context) {

    var threadInput apimodels.ThreadInput

    err := context.ShouldBindJSON(&threadInput)

    if err != nil {
        // return error
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    userId, err := api.GetTokenUserId(context)

    if err != nil {
        // return error
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    var interests []databasemodels.Interest

    interests, err = dataaccess.FindInterestByIds(threadInput.Interests)

    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    thread := databasemodels.Thread{
        Title:     threadInput.Title,
        Body:      threadInput.Body,
        Interests: interests,
        UserID:    userId,
    }

    newThread, err := dataaccess.CreateNewThread(&thread)

    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    context.JSON(http.StatusOK, gin.H{"thread": newThread})
}
</code>```

dataaccess:

```<code>func CreateNewThread(thread *databasemodels.Thread) (*databasemodels.Thread, error) {
    // Generate ID and hash password
    thread.ID = api.GenerateUUID()

    // store to database
    err := database.Database.Create(&thread).Error
    if err != nil {
        return &(databasemodels.Thread{}), err
    }
    return thread, nil
}
</code>```

And this is how I migrate my database:

```<code>var Database *gorm.DB

// start a connection to the specified postgresql db from env file
func ConnectDb() {
    var err error
    host := os.Getenv("DB_HOST")
    username := os.Getenv("DB_USER")
    password := os.Getenv("DB_PASSWORD")
    databaseName := os.Getenv("DB_NAME")
    port := os.Getenv("DB_PORT")

    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Africa/Lagos", host, username, password, databaseName, port)
    Database, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic(err)
    } else {
        fmt.Println("Successfully connected to the database")
    }
}

// conducts migrations to the connected database (built-in GORM functionality)

func AutoMigrateDb() {

    Database.AutoMigrate(
        &(databasemodels.User{}),
        &(databasemodels.UserProfile{}),
        &(databasemodels.Interest{}),
        &(databasemodels.UserInterest{}),
        &(databasemodels.Comment{}),
        &(databasemodels.Thread{}),
        &(databasemodels.ThreadInterest{}),
        &(databasemodels.PostLike{}),
        &(databasemodels.PostDislike{}),
        &(databasemodels.CommentLike{}),
        &(databasemodels.CommentDislike{}),
    )
}
</code>```

Body:
Two structs Thread & Interest have a many to many relationship with each other. According to the documentation this is how both structs looks like:

type Thread struct {
    ID        uuid.UUID `gorm:"primaryKey" json:"threadId"`
    Title     string    `gorm:"not null" json:"title"`
    Body      string    `gorm:"not null" json:"body"`
    CreatedAt time.Time
    UpdatedAt time.Time

    // Foreign keys
    UserID uuid.UUID `json:"userId"`

    // Has many association
    Comments []Comment `json:"comments"`

    // many to many associations
    Interests     []Interest `gorm:"many2many:thread_interests;" json:"interests"`
    UsersLiked    []User     `gorm:"many2many:post_likes;" json:"usersLiked"`
    UsersDisliked []User     `gorm:"many2many:post_dislikes;" json:"usersDisliked"`
}

type Interest struct {
    ID        uuid.UUID `gorm:"primaryKey" json:"interestId"`
    Name      string    `json:"name"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`

    // Many to many associations
    UserProfiles []UserProfile `gorm:"many2many:user_interests;" json:"userProfiles"`
    Threads      []Thread      `gorm:"many2many:thread_interests;" json:"threads"`
}

Since it is many to many between both structs I created another struct to act as join table named ThreadInterest. The code:

type ThreadInterest struct {
    ThreadID   uuid.UUID `gorm:"primaryKey;"`
    InterestID uuid.UUID `gorm:"primaryKey;"`
    CreatedAt  time.Time
    UpdatedAt  time.Time
}

The problem is that whenever I create a new thread with the corresponding interests it creates the thread record but no new record is created in the join table ThreadInterest. I tried reading the documentation and searching online but I can't find a solution. I hope you guys could help me on this.

UPDATE:
Here is how I create the thread

handler:

func HandleCreateThread(context *gin.Context) {

    var threadInput apimodels.ThreadInput

    err := context.ShouldBindJSON(&threadInput)

    if err != nil {
        // return error
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    userId, err := api.GetTokenUserId(context)

    if err != nil {
        // return error
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    var interests []databasemodels.Interest

    interests, err = dataaccess.FindInterestByIds(threadInput.Interests)

    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    thread := databasemodels.Thread{
        Title:     threadInput.Title,
        Body:      threadInput.Body,
        Interests: interests,
        UserID:    userId,
    }

    newThread, err := dataaccess.CreateNewThread(&thread)

    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    context.JSON(http.StatusOK, gin.H{"thread": newThread})
}

dataaccess:

func CreateNewThread(thread *databasemodels.Thread) (*databasemodels.Thread, error) {
    // Generate ID and hash password
    thread.ID = api.GenerateUUID()

    // store to database
    err := database.Database.Create(&thread).Error
    if err != nil {
        return &(databasemodels.Thread{}), err
    }
    return thread, nil
}

And this is how I migrate my database:

var Database *gorm.DB

// start a connection to the specified postgresql db from env file
func ConnectDb() {
    var err error
    host := os.Getenv("DB_HOST")
    username := os.Getenv("DB_USER")
    password := os.Getenv("DB_PASSWORD")
    databaseName := os.Getenv("DB_NAME")
    port := os.Getenv("DB_PORT")

    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Africa/Lagos", host, username, password, databaseName, port)
    Database, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic(err)
    } else {
        fmt.Println("Successfully connected to the database")
    }
}

// conducts migrations to the connected database (built-in GORM functionality)

func AutoMigrateDb() {

    Database.AutoMigrate(
        &(databasemodels.User{}),
        &(databasemodels.UserProfile{}),
        &(databasemodels.Interest{}),
        &(databasemodels.UserInterest{}),
        &(databasemodels.Comment{}),
        &(databasemodels.Thread{}),
        &(databasemodels.ThreadInterest{}),
        &(databasemodels.PostLike{}),
        &(databasemodels.PostDislike{}),
        &(databasemodels.CommentLike{}),
        &(databasemodels.CommentDislike{}),
    )
}


问:
D3 how to use collision with text elements
I am making an application in which there are words displayed on screen. The users can drag them (this works).

I wanted to add an additional functionality though. I want the words to push each other away/prevent overlap when they are being dragged to each other.

I have tried to mess around with the code below, but I can't figure it out.

```<code>const simulation = d3
                .forceSimulation()
                .alphaTarget(0.8) // stay hot
                .velocityDecay(0.1) // low friction
                .force("x", d3.forceX().strength(0.05))
                .force("y", d3.forceY().strength(0.05))
                .force("collide", d3.forceCollide().strength(1).radius(15).iterations(10))
                .force("charge", d3.forceManyBody().strength(0.4)) // Nodes are attracted one each other of value is > 0
                .on("tick", function () {
                    wordcloudSvg
                        .selectAll(".keywords")
                        .attr("x", function (d) {
                            return d.x;
                        })
                        .attr("y", function (d) {
                            return d.y;
                        });
                });
            simulation.nodes(this.keywords).alphaTarget(0.5).alphaDecay(0.05).restart();
</code>```

I have messed with adding extra things like force many body, and changing the strength/radius. But nothing seems to work.

Here is my svg:

```<code>let wordcloudSvg = d3
                .select(".wordcloud-svg .keywords")
                .selectAll("text")
                .data(this.keywords)
                .enter()
                .append("text")
                .text(function (d) {
                    return d.title;
                })
                .attr("x", function (d) {
                    return d.position_x;
                })
                .attr("y", function (d) {
                    return d.position_y;
                })
                .attr("fill", function (d) {
                    return d.color;
                })
                .style("font-size", function (d) {
                    return d.font_size + "px";
                })
                .attr("data-id", function (d) {
                    return d.id;
                })
                .attr("class", "keyword")
                .call(d3
                        .drag()
                        .on("start", function (event) {
                            // simulation.stop();
                            let current = d3.select(this);
                            deltaX = current.attr("x") - event.x;
                            deltaY = current.attr("y") - event.y;
                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });
                        })
                        .on("drag", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });
                        })
                        .on("end", function (event) {
                            let current = d3.select(this);

                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });

                            self.keywords.filter((obj) => {
                                if (obj.title == current.text()) {
                                    obj.position_x = event.x + deltaX;
                                    obj.position_y = event.y + deltaY;
                                }
                            });
                            transcriptApi.updateKeywords(self.routeId, current);
                            const keywordElements = document.querySelectorAll(".keyword");

                            if (event.sourceEvent.clientX >= 43 && event.sourceEvent.clientX <= 140 && event.sourceEvent.clientY >= 20 && event.sourceEvent.clientY <= 170) {
                                keywordElements.forEach((el) => {
                                    if (current.text() == el.textContent) {
                                        self.keywords.filter((obj) => {
                                            if (obj.title == el.textContent) {
                                                el.remove();
                                                transcriptApi.deleteKeyword(self.routeId, obj.id);
                                                let index = self.keywords.indexOf(obj);
                                                self.keywords.splice(index, 1);
                                                window.Echo.private("meeting." + self.$route.params.id).whisper("context", { data: "nothing", id: el.getAttribute("data-id"), type: "delete" });
                                            }
                                        });
                                    }
                                });
                            }
                        })
                );d3
                        .drag()
                        .on("start", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                            });
                        })
                        .on("drag", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                        })
                        .on("end", function (event) {
                            let current = d3.select(this);

                            self.keywords.filter((obj) => {
                                if (obj.title == current.text()) {
                                    obj.position_x = event.x + deltaX;
                                    obj.position_y = event.y + deltaY;
                                }
                            });

                        })
                );
</code>```

Body:
I am making an application in which there are words displayed on screen. The users can drag them (this works).

I wanted to add an additional functionality though. I want the words to push each other away/prevent overlap when they are being dragged to each other.

I have tried to mess around with the code below, but I can't figure it out.

const simulation = d3
                .forceSimulation()
                .alphaTarget(0.8) // stay hot
                .velocityDecay(0.1) // low friction
                .force("x", d3.forceX().strength(0.05))
                .force("y", d3.forceY().strength(0.05))
                .force("collide", d3.forceCollide().strength(1).radius(15).iterations(10))
                .force("charge", d3.forceManyBody().strength(0.4)) // Nodes are attracted one each other of value is > 0
                .on("tick", function () {
                    wordcloudSvg
                        .selectAll(".keywords")
                        .attr("x", function (d) {
                            return d.x;
                        })
                        .attr("y", function (d) {
                            return d.y;
                        });
                });
            simulation.nodes(this.keywords).alphaTarget(0.5).alphaDecay(0.05).restart();

I have messed with adding extra things like force many body, and changing the strength/radius. But nothing seems to work.

Here is my svg:

let wordcloudSvg = d3
                .select(".wordcloud-svg .keywords")
                .selectAll("text")
                .data(this.keywords)
                .enter()
                .append("text")
                .text(function (d) {
                    return d.title;
                })
                .attr("x", function (d) {
                    return d.position_x;
                })
                .attr("y", function (d) {
                    return d.position_y;
                })
                .attr("fill", function (d) {
                    return d.color;
                })
                .style("font-size", function (d) {
                    return d.font_size + "px";
                })
                .attr("data-id", function (d) {
                    return d.id;
                })
                .attr("class", "keyword")
                .call(d3
                        .drag()
                        .on("start", function (event) {
                            // simulation.stop();
                            let current = d3.select(this);
                            deltaX = current.attr("x") - event.x;
                            deltaY = current.attr("y") - event.y;
                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });
                        })
                        .on("drag", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });
                        })
                        .on("end", function (event) {
                            let current = d3.select(this);

                            window.Echo.private("meeting." + self.routeId).whisper("drag", {
                                id: current.attr("data-id"),
                                phase: "start",
                                delta: { deltaX, deltaY },
                                event: event,
                                title: current.text(),
                            });

                            self.keywords.filter((obj) => {
                                if (obj.title == current.text()) {
                                    obj.position_x = event.x + deltaX;
                                    obj.position_y = event.y + deltaY;
                                }
                            });
                            transcriptApi.updateKeywords(self.routeId, current);
                            const keywordElements = document.querySelectorAll(".keyword");

                            if (event.sourceEvent.clientX >= 43 && event.sourceEvent.clientX <= 140 && event.sourceEvent.clientY >= 20 && event.sourceEvent.clientY <= 170) {
                                keywordElements.forEach((el) => {
                                    if (current.text() == el.textContent) {
                                        self.keywords.filter((obj) => {
                                            if (obj.title == el.textContent) {
                                                el.remove();
                                                transcriptApi.deleteKeyword(self.routeId, obj.id);
                                                let index = self.keywords.indexOf(obj);
                                                self.keywords.splice(index, 1);
                                                window.Echo.private("meeting." + self.$route.params.id).whisper("context", { data: "nothing", id: el.getAttribute("data-id"), type: "delete" });
                                            }
                                        });
                                    }
                                });
                            }
                        })
                );d3
                        .drag()
                        .on("start", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                            });
                        })
                        .on("drag", function (event) {
                            let current = d3.select(this);
                            if (event.x >= 60 && event.x <= 1400) {
                                d3.select(this).attr("x", event.x + deltaX);
                            }
                            if (event.y >= 30 && event.y <= 545) {
                                d3.select(this).attr("y", event.y + deltaY);
                            }
                        })
                        .on("end", function (event) {
                            let current = d3.select(this);

                            self.keywords.filter((obj) => {
                                if (obj.title == current.text()) {
                                    obj.position_x = event.x + deltaX;
                                    obj.position_y = event.y + deltaY;
                                }
                            });

                        })
                );


问:
Fetch signature from IONOS webmail
I am using SMTP in Python to send the emails from IONOS webmail and it is working fine. However, I would need to send emails with the signature that I have setup in IONOS webmail and I cant find a way to fetch that signature with Image. Please help out.</p>

Title: Fetch signature from IONOS webmail


问:
problem with file mounts in Nginx and php fpm containers
I have two containers:

laravel with php:8.1-fpm-bullseye container exposed on 9000

nginx with nginx:1.23.1

nginx uses fastcgi_pass directive in configuration file

Question:
why do i need to also mount my app source code to nginx /var/www/html directory when all nginx does is that it turns http request to fastcgi request and passes them to laravel container? ( I commented out try_files directive in configuration but I'm still getting 404 response from nginx)

./nginx/nginx-default.conf:

```<code>upstream backend {
    server laravel:9000;
}

server {
    listen 80;
    listen [::]:80;
    server_name _;

    error_log /var/log/nginx/error80.log;
    access_log /var/log/nginx/access80.log custom;

    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl_certificate /etc/ssl/certs/localhost.crt;
    ssl_certificate_key /etc/ssl/private/localhost.key;

    root /var/www/html/public;

    error_log /var/log/nginx/error443.log;
    access_log /var/log/nginx/access443.log custom;

    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ [^/]\.php(/|$) {
        try_files $uri =404;
        fastcgi_pass backend;
        fastcgi_index index.php;
        fastcgi_keep_conn on;
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param CONTENT_TYPE $content_type;
        fastcgi_param CONTENT_LENGTH $content_length;
        fastcgi_param REDIRECT_STATUS 200;
    }

}
</code>```

./docker-compose.yml:

```<code>version: "3.8"

services:
  user:
    container_name: user
    build:
      context: ./
      dockerfile: Dockerfile.development
    volumes:
      - ./:/var/www/html:rw
    networks:
      - user
  user-nginx:
    container_name: user-nginx
    build:
      context: ./nginx
      dockerfile: Dockerfile.development
    volumes:
      # - ./:/var/www/html:rw # here !
      - ./nginx/nginx-default.conf:/etc/nginx/conf.d/default.conf:rw
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:rw
      - ./nginx/logs:/var/log/nginx:rw
    networks:
      - user
    depends_on:
      - user

networks:
  user:
    driver: bridge

</code>```

./nginx/Dockerfile.development:

```<code>FROM nginx:1.23.3

USER root

RUN usermod -aG root nginx

EXPOSE 80 443
</code>```

Body:
I have two containers:

laravel with php:8.1-fpm-bullseye container exposed on 9000

nginx with nginx:1.23.1

nginx uses fastcgi_pass directive in configuration file

Question:
why do i need to also mount my app source code to nginx /var/www/html directory when all nginx does is that it turns http request to fastcgi request and passes them to laravel container? ( I commented out try_files directive in configuration but I'm still getting 404 response from nginx)

./nginx/nginx-default.conf:

upstream backend {
    server laravel:9000;
}

server {
    listen 80;
    listen [::]:80;
    server_name _;

    error_log /var/log/nginx/error80.log;
    access_log /var/log/nginx/access80.log custom;

    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl_certificate /etc/ssl/certs/localhost.crt;
    ssl_certificate_key /etc/ssl/private/localhost.key;

    root /var/www/html/public;

    error_log /var/log/nginx/error443.log;
    access_log /var/log/nginx/access443.log custom;

    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ [^/]\.php(/|$) {
        try_files $uri =404;
        fastcgi_pass backend;
        fastcgi_index index.php;
        fastcgi_keep_conn on;
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param CONTENT_TYPE $content_type;
        fastcgi_param CONTENT_LENGTH $content_length;
        fastcgi_param REDIRECT_STATUS 200;
    }

}

./docker-compose.yml:

version: "3.8"

services:
  user:
    container_name: user
    build:
      context: ./
      dockerfile: Dockerfile.development
    volumes:
      - ./:/var/www/html:rw
    networks:
      - user
  user-nginx:
    container_name: user-nginx
    build:
      context: ./nginx
      dockerfile: Dockerfile.development
    volumes:
      # - ./:/var/www/html:rw # here !
      - ./nginx/nginx-default.conf:/etc/nginx/conf.d/default.conf:rw
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:rw
      - ./nginx/logs:/var/log/nginx:rw
    networks:
      - user
    depends_on:
      - user

networks:
  user:
    driver: bridge

./nginx/Dockerfile.development:

FROM nginx:1.23.3

USER root

RUN usermod -aG root nginx

EXPOSE 80 443


问:
How can I detect any change in Linear Regression Candle color from red to green or green to red after plotting them using plotcandle()
Assume lrcopen, lrchigh, lrclow, lrcclose are the open, high, low, close of Linear Regression Candle which is plotted using plotcandle(). I want to check and compare the lrcopen < lrcclose value for last two closed Linear Regression Candle to see whether it changes from false to true or vice versa after plotting</p>
```<code>//@version=4
study(title="Humble LinReg Candles", shorttitle="LinReg Candles", format=format.price, precision=4, overlay=true)

signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 200, defval =7)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=true)

lin_reg = input(title="Lin Reg", type=input.bool, defval=true)
linreg_length = input(title="Linear Regression Length", type=input.integer, minval = 1, maxval = 200, defval = 11)

bopen = lin_reg ? linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? linreg(high, linreg_length, 0) : high
blow = lin_reg ? linreg(low, linreg_length, 0) : low
bclose = lin_reg ? linreg(close, linreg_length, 0) : close

r = bopen < bclose

signal = sma_signal ? sma(bclose, signal_length) : ema(bclose, signal_length)

plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow: na, r ? bclose : na, title="LinReg Candles", color= color.green, wickcolor=color.green, bordercolor=color.green, editable= true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose, title="LinReg Candles", color=color.red, wickcolor=color.red, bordercolor=color.red, editable= true)

// I want to detect the change of color of just plotted Linear Regression Candle here
</code>```

Body:
Assume lrcopen, lrchigh, lrclow, lrcclose are the open, high, low, close of Linear Regression Candle which is plotted using plotcandle(). I want to check and compare the lrcopen < lrcclose value for last two closed Linear Regression Candle to see whether it changes from false to true or vice versa after plotting

//@version=4
study(title="Humble LinReg Candles", shorttitle="LinReg Candles", format=format.price, precision=4, overlay=true)

signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 200, defval =7)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=true)

lin_reg = input(title="Lin Reg", type=input.bool, defval=true)
linreg_length = input(title="Linear Regression Length", type=input.integer, minval = 1, maxval = 200, defval = 11)

bopen = lin_reg ? linreg(open, linreg_length, 0) : open
bhigh = lin_reg ? linreg(high, linreg_length, 0) : high
blow = lin_reg ? linreg(low, linreg_length, 0) : low
bclose = lin_reg ? linreg(close, linreg_length, 0) : close

r = bopen < bclose

signal = sma_signal ? sma(bclose, signal_length) : ema(bclose, signal_length)

plotcandle(r ? bopen : na, r ? bhigh : na, r ? blow: na, r ? bclose : na, title="LinReg Candles", color= color.green, wickcolor=color.green, bordercolor=color.green, editable= true)
plotcandle(r ? na : bopen, r ? na : bhigh, r ? na : blow, r ? na : bclose, title="LinReg Candles", color=color.red, wickcolor=color.red, bordercolor=color.red, editable= true)

// I want to detect the change of color of just plotted Linear Regression Candle here


问:
I am using Java SE 17 for my project. But to access an endpoint I need to use compiler level SE 1.7 or below
I am using SE 17 but to access an SOAP API Endpoint in java I need a jdk version of 1.7 or below , else the compiler throws me and exception as "The package javax.xml.namespace is accessible from more than one module: , java.xml".I've tried to add the java.xml package into classpath and re-run my whole project but it's still not working.I need to run javax.xml.namespace in simple core JAVA SE 17 (not any maven or gradle project).</p>


问:
Nextjs Apache .htaccess redirects my app to base url on refresh
I have a static application in production, and it's hosted on apache server, now everything is working fine except when I go to a single resource (details page), and refresh, the app goes back to the base url.

https://{base_url}/dashboard/invoices/list/ (refreshes alright)

https://{base_url}/dashboard/invoices/150/ (goes back to {base_url})

My .htaccess file:

```<code>RewriteEngine On

RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.html [L]
</code>```

Body:
I have a static application in production, and it's hosted on apache server, now everything is working fine except when I go to a single resource (details page), and refresh, the app goes back to the base url.

https://{base_url}/dashboard/invoices/list/ (refreshes alright)

https://{base_url}/dashboard/invoices/150/ (goes back to {base_url})

My .htaccess file:

RewriteEngine On

RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.html [L]