问:
Why can some PKCS#8 private keys be imported and some can not?
I have been trying to import my PKCS#8 private key from Apple (used for signing JWTs for their Web services/APIs), for use with the browser's Subtle Crypto API (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import). When I try with my private key it fails saying "Data provided to an operation does not meet requirements" but when I use the private key used in the example, it works. The code I have been trying with is from the example on the above URL.

I need a solution that works with vanilla JS, so I can't use npm packages.

The code I use for importing is this:

async function getPrivateKey() {
  try {
    const privateKey = await importPrivateKey(failingPemEncodedKey);
    //const privateKey = await importPrivateKey(succeedingPemEncodedKey);
    console.log('privateKey', privateKey);
  } catch (error) {
    console.log('ERROR', error.message);
  }
  return privateKey;
}

const failingPemEncodedKey = `-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg/zwtY1nn6uLpYyukIMgEX4pNgp7GQFevZSr9jkMFSR6gCgYIKoZIzj0DAQehRANCAASC0fq/OiBuA2UpHukZHxj88cZJXoesjhxBfO/XAKGlnRFM0QomoF1aoFlkFGvHU/3h53J/dxAwRzNSy++6CyEu
-----END PRIVATE KEY-----`;

const succeedingPemEncodedKey = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDD0tPV/du2vftjvXj1t/gXTK39sNBVrOAEb/jKzXae+Xa0H+3LhZaQIQNMfACiBSgIfZUvEGb+7TqXWQpoLoFR/R7MvGWcSk98JyrVtveD8ZmZYyItSY7m2hcasqAFiKyOouV5vzyRe87/lEyzzBpF3bQQ4IDaQu+K9Hj5fKuU6rrOeOhsdnJc+VdDQLScHxvMoLZ9Vtt+oK9J4/tOLwr4CG8khDlBURcBY6gPcLo3dPU09SW+6ctX2cX4mkXx6O/0mmdTmacr/vu50KdRMleFeZYOWPAEhhMfywybTuzBiPVIZVP8WFCSKNMbfi1S9A9PdBqnebwwHhX3/hsEBt2BAgMBAAECggEABEI1P6nf6Zs7mJlyBDv+Pfl5rjL2cOqLy6TovvZVblMkCPpJyFuNIPDK2tK2i897ZaXfhPDBIKmllM2Hq6jZQKB110OAnTPDg0JxzMiIHPs32S1d/KilHjGff4Hjd4NXp1l1Dp8BUPOllorR2TYm2x6dcCGFw9lhTr8O03Qp4hjn84VjGIWADYCk83mgS4nRsnHkdiqYnWx1AjKlY51yEK6RcrDMi0Th2RXrrINoC35sVv+APt2rkoMGi52RwTEseA1KZGFrxjq61ReJif6p2VXEcvHeX6CWLx014LGk43z6Q28P6HgeEVEfIjyqCUea5Du/mYb/QsRSCosXLxBqwQKBgQD1+fdC9ZiMrVI+km7Nx2CKBn8rJrDmUh5SbXn2MYJdrUd8bYNnZkCgKMgxVXsvJrbmVOrby2txOiqudZkk5mD3E5O/QZWPWQLgRu8ueYNpobAX9NRgNfZ7rZD+81vh5MfZiXfuZOuzv29iZhU0oqyZ9y75eHkLdrerNkwYOe5aUQKBgQDLzapDi1NxkBgsj9iiO4KUa7jvD4JjRqFy4Zhj/jbQvlvM0F/uFp7sxVcHGx4r11C+6iCbhX4u+Zuu0HGjT4d+hNXmgGyxR8fIUVxOlOtDkVJa5sOBZK73/9/MBeKusdmJPRhalZQfMUJRWIoEVDMhfg3tW/rBj5RYAtP2dTVUMQKBgDs8yr52dRmT+BWXoFWwaWB0NhYHSFz/c8v4D4Ip5DJ5M5kUqquxJWksySGQa40sbqnD05fBQovPLU48hfgr/zghn9hUjBcsoZOvoZR4sRw0UztBvA+7jzOz1hKAOyWIulR6Vca0yUrNlJ6G5R56+sRNkiOETupi2dLCzcqb0PoxAoGAZyNHvTLvIZN4iGSrjz5qkM4LIwBIThFadxbv1fq6pt0O/BGf2o+cEdq0diYlGK64cEVwBwSBnSg4vzlBqRIAUejLjwEDAJyA4EE8Y5A9l04dzV7nJb5cRak6CrgXxay/mBJRFtaHxVlaZGxYPGSYE6UFS0+3EOmmevvDZQBf4qECgYEA0ZF6Vavz28+8wLO6SP3w8NmpHk7K9tGEvUfQ30SgDx4G7qPIgfPrbB4OP/E0qCfsIImi3sCPpjvUMQdVVZyPOIMuB+rV3ZOxkrzxEUOrpOpR48FZbL7RN90yRQsAsrp9e4iv8QwB3VxLe7X0TDqqnRyqrc/osGzuS2ZcHOKmCU8=
-----END PRIVATE KEY-----`;

async function importPrivateKey(pem) {
  const pemHeader = '-----BEGIN PRIVATE KEY-----';
  const pemFooter = '-----END PRIVATE KEY-----';
  const pemContents = pem.substring(
    pemHeader.length,
    pem.length - pemFooter.length
  );
  const binaryDerString = window.atob(pemContents);
  const binaryDer = str2ab(binaryDerString);
  const privateKey = await window.crypto.subtle.importKey(
    'pkcs8',
    binaryDer,
    {
      name: 'RSA-PSS',
      hash: 'SHA-256',
    },
    true,
    ['sign']
  );
  return privateKey;
}
```

I have tried the code in a StackBlitz but it is the same result. Does it make sense to someone, that can explain what I am doing wrong?
https://stackblitz.com/edit/js-kg244r?file=index.js

Body:
I have been trying to import my PKCS#8 private key from Apple (used for signing JWTs for their Web services/APIs), for use with the browser's Subtle Crypto API (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import). When I try with my private key it fails saying "Data provided to an operation does not meet requirements" but when I use the private key used in the example, it works. The code I have been trying with is from the example on the above URL.

I need a solution that works with vanilla JS, so I can't use npm packages.

The code I use for importing is this:

async function getPrivateKey() {
  try {
    const privateKey = await importPrivateKey(failingPemEncodedKey);
    //const privateKey = await importPrivateKey(succeedingPemEncodedKey);
    console.log('privateKey', privateKey);
  } catch (error) {
    console.log('ERROR', error.message);
  }
  return privateKey;
}

const failingPemEncodedKey = `-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg/zwtY1nn6uLpYyukIMgEX4pNgp7GQFevZSr9jkMFSR6gCgYIKoZIzj0DAQehRANCAASC0fq/OiBuA2UpHukZHxj88cZJXoesjhxBfO/XAKGlnRFM0QomoF1aoFlkFGvHU/3h53J/dxAwRzNSy++6CyEu
-----END PRIVATE KEY-----`;

const succeedingPemEncodedKey = `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDD0tPV/du2vftjvXj1t/gXTK39sNBVrOAEb/jKzXae+Xa0H+3LhZaQIQNMfACiBSgIfZUvEGb+7TqXWQpoLoFR/R7MvGWcSk98JyrVtveD8ZmZYyItSY7m2hcasqAFiKyOouV5vzyRe87/lEyzzBpF3bQQ4IDaQu+K9Hj5fKuU6rrOeOhsdnJc+VdDQLScHxvMoLZ9Vtt+oK9J4/tOLwr4CG8khDlBURcBY6gPcLo3dPU09SW+6ctX2cX4mkXx6O/0mmdTmacr/vu50KdRMleFeZYOWPAEhhMfywybTuzBiPVIZVP8WFCSKNMbfi1S9A9PdBqnebwwHhX3/hsEBt2BAgMBAAECggEABEI1P6nf6Zs7mJlyBDv+Pfl5rjL2cOqLy6TovvZVblMkCPpJyFuNIPDK2tK2i897ZaXfhPDBIKmllM2Hq6jZQKB110OAnTPDg0JxzMiIHPs32S1d/KilHjGff4Hjd4NXp1l1Dp8BUPOllorR2TYm2x6dcCGFw9lhTr8O03Qp4hjn84VjGIWADYCk83mgS4nRsnHkdiqYnWx1AjKlY51yEK6RcrDMi0Th2RXrrINoC35sVv+APt2rkoMGi52RwTEseA1KZGFrxjq61ReJif6p2VXEcvHeX6CWLx014LGk43z6Q28P6HgeEVEfIjyqCUea5Du/mYb/QsRSCosXLxBqwQKBgQD1+fdC9ZiMrVI+km7Nx2CKBn8rJrDmUh5SbXn2MYJdrUd8bYNnZkCgKMgxVXsvJrbmVOrby2txOiqudZkk5mD3E5O/QZWPWQLgRu8ueYNpobAX9NRgNfZ7rZD+81vh5MfZiXfuZOuzv29iZhU0oqyZ9y75eHkLdrerNkwYOe5aUQKBgQDLzapDi1NxkBgsj9iiO4KUa7jvD4JjRqFy4Zhj/jbQvlvM0F/uFp7sxVcHGx4r11C+6iCbhX4u+Zuu0HGjT4d+hNXmgGyxR8fIUVxOlOtDkVJa5sOBZK73/9/MBeKusdmJPRhalZQfMUJRWIoEVDMhfg3tW/rBj5RYAtP2dTVUMQKBgDs8yr52dRmT+BWXoFWwaWB0NhYHSFz/c8v4D4Ip5DJ5M5kUqquxJWksySGQa40sbqnD05fBQovPLU48hfgr/zghn9hUjBcsoZOvoZR4sRw0UztBvA+7jzOz1hKAOyWIulR6Vca0yUrNlJ6G5R56+sRNkiOETupi2dLCzcqb0PoxAoGAZyNHvTLvIZN4iGSrjz5qkM4LIwBIThFadxbv1fq6pt0O/BGf2o+cEdq0diYlGK64cEVwBwSBnSg4vzlBqRIAUejLjwEDAJyA4EE8Y5A9l04dzV7nJb5cRak6CrgXxay/mBJRFtaHxVlaZGxYPGSYE6UFS0+3EOmmevvDZQBf4qECgYEA0ZF6Vavz28+8wLO6SP3w8NmpHk7K9tGEvUfQ30SgDx4G7qPIgfPrbB4OP/E0qCfsIImi3sCPpjvUMQdVVZyPOIMuB+rV3ZOxkrzxEUOrpOpR48FZbL7RN90yRQsAsrp9e4iv8QwB3VxLe7X0TDqqnRyqrc/osGzuS2ZcHOKmCU8=
-----END PRIVATE KEY-----`;

async function importPrivateKey(pem) {
  const pemHeader = '-----BEGIN PRIVATE KEY-----';
  const pemFooter = '-----END PRIVATE KEY-----';
  const pemContents = pem.substring(
    pemHeader.length,
    pem.length - pemFooter.length
  );
  const binaryDerString = window.atob(pemContents);
  const binaryDer = str2ab(binaryDerString);
  const privateKey = await window.crypto.subtle.importKey(
    'pkcs8',
    binaryDer,
    {
      name: 'RSA-PSS',
      hash: 'SHA-256',
    },
    true,
    ['sign']
  );
  return privateKey;
}

I have tried the code in a StackBlitz but it is the same result. Does it make sense to someone, that can explain what I am doing wrong?
https://stackblitz.com/edit/js-kg244r?file=index.js


来源: stackexchange

问:
Unable to get SVGR to load SVGs in my Next JS Project
I'm a beginner web developer who is working on their first project with Next.js. I have hit an error with getting SVGs to load into my project as SVGs and could use some help finding the cause of it. Following online guides, I installed SVGR and updated my next.config.js file to this:

```<code>module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ["@svgr/webpack"],
    });

    return config;
  },
};
</code>```

I then imported my SVG file into my component as a component (following the SVGR guide I was using):

```<code>import Pizza from "/images/icons/pizza.svg";
</code>```

Which causes this error to pop up:

```<code>./pages/index.js:2:0
Module not found: Can't resolve '/images/icons/pizza.svg'
  1 | import Image from "next/image";
> 2 | import Pizza from "/images/icons/pizza.svg";
</code>```

I've spent the last day trying different fixes to similar issues I've found online but nothing seems to work. Can anyone spot why SVGR isn't working for me? Apologies if it's something super obvious. I appreciate any help or insight!

ContentLicense: CC BY-SA 4.0

Body:
I'm a beginner web developer who is working on their first project with Next.js. I have hit an error with getting SVGs to load into my project as SVGs and could use some help finding the cause of it. Following online guides, I installed SVGR and updated my next.config.js file to this:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ["@svgr/webpack"],
    });

    return config;
  },
};

I then imported my SVG file into my component as a component (following the SVGR guide I was using):

import Pizza from "/images/icons/pizza.svg";

Which causes this error to pop up:

./pages/index.js:2:0
Module not found: Can't resolve '/images/icons/pizza.svg'
  1 | import Image from "next/image";
> 2 | import Pizza from "/images/icons/pizza.svg";

I've spent the last day trying different fixes to similar issues I've found online but nothing seems to work. Can anyone spot why SVGR isn't working for me? Apologies if it's something super obvious. I appreciate any help or insight!


问:
Getting "Xref table not zero-indexed. ID numbers for objects will be corrected" warning
I have the following code (comments explain what is occuring):

```<code>
import os
from io import StringIO
from PyPDF2 import PdfFileReader

# Path to the directory containing the PDF files
pdf_dir = '/path/to/pdf/files'

# Iterate over the files in the directory
for filename in os.listdir(pdf_dir):
  # Check if the file is a PDF file
  if filename.endswith('.pdf'):
    # Construct the full path to the file
    filepath = os.path.join(pdf_dir, filename)

    # Open the PDF file and read its contents
    with open(filepath, 'rb') as f:
      pdf = PdfFileReader(f)

      # Extract the text from the PDF file
      text = ''
      for page in pdf.pages:
        text += page.extractText()

    # Construct the name of the output text file
    txt_filename = filename[:-4] + '.txt'

    # Write the text to the output file
    with open(txt_filename, 'w') as f:
      f.write(text)

</code>```

When I run the code, it produces a Xref table not zero-indexed. ID numbers for objects will be corrected warning.  It is not a hard error, but it makes me wonder if there's a different way I should be doing this.

Thanks for any suggestions.

Body:
I have the following code (comments explain what is occuring):

import os
from io import StringIO
from PyPDF2 import PdfFileReader

# Path to the directory containing the PDF files
pdf_dir = '/path/to/pdf/files'

# Iterate over the files in the directory
for filename in os.listdir(pdf_dir):
  # Check if the file is a PDF file
  if filename.endswith('.pdf'):
    # Construct the full path to the file
    filepath = os.path.join(pdf_dir, filename)

    # Open the PDF file and read its contents
    with open(filepath, 'rb') as f:
      pdf = PdfFileReader(f)

      # Extract the text from the PDF file
      text = ''
      for page in pdf.pages:
        text += page.extractText()

    # Construct the name of the output text file
    txt_filename = filename[:-4] + '.txt'

    # Write the text to the output file
    with open(txt_filename, 'w') as f:
      f.write(text)

When I run the code, it produces a Xref table not zero-indexed. ID numbers for objects will be corrected warning.  It is not a hard error, but it makes me wonder if there's a different way I should be doing this.

Thanks for any suggestions.


问:
Workaround to add JSON with errors to mongodb atlas collection
In my database class we were given an assignment to work with two JSON files (add them to a mongodb atlas collection and query certain results)

Both JSON files had "errors" the first being :

```<code>{ "_id" : { "$oid" : "50b59cd75bed76f46522c34e" }, "student_id" : 0, "class_id" : 2, "scores" : [ { "type" : "exam", "score" : 57.92947112575566 }, { "type" : "quiz", "score" : 21.24542588206755 }, { "type" : "homework", "score" : 68.19567810587429 }, { "type" : "homework", "score" : 67.95019716560351 }, { "type" : "homework", "score" : 18.81037253352722 } ] }
</code>```

and the second being :

```<code>{"_id":0,"name":"aimee Zank","scores":[{"score":1.463179736705023,"type":"exam"},{"score":11.78273309957772,"type":"quiz"},{"score":35.8740349954354,"type":"homework"}]},
{"_id":1,"name":"Aurelia Menendez","scores":[{"score":60.06045071030959,"type":"exam"},{"score":52.79790691903873,"type":"quiz"},{"score":71.76133439165544,"type":"homework"}]},
</code>```

I fixed error 1 by removing the $oid and replacing it with just oid: as there was an error trying to add objects with $oid as a value to my collection. I also needed to add everything to an array.

I fixed the second by putting the entire object inside an array [].

When I asked my professor why these errors were in the JSON files and if it was on purpose, he said that they were there on for a reason and that we needed to find a "work around".

I am curious what work around there is to load JSON data that is incorrect into a collection? I am at a complete loss as to what he expected. Is there some way I can just load individual objects line by line from the JSON file to the collection?

This is how I loaded the JSON data after fixing the files directly:

```<code>const fs = require('fs');
var data = JSON.parse(fs.readFileSync("./students.json"));
JSON.stringify(data);
const database = "college";
const collection = "students";

use(database);
db.students.drop();
db.createCollection(collection);

db.students.insertMany(data);
</code>```

--- All the importing of data should be done in VS Code and not using --mongodb import

And a side note that this assignment has since passed so I am not asking for help in completing my homework, simply trying to see if there was something I could of done that would not of required me to edit the JSON file itself. My professor has not responded to me regarding this question.

Body:
In my database class we were given an assignment to work with two JSON files (add them to a mongodb atlas collection and query certain results)

Both JSON files had "errors" the first being :

{ "_id" : { "$oid" : "50b59cd75bed76f46522c34e" }, "student_id" : 0, "class_id" : 2, "scores" : [ { "type" : "exam", "score" : 57.92947112575566 }, { "type" : "quiz", "score" : 21.24542588206755 }, { "type" : "homework", "score" : 68.19567810587429 }, { "type" : "homework", "score" : 67.95019716560351 }, { "type" : "homework", "score" : 18.81037253352722 } ] }

and the second being :

{"_id":0,"name":"aimee Zank","scores":[{"score":1.463179736705023,"type":"exam"},{"score":11.78273309957772,"type":"quiz"},{"score":35.8740349954354,"type":"homework"}]},
{"_id":1,"name":"Aurelia Menendez","scores":[{"score":60.06045071030959,"type":"exam"},{"score":52.79790691903873,"type":"quiz"},{"score":71.76133439165544,"type":"homework"}]},

I fixed error 1 by removing the $oid and replacing it with just oid: as there was an error trying to add objects with $oid as a value to my collection. I also needed to add everything to an array.

I fixed the second by putting the entire object inside an array [].

When I asked my professor why these errors were in the JSON files and if it was on purpose, he said that they were there on for a reason and that we needed to find a "work around".

I am curious what work around there is to load JSON data that is incorrect into a collection? I am at a complete loss as to what he expected. Is there some way I can just load individual objects line by line from the JSON file to the collection?

This is how I loaded the JSON data after fixing the files directly:

const fs = require('fs');
var data = JSON.parse(fs.readFileSync("./students.json"));
JSON.stringify(data);
const database = "college";
const collection = "students";

use(database);
db.students.drop();
db.createCollection(collection);

db.students.insertMany(data);

--- All the importing of data should be done in VS Code and not using --mongodb import

And a side note that this assignment has since passed so I am not asking for help in completing my homework, simply trying to see if there was something I could of done that would not of required me to edit the JSON file itself. My professor has not responded to me regarding this question.


问:
error coming when i deploy smart contract on tronide.io
Error encoding arguments: Error: invalid address (argument="address", value="", code=INVALID_ARGUMENT, version=address/5.6.1) (argument=null, value="", code=INVALID_ARGUMENT, version=abi/5.6.4)</p>
```<code>i

i got this this error when i deploy smart contract on tronide.io please help me

please help me   xxxxx
</code>```

Body:
Error encoding arguments: Error: invalid address (argument="address", value="", code=INVALID_ARGUMENT, version=address/5.6.1) (argument=null, value="", code=INVALID_ARGUMENT, version=abi/5.6.4)

i

i got this this error when i deploy smart contract on tronide.io please help me

please help me   xxxxx


问:
Full Calendar Same time events showing one below the other
So, I have many events at the same time (usually 6-9 events).
So the week view, which i am using for my page, shows the events the one next to the other causing shrink and not showing the titles properly.

Is there a way to show the events one below the other and force the row height to stretch?

I tried

```<code>   /* .fc-timegrid-event-harness {
        position: relative;
        width: 100%;
    display: block;
    left: 0 !important;
    height: 50px;
    } */
</code>```

but of course the table is not resizing according to my needs

Body:
So, I have many events at the same time (usually 6-9 events).
So the week view, which i am using for my page, shows the events the one next to the other causing shrink and not showing the titles properly.

Is there a way to show the events one below the other and force the row height to stretch?

I tried

   /* .fc-timegrid-event-harness {
        position: relative;
        width: 100%;
    display: block;
    left: 0 !important;
    height: 50px;
    } */

but of course the table is not resizing according to my needs


问:
Lambda invocation failed with status: 403 on new AWS region
I enabled a new AWS region (Africa, Cape Town)

I created a new lambda on the new region. I connected the mentioned lambda to my API-Gateway located in Frankfurt region and when trying to access it, there is a internal server error.

CloudWatch shows the following:

```<code>(ee2d73a9-e0ff-4ba2-a445-4348e86bcfc1) Lambda invocation failed with status: 403. Lambda request id: ed3b6fc8-0959-4f43-8c3c-32d6c811e9f2
(ee2d73a9-e0ff-4ba2-a445-4348e86bcfc1) Execution failed due to configuration error: The security token included in the request is invalid
</code>```

However, when I create another API Gateway in Africa, I can only access African Lambdas, and I get the same error trying to access anything outside Africa.

Any solutions?

Body:
I enabled a new AWS region (Africa, Cape Town)

I created a new lambda on the new region. I connected the mentioned lambda to my API-Gateway located in Frankfurt region and when trying to access it, there is a internal server error.

CloudWatch shows the following:

(ee2d73a9-e0ff-4ba2-a445-4348e86bcfc1) Lambda invocation failed with status: 403. Lambda request id: ed3b6fc8-0959-4f43-8c3c-32d6c811e9f2
(ee2d73a9-e0ff-4ba2-a445-4348e86bcfc1) Execution failed due to configuration error: The security token included in the request is invalid

However, when I create another API Gateway in Africa, I can only access African Lambdas, and I get the same error trying to access anything outside Africa.

Any solutions?


问:
ExoPlayer - Player is accessed on the wrong thread with RxJava2
From past developers, I got a large library, which is built on the basis of ExoPlayer, which allows you to listen to audio books.

Everything worked fine until the library itself had to update the version of ExoPlayer to a newer one (this was very important)

In short: there is a small interface that has a ProgressBar showing how many seconds the audio has already been playing. Here is the code for this:

```<code>private lateinit var mExoPlayer : ExoPlayer

private val compositeDisposable = CompositeDisposable()
private val currentTrackProgress = MutableLiveData<Long>()

private var currentTrackProgressDisposable : Disposable? = null
private val playbackProgressObservable : Observable<Long> =
    Observable.interval(1, TimeUnit.MILLISECONDS).map {
        mExoPlayer.currentPosition
    }.observeOn(AndroidSchedulers.mainThread())

////////////////////// So many code here
////////////////////// Somewhere there is a call to the "createExoPlayer()" function

private fun createExoPlayer() {
    mExoPlayer = ExoPlayer.Builder(this).build()

    mExoPlayer.addListener(object : Player.Listener {

        override fun onIsPlayingChanged(isPlaying : Boolean) {
            if (isPlaying) {
                currentTrackProgressDisposable = playbackProgressObservable.subscribeBy(
                    onError = { error ->
                        Log.d("error", error.toString())
                    },
                    onNext = { progress ->
                        currentTrackProgress.value = progress
                    }
                )
                compositeDisposable.add(currentTrackProgressDisposable!!)
            }
        }
    })

    mExoPlayer.playWhenReady = true
}
</code>```

Before updating ExoPlayer version, everything worked fine, but after updating to the latest version, an error began to appear in onError:

```<code>java.lang.IllegalStateException: Player is accessed on the wrong thread.
Current thread: 'RxComputationThreadPool-1'
Expected thread: 'main'
</code>```

What could be the reason for this and how to fix it? After all, I didn’t even update the RxJava2 version, but only updated ExoPlayer

Body:
From past developers, I got a large library, which is built on the basis of ExoPlayer, which allows you to listen to audio books.

Everything worked fine until the library itself had to update the version of ExoPlayer to a newer one (this was very important)

In short: there is a small interface that has a ProgressBar showing how many seconds the audio has already been playing. Here is the code for this:

private lateinit var mExoPlayer : ExoPlayer

private val compositeDisposable = CompositeDisposable()
private val currentTrackProgress = MutableLiveData<Long>()

private var currentTrackProgressDisposable : Disposable? = null
private val playbackProgressObservable : Observable<Long> =
    Observable.interval(1, TimeUnit.MILLISECONDS).map {
        mExoPlayer.currentPosition
    }.observeOn(AndroidSchedulers.mainThread())

////////////////////// So many code here
////////////////////// Somewhere there is a call to the "createExoPlayer()" function

private fun createExoPlayer() {
    mExoPlayer = ExoPlayer.Builder(this).build()

    mExoPlayer.addListener(object : Player.Listener {

        override fun onIsPlayingChanged(isPlaying : Boolean) {
            if (isPlaying) {
                currentTrackProgressDisposable = playbackProgressObservable.subscribeBy(
                    onError = { error ->
                        Log.d("error", error.toString())
                    },
                    onNext = { progress ->
                        currentTrackProgress.value = progress
                    }
                )
                compositeDisposable.add(currentTrackProgressDisposable!!)
            }
        }
    })

    mExoPlayer.playWhenReady = true
}

Before updating ExoPlayer version, everything worked fine, but after updating to the latest version, an error began to appear in onError:

java.lang.IllegalStateException: Player is accessed on the wrong thread.
Current thread: 'RxComputationThreadPool-1'
Expected thread: 'main'

What could be the reason for this and how to fix it? After all, I didn’t even update the RxJava2 version, but only updated ExoPlayer


问:
Initialize PreTrainedModel from bytes
I have my model file loaded onto a database, so when I retrieve it in code, it has the datatype bytes. Can I somehow initialize a PreTrainedModel from this. I don't want to have to save the model to the disk and then read it again.</p>

Title: Initialize PreTrainedModel from bytes


问:
How do I make a convex shape infinitely rotate in SFML
I am making a game where I need a player to be constantly rotating. I have tried using a vertex array instead of a convex shape so that I could use trig to move the points around (which was shown to me in a tutorial), but it does not load my texture correctly. The player is a triangle and when I try to load the texture to the vertex array it displays it as completely black, and I want it to actually load my texture. when I used a convex shape, it did load the texture correctly, but I don't know how I'm going to make it rotate. I would prefer to use a convex shape since for me it's easier to work with.</p>
```<code>#include <SFML/Graphics.hpp>
#include <math.h>
#include <stdlib.h>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800,800), "High noon showdown", sf::Style::Close | sf::Style::Titlebar);
    sf::Texture p1texture;
    p1texture.loadFromFile("2nd hns bandit.png");
    sf::ConvexShape p1;
    p1.setPointCount(3);
    p1.setTexture(&p1texture);
    //points for player 1
    p1.setPoint(0, sf::Vector2f(70.0f, 380.0f));
    p1.setPoint(1, sf::Vector2f(30.0f, 380.0f));
    p1.setPoint(2, sf::Vector2f(30.0f, 310.0f));
    //game loop
    while(window.isOpen()) {
        sf::Event evnt;
        while(window.pollEvent(evnt)) {

            switch(evnt.type){

            case sf::Event::Closed:
                window.close();
                break;

            }

        }

        window.clear(sf::Color(210,180,140,100));
        window.draw(p1);
        window.display();
    }

    return 0;
}

</code>```

Body:
I am making a game where I need a player to be constantly rotating. I have tried using a vertex array instead of a convex shape so that I could use trig to move the points around (which was shown to me in a tutorial), but it does not load my texture correctly. The player is a triangle and when I try to load the texture to the vertex array it displays it as completely black, and I want it to actually load my texture. when I used a convex shape, it did load the texture correctly, but I don't know how I'm going to make it rotate. I would prefer to use a convex shape since for me it's easier to work with.

#include <SFML/Graphics.hpp>
#include <math.h>
#include <stdlib.h>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800,800), "High noon showdown", sf::Style::Close | sf::Style::Titlebar);
    sf::Texture p1texture;
    p1texture.loadFromFile("2nd hns bandit.png");
    sf::ConvexShape p1;
    p1.setPointCount(3);
    p1.setTexture(&p1texture);
    //points for player 1
    p1.setPoint(0, sf::Vector2f(70.0f, 380.0f));
    p1.setPoint(1, sf::Vector2f(30.0f, 380.0f));
    p1.setPoint(2, sf::Vector2f(30.0f, 310.0f));
    //game loop
    while(window.isOpen()) {
        sf::Event evnt;
        while(window.pollEvent(evnt)) {

            switch(evnt.type){

            case sf::Event::Closed:
                window.close();
                break;

            }

        }

        window.clear(sf::Color(210,180,140,100));
        window.draw(p1);
        window.display();
    }

    return 0;
}


问:
Google Drive for Desktop sync problem with RStudio: generates random empty folders
My research lab has a lab Google account to which we are expected to save/upload all of our files. To avoid the messy challenge of maintaining local files that can be read by RStudio as well as Cloud versions on the shared Google Drive account, I have recently began using Drive for Desktop to stream files from the Drive to my desktop to open in RStudio. (More specifically, I share my folder in the lab Drive with my personal Drive which in turn is synced/streamed to my Mac desktop.)

However, I believe this creates conflicts when Drive tries to sync/access files while RStudio is also updating those files (see: zero, one, two, three, four, five, six, seven). I do get a pop-up every so often that I have to close, but that is manageable. A bigger problem for now is that I have noticed that the Drive is now filled with random empty folders (see screenshot below). These folders are located within .Rproj.user. Does anyone know how to prevent these random folders from being generated when I use RStudio in this fashion? It is annoying because they show up in the Google Drive 'home page' and 'Recents' for everyone who accesses the shared Drive.

The other posts linked above describe the need to exclude some file types from sync in order to prevent conflicts, but the directions were for the old Google Drive Back Up and Sync system. I cannot find these settings in the new Drive for Desktop system, and I do not know if this would solve the random folder generation problem.

Has anyone encountered this problem before, know what causes it, or how to fix it?

Many thanks in advance.


问:
Adding Rows to DataFrame in Pandas - Error - ValueError: cannot set a row with mismatched columns
Learning Pandas and trying to make a code for myself so noob in this.

I'm running into an error:

ValueError: cannot set a row with mismatched columns

I have an app created in PySimpleGui which would take input from user and create a database with columns predefined.

I'm unable to add the rows and running into this issue.

I've made sure I have 6 columns and therefore the number of data to be inserted is 6 but I still get this error.

The code I have at the moment is :

```<code>output_path_csv = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Daily_Tracker.xlsx')
if os.path.exists(output_path_csv):
    pass
else:
    x_header = ['Date', 'Case Number', 'Serial Number', 'Product Name', 'Version', 'Issue']
    df = pd.DataFrame( columns=x_header )
    df.to_excel( output_path_csv, index=False)
</code>```
```<code>p_name = prod_name(values['Serial_Num'])  # Determining the product name
values['Product_Name'] = p_name

v_name = ver_name(values['Serial_Num'])  # Determining the version type of the product selected
values['Product_Type'] = v_name
c_num = values.get('Case_Num')
s_num = values.get('Serial_Num')
c_Issue = values.get('Issue')

# to check for e-mail address
sp_char = "@"
if sp_char in values['Email_Add']:
    doc.render(values)
    output_path_doc = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Notes.docx')
    try:
        doc.save(output_path_doc)
        popup("File Saved", f"File has been saved here : {output_path_doc}")
        os.startfile(output_path_doc)
    except PermissionError:
        popup('File seems to be opened! Please close the file!')
        pass
else:
    popup('Missing @ character in the e-mail. Please update')
    pass
df2 = pd.read_excel( output_path_csv )
df2.loc[len( df2.index )] = [to_date, c_num, s_num, p_name, v_name, c_Issue]
df2.to_excel( output_path_csv )
</code>```

Body:
Learning Pandas and trying to make a code for myself so noob in this.

I'm running into an error:

ValueError: cannot set a row with mismatched columns

I have an app created in PySimpleGui which would take input from user and create a database with columns predefined.

I'm unable to add the rows and running into this issue.

I've made sure I have 6 columns and therefore the number of data to be inserted is 6 but I still get this error.

The code I have at the moment is :

output_path_csv = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Daily_Tracker.xlsx')
if os.path.exists(output_path_csv):
    pass
else:
    x_header = ['Date', 'Case Number', 'Serial Number', 'Product Name', 'Version', 'Issue']
    df = pd.DataFrame( columns=x_header )
    df.to_excel( output_path_csv, index=False)

p_name = prod_name(values['Serial_Num'])  # Determining the product name
values['Product_Name'] = p_name

v_name = ver_name(values['Serial_Num'])  # Determining the version type of the product selected
values['Product_Type'] = v_name
c_num = values.get('Case_Num')
s_num = values.get('Serial_Num')
c_Issue = values.get('Issue')

# to check for e-mail address
sp_char = "@"
if sp_char in values['Email_Add']:
    doc.render(values)
    output_path_doc = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\Notes.docx')
    try:
        doc.save(output_path_doc)
        popup("File Saved", f"File has been saved here : {output_path_doc}")
        os.startfile(output_path_doc)
    except PermissionError:
        popup('File seems to be opened! Please close the file!')
        pass
else:
    popup('Missing @ character in the e-mail. Please update')
    pass
df2 = pd.read_excel( output_path_csv )
df2.loc[len( df2.index )] = [to_date, c_num, s_num, p_name, v_name, c_Issue]
df2.to_excel( output_path_csv )


问:
Why is Koloboke HashObjObjMaps collections so slow at putIfAbsent when using Longs as keys?
The following code shows that Koloboke HashHashObjs maps are very slow at putIfAbsent, is there a design flaw here?

```<code>import com.koloboke.collect.map.hash.HashObjObjMaps;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Koloboke {
  public static void main(String [] args) {
    Map<Long, String> normalMap = new HashMap<>();
    Map<Long, String> kolobokeMap = HashObjObjMaps.newMutableMap();
    long iterations = 100_000;
    for(long i = 0;i<iterations;i++) {
        normalMap.put(i, Long.toString(i));
        kolobokeMap.put(i, Long.toString(i));
    }
    long nanoStart= System.nanoTime();
    for(long i = 0;i<iterations;i++) {
        normalMap.putIfAbsent(i, Long.toString(i));
    }
    System.out.println("hashmap putIfAbsent took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-nanoStart) + " millis");

    nanoStart= System.nanoTime();
    for(long i = 0;i<iterations;i++) {
        kolobokeMap.putIfAbsent(i, Long.toString(i));
    }
    System.out.println("koloboke putIfAbsent took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-nanoStart) + " millis");
  }
}
</code>```

Output:

hashmap putIfAbsent took 27 millis

koloboke putIfAbsent took 19733 millis

Body:
The following code shows that Koloboke HashHashObjs maps are very slow at putIfAbsent, is there a design flaw here?

import com.koloboke.collect.map.hash.HashObjObjMaps;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Koloboke {
  public static void main(String [] args) {
    Map<Long, String> normalMap = new HashMap<>();
    Map<Long, String> kolobokeMap = HashObjObjMaps.newMutableMap();
    long iterations = 100_000;
    for(long i = 0;i<iterations;i++) {
        normalMap.put(i, Long.toString(i));
        kolobokeMap.put(i, Long.toString(i));
    }
    long nanoStart= System.nanoTime();
    for(long i = 0;i<iterations;i++) {
        normalMap.putIfAbsent(i, Long.toString(i));
    }
    System.out.println("hashmap putIfAbsent took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-nanoStart) + " millis");

    nanoStart= System.nanoTime();
    for(long i = 0;i<iterations;i++) {
        kolobokeMap.putIfAbsent(i, Long.toString(i));
    }
    System.out.println("koloboke putIfAbsent took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-nanoStart) + " millis");
  }
}

Output:

hashmap putIfAbsent took 27 millis

koloboke putIfAbsent took 19733 millis


问:
How to create m3u8 playlist from multiple segment.mp4 files with ffmpeg
We are storing a cameras stream as segment files using these ffmpeg output args (only listing relevant args) -f segment -segment_time 10 -segment_format mp4

All of the questions I've found are about creating an m3u8 playlist from a single .mp4 file. I would like to avoid concatenation as that will introduce too much latency. Is the best way to convert each segment into a .ts file separately and build the m3u8 manually, or does ffmpeg support this?


问:
Cannot display data in the table
Problem:

It doesn't work to use "  const [data, setData] = useState<IHit[]>([]);" because I get the error "data.map is not a function"

What part am I missing?

Thank you!

```<code>import React, { useState, useEffect } from 'react';
import { render } from 'react-dom';
import axios from 'axios';
import './style.css';
import { IHit } from './responseTypes';

function App() {
  const [data, setData] = useState<IHit[]>([]);

  const [query, setQuery] = useState('react');

  useEffect(() => {
    let ignore = false;
    console.log('useeffect: ', ignore);
    async function fetchData() {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=' + query
      );
      if (!ignore) setData(result.data);
    }

    fetchData();

    return () => {
      ignore = true;
      console.log('return: ', ignore);
    };
  }, [query]);

  if (data.length === 0) return <div>Testtest</div>;

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <ul>
        {data.map(({ url, objectID, title }: IHit) => (
          <a href={url}>
            <li key={objectID}>{title}</li>
          </a>
        ))}
      </ul>
    </div>
  );
}

render(<App />, document.getElementById('root'));
</code>```

https://stackblitz.com/edit/usereducer-typescript-state-uaft7n?file=index.tsx

Title: Cannot display data in the table

Body:
Problem:

It doesn't work to use "  const [data, setData] = useState<IHit[]>([]);" because I get the error "data.map is not a function"

What part am I missing?

Thank you!

import React, { useState, useEffect } from 'react';
import { render } from 'react-dom';
import axios from 'axios';
import './style.css';
import { IHit } from './responseTypes';

function App() {
  const [data, setData] = useState<IHit[]>([]);

  const [query, setQuery] = useState('react');

  useEffect(() => {
    let ignore = false;
    console.log('useeffect: ', ignore);
    async function fetchData() {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=' + query
      );
      if (!ignore) setData(result.data);
    }

    fetchData();

    return () => {
      ignore = true;
      console.log('return: ', ignore);
    };
  }, [query]);

  if (data.length === 0) return
Testtest
;

  return (

      <input value={query} onChange={(e) => setQuery(e.target.value)} />

        {data.map(({ url, objectID, title }: IHit) => (

{title}

        ))}

  );
}

render(<App />, document.getElementById('root'));

https://stackblitz.com/edit/usereducer-typescript-state-uaft7n?file=index.tsx


问:
How do I open a plasticscm project in Unity?
I have created a partial game on unity, connected it to plastic scm and I want my friend to contribute.
My friend has joined my organization on plastic scm, and upon opening plastic scm he can view all files.
My only issue is, he cannot open the project in unity. How can he do that?

I tried:
Googling it
Opening plastic scm on my pc and contributing as him
Using teamviewer to do it for him


问:
in app billing version 5 not launchPurchaseFlow
I am using version 5.1 of Google In-App Payments.
But when I click on the product, the value of List list in the function
queryProductDetailsAsync is zero.
I have also added the product in the panel.
What is the problem?

```<code>ImmutableList productList = ImmutableList.of(
        //Product 1 = index is 0
        QueryProductDetailsParams.Product.newBuilder()
                .setProductId("test_billing")
                .setProductType(BillingClient.ProductType.INAPP)
                .build()
);

QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
        .setProductList(productList)
        .build();

billingClient.queryProductDetailsAsync(params, new ProductDetailsResponseListener() {
    @Override
    public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List<ProductDetails> list) {
        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && !list.isEmpty()) {
            // Handle the success of the consume operation.
            //inja find , set beshe

            for (ProductDetails productDetails : list) {
                if (productDetails.getProductId().equals("test_billing")) {
                    rl1.setOnClickListener(view -> {
                        launchPurchaseFlow(productDetails);
                    });
                }
            }

        }else{

        }

</code>```

google play billing
android

Body:
I am using version 5.1 of Google In-App Payments.
But when I click on the product, the value of List list in the function
queryProductDetailsAsync is zero.
I have also added the product in the panel.
What is the problem?

ImmutableList productList = ImmutableList.of(
        //Product 1 = index is 0
        QueryProductDetailsParams.Product.newBuilder()
                .setProductId("test_billing")
                .setProductType(BillingClient.ProductType.INAPP)
                .build()
);

QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
        .setProductList(productList)
        .build();

billingClient.queryProductDetailsAsync(params, new ProductDetailsResponseListener() {
    @Override
    public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List<ProductDetails> list) {
        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && !list.isEmpty()) {
            // Handle the success of the consume operation.
            //inja find , set beshe

            for (ProductDetails productDetails : list) {
                if (productDetails.getProductId().equals("test_billing")) {
                    rl1.setOnClickListener(view -> {
                        launchPurchaseFlow(productDetails);
                    });
                }
            }

        }else{

        }

google play billing
android


问:
Remove Image from image array React Native
I need to remove or hide image from array after click on this image.
I'm trying to do this, but it's not work for me

I just study React Native, please help me

```<code>const [hiddenObject, setHiddenObject] = useState(false);
const findObjects = {
  postList: [
    { img: require("../obj1.png"), opacity: 1, w: 35, h: 50, left: 0, top: 0 },
    {
      img: require("../obj2.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 170,
      top: 20,
    },
    {
      img: require("../obj3.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 277,
      top: 50,
    },
    {
      img: require("../obj1.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 510,
      top: 7,
    },
  ],
};

const hiddenObject2 = (item) => {
  item.opacity = 0;
  setHiddenObject(hiddenObject);
  findObjects.postList.splice(item, 1);
};

return (
  <View>
    {findObjects.postList.map((item) => {
      return (
        <TouchableOpacity
          onPress={hiddenObject2}
          key={Math.random()}
          style={{ width: "auto", opacity: hiddenObject ? 0 : item.opacity }}
        >
          <Image
            source={item.img}
            style={[
              gStyle.imgObject,
              {
                width: item.w,
                height: item.h,
                left: item.left,
                top: item.top,
                opacity: hiddenObject ? 0 : item.opacity,
              },
            ]}
          />
        </TouchableOpacity>
      );
    })}
  </View>
);
</code>```

Body:
I need to remove or hide image from array after click on this image.
I'm trying to do this, but it's not work for me

I just study React Native, please help me

const [hiddenObject, setHiddenObject] = useState(false);
const findObjects = {
  postList: [
    { img: require("../obj1.png"), opacity: 1, w: 35, h: 50, left: 0, top: 0 },
    {
      img: require("../obj2.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 170,
      top: 20,
    },
    {
      img: require("../obj3.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 277,
      top: 50,
    },
    {
      img: require("../obj1.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 510,
      top: 7,
    },
  ],
};

const hiddenObject2 = (item) => {
  item.opacity = 0;
  setHiddenObject(hiddenObject);
  findObjects.postList.splice(item, 1);
};

return (
  <View>
    {findObjects.postList.map((item) => {
      return (
        <TouchableOpacity
          onPress={hiddenObject2}
          key={Math.random()}
          style={{ width: "auto", opacity: hiddenObject ? 0 : item.opacity }}
        >
          <Image
            source={item.img}
            style={[
              gStyle.imgObject,
              {
                width: item.w,
                height: item.h,
                left: item.left,
                top: item.top,
                opacity: hiddenObject ? 0 : item.opacity,
              },
            ]}
          />
        </TouchableOpacity>
      );
    })}
  </View>
);


问:
Unsuccessfull runs for time-based trigger action on other accounts, but works fine on mine
I have a Google Apps Script that works perfectly on my account. I've deployed that script as a web app and shared it with my friend, sadly each time the time-based function should be called I see errors for his account.

My test script is very simple (based on Trigger error: We're sorry, a server error occurred while reading from storage. Error code PERMISSION_DENIED):

```<code>function doGet() {

  const triggers = ScriptApp.getProjectTriggers()

  for (var i = 0; i < triggers.length; i++) {
    const handlerFunction = triggers[i].getHandlerFunction();
    if (handlerFunction === 'myFunction') {
      ScriptApp.deleteTrigger(triggers[i])
    }
  }
  ScriptApp.newTrigger("myFunction")
    .timeBased()
    .everyMinutes(1)
    .create();

  return HtmlService.createHtmlOutput('<h1>Trigger test installed</h1>');
}

function myFunction() {
  var email = Session.getEffectiveUser().getEmail();
  Logger.log("Hello "+ email);
}
</code>```

My project runs on V8 and I have this appsscript.json:

```<code>{
  "timeZone": "Europe/Warsaw",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "ANYONE"
  }
}
</code>```

I'm not sure if the issue from a 2 years old question is still there, but my case is a bit different, because as I wrote on start, this works perfectly on my account, but not on others account.

In the linked question the answer suggests disabling the V8, but this way I'm unable to debug my code (I'm using the web editor), so it will be a pain to develop the script.

My question is: How to fix this error using V8 runtime and sharing the web app (published Apps Script) with others

Steps to reproduce the issue:

In Chrome open https://script.google.com/home

Create a new project, and call it "Bug Report"

Paste the above code in the editor and save the changes:

Click on deploy > new deploy and pick web app as the type. Specify Execute as to user opening the website and allow access to anyone having a google account:

Hit deploy and copy the generated link

Access the link in the new tab (still logged in to google), view permissions, and finally, you will get the "Trigger test installed" sign.

Return to your Apps Script project and go to logs, you will see info that myFunction was successfully executed:

Open a different browser (Edge in my case), log in to a different google account, and open the same link you got in step 4. View and accept permissions.

You will get the same message ("Trigger test installed")

Return to Chrome, to logs and you will get the error messages:

Body:
I have a Google Apps Script that works perfectly on my account. I've deployed that script as a web app and shared it with my friend, sadly each time the time-based function should be called I see errors for his account.

My test script is very simple (based on Trigger error: We're sorry, a server error occurred while reading from storage. Error code PERMISSION_DENIED):

function doGet() {

  const triggers = ScriptApp.getProjectTriggers()

  for (var i = 0; i < triggers.length; i++) {
    const handlerFunction = triggers[i].getHandlerFunction();
    if (handlerFunction === 'myFunction') {
      ScriptApp.deleteTrigger(triggers[i])
    }
  }
  ScriptApp.newTrigger("myFunction")
    .timeBased()
    .everyMinutes(1)
    .create();

  return HtmlService.createHtmlOutput('
Trigger test installed
');
}

function myFunction() {
  var email = Session.getEffectiveUser().getEmail();
  Logger.log("Hello "+ email);
}

My project runs on V8 and I have this appsscript.json:

{
  "timeZone": "Europe/Warsaw",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "ANYONE"
  }
}

I'm not sure if the issue from a 2 years old question is still there, but my case is a bit different, because as I wrote on start, this works perfectly on my account, but not on others account.

In the linked question the answer suggests disabling the V8, but this way I'm unable to debug my code (I'm using the web editor), so it will be a pain to develop the script.

My question is: How to fix this error using V8 runtime and sharing the web app (published Apps Script) with others

Steps to reproduce the issue:

In Chrome open https://script.google.com/home

Create a new project, and call it "Bug Report"

Paste the above code in the editor and save the changes:

Click on deploy > new deploy and pick web app as the type. Specify Execute as to user opening the website and allow access to anyone having a google account:

Hit deploy and copy the generated link

Access the link in the new tab (still logged in to google), view permissions, and finally, you will get the "Trigger test installed" sign.

Return to your Apps Script project and go to logs, you will see info that myFunction was successfully executed:

Open a different browser (Edge in my case), log in to a different google account, and open the same link you got in step 4. View and accept permissions.

You will get the same message ("Trigger test installed")

Return to Chrome, to logs and you will get the error messages:


问:
How to understand shape of weights returned by layer.get_weights() function?
I was working with manipulating weights of a CNN model (LENET-5) for my academical project where I encountered this problem that it was very difficult to understand what the keras function layer.get_weights() return? My model is

```<code># Create Model LENET-5 Traditional
model = Sequential([
    Conv2D(filters=6, kernel_size=(5, 5), activation='tanh', input_shape=(28, 28, 1), padding="same"),
    AveragePooling2D(),  # pool_size=(2, 2),
    Conv2D(filters=16, kernel_size=(5, 5), activation='tanh', input_shape=(10, 10, 1)),
    AveragePooling2D(),
    Flatten(),
    Dense(units=120, activation='tanh'),
    Dense(units=84, activation='tanh'),
    # Softmax function gives probabilities of each output class
    Dense(units=10, activation='softmax')
])
</code>```

that gives us a summary of:

Now after compiling and training the model, the get_weights() function for a first conv2d layer returns a np array of shape: (5, 5, 1, 6)

Now we know that in first Conv2d layer of LENET-5, there are 6 kernels of 1 channel (grayscale) all containing 5x5 = 25 parameters right? but the array looks like this:

it is 1 array that contains 5 arrays that have 5 more arrays with 1 array of 6 elements. how do I map these to 6 kernels ? which 25 values are from 1st kernel ?  it is not understandable because 6 kernels that contains 5x5 weights are present there. Can anyone please elaborate the mapping of these weights to kernels/filters?

To get access of a single weight I need weight[0][0][0][0][0] that returns the first element of first array but I don't know how and which kernel it belongs to. and let's suppose if I want to access weight of 3rd kernel that is on 3rd row and 3rd column how can I access that? there must be an interpretation to that.
I expect someone to please explain me about the shape of weight returned by get_weights() function and how I can map them to kernels of conv2d layer.. Visualization can help a lot too.

Body:
I was working with manipulating weights of a CNN model (LENET-5) for my academical project where I encountered this problem that it was very difficult to understand what the keras function layer.get_weights() return? My model is

# Create Model LENET-5 Traditional
model = Sequential([
    Conv2D(filters=6, kernel_size=(5, 5), activation='tanh', input_shape=(28, 28, 1), padding="same"),
    AveragePooling2D(),  # pool_size=(2, 2),
    Conv2D(filters=16, kernel_size=(5, 5), activation='tanh', input_shape=(10, 10, 1)),
    AveragePooling2D(),
    Flatten(),
    Dense(units=120, activation='tanh'),
    Dense(units=84, activation='tanh'),
    # Softmax function gives probabilities of each output class
    Dense(units=10, activation='softmax')
])

that gives us a summary of:

Now after compiling and training the model, the get_weights() function for a first conv2d layer returns a np array of shape: (5, 5, 1, 6)

Now we know that in first Conv2d layer of LENET-5, there are 6 kernels of 1 channel (grayscale) all containing 5x5 = 25 parameters right? but the array looks like this:

it is 1 array that contains 5 arrays that have 5 more arrays with 1 array of 6 elements. how do I map these to 6 kernels ? which 25 values are from 1st kernel ?  it is not understandable because 6 kernels that contains 5x5 weights are present there. Can anyone please elaborate the mapping of these weights to kernels/filters?

To get access of a single weight I need weight[0][0][0][0][0] that returns the first element of first array but I don't know how and which kernel it belongs to. and let's suppose if I want to access weight of 3rd kernel that is on 3rd row and 3rd column how can I access that? there must be an interpretation to that.
I expect someone to please explain me about the shape of weight returned by get_weights() function and how I can map them to kernels of conv2d layer.. Visualization can help a lot too.


问:
Add a new row in Named Table (Table1) and add data from txtboxes into last empty cells based on header named of the Table1
I have a named Table1 with columns test1, test2, test3, test4 and textbox1,textbox2,textbox3,textbox4
Using click procedure, I would like to create a VBA to add a new row in Table1 and based on with header name of the Table1, the data to be populated from textboxes, so for example, if i want to upload data from textbox1, the code will search in table1 the header test2,then the last empty cell and populate the data in cell
I tried but didnt work.:(...Anyone can guide me on this, please?

```<code>Dim col As Long
Dim Row As Long
col = ActiveSheet.ListObjects("Table1").ListColumns("test2").Range.Column`
Row = Cells(Rows.Count, col).End(xlUp).Row
Cells(FirstEmptyRow + 1, col) = Me.textbox1.Value
</code>```

I tried but didnt work.:(...Anyone can guide me on this, please?

Body:
I have a named Table1 with columns test1, test2, test3, test4 and textbox1,textbox2,textbox3,textbox4
Using click procedure, I would like to create a VBA to add a new row in Table1 and based on with header name of the Table1, the data to be populated from textboxes, so for example, if i want to upload data from textbox1, the code will search in table1 the header test2,then the last empty cell and populate the data in cell
I tried but didnt work.:(...Anyone can guide me on this, please?

Dim col As Long
Dim Row As Long
col = ActiveSheet.ListObjects("Table1").ListColumns("test2").Range.Column`
Row = Cells(Rows.Count, col).End(xlUp).Row
Cells(FirstEmptyRow + 1, col) = Me.textbox1.Value

I tried but didnt work.:(...Anyone can guide me on this, please?


问:
vscode live server extension is not opening safari browser in Mac OS Ventura
I am using a Mac Book Pro with M1 chip, and my MacOS is Ventura 13.0.1.
I have installed live server on vs code, but when I open (run) the live server the safari browser doesn't open.

Extension version: 5.7.9
VS Code version: Code 1.74.0 (Universal) (5235c6bb189b60b01b1f49062f4ffa42384f8c91, 2022-12-05T16:43:37.594Z)
OS version: Darwin arm64 22.1.0

I have tried almost everything that exists in Internet, but nothing makes it run.
So, I have a index.html file, under a folder names starter, I right click the file and select the "Open with Live Server" option.
A new page in Safari opens (unter the 127.0.0.1 and the available port) but it never loads.
The same thing happens if I start live server (Go Live)  from vs code button that exists in the status bar. Safari is opening the page but it never loads.
I would expect for the Safari page to open and see the folder that my index.html file is lying. I would also expect after the Safari page has opened, after selecting the "Show Javascript console" in the browser and after choosing my .js code to automatically show me the result of my program.


问:
Why does GCC output bloat in 32-bit mode?
I tested this C code on Compiler Explorer:

```<code>#include <stdio.h>

int main(void)
{
    printf("Hello world!\n");
}
</code>```

I selected the compiler x86-64 gcc 12.2 with the parameters -std=c17 -O3 -m32.

In 64-bit mode (no -m32 option) the output looks OK and optimized (online example):

```<code>.LC0:
        .string "Hello world!"
main:
        sub     rsp, 8
        mov     edi, OFFSET FLAT:.LC0
        call    puts
        xor     eax, eax
        add     rsp, 8
        ret
</code>```

In 32-bit mode, the output is bloated by a lot of non-sense (online example):

```<code>.LC0:
        .string "Hello world!"
main:
        lea     ecx, [esp+4]   # OK, so ecx = esp + 4, but main has no parameters...why?
        and     esp, -16
        push    DWORD PTR [ecx-4]   # push [ecx - 4], which is the return address...why?
        push    ebp
        mov     ebp, esp
        push    ecx   # saves the stack address above the return address...what is going on?
        sub     esp, 16   # what is this for?
        push    OFFSET FLAT:.LC0
        call    puts
        mov     ecx, DWORD PTR [ebp-4]   # restores that address
        add     esp, 16   # cleans that add esp, 16??
        xor     eax, eax
        leave
        lea     esp, [ecx-4]   # restores stack as it was on function entry
        ret
</code>```

I expected something along the lines of:

```<code>.LC0:
        .string "Hello world!"
main:
        sub esp, 12   # GCC wants 16-byte aligned stack
        push OFFSET FLAT:.LC0
        call puts
        xor eax, eax
        add esp, 12
        ret
</code>```

Considering I used the -O3 option, why does the output look like that?

Body:
I tested this C code on Compiler Explorer:

#include <stdio.h>

int main(void)
{
    printf("Hello world!\n");
}

I selected the compiler x86-64 gcc 12.2 with the parameters -std=c17 -O3 -m32.

In 64-bit mode (no -m32 option) the output looks OK and optimized (online example):

.LC0:
        .string "Hello world!"
main:
        sub     rsp, 8
        mov     edi, OFFSET FLAT:.LC0
        call    puts
        xor     eax, eax
        add     rsp, 8
        ret

In 32-bit mode, the output is bloated by a lot of non-sense (online example):

.LC0:
        .string "Hello world!"
main:
        lea     ecx, [esp+4]   # OK, so ecx = esp + 4, but main has no parameters...why?
        and     esp, -16
        push    DWORD PTR [ecx-4]   # push [ecx - 4], which is the return address...why?
        push    ebp
        mov     ebp, esp
        push    ecx   # saves the stack address above the return address...what is going on?
        sub     esp, 16   # what is this for?
        push    OFFSET FLAT:.LC0
        call    puts
        mov     ecx, DWORD PTR [ebp-4]   # restores that address
        add     esp, 16   # cleans that add esp, 16??
        xor     eax, eax
        leave
        lea     esp, [ecx-4]   # restores stack as it was on function entry
        ret

I expected something along the lines of:

.LC0:
        .string "Hello world!"
main:
        sub esp, 12   # GCC wants 16-byte aligned stack
        push OFFSET FLAT:.LC0
        call puts
        xor eax, eax
        add esp, 12
        ret

Considering I used the -O3 option, why does the output look like that?


问:
Permission denied in VS Code installing R library while running as administrator
I have a new instance of VS Code up running as administrator, and I started a R terminal instance and ran

```<code>install.packages("cli")
</code>```

and I get the following message

```<code>Warning message:
In file.copy(savedcopy, lib, recursive = TRUE) :
  problem copying C:\Users\MYUSER\AppData\Local\R\win-library\4.2\00LOCK\cli\libs\x64\cli.dll to C:\Users\MYUSER\AppData\Local\R\win-library\4.2\cli\libs\x64\cli.dll: Permission denied
</code>```

Any idea? I assumed running as administrator would solve it so now I have no idea...

Body:
I have a new instance of VS Code up running as administrator, and I started a R terminal instance and ran

install.packages("cli")

and I get the following message

Warning message:
In file.copy(savedcopy, lib, recursive = TRUE) :
  problem copying C:\Users\MYUSER\AppData\Local\R\win-library\4.2\00LOCK\cli\libs\x64\cli.dll to C:\Users\MYUSER\AppData\Local\R\win-library\4.2\cli\libs\x64\cli.dll: Permission denied

Any idea? I assumed running as administrator would solve it so now I have no idea...


问:
Start spark from a scala shell
How can I start spark from an sbt shell. I don't want to use the spark-shell command. I would like to use spark and use the objects in my sbt project.</p>

Title: Start spark from a scala shell


问:
Why Would This C++ Code Deadlock or Freeze?
I have what I think is a simple background worker thread setup that has been working for millions of executions over many days. Recently I got a hang at this point in my code and am wondering if I've missed something in my setup that led to a deadlock.

Code snippet (will not compile):

```<code>cout << "Starting." << endl;
atomic<bool> keepThreadRunning;
mutex coutMutex;
keepThreadRunning = true;
auto doBackgroundTask1 = [&keepThreadRunning, &backgroundData1, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData1->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 1 tasks." << endl;
    coutMutex.unlock();
};
auto doBackgroundTask2 = [&keepThreadRunning, &backgroundData2, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData2->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 2 tasks." << endl;
    coutMutex.unlock();
};
thread backgroundThread1(doBackgroundTask1);
thread backgroundThread2(doBackgroundTask2);
doForegroundWork();
keepThreadRunning = false;
backgroundThread1.join();
backgroundThread2.join();
cout << "Finished." << endl;
</code>```

I suspect I'm doing something wrong with the atomic or the mutex. I have no way of proving this to you, but the two sets of background data and the foreground work are completely isolated, so the threads have no buried locks or conflicts over that data. I'm showing two threads just in case I've missed something with the mutex around cout.

Body:
I have what I think is a simple background worker thread setup that has been working for millions of executions over many days. Recently I got a hang at this point in my code and am wondering if I've missed something in my setup that led to a deadlock.

Code snippet (will not compile):

cout << "Starting." << endl;
atomic<bool> keepThreadRunning;
mutex coutMutex;
keepThreadRunning = true;
auto doBackgroundTask1 = [&keepThreadRunning, &backgroundData1, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData1->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 1 tasks." << endl;
    coutMutex.unlock();
};
auto doBackgroundTask2 = [&keepThreadRunning, &backgroundData2, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData2->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 2 tasks." << endl;
    coutMutex.unlock();
};
thread backgroundThread1(doBackgroundTask1);
thread backgroundThread2(doBackgroundTask2);
doForegroundWork();
keepThreadRunning = false;
backgroundThread1.join();
backgroundThread2.join();
cout << "Finished." << endl;

I suspect I'm doing something wrong with the atomic or the mutex. I have no way of proving this to you, but the two sets of background data and the foreground work are completely isolated, so the threads have no buried locks or conflicts over that data. I'm showing two threads just in case I've missed something with the mutex around cout.


问:
WordPress - How to put all images from post into the one gallery. After click on any image from post, open whole gallery and be able to list throught
please I need an advice for WordPress.
I need to reach one gallery for all pictures from one post.
I literally need some plugin which can help me to make exactly this gallery from this link(exactly the same):

https://www.archdaily.com/992555/amago-house-bruno-dias-arquitectura?ad_content=992555&ad_medium=widget&ad_name=featured_loop_main

I need to reach Thumbnail-Pictures-text(content)-picture-text(content)-picture
But if i open any picture from that post in lightbox i can list throught whole gallery from that post.

Can anyone give me an advice how can i make it please?
Im clueless.

I tried a lot of gallery pluggins for wordpress but no one have option to insert chosen images from gallery. If i insert one image from gallery into the post and then open it in lightbox i want to show whole gallery of that image. Cant find plugin with that functionality.


问:
How to override default Minecraft ids
I'm trying to override the default Minecraft armor by replacing it with custom armor but so far it's told me to use .set()

I've tried to set my mod id to Minecraft and got told to use .set() Code:

```<code>LEATHER_HELMET = Registry.register(Registry.ITEM, new ResourceLocation(Armor.MODID, "leather_helmet"), new Leather.Helmet());
</code>```

Then I tried Registry.set() which wouldn't even compile and I then looked it up on ChatGPT as a last resort and it told me to use

```<code>LEATHER_HELMET = Item.REGISTRY.set(new ResourceLocation("minecraft:leather_helmet"), 1152, new ItemStack(Test2ModItems.LEATHER_HELMET));
</code>```

but my IDE told me that it "cannot resolve symbol 'REGISTRY'"

Title: How to override default Minecraft ids

Body:
I'm trying to override the default Minecraft armor by replacing it with custom armor but so far it's told me to use .set()

I've tried to set my mod id to Minecraft and got told to use .set() Code:

LEATHER_HELMET = Registry.register(Registry.ITEM, new ResourceLocation(Armor.MODID, "leather_helmet"), new Leather.Helmet());

Then I tried Registry.set() which wouldn't even compile and I then looked it up on ChatGPT as a last resort and it told me to use

LEATHER_HELMET = Item.REGISTRY.set(new ResourceLocation("minecraft:leather_helmet"), 1152, new ItemStack(Test2ModItems.LEATHER_HELMET));

but my IDE told me that it "cannot resolve symbol 'REGISTRY'"


问:
React JS, node backend, GET or POST, retrieving data not working
so recently ive been programming my first React JS project, but ive been running into a few problems when trying to reach my backend and retrieve data from my database. I think its probably a very silly mistake only a rookie like me could make, but ive tried for hours now and just cant figure it out. any help appreciated :)

tried fetch() with GET and POST with parameters in the body aswell as a paramstring, aswell as some Axios stuff ive seen some indian fellow do in a tutortial, none have worked so far. I think my backend seems to be fine because if i hardcode the parameter it works fine. so my guess is that my problem has something to do with the parameters

fetch 'GET'

```<code>    async function checkEmailTaken(email) {
        await fetch("/api/emailtaken?" + new URLSearchParams({ email: email }).toString())
                .then(res => res.json())
                .then(data => {
                    console.log(data);
                    if(data.length > 0) return true;
                });
</code>```

fetch 'POST'

```<code>    async function checkEmailTaken(email) {
        await fetch("/api/emailtaken", {
            method: 'POST',
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: email,
            })
        })
        .then(res => res.json())
        .then(data => {
            console.log(data);
            if(data.length > 0) return true;
        });
    }
</code>```

have also tried with async so i fairly confident thats not it

Backend:

```<code>const express = require('express');
const app = express();
const mysql = require('mysql');

const db = mysql.createPool({
    host:"localhost",
    user:"root",
    database:"skinport-bot"
});

app.use(express.json());

app.post("/api/emailtaken", (req, res) => {
    const email = req.params.email

    const sql = "SELECT * FROM user WHERE email = ?";
    db.query(sql, [email], (error, result) => {
        if (error) throw console.log(error);
        res.send(result);
    });
});

app.listen(3001, () => {
    console.log("running on port 3001");
});
</code>```

Body:
so recently ive been programming my first React JS project, but ive been running into a few problems when trying to reach my backend and retrieve data from my database. I think its probably a very silly mistake only a rookie like me could make, but ive tried for hours now and just cant figure it out. any help appreciated :)

tried fetch() with GET and POST with parameters in the body aswell as a paramstring, aswell as some Axios stuff ive seen some indian fellow do in a tutortial, none have worked so far. I think my backend seems to be fine because if i hardcode the parameter it works fine. so my guess is that my problem has something to do with the parameters

fetch 'GET'

    async function checkEmailTaken(email) {
        await fetch("/api/emailtaken?" + new URLSearchParams({ email: email }).toString())
                .then(res => res.json())
                .then(data => {
                    console.log(data);
                    if(data.length > 0) return true;
                });

fetch 'POST'

    async function checkEmailTaken(email) {
        await fetch("/api/emailtaken", {
            method: 'POST',
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: email,
            })
        })
        .then(res => res.json())
        .then(data => {
            console.log(data);
            if(data.length > 0) return true;
        });
    }

have also tried with async so i fairly confident thats not it

Backend:

const express = require('express');
const app = express();
const mysql = require('mysql');

const db = mysql.createPool({
    host:"localhost",
    user:"root",
    database:"skinport-bot"
});

app.use(express.json());

app.post("/api/emailtaken", (req, res) => {
    const email = req.params.email

    const sql = "SELECT * FROM user WHERE email = ?";
    db.query(sql, [email], (error, result) => {
        if (error) throw console.log(error);
        res.send(result);
    });
});

app.listen(3001, () => {
    console.log("running on port 3001");
});


问:
Exception: Java gateway process exited before sending its port number
I created a docken container from this bigdl image.
However wheb I tried to start nn_context:

```<code>sc = init_nncontext("...")
spark= SparkContext(sc)
</code>```

I got this error: Exception: Java gateway process exited before sending its port number

```<code>/tmp/ipykernel_188/2945161649.py in <module>
----> 1 sc = init_nncontext("anomaly detection")
      2 spark= SparkContext(sc)

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in init_nncontext(conf, cluster_mode, spark_log_level, redirect_spark_log, **kwargs)
    534         spark_args.update(conf.getAll())
    535     if cluster_mode == "spark-submit":
--> 536         sc = init_internal_nncontext(conf, spark_log_level, redirect_spark_log)
    537     elif cluster_mode == "local":
    538         if conf:

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in init_internal_nncontext(conf, spark_log_level, redirect_spark_log)
    642
    643     if isinstance(conf, six.string_types):
--> 644         sc = getOrCreateSparkContext(conf=None, appName=conf)
    645     else:
    646         sc = getOrCreateSparkContext(conf=conf)

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in getOrCreateSparkContext(conf, appName)
    684             if appName:
    685                 spark_conf.setAppName(appName)
--> 686             return SparkContext.getOrCreate(spark_conf)
    687         else:
    688             return SparkContext.getOrCreate()

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in getOrCreate(cls, conf)
    382         with SparkContext._lock:
    383             if SparkContext._active_spark_context is None:
--> 384                 SparkContext(conf=conf or SparkConf())
    385             return SparkContext._active_spark_context
    386

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in __init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
    142                 " is not allowed as it is a security risk.")
    143
--> 144         SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
    145         try:
    146             self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer,

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in _ensure_initialized(cls, instance, gateway, conf)
    329         with SparkContext._lock:
    330             if not SparkContext._gateway:
--> 331                 SparkContext._gateway = gateway or launch_gateway(conf)
    332                 SparkContext._jvm = SparkContext._gateway.jvm
    333

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/java_gateway.py in launch_gateway(conf, popen_kwargs)
    106
    107             if not os.path.isfile(conn_info_file):
--> 108                 raise Exception("Java gateway process exited before sending its port number")
    109
    110             with open(conn_info_file, "rb") as info:

Exception: Java gateway process exited before sending its port number
</code>```

Body:
I created a docken container from this bigdl image.
However wheb I tried to start nn_context:

sc = init_nncontext("...")
spark= SparkContext(sc)

I got this error: Exception: Java gateway process exited before sending its port number

/tmp/ipykernel_188/2945161649.py in <module>
----> 1 sc = init_nncontext("anomaly detection")
      2 spark= SparkContext(sc)

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in init_nncontext(conf, cluster_mode, spark_log_level, redirect_spark_log, **kwargs)
    534         spark_args.update(conf.getAll())
    535     if cluster_mode == "spark-submit":
--> 536         sc = init_internal_nncontext(conf, spark_log_level, redirect_spark_log)
    537     elif cluster_mode == "local":
    538         if conf:

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in init_internal_nncontext(conf, spark_log_level, redirect_spark_log)
    642
    643     if isinstance(conf, six.string_types):
--> 644         sc = getOrCreateSparkContext(conf=None, appName=conf)
    645     else:
    646         sc = getOrCreateSparkContext(conf=conf)

/opt/work/bigdl-2.1.0/python/bigdl-spark_3.1.2-2.1.0-python-api.zip/bigdl/dllib/nncontext.py in getOrCreateSparkContext(conf, appName)
    684             if appName:
    685                 spark_conf.setAppName(appName)
--> 686             return SparkContext.getOrCreate(spark_conf)
    687         else:
    688             return SparkContext.getOrCreate()

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in getOrCreate(cls, conf)
    382         with SparkContext._lock:
    383             if SparkContext._active_spark_context is None:
--> 384                 SparkContext(conf=conf or SparkConf())
    385             return SparkContext._active_spark_context
    386

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in __init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
    142                 " is not allowed as it is a security risk.")
    143
--> 144         SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
    145         try:
    146             self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer,

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/context.py in _ensure_initialized(cls, instance, gateway, conf)
    329         with SparkContext._lock:
    330             if not SparkContext._gateway:
--> 331                 SparkContext._gateway = gateway or launch_gateway(conf)
    332                 SparkContext._jvm = SparkContext._gateway.jvm
    333

/opt/work/spark-3.1.2/python/lib/pyspark.zip/pyspark/java_gateway.py in launch_gateway(conf, popen_kwargs)
    106
    107             if not os.path.isfile(conn_info_file):
--> 108                 raise Exception("Java gateway process exited before sending its port number")
    109
    110             with open(conn_info_file, "rb") as info:

Exception: Java gateway process exited before sending its port number


问:
Spring Boot MessageSource retrieves message from localized properties file, even when locale not matching
I've found a strange behavior of my spring boot (2.7.5) application.

I added i18n.
My configuration class (annotated with @Configuration and implements WebMvcConfigurer):

```<code>@Bean
public LocaleResolver localeResolver ( ) {
    SessionLocaleResolver resolver = new SessionLocaleResolver ( );
    resolver.setDefaultLocale ( Locale.GERMAN );
    return resolver;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor ( ) {
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor ( );
    interceptor.setParamName ( "lang" );
    return interceptor;
}

@Bean
public MessageSource messageSource ( ) {
    ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource ( );
    source.setBasename ( "classpath:/lang/messages" );
    source.setDefaultEncoding ( "UTF-8" );
    source.setCacheSeconds ( 600 );
    return source;
}

@Override
public void addInterceptors ( InterceptorRegistry registry ) {
    registry.addInterceptor ( localeChangeInterceptor ( ) );
}
</code>```

Added 3 message.properties files under resources/lang with "lang.test" as reference

messages.properties           -> lang.test = test default

messages_en_US.properties     -> lang.test = test german

messages_en_DE.properties     -> lang.test = test usa

Also I created a test method which iterates over all locales.

```<code>public void test ( ) {
    String defaultMessage = "NOT FOUND";
    for ( Locale locale : Locale.getAvailableLocales ( ) ) {
        String testMessage = messenger.getMessage ( "lang.test", null, defaultMessage, locale );
        System.out.println ( "test message: " + testMessage + " for locale " + locale );
    }
}
</code>```

I would expect to have just 2 outputs. One for en_US with "test usa" and another with "test german" for de_DE.

But the output looks like:

test message: test german for locale
test message: test german for locale he
test message: test german for locale th_TH_#Thai
test message: test german for locale nds
test message: test german for locale tk_TM_#Latn
test message: test german for locale ti_ET
test message: test german for locale ta_SG
test message: test german for locale lv
test message: test german for locale en_NU
...
```

Why do I get the output of messages_de_DE.properties for all locales?

Body:
I've found a strange behavior of my spring boot (2.7.5) application.

I added i18n.
My configuration class (annotated with @Configuration and implements WebMvcConfigurer):

@Bean
public LocaleResolver localeResolver ( ) {
    SessionLocaleResolver resolver = new SessionLocaleResolver ( );
    resolver.setDefaultLocale ( Locale.GERMAN );
    return resolver;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor ( ) {
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor ( );
    interceptor.setParamName ( "lang" );
    return interceptor;
}

@Bean
public MessageSource messageSource ( ) {
    ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource ( );
    source.setBasename ( "classpath:/lang/messages" );
    source.setDefaultEncoding ( "UTF-8" );
    source.setCacheSeconds ( 600 );
    return source;
}

@Override
public void addInterceptors ( InterceptorRegistry registry ) {
    registry.addInterceptor ( localeChangeInterceptor ( ) );
}

Added 3 message.properties files under resources/lang with "lang.test" as reference

messages.properties           -> lang.test = test default

messages_en_US.properties     -> lang.test = test german

messages_en_DE.properties     -> lang.test = test usa

Also I created a test method which iterates over all locales.

public void test ( ) {
    String defaultMessage = "NOT FOUND";
    for ( Locale locale : Locale.getAvailableLocales ( ) ) {
        String testMessage = messenger.getMessage ( "lang.test", null, defaultMessage, locale );
        System.out.println ( "test message: " + testMessage + " for locale " + locale );
    }
}

I would expect to have just 2 outputs. One for en_US with "test usa" and another with "test german" for de_DE.

But the output looks like:

test message: test german for locale
test message: test german for locale he
test message: test german for locale th_TH_#Thai
test message: test german for locale nds
test message: test german for locale tk_TM_#Latn
test message: test german for locale ti_ET
test message: test german for locale ta_SG
test message: test german for locale lv
test message: test german for locale en_NU
...

Why do I get the output of messages_de_DE.properties for all locales?


问:
PySpark application on EMR fails with error "User application exited with status 1"
I am running my first PySpark application on EMR. My step fails with error "Unknown error". I checked the stderr log file and all it says is "User application exited with status 1". After researching a bit, I found out this happens when you don't pas your arguments correctly. Below is the kist of arguments I am passing. Can someone take a look and advise what's wrong here?

Thanks!

Jatin

```<code>spark-submit --deploy-mode cluster --master yarn s3://dpsdl-184210370075-prod-us-east-1-appobjects/scripts/spectre_matchedevent/scm_case_alert_data_sanitized_emr.py -source_bucket dpsdl-184210370075-prod-us-east-1-transformed -source_prefix_match spectre_matchedevent/output/spectre_match.parquet/ -source_prefix_alert spectre_matchedevent/output/spectre_case.parquet/ -source_prefix_ap spectre_matchedevent/output/spectre_amazonparty.parquet/ -source_prefix_dp spectre_matchedevent/output/spectre_deniedparty.parquet/ -dest_bucket dpsdl-184210370075-prod-us-east-1-enriched -dest_db_table read_out_secure.jk_scm_case_alert_data_new -dest_db_table_stg read_out_secure.jk_scad_updated_data_stg -dest_db_table_updated_cases_stg read_out_secure.jk_scm_case_alert_data_updated_cases_stg -dest_work_prefix_scad spectre_matchedevent/workdir/scm_case_alert_data/ -dest_work_prefix_updated_cases spectre_matchedevent/workdir/scad_updated_cases/ -dest_prefix_scad spectre_matchedevent/datamart-tables/scm_case_alert_data/ -iam_role arn:aws:iam::184210370075:role/as-redshift-load-for-scheduled -update_mode overwrite -default_matchtime_lower_threshold 2022-12-09
</code>```

Body:
I am running my first PySpark application on EMR. My step fails with error "Unknown error". I checked the stderr log file and all it says is "User application exited with status 1". After researching a bit, I found out this happens when you don't pas your arguments correctly. Below is the kist of arguments I am passing. Can someone take a look and advise what's wrong here?

Thanks!

Jatin

spark-submit --deploy-mode cluster --master yarn s3://dpsdl-184210370075-prod-us-east-1-appobjects/scripts/spectre_matchedevent/scm_case_alert_data_sanitized_emr.py -source_bucket dpsdl-184210370075-prod-us-east-1-transformed -source_prefix_match spectre_matchedevent/output/spectre_match.parquet/ -source_prefix_alert spectre_matchedevent/output/spectre_case.parquet/ -source_prefix_ap spectre_matchedevent/output/spectre_amazonparty.parquet/ -source_prefix_dp spectre_matchedevent/output/spectre_deniedparty.parquet/ -dest_bucket dpsdl-184210370075-prod-us-east-1-enriched -dest_db_table read_out_secure.jk_scm_case_alert_data_new -dest_db_table_stg read_out_secure.jk_scad_updated_data_stg -dest_db_table_updated_cases_stg read_out_secure.jk_scm_case_alert_data_updated_cases_stg -dest_work_prefix_scad spectre_matchedevent/workdir/scm_case_alert_data/ -dest_work_prefix_updated_cases spectre_matchedevent/workdir/scad_updated_cases/ -dest_prefix_scad spectre_matchedevent/datamart-tables/scm_case_alert_data/ -iam_role arn:aws:iam::184210370075:role/as-redshift-load-for-scheduled -update_mode overwrite -default_matchtime_lower_threshold 2022-12-09


问:
Problem with exec() function in KKT conditions by using SymPy
I'm writing a not full-implemented Python function using SymPy library which looks for the critical points of a mathematical function f through the KKT conditions, as it follows:

```<code>def KKT(f: str, h=[], g=[], max=True):

  # NOTE: The expressions contained in g must be such that g <= 0 and the ones contained in h must be such that h = 0. Both g and h are string lists

  import sympy as sp # Importing a SymPy library
  n = len(h) # Quantity of equality constraints
  m = len(g) # Quantity of inequality constraints

  f = sp.parse_expr(f) # Constructing the f function by passing a string as an argument
  vars = f.free_symbols # Getting the variables set
  pars = list(vars) # Parameters list

  if n > 0:
    for i in range(n):
      exec(f'h{i+1} = sp.Symbol("h_{i+1}")')
      exec(f'h{i+1} = sp.parse_expr(h[{i}])') # Create the equality constraint h_i
      exec(f'l{i+1} = sp.Symbol("\\lambda_{i+1}")') # Create the parameter lambda_i
      exec(f'pars.append(l{i+1})') # Adding lambda_i to parameters list

  if m > 0:
    for j in range(m):
      exec(f'g_{j+1} = sp.Symbol("g_{j+1}")')
      exec(f'g{j+1} = sp.parse_expr(g[{j}])') # Create the inequality constraint g_i
      exec(f'u{j+1} = sp.Symbol("\\mu_{j+1}", negative=False)') # Create the parameter mu_i
      exec(f'pars.append(u{j+1})') # Add mu_i to parameters list
      exec(f'p{j+1} = sp.Symbol("p_{j+1}", negative=False)') # Create fill portion p_i
      exec(f'pars.append(p{j+1})') # Add p_i to parameters list

  # Creating the Lagrangean

  L = f

  if n > 0:
    for i in range(n):
      exec(f'L = L - l{i+1} * h{i+1}') 'Adding lambda_j * h_j to the Lagrangean

  if m > 0:
    for j in range(m):
      exec(f'L = L - u{j+1} * g{j+1}') # <- THIS LINE IS NOT WORKING
      # Adding mu_i * g_i to the Lagrangean
      print(f'j: {j}')
      print(f'{L}\n')

  # Creating the KKT condition from Lagrangean

  R = [] # Constraint's set

  for var in vars:
    R.append(sp.diff(L, var)) # Add the Lagrangean's partial derivative with respect to var

  if n > 0:
    for i in range(n):
      exec(f'R.append(h{i+1})')

  if m > 0:
    for j in range(m):
      exec(f'R.append(u{j+1} * g{j+1})')
      exec(f'R.append(g{j+1} + p{j+1})')

  # Solving KKT conditions

  sols_lagr = sp.solve(R, pars, dict=True) # Lagrangian solutions
  critical_points = [{var: sol.get(var) for var in sol if var in vars} for sol in sols_lagr]

  return critical_points

KKT('24*x_1 - x_1**2 + 10*x_2 - 2*x_2**2',
    [],
    ['x_1 - 8', 'x_2 - 7', '-x_1', '-x_2']
   )
</code>```

However, for some reason, the following line code doesn't work:

```<code>exec(f'L = L - u{j+1} * g{j+1}')
</code>```

Because I'm getting this result when I execute this code's block:

```<code>j: 0
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 1
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 2
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 3
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2
</code>```

Which shows the Lagrangean is not adding up the parcels. I'd be grateful if someone could help me.

Body:
I'm writing a not full-implemented Python function using SymPy library which looks for the critical points of a mathematical function f through the KKT conditions, as it follows:

def KKT(f: str, h=[], g=[], max=True):

  # NOTE: The expressions contained in g must be such that g <= 0 and the ones contained in h must be such that h = 0. Both g and h are string lists

  import sympy as sp # Importing a SymPy library
  n = len(h) # Quantity of equality constraints
  m = len(g) # Quantity of inequality constraints

  f = sp.parse_expr(f) # Constructing the f function by passing a string as an argument
  vars = f.free_symbols # Getting the variables set
  pars = list(vars) # Parameters list

  if n > 0:
    for i in range(n):
      exec(f'h{i+1} = sp.Symbol("h_{i+1}")')
      exec(f'h{i+1} = sp.parse_expr(h[{i}])') # Create the equality constraint h_i
      exec(f'l{i+1} = sp.Symbol("\\lambda_{i+1}")') # Create the parameter lambda_i
      exec(f'pars.append(l{i+1})') # Adding lambda_i to parameters list

  if m > 0:
    for j in range(m):
      exec(f'g_{j+1} = sp.Symbol("g_{j+1}")')
      exec(f'g{j+1} = sp.parse_expr(g[{j}])') # Create the inequality constraint g_i
      exec(f'u{j+1} = sp.Symbol("\\mu_{j+1}", negative=False)') # Create the parameter mu_i
      exec(f'pars.append(u{j+1})') # Add mu_i to parameters list
      exec(f'p{j+1} = sp.Symbol("p_{j+1}", negative=False)') # Create fill portion p_i
      exec(f'pars.append(p{j+1})') # Add p_i to parameters list

  # Creating the Lagrangean

  L = f

  if n > 0:
    for i in range(n):
      exec(f'L = L - l{i+1} * h{i+1}') 'Adding lambda_j * h_j to the Lagrangean

  if m > 0:
    for j in range(m):
      exec(f'L = L - u{j+1} * g{j+1}') # <- THIS LINE IS NOT WORKING
      # Adding mu_i * g_i to the Lagrangean
      print(f'j: {j}')
      print(f'{L}\n')

  # Creating the KKT condition from Lagrangean

  R = [] # Constraint's set

  for var in vars:
    R.append(sp.diff(L, var)) # Add the Lagrangean's partial derivative with respect to var

  if n > 0:
    for i in range(n):
      exec(f'R.append(h{i+1})')

  if m > 0:
    for j in range(m):
      exec(f'R.append(u{j+1} * g{j+1})')
      exec(f'R.append(g{j+1} + p{j+1})')

  # Solving KKT conditions

  sols_lagr = sp.solve(R, pars, dict=True) # Lagrangian solutions
  critical_points = [{var: sol.get(var) for var in sol if var in vars} for sol in sols_lagr]

  return critical_points

KKT('24*x_1 - x_1**2 + 10*x_2 - 2*x_2**2',
    [],
    ['x_1 - 8', 'x_2 - 7', '-x_1', '-x_2']
   )

However, for some reason, the following line code doesn't work:

exec(f'L = L - u{j+1} * g{j+1}')

Because I'm getting this result when I execute this code's block:

j: 0
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 1
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 2
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

j: 3
-x_1**2 + 24*x_1 - 2*x_2**2 + 10*x_2

Which shows the Lagrangean is not adding up the parcels. I'd be grateful if someone could help me.


问:
Lucee 6.0.0.313-SNAPSHOT Error (java.util.NoSuchElementException)

lucee.runtime.exp.NativeException: Pool exhausted

Getting this error every two hours on lucee server.
Message: Pool exhausted