问:
Filtering an IQueryable in C#
I'm trying to filter a view of records from my database to only show records that match search filters provided by the user. Here's my code:

```<code>    public async Task<IActionResult> Index(string searchSerial, string searchRoom, decimal searchPrice1, decimal searchPrice2, DateTime searchDate1, DateTime searchDate2)
    {
        var computers = from m in _context.Computers
                        select m;

        if (!String.IsNullOrEmpty(searchSerial))
        {
            computers = computers.Where(s => s.ManufacturerSerialNumber.ToString()!.Equals(searchSerial));

        }

        if (!String.IsNullOrEmpty(searchRoom))
        {
            computers = computers.Where(s => s.OfficeRoomNumber!.Equals(searchRoom));

        }

        if (!String.IsNullOrEmpty(""+searchPrice1) || !String.IsNullOrEmpty(""+searchPrice2))
        {
            if (String.IsNullOrEmpty("" + searchPrice1))
            {
                computers = computers.Where(s => !(s.Price > searchPrice2));

            }
            else if (String.IsNullOrEmpty("" + searchPrice2))
            {
                computers = computers.Where(s => !(s.Price < searchPrice1));

            }
            else
            {
                computers = computers.Where(s => !(s.Price < searchPrice1));
                computers = computers.Where(s => !(s.Price > searchPrice2));

            }
        }

        if (!String.IsNullOrEmpty(""+searchDate1) || !String.IsNullOrEmpty("" + searchDate2))
        {

            if (String.IsNullOrEmpty("" + searchDate1))
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate2) < 0));

            }
            else if (String.IsNullOrEmpty("" + searchDate2))
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate1) > 0));

            }
            else
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate2) < 0));
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate1) > 0));

            }
        }
        return View(await computers.ToListAsync());
    }
</code>```

I am running into an issue with my searchPrice and searchDate filters. I believe it has to do with the if not null check. If I comment out these 2 sections my code works fine so it has to be something within these 2 sections.

I have tried switching the > and < with <= and >= operators and I have also tried the ToString instead of concatenating the search criteria and none of it worked.

EDIT: The issue I am running into is that my method enters into the if statements for searchPrice and searchDate even if there is no user input, when it is supposed to skip all of the if statements and return all computers.

EDIT 2: I have altered my method to have all string parameters and parsing their respective values in their respective if statements. this has solved the problem of entering the if statements prematurely but now my logic is wrong. The searchPrice now works as it should, but the installationDate filter does not. It takes in the values properly but does not do the comparison correctly. for example, if I enter 11/14/2019 in the 1st and leave the other blank, it shows me computers with 11/15/2019 as the installation date when it should show computers with dates before 11/14/2019. switching the logical operators around did not fix it either.

Title: Filtering an IQueryable in C#

Body:
I'm trying to filter a view of records from my database to only show records that match search filters provided by the user. Here's my code:

    public async Task<IActionResult> Index(string searchSerial, string searchRoom, decimal searchPrice1, decimal searchPrice2, DateTime searchDate1, DateTime searchDate2)
    {
        var computers = from m in _context.Computers
                        select m;

        if (!String.IsNullOrEmpty(searchSerial))
        {
            computers = computers.Where(s => s.ManufacturerSerialNumber.ToString()!.Equals(searchSerial));

        }

        if (!String.IsNullOrEmpty(searchRoom))
        {
            computers = computers.Where(s => s.OfficeRoomNumber!.Equals(searchRoom));

        }

        if (!String.IsNullOrEmpty(""+searchPrice1) || !String.IsNullOrEmpty(""+searchPrice2))
        {
            if (String.IsNullOrEmpty("" + searchPrice1))
            {
                computers = computers.Where(s => !(s.Price > searchPrice2));

            }
            else if (String.IsNullOrEmpty("" + searchPrice2))
            {
                computers = computers.Where(s => !(s.Price < searchPrice1));

            }
            else
            {
                computers = computers.Where(s => !(s.Price < searchPrice1));
                computers = computers.Where(s => !(s.Price > searchPrice2));

            }
        }

        if (!String.IsNullOrEmpty(""+searchDate1) || !String.IsNullOrEmpty("" + searchDate2))
        {

            if (String.IsNullOrEmpty("" + searchDate1))
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate2) < 0));

            }
            else if (String.IsNullOrEmpty("" + searchDate2))
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate1) > 0));

            }
            else
            {
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate2) < 0));
                computers = computers.Where(s => !(s.InstallationDate.CompareTo(searchDate1) > 0));

            }
        }
        return View(await computers.ToListAsync());
    }

I am running into an issue with my searchPrice and searchDate filters. I believe it has to do with the if not null check. If I comment out these 2 sections my code works fine so it has to be something within these 2 sections.

I have tried switching the > and < with <= and >= operators and I have also tried the ToString instead of concatenating the search criteria and none of it worked.

EDIT: The issue I am running into is that my method enters into the if statements for searchPrice and searchDate even if there is no user input, when it is supposed to skip all of the if statements and return all computers.

EDIT 2: I have altered my method to have all string parameters and parsing their respective values in their respective if statements. this has solved the problem of entering the if statements prematurely but now my logic is wrong. The searchPrice now works as it should, but the installationDate filter does not. It takes in the values properly but does not do the comparison correctly. for example, if I enter 11/14/2019 in the 1st and leave the other blank, it shows me computers with 11/15/2019 as the installation date when it should show computers with dates before 11/14/2019. switching the logical operators around did not fix it either.


来源: stackexchange

问:
How to fill the space between y_axis and a plot with python?

I have 2 lists x and y. I have plotted the graph using matplotlib library.

Actually, I would like to fill the space between the the graph and the y axis (x =0).

```<code>from matplotlib.figure import Figure
fig = Figure(figsize=(11, 45), dpi=300)

axes1 = fig.add_subplot(121)
axes2 = fig.add_subplot(122)

x = [10, 3, 15, -2, 25]
y= [1, 2, 3, 4, 5]

z = [0, 0, 0, 0, 0]

axes1.fill_between(x, y, z, color='red', alpha=.5)
axes2.plot(x, y)

#axes1.invert_yaxis()
#axes2.invert_yaxis()

fig.savefig('Axis.png')
</code>```

I want to fill the right side graph as shown on the image

ContentLicense: CC BY-SA 4.0

Body:
I have 2 lists x and y. I have plotted the graph using matplotlib library.

Actually, I would like to fill the space between the the graph and the y axis (x =0).

from matplotlib.figure import Figure
fig = Figure(figsize=(11, 45), dpi=300)

axes1 = fig.add_subplot(121)
axes2 = fig.add_subplot(122)

x = [10, 3, 15, -2, 25]
y= [1, 2, 3, 4, 5]

z = [0, 0, 0, 0, 0]

axes1.fill_between(x, y, z, color='red', alpha=.5)
axes2.plot(x, y)

#axes1.invert_yaxis()
#axes2.invert_yaxis()

fig.savefig('Axis.png')

I want to fill the right side graph as shown on the image


问:
Cant run because of java.lang.reflect.InvocationTargetException with javaFX without using FXML
```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1082)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
        at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Hello I added all my javafx-sdk in my classpath :

```<code>"/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.base.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.controls.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.fxml.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.graphics.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.media.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.swing.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.web.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx-swt.jar"
</code>```

And also added the

```<code>            "vmArgs": "--module-path \"/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib\" --add-modules javafx.controls,javafx.graphics,javafx.base,javafx.media",

</code>```

And even with that i still have this error (I'm on Ubuntu 22.04, Java 17, Java FX 19):
If someone has already encounter this. This will really help me (i have the same problem on my windows pc on both eclipse and vscode. The project is working fine on all of my mates computers.

Body:
Exception in Application start method
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:568)
        at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1082)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
        at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
        at java.base/java.lang.Thread.run(Thread.java:833)

Hello I added all my javafx-sdk in my classpath :

"/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.base.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.controls.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.fxml.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.graphics.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.media.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.swing.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx.web.jar",
        "/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib/javafx-swt.jar"

And also added the

            "vmArgs": "--module-path \"/home/emilio/openjfx-19_linux-x64_bin-sdk/javafx-sdk-19/lib\" --add-modules javafx.controls,javafx.graphics,javafx.base,javafx.media",

And even with that i still have this error (I'm on Ubuntu 22.04, Java 17, Java FX 19):
If someone has already encounter this. This will really help me (i have the same problem on my windows pc on both eclipse and vscode. The project is working fine on all of my mates computers.


问:
Node JS - Schedule MySQL back-up and send it by e-mail using Google Cloud
I am trying to build a NodeJS script to save a mySQL database, send it to me by e-mail as an attachement (the file is about 1MB), and I want to schedule the whole thing to run once a week. So far my script runs perfectly when run locally. I've set up the scheduling to run once every minute as a testing purpose.

I am struggling when trying to make it run on google cloud. The deployment went without issue, but then I only see in the logs Saving Database... so the scheduling part works fine, but I don't see the Dump File OK so I am assuming there is something wrong with mysqldump, but no error message. I didn't do anything specific with GCS, should I have ?

Thanks

require("dotenv").config();
const mysqldump = require("mysqldump");
const fs = require("fs");
var nodemailer = require("nodemailer");
var cron = require("node-cron");

async function saveDatabase() {
  console.error("Saving Database...");

  // dump the result straight to a file
   try {
    await mysqldump({
      connection: {
        host: process.env.MYSQL_HOST,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PWD,
        database: process.env.MYSQL_DB,
      },
      dumpToFile: "./dump.sql",
    });
    console.error("Dump File OK");
  } catch (error) {
    console.error(error);
  }

  // mail server config and authentication
  var transporter = nodemailer.createTransport({
    host: "smtp.hostinger.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAIL_ADDRESS,
      pass: process.env.MAIL_PWD,
    },
  });

  console.error("Mail Server OK");

  // mail options
  var mailOptions = {
    from: process.env.MAIL_ADDRESS,
    to: "************@gmail.com",
    subject: "Sauvegarde Base de Données",
    text: "Base de donnée sauvegardée.",
    attachments: [
      {
        path: "./dump.sql",
      },
    ],
  };

  // send the e-mail
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.error(error);
    } else {
      console.error("E-mail sent");
    }
  });
}

cron.schedule("* * * * *", () => saveDatabase());
```
<p>I have added a try/catch around my mysqldump and indeed I got this error message :</p>
```Error: EROFS: read-only file system, open './dump.sql'
    at Object.openSync (node:fs:590:3)
    at Object.writeFileSync (node:fs:2202:35)
    at /workspace/node_modules/mysqldump/dist/cjs.js:883:20
    at Generator.next (<anonymous>)
    at /workspace/node_modules/mysqldump/dist/cjs.js:44:71
    at new Promise (<anonymous>)
    at __awaiter (/workspace/node_modules/mysqldump/dist/cjs.js:40:12)
    at main (/workspace/node_modules/mysqldump/dist/cjs.js:855:12)
    at saveDatabase (/workspace/index.js:12:11)
    at Task._execution (/workspace/index.js:62:34) {
```
<p>So that's an issue when trying to save the file so as I thought there's probably something I should have done differently like set up google storage.
Since I don't need the file to be save on GCS, I could save the result of mysqldump in a variable instead than in a file, but then I don't know how to send that as an attachment of an e-mail without creating a file at some point.</p>
<p>EDIT : Solution without needing to write into a file</p>
<pre class="lang-js prettyprint-override"><code>async function saveDatabase() {
  // dump the result
  const result = await mysqldump({
    connection: {
      host: process.env.MYSQL_HOST,
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PWD,
      database: process.env.MYSQL_DB,
    },
  });

  // mail server config and authentication
  var transporter = nodemailer.createTransport({
    host: "smtp.hostinger.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAIL_ADDRESS,
      pass: process.env.MAIL_PWD,
    },
  });

  // mail options
  var mailOptions = {
    from: process.env.MAIL_ADDRESS,
    to: "*********@gmail.com",
    subject: "Sauvegarde Base de Données",
    text: "Base de donnée sauvegardée.",
    attachments: [
      {
        filename: "data.sql",
        content: result.dump.data,
      },
      {
        filename: "schema.sql",
        content: result.dump.schema,
      },
    ],
  };

  // send the e-mail
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.error(error);
    } else {
      console.error("E-mail sent");
    }
  });
}

cron.schedule("0 0 * * Sunday", () => saveDatabase());
</code>```

EDIT 2 :
Just an additional edit since node-cron doesn't work well on google cloud, but you can just use Google Cloud Scheduler that works pretty much the same way.

Body:
I am trying to build a NodeJS script to save a mySQL database, send it to me by e-mail as an attachement (the file is about 1MB), and I want to schedule the whole thing to run once a week. So far my script runs perfectly when run locally. I've set up the scheduling to run once every minute as a testing purpose.

I am struggling when trying to make it run on google cloud. The deployment went without issue, but then I only see in the logs Saving Database... so the scheduling part works fine, but I don't see the Dump File OK so I am assuming there is something wrong with mysqldump, but no error message. I didn't do anything specific with GCS, should I have ?

Thanks

require("dotenv").config();
const mysqldump = require("mysqldump");
const fs = require("fs");
var nodemailer = require("nodemailer");
var cron = require("node-cron");

async function saveDatabase() {
  console.error("Saving Database...");

  // dump the result straight to a file
   try {
    await mysqldump({
      connection: {
        host: process.env.MYSQL_HOST,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PWD,
        database: process.env.MYSQL_DB,
      },
      dumpToFile: "./dump.sql",
    });
    console.error("Dump File OK");
  } catch (error) {
    console.error(error);
  }

  // mail server config and authentication
  var transporter = nodemailer.createTransport({
    host: "smtp.hostinger.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAIL_ADDRESS,
      pass: process.env.MAIL_PWD,
    },
  });

  console.error("Mail Server OK");

  // mail options
  var mailOptions = {
    from: process.env.MAIL_ADDRESS,
    to: "************@gmail.com",
    subject: "Sauvegarde Base de Données",
    text: "Base de donnée sauvegardée.",
    attachments: [
      {
        path: "./dump.sql",
      },
    ],
  };

  // send the e-mail
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.error(error);
    } else {
      console.error("E-mail sent");
    }
  });
}

cron.schedule("* * * * *", () => saveDatabase());

I have added a try/catch around my mysqldump and indeed I got this error message :

Error: EROFS: read-only file system, open './dump.sql'
    at Object.openSync (node:fs:590:3)
    at Object.writeFileSync (node:fs:2202:35)
    at /workspace/node_modules/mysqldump/dist/cjs.js:883:20
    at Generator.next (<anonymous>)
    at /workspace/node_modules/mysqldump/dist/cjs.js:44:71
    at new Promise (<anonymous>)
    at __awaiter (/workspace/node_modules/mysqldump/dist/cjs.js:40:12)
    at main (/workspace/node_modules/mysqldump/dist/cjs.js:855:12)
    at saveDatabase (/workspace/index.js:12:11)
    at Task._execution (/workspace/index.js:62:34) {

So that's an issue when trying to save the file so as I thought there's probably something I should have done differently like set up google storage.
Since I don't need the file to be save on GCS, I could save the result of mysqldump in a variable instead than in a file, but then I don't know how to send that as an attachment of an e-mail without creating a file at some point.

EDIT : Solution without needing to write into a file

async function saveDatabase() {
  // dump the result
  const result = await mysqldump({
    connection: {
      host: process.env.MYSQL_HOST,
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PWD,
      database: process.env.MYSQL_DB,
    },
  });

  // mail server config and authentication
  var transporter = nodemailer.createTransport({
    host: "smtp.hostinger.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAIL_ADDRESS,
      pass: process.env.MAIL_PWD,
    },
  });

  // mail options
  var mailOptions = {
    from: process.env.MAIL_ADDRESS,
    to: "*********@gmail.com",
    subject: "Sauvegarde Base de Données",
    text: "Base de donnée sauvegardée.",
    attachments: [
      {
        filename: "data.sql",
        content: result.dump.data,
      },
      {
        filename: "schema.sql",
        content: result.dump.schema,
      },
    ],
  };

  // send the e-mail
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.error(error);
    } else {
      console.error("E-mail sent");
    }
  });
}

cron.schedule("0 0 * * Sunday", () => saveDatabase());

EDIT 2 :
Just an additional edit since node-cron doesn't work well on google cloud, but you can just use Google Cloud Scheduler that works pretty much the same way.


问:
warning: friend declaration 'void traverse(List<T>)' declares a non-template function [-Wnon-template-friend]
i have a Node template class in one "Node.cpp" and included in file "List.cpp" and List template class
i have to create a traverse function which is friend to the List class to traverse all the node in a List but facing an error here is my error proner

List Class Decleration

```<code>template<typename T>
class List{
    private:
        Node<T> *headNode;
        Node<T> *currentNode;
        Node<T> *lastCurrentNode;
        int size;
    public:
        List();
        void add(T);
        T get();
        bool next();
        friend void traverse(List<T>); // **there is an issue**
};
</code>```

Friend function Intialization

```<code>template <typename T>
void traverse(List <T>list)
{
    Node<T> *savedCurrentNode = new Node<T>();
    list.currentNode = list.headNode;

    for(int i=1; list.next(); i++)
    {
        cout << "\n Element " << i << " " << list.get();
    }
    list.currentNode = savedCurrentNode;
}
</code>```

i am a bigner and try to implement using templates but stuck into a problem now i have no idea how to solve this

Body:
i have a Node template class in one "Node.cpp" and included in file "List.cpp" and List template class
i have to create a traverse function which is friend to the List class to traverse all the node in a List but facing an error here is my error proner

List Class Decleration

template<typename T>
class List{
    private:
        Node<T> *headNode;
        Node<T> *currentNode;
        Node<T> *lastCurrentNode;
        int size;
    public:
        List();
        void add(T);
        T get();
        bool next();
        friend void traverse(List<T>); // **there is an issue**
};

Friend function Intialization

template <typename T>
void traverse(List <T>list)
{
    Node<T> *savedCurrentNode = new Node<T>();
    list.currentNode = list.headNode;

    for(int i=1; list.next(); i++)
    {
        cout << "\n Element " << i << " " << list.get();
    }
    list.currentNode = savedCurrentNode;
}

i am a bigner and try to implement using templates but stuck into a problem now i have no idea how to solve this


问:
Get Private Key using Kotlin and Bouncy Castle
I'm trying to retrieve a private key, using the Bouncy Castle, Ktor and Kotlin.

```<code>fun readPrivateKey(filePath: String): Result<RSAPrivateKey> = runCatching {
  val pemParse = PEMParser(FileReader(filePath))
  val privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())
  JcaPEMKeyConverter().getPrivateKey(privateKey) as RSAPrivateKey
}.onFailure { throw it }
</code>```

but when testing the function, I get the following error

unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo
java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo

the error occurs in this line:   privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())

I generated my private key with the following code:

```<code>openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes-256-cbc -out development_erp_private.key

</code>```

what am I doing wrong?

Body:
I'm trying to retrieve a private key, using the Bouncy Castle, Ktor and Kotlin.

fun readPrivateKey(filePath: String): Result<RSAPrivateKey> = runCatching {
  val pemParse = PEMParser(FileReader(filePath))
  val privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())
  JcaPEMKeyConverter().getPrivateKey(privateKey) as RSAPrivateKey
}.onFailure { throw it }

but when testing the function, I get the following error

unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo
java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo

the error occurs in this line:   privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())

I generated my private key with the following code:

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes-256-cbc -out development_erp_private.key

what am I doing wrong?


问:
mobile navigator for custom truck route
what mobile navigator are you using , who is able to accept  custom made route for trucks with Here Maps?
Here Wego is not for commercial use and is not accepting multiple way points from the custom made route ,

Thank you!

made some tests with Here WeGo , but is not accepting multiple waypoints  from the custom made route,

Title: mobile navigator for custom truck route


问:
how to evaluate the combination of tfidf and kmeans
For my nlp problem I'm using a combination of TFIDF and KMeans from the sklearn package. The tfidf gets the vectors and then I use Kmeans to cluster the texts based on the vectors. I have a few parameters of the TFIDF that I play around with like the n_gram, the input features, and the stop_words. The problem is how do I evaluate this model? My guess is I don't have to evaluate the KMeans model since its role is just to calculate the distances between points and that I just have to focus on the TFIDF model and parameters I end up using. Is this correct? If it is, how do I evaluate this model apart from manually shifting through the clusters to see if items are grouped correctly?</p>


问:
An Invalid value None for TO_TIMESTAMP
Not able to perform TO_TIMESTAMP on my date field.

select TO_TIMESTAMP(  mydate ,'YYYY-MM-DD HH24:MI:SS')  as mydate from cte3

Error Msg.

```<code>ERROR:  invalid value "None" for "YYYY"
DETAIL:  Value must be an integer.
SQL state: 22007```

```

Title: An Invalid value None for TO_TIMESTAMP

Body:
Not able to perform TO_TIMESTAMP on my date field.

select TO_TIMESTAMP(  mydate ,'YYYY-MM-DD HH24:MI:SS')  as mydate from cte3

Error Msg.

ERROR:  invalid value "None" for "YYYY"
DETAIL:  Value must be an integer.
SQL state: 22007```


问:
Connect remotely via SSH on docker container
I am trying to create an ssh connection to a docker container I built.

I can successfully access the docker container from my remote machine using:
docker exec -it <container_name> /bin/bash

In the docker container, I modified the file /etc/ssh/sshd_config by changing:

Allowroot: yes

Setting a password in my docker container I can create a ssh connection from my remote server by using:

ssh root@localhost -p 2200
(I mapped 2200:22).

This works.

However from my local machine I am trying to connect to the docker container using:

ssh root@192.168.1.33 -p 2200 and I got permission denied.
where 192.168.1.33 is the ip adress of my remote machine where my docker container is running.
Would you have any clue?

thanks :)

ssh root@192.168.1.33 -p 2200 and I got permission denied.
where 192.168.1.33 is the ip adress of my remote machine where my docker container is running.
Would you have any clue?

thanks :)


问:
Excel calculate variance with 3-color scale
I have an excel file with

sheet1

sheet2
then 3rd sheet called "variance"
with formula (sheet1/sheet2)-1
[if its not true correct me]
However, I want to create conditions

if the variance is 0% or greater the cell color is green

if it's greater than 0.003 or equal then it's yellow

if it's greater than 0.005 it's red

I'm having hard time trying to find the write condition

I did something like
From New Formatting -> use formula to determine which cells to format

=$B$2+$K$124 > 0


问:
Rest Assured Post request erase previous data
I am using json-server and have a dummy json. When i am adding a new student (say id=100) using post request. Every time it erase previous student (id=14) and then create new student.

Below is the payload.

{
  "data": {
    "studname": null,
    "student": [
      {
        "name": "JJJ",
        "location": null,
        "phone": null,
        "courses": null,
        "id": 14
      }
    ]
  }
}
```
<p>Here is my rest assured code which i am running through eclipse:</p>
<pre class="lang-java prettyprint-override"><code>@Test
public void addStudentData() {
  StudentList Studentdetails = new StudentList();

  StudentsDetails mainDetails = new StudentsDetails();
  mainDetails.setName("JJJ");
  mainDetails.setId(15);

  List < StudentsDetails > details = new ArrayList < StudentsDetails > ();

  details.add(mainDetails);

  Studentdetails.setStudent(details);

  given()
    .contentType("application/json")
    .body(Studentdetails)
    .when()
    .post(EndPoints.CREATE_STUDENTS)
    .then()
    .extract().response().asString();
}
</code>```

output: Status 201

"data": {
  "studname": null,
  "student": [
    {
      "name": "James",
      "location": null,
      "phone": null,
      "courses": null,
      "id": 101
    }
  ]
}
```

Body:
I am using json-server and have a dummy json. When i am adding a new student (say id=100) using post request. Every time it erase previous student (id=14) and then create new student.

Below is the payload.

{
  "data": {
    "studname": null,
    "student": [
      {
        "name": "JJJ",
        "location": null,
        "phone": null,
        "courses": null,
        "id": 14
      }
    ]
  }
}

Here is my rest assured code which i am running through eclipse:

@Test
public void addStudentData() {
  StudentList Studentdetails = new StudentList();

  StudentsDetails mainDetails = new StudentsDetails();
  mainDetails.setName("JJJ");
  mainDetails.setId(15);

  List < StudentsDetails > details = new ArrayList < StudentsDetails > ();

  details.add(mainDetails);

  Studentdetails.setStudent(details);

  given()
    .contentType("application/json")
    .body(Studentdetails)
    .when()
    .post(EndPoints.CREATE_STUDENTS)
    .then()
    .extract().response().asString();
}

output: Status 201

"data": {
  "studname": null,
  "student": [
    {
      "name": "James",
      "location": null,
      "phone": null,
      "courses": null,
      "id": 101
    }
  ]
}


问:
Roles restricting access to import Hot folder throuh impex backoffice hybris
I need an impex that will prohibit the import of data into the hot folder for users of a specific group.
In other i need those buttons to be muted.

image

Appreciate your inputs.

I've tried something like this, but i'm not sure what to write in a gap.

`
$START_USERRIGHTS; ; ; ; ; ; ; ; ;

Type ; UID ; MemberOfGroups ; Password ; Target ; read ; change ; create ;
remove ; change_perm

Role ; ReadGroup ;

;;;; HotFolderMediabatch ;+;-;-;-;

$END_USERRIGHTS`


问:
Keycloak as broker to another keycloak as idp and using curl
I configured keycloak1 as identity-provider and keycloak2 as broker.

Was also able to connect them.

But I try to get a token for a user of keycloak1 via curl. But it does not work. I thought, it can pass it through as a kind of proxy?

Does ist only work with browser redirection or can I configure the broker to passthrough my request to the identity-provider and get the token from it?

thanks!


问:
Testing collision ONLY between two objects using Unity. (If possible)
I've recently dived into Unity and I've been playing around with the tools Unity provides. I'm experienced in making my own little 2D game engines for fun but decided to try and see what Unity has to offer.

I'm making a simple bullet hell game but when implementing collision I noticed that Unity's "OnTriggerEnter" method tests collision on everything. I can't find a built in way of testing collision from just the bullet to the player. The solutions I found online was inside the method to test if the collision was the desired object. But I can imagine that this is very performant for 100s of projectiles to test collision on each other.

Before I do my own collision detection I wanted to make sure there's not some perfect method out there that I just can't find. I find myself often reinventing the wheel for something that already exists in Unity.

Thank you!


问:
How do I utilize the index for my callback?
Going through some practice problems and can't figure out how correctly callback. It returns "

let myForEach = function(array, cb) {
  for (let j = 0; j < array.length; j++) {
    cb(array[j])
  }
};

myForEach(['a', 'b', 'c'], function(el, i) {
  console.log(el + ' is at index ' + i);
});

// expected return "a is at index 1"
// actual return "a is at index undefined"```

I tried to call i as an extra argument, and tried to use this.i, call it within the scope of the cb, all either return undefined or are ignored.

Body:
Going through some practice problems and can't figure out how correctly callback. It returns "

let myForEach = function(array, cb) {
  for (let j = 0; j < array.length; j++) {
    cb(array[j])
  }
};

myForEach(['a', 'b', 'c'], function(el, i) {
  console.log(el + ' is at index ' + i);
});

// expected return "a is at index 1"
// actual return "a is at index undefined"

I tried to call i as an extra argument, and tried to use this.i, call it within the scope of the cb, all either return undefined or are ignored.


问:
How to show the status of creating or updating a stack with Cloudformation using AWS cli
I'm trying to find a command that allows me to see the latest status of the creation/update of a Cloudformation stack.

I thought I could use wait preceding the command stack-update-complete (in this case for update) but nothing happens.

This is what I'm doing:

I execute the command to update my stack:

```<code>aws cloudformation update-stack --stack-name my-stack \
  --template-body file://my-stack.yml
</code>```

Immediately after I run:

```<code>aws cloudformation wait stack-update-complete --stack-name my-stack
</code>```

I want to see the latest status including the result (create, update, delete, and rollback) so I don't have to login into AWS console.

Thanks!

Body:
I'm trying to find a command that allows me to see the latest status of the creation/update of a Cloudformation stack.

I thought I could use wait preceding the command stack-update-complete (in this case for update) but nothing happens.

This is what I'm doing:

I execute the command to update my stack:

aws cloudformation update-stack --stack-name my-stack \
  --template-body file://my-stack.yml

Immediately after I run:

aws cloudformation wait stack-update-complete --stack-name my-stack

I want to see the latest status including the result (create, update, delete, and rollback) so I don't have to login into AWS console.

Thanks!


问:
Can I pass additional params to the rails credentials?
I have a file, for example:
config/credentials/development.yml.enc
Call for this file:
Rails.application.credentials[Rails.env.to_sym][:some_key]
Can I pass params in this call?

I need to do in file with credentials something like this:

```<code>development:
    some_key: its_my_key_with_params_#{params}
</code>```

Body:
I have a file, for example:
config/credentials/development.yml.enc
Call for this file:
Rails.application.credentials[Rails.env.to_sym][:some_key]
Can I pass params in this call?

I need to do in file with credentials something like this:

development:
    some_key: its_my_key_with_params_#{params}


问:
API Request - application/octet-stream - ImmutableMultiDict -> to JPG
I'm working on app written in Flutter. I'm sending image from Flutter to GCP function as a post request. I want to save received data as JPG to GCP storage. Can you help me how to do it, please?

request is:

```<code><class 'flask.wrappers.Request'>
</code>```

When I look at request.data I can see this bytes:

```<code>b'--dart-http-boundary-R5+NnDXreIr_AQAVbGTlNM_Y2jcBnZ0EFEPQdsflP1reT.3g9QI\r\ncontent-type: application/octet-stream\r\ncontent-disposition: form-data; name="image"; filename="image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg"\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00H\x00\x00\xff\xe1\x048Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x0c\x01\x0f\x00\x02\x00\x00\x00\x12\x00\x00\x00\x9e\x01\x10\x00\x02\x00\x00\x00\x0c\x00\x00\x00\xb0\x01\x12\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00\x01\x1a\x00\x05\x00\x00\x00\x01\x00\x00\x00\xbc\x01\x1b\x00\x05\x00\x00\x00\x01\x0
</code>```

request.content_type is:

```<code> multipart/form-data; boundary=dart-http-boundary-R5+NnDXreIr_AQAVbGTlNM_Y2jcBnZ0EFEPQdsflP1reT.3g9QI"
</code>```

request.files show me:

```<code> ImmutableMultiDict([('image', <FileStorage: 'image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg' ('application/octet-stream')>)])"
</code>```

request.getlist('image')

```<code>[<FileStorage: 'image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg' ('application/octet-stream')>]
</code>```

Body:
I'm working on app written in Flutter. I'm sending image from Flutter to GCP function as a post request. I want to save received data as JPG to GCP storage. Can you help me how to do it, please?

request is:

<class 'flask.wrappers.Request'>

When I look at request.data I can see this bytes:

b'--dart-http-boundary-R5+NnDXreIr_AQAVbGTlNM_Y2jcBnZ0EFEPQdsflP1reT.3g9QI\r\ncontent-type: application/octet-stream\r\ncontent-disposition: form-data; name="image"; filename="image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg"\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00H\x00\x00\xff\xe1\x048Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x0c\x01\x0f\x00\x02\x00\x00\x00\x12\x00\x00\x00\x9e\x01\x10\x00\x02\x00\x00\x00\x0c\x00\x00\x00\xb0\x01\x12\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00\x01\x1a\x00\x05\x00\x00\x00\x01\x00\x00\x00\xbc\x01\x1b\x00\x05\x00\x00\x00\x01\x0

request.content_type is:

 multipart/form-data; boundary=dart-http-boundary-R5+NnDXreIr_AQAVbGTlNM_Y2jcBnZ0EFEPQdsflP1reT.3g9QI"

request.files show me:

 ImmutableMultiDict([('image', <FileStorage: 'image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg' ('application/octet-stream')>)])"

request.getlist('image')

[<FileStorage: 'image_picker_7BA6B737-6700-4640-B0BC-0F5A79EBD7C9-37408-0000006141AC7FF9.jpg' ('application/octet-stream')>]


问:
The argument type 'Product (where Product is defined in '...' can't be assigned to the parameter type 'Product (where Product is defined in '...')
I am trying to create a form and add data from it to my server. And get this 'The argument type 'Product (where Product is defined in C:\Study\kursova_bd\lib\logic\classes.dart)' can't be assigned to the parameter type 'Product (where Product is defined in C:\study\kursova_bd\lib\logic\classes.dart)'.'

```<code>ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF613CEA),
                // backgroundColor: const Color(0xFFA2A6B1),

                padding: const EdgeInsets.fromLTRB(40,20,40,20),
              ),
              child: const Text('SAVE CHANGES'),
              onPressed: () {
                if(_formKey.currentState!.validate()){

                  var newItem = Product(productId: 0, name: _name.text, dateOfReceipt: _dateOfReceipt.text, expirationDate: _expirationDate.text, amount: int.parse(_amount.text), price: double.parse(_price.text), madeOf: int.parse(_made_of.text), ownerId: 22);

                  print('${newItem}');

                  Processing.putProduct(newItem);

                  Navigator.pop(context);
                  //update page func
                  print('sent');
                }

              },
            ),
</code>```

[here is my putProduct function]

```<code>  static Future<String> putProduct(Product product) async {
try {
  var map = product.toJson();
  map['action'] = 'ADD_ITEM';
  final response = await http.post(
      Uri.http('161.252.125.133', '/dbkursach/itemactions.php'),
      body: map); //instead of "localhost" input ur local IPv4
  if (200 == response.statusCode) {
    return response.body;
  } else {
    return 'error';
  }
} catch (e) {
  return 'error';
}
</code>```

}

I tried to put the constructor in the agrument

Body:
I am trying to create a form and add data from it to my server. And get this 'The argument type 'Product (where Product is defined in C:\Study\kursova_bd\lib\logic\classes.dart)' can't be assigned to the parameter type 'Product (where Product is defined in C:\study\kursova_bd\lib\logic\classes.dart)'.'

ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF613CEA),
                // backgroundColor: const Color(0xFFA2A6B1),

                padding: const EdgeInsets.fromLTRB(40,20,40,20),
              ),
              child: const Text('SAVE CHANGES'),
              onPressed: () {
                if(_formKey.currentState!.validate()){

                  var newItem = Product(productId: 0, name: _name.text, dateOfReceipt: _dateOfReceipt.text, expirationDate: _expirationDate.text, amount: int.parse(_amount.text), price: double.parse(_price.text), madeOf: int.parse(_made_of.text), ownerId: 22);

                  print('${newItem}');

                  Processing.putProduct(newItem);

                  Navigator.pop(context);
                  //update page func
                  print('sent');
                }

              },
            ),

[here is my putProduct function]

  static Future<String> putProduct(Product product) async {
try {
  var map = product.toJson();
  map['action'] = 'ADD_ITEM';
  final response = await http.post(
      Uri.http('161.252.125.133', '/dbkursach/itemactions.php'),
      body: map); //instead of "localhost" input ur local IPv4
  if (200 == response.statusCode) {
    return response.body;
  } else {
    return 'error';
  }
} catch (e) {
  return 'error';
}

}

I tried to put the constructor in the agrument


问:
Azure Policy Initiative Set Deployment
I am trying to deploy a TLS Requirement policy for resources without Encryption. Here is a link to the actual Policy: https://www.azadvertizer.net/azpolicyinitiativesadvertizer/Enforce-EncryptTransit.html

I am using Terraform to deploy this policy with custom variables for the Policy Definition and the Policy Assignment like each.key, each.value, jsonencode.

This is the message I keep receiving:

Error: Unsupported attribute
│
│   on policies.tf line 81, in resource "azurerm_policy_definition" "custom_policies":
│   81:   policy_rule         = jsonencode(each.value.properties.policyRule)
│     ├────────────────
│     │ each.value.properties is object with 6 attributes
│
│ This object does not have an attribute named "policyRule".

The policy does not have the policyRule within the json file. Instead, it has policyDefinitions.

The question is, how to configure the Terraform code to deploy this type of policy into Azure?

I have tried to reconfigure the Terraform code to recognize the Policy Definition with no luck at all. Separated the JSON file from the rest of the files as a Policy Set, same result. Did some research on examples of deploying a policy set like this.

Title: Azure Policy Initiative Set Deployment


问:
Interacting with nested iframes in py selenium
I'm trying to automate a signup page that is made using google scripts and has nested iframes that I am unable to get around, my current solution is as follows

```<code> def signin(args): # args: {"guess": "password", "url": url, "cookie": cookieDict], "usr": "username"}

    import re

    guess = args["guess"]
    url = args["url"]
    cookie = args["cookie"]
    usr = args["usr"]
    usr = usr

    jar = requests.cookies.RequestsCookieJar()
    if cookie is None:
        import pickle
        cookie = pickle.load(open("cookies.pkl", "rb"))

    for c in cookie:
        jar.set(c["name"], c["value"], domain=c["domain"], path=c["path"])

    pars = params
    pars["pass"] = "#"+guess
    pars["uname"] = usr
    r = requests.Session()
    r.cookies = jar

    r = r.post(url, headers=header, params=pars)

    if "App is closed for students" not in str(r.content):
        # decode the maual way
        studentInfo = str(r.content).replace(r'\\x3c', '<').replace(r'\\x3e', '>').replace(r'\\x3d', '=').replace(r'\\x22', '"').replace(r'\\x7b', '{').replace(r'\\x7d', '}').replace(r'\\x2f', '/').replace(r'\\x3a', ':').replace(r'\\x2c', ',').replace(r'\\x5c', '\\').replace(r'\\x27', "'").replace(r'\\x3b', ';').replace(r'\\x5b', '[').replace(r'\\x5d', ']').replace(r'\\\\"','"').replace(r'\\\\/', '/').replace(r'\\\\n', '\n').replace(r'\\/','/').replace(r'\\n', '\n').replace(r'\\"', '"').replace(r'\\/', '/').replace(r'\\', '').replace(r'\\26','&')
        try:
            studentInfo = re.search("<hidden id=\"studentId\" data-student='(.*)'>", studentInfo).group(1)
            # replace all encoded characters
            studentInfo = studentInfo.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'")
            studentInfo = json.loads(studentInfo)
        except Exception as e:
            print(e)
            return [False, guess, r.status_code, r.text]
    else:
        return [True, guess, r.status_code, "App Closed"]

    if ('required' in str(r.content)) and (r'Invalid username and\\/or password.' not in str(r.content)):
        return [True, guess, r.status_code, studentInfo]
    else:
        return [False, guess, r.status_code, r.text]
</code>```

Cookies are from a google authentication and filter for google domains. Page inital html is just an iframe with an external source that creates another iframe that contains the ui.

I have looked through lots of forums and found nothing better than request sessions, but this lacks the ability to interact with the website as it uses 'one time google generated tokens' which is preferable.

Is there a better way than request sessions or a way to do it in selenium?

I have tried using selenium to locate elements but it always returns 'no such element', this happens with all methods of locating elements.

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"sandboxFrame")))
</code>```

-return an error

```<code>[14232:10856:1206/110139.141:ERROR:util.cc(133)] Can't create base directory: C:\Program Files\Google\GoogleUpdater
Message:
Stacktrace:
Backtrace:
        (No symbol) [0x0070F243]
        (No symbol) [0x00697FD1]
        (No symbol) [0x0058D04D]
        (No symbol) [0x005BC0B0]
        (No symbol) [0x005BC22B]
        (No symbol) [0x005EE612]
        (No symbol) [0x005D85D4]
        (No symbol) [0x005EC9EB]
        (No symbol) [0x005D8386]
        (No symbol) [0x005B163C]
        (No symbol) [0x005B269D]
        GetHandleVerifier [0x009A9A22+2655074]
        GetHandleVerifier [0x0099CA24+2601828]
        GetHandleVerifier [0x007B8C0A+619850]
        GetHandleVerifier [0x007B7830+614768]
        (No symbol) [0x006A05FC]
        (No symbol) [0x006A5968]
        (No symbol) [0x006A5A55]
        (No symbol) [0x006B051B]
        BaseThreadInitThunk [0x76217BA9+25]
        RtlInitializeExceptionChain [0x7722BB3B+107]
        RtlClearBits [0x7722BABF+191]
</code>```

iframe information:

```<code>
    id='sandboxFram'
    Title='title here'
    xpath='/html/body/iframe

</code>```

Page

```<code><!doctype html>
<html>
<head>
<meta name="chromevox" content-script="no">
<title>App</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" nonce="code"><link rel="stylesheet" href="/static/macros/client/css/2498103415-mae_html_css_ltr.css">
<script type="text/javascript" src="/static/macros/client/js/2838233174-warden_bin_i18n_warden.js" nonce="nonce"></script>
</head>
<body>
<iframe id="sandboxFrame" title="App" allow="allows" sandbox="permissions">
</iframe>
<script type="text/javascript" nonce="Na-nbmgTUciE6SvnTZ0S4w">
(function() {
var el = document.getElementById('sandboxFrame');
el.onload = function() {
goog.script.init("[page source]");
el.src = 'https:\/\/n-[more-stuffs]-2lu-script.googleusercontent.com\/userCodeAppPanel';
}());
</script>
</body>
</html>
</code>```

Body:
I'm trying to automate a signup page that is made using google scripts and has nested iframes that I am unable to get around, my current solution is as follows

 def signin(args): # args: {"guess": "password", "url": url, "cookie": cookieDict], "usr": "username"}

    import re

    guess = args["guess"]
    url = args["url"]
    cookie = args["cookie"]
    usr = args["usr"]
    usr = usr

    jar = requests.cookies.RequestsCookieJar()
    if cookie is None:
        import pickle
        cookie = pickle.load(open("cookies.pkl", "rb"))

    for c in cookie:
        jar.set(c["name"], c["value"], domain=c["domain"], path=c["path"])

    pars = params
    pars["pass"] = "#"+guess
    pars["uname"] = usr
    r = requests.Session()
    r.cookies = jar

    r = r.post(url, headers=header, params=pars)

    if "App is closed for students" not in str(r.content):
        # decode the maual way
        studentInfo = str(r.content).replace(r'\\x3c', '<').replace(r'\\x3e', '>').replace(r'\\x3d', '=').replace(r'\\x22', '"').replace(r'\\x7b', '{').replace(r'\\x7d', '}').replace(r'\\x2f', '/').replace(r'\\x3a', ':').replace(r'\\x2c', ',').replace(r'\\x5c', '\\').replace(r'\\x27', "'").replace(r'\\x3b', ';').replace(r'\\x5b', '[').replace(r'\\x5d', ']').replace(r'\\\\"','"').replace(r'\\\\/', '/').replace(r'\\\\n', '\n').replace(r'\\/','/').replace(r'\\n', '\n').replace(r'\\"', '"').replace(r'\\/', '/').replace(r'\\', '').replace(r'\\26','&')
        try:
            studentInfo = re.search("<hidden id=\"studentId\" data-student='(.*)'>", studentInfo).group(1)
            # replace all encoded characters
            studentInfo = studentInfo.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'")
            studentInfo = json.loads(studentInfo)
        except Exception as e:
            print(e)
            return [False, guess, r.status_code, r.text]
    else:
        return [True, guess, r.status_code, "App Closed"]

    if ('required' in str(r.content)) and (r'Invalid username and\\/or password.' not in str(r.content)):
        return [True, guess, r.status_code, studentInfo]
    else:
        return [False, guess, r.status_code, r.text]

Cookies are from a google authentication and filter for google domains. Page inital html is just an iframe with an external source that creates another iframe that contains the ui.

I have looked through lots of forums and found nothing better than request sessions, but this lacks the ability to interact with the website as it uses 'one time google generated tokens' which is preferable.

Is there a better way than request sessions or a way to do it in selenium?

I have tried using selenium to locate elements but it always returns 'no such element', this happens with all methods of locating elements.

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"sandboxFrame")))

-return an error

[14232:10856:1206/110139.141:ERROR:util.cc(133)] Can't create base directory: C:\Program Files\Google\GoogleUpdater
Message:
Stacktrace:
Backtrace:
        (No symbol) [0x0070F243]
        (No symbol) [0x00697FD1]
        (No symbol) [0x0058D04D]
        (No symbol) [0x005BC0B0]
        (No symbol) [0x005BC22B]
        (No symbol) [0x005EE612]
        (No symbol) [0x005D85D4]
        (No symbol) [0x005EC9EB]
        (No symbol) [0x005D8386]
        (No symbol) [0x005B163C]
        (No symbol) [0x005B269D]
        GetHandleVerifier [0x009A9A22+2655074]
        GetHandleVerifier [0x0099CA24+2601828]
        GetHandleVerifier [0x007B8C0A+619850]
        GetHandleVerifier [0x007B7830+614768]
        (No symbol) [0x006A05FC]
        (No symbol) [0x006A5968]
        (No symbol) [0x006A5A55]
        (No symbol) [0x006B051B]
        BaseThreadInitThunk [0x76217BA9+25]
        RtlInitializeExceptionChain [0x7722BB3B+107]
        RtlClearBits [0x7722BABF+191]

iframe information:

    id='sandboxFram'
    Title='title here'
    xpath='/html/body/iframe

Page

<!doctype html>

<meta name="chromevox" content-script="no">
<title>App</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" nonce="code"><link rel="stylesheet" href="/static/macros/client/css/2498103415-mae_html_css_ltr.css">


问:
Using Apache PDFBox 1.3.1 - Trying to scale down all images in PDF file
I am forced to use ver. 1.3.1 of Apache PDFBox.  I wish I could use ver 2.+ but can't.  Anyway, I am trying to scale down the images in some PDF files but am having trouble.  If I was using ver 2.+ I could as I understand it use the {PDPageContentStream_obj}.transform(...) method but that's not avail. to me.  Instead as I understand it, I need to apply the .concatenate2CTM(...) method.  I am trying that but not getting the anticipated results; my resulting .pdf files display their graphics unchanged in scale.  Need to do this to reduce file size to under 5 MB so it can be successfully sent through a gateway that would time out if the file was bigger.  Changing the gateway timeout is not an option, unfortunately.  My code currently looks like this:

```<code>private File compressFile2(File file) throws Exception {
    try {
        PDDocument doc = PDDocument.load(file);
        List<PDPage> pdPages = doc.getDocumentCatalog().getAllPages();
        Iterator<PDPage> iterPdPages = pdPages.iterator();

        while (iterPdPages.hasNext()) {
            PDPage page = iterPdPages.next();
            PDPageContentStream cs = new PDPageContentStream(doc, page, true, true);
            cs.saveGraphicsState();
            cs.concatenate2CTM(.5, 0, 0, .5, 0, 0);
            cs.saveGraphicsState();
        }
        doc.save(file.getAbsolutePath() + "_compressed");
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return new File(file.getAbsolutePath() + "_compressed");
}
</code>```

Any ideas are appreciated.  Thank you.

Body:
I am forced to use ver. 1.3.1 of Apache PDFBox.  I wish I could use ver 2.+ but can't.  Anyway, I am trying to scale down the images in some PDF files but am having trouble.  If I was using ver 2.+ I could as I understand it use the {PDPageContentStream_obj}.transform(...) method but that's not avail. to me.  Instead as I understand it, I need to apply the .concatenate2CTM(...) method.  I am trying that but not getting the anticipated results; my resulting .pdf files display their graphics unchanged in scale.  Need to do this to reduce file size to under 5 MB so it can be successfully sent through a gateway that would time out if the file was bigger.  Changing the gateway timeout is not an option, unfortunately.  My code currently looks like this:

private File compressFile2(File file) throws Exception {
    try {
        PDDocument doc = PDDocument.load(file);
        List<PDPage> pdPages = doc.getDocumentCatalog().getAllPages();
        Iterator<PDPage> iterPdPages = pdPages.iterator();

        while (iterPdPages.hasNext()) {
            PDPage page = iterPdPages.next();
            PDPageContentStream cs = new PDPageContentStream(doc, page, true, true);
            cs.saveGraphicsState();
            cs.concatenate2CTM(.5, 0, 0, .5, 0, 0);
            cs.saveGraphicsState();
        }
        doc.save(file.getAbsolutePath() + "_compressed");
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return new File(file.getAbsolutePath() + "_compressed");
}

Any ideas are appreciated.  Thank you.


问:
Spring boot websocket ping/pong
Websocket implementation with spring boot to test ping /pong protocol

```<code>public class HandlePingRequest implements WebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // TODO Auto-generated method stub

       log.info("received websocket  message {}",message);
       Thread.sleep(30000);
       session.sendMessage(new TextMessage("Response message"));

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }

}

</code>```

Client implement in python

```<code>import websocket
import time
websocket.enableTrace(True)
ws = websocket.WebSocket()

ws.connect("ws://localhost:8080/v0")
ws.ping()
ws.send('Hello')
ws.ping()
time.sleep(800)
ws.close()
</code>```

when the server is handling a text message or binary message, the server does not respond to the ping until it send an response for the text/binary or in the RFC it says the server should respond immediately.
In this exemple the response for the second ping is received 30s after the request.

Was expecting that the ping/pong message be handled by tomcat/jetty server, so how it is possible to handle the received ping message on the websocket handler instead of let the server handle it?

Title: Spring boot websocket ping/pong

Body:
Websocket implementation with spring boot to test ping /pong protocol

public class HandlePingRequest implements WebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // TODO Auto-generated method stub

       log.info("received websocket  message {}",message);
       Thread.sleep(30000);
       session.sendMessage(new TextMessage("Response message"));

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }

}

Client implement in python

import websocket
import time
websocket.enableTrace(True)
ws = websocket.WebSocket()

ws.connect("ws://localhost:8080/v0")
ws.ping()
ws.send('Hello')
ws.ping()
time.sleep(800)
ws.close()

when the server is handling a text message or binary message, the server does not respond to the ping until it send an response for the text/binary or in the RFC it says the server should respond immediately.
In this exemple the response for the second ping is received 30s after the request.

Was expecting that the ping/pong message be handled by tomcat/jetty server, so how it is possible to handle the received ping message on the websocket handler instead of let the server handle it?


问:
ANTLR4 Grammar not detecting fields inside mode properly
I'm trying to make a grammar to parse easy schema in a structure like the prisma orm uses. After trying a lot of different things it still doesn't parse it properly and I am not sure where the issue lies.

This is the lexer I have written:

```<code>lexer grammar OrmLexer;

MODEL: 'model';
MODELNAME : LETTERS+;
OPEN : '{' NEWLINE?;

OPENMODEL   : MODEL MODELNAME OPEN -> pushMode(MODELMODE) ;

WHITESPACE : ' ' -> skip ;
NEWLINE: '\r' '\n' | '\n' | '\r';

mode MODELMODE ;
FIELD: FIELDNAME FIELDTYPE NEWLINE;
FIELDNAME   : LETTERS+;
FIELDTYPE   : LETTERS+;
CLOSE: '}' -> popMode ;

fragment LETTERS  : [a-zA-Z] ;
</code>```

This is the parser I have written:

```<code>parser grammar OrmParser;

options { tokenVocab=OrmLexer; }

start: root | EOF ;
root: model*;

model : modelstart modelbody modelend;
modelbody: modelfield*;
modelstart : MODEL MODELNAME OPEN ;
modelfield : FIELDNAME FIELDTYPE NEWLINE ;
modelend: CLOSE ;
</code>```

I am testing the grammar on an example schema which looks like:

```<code>model test {
    id test
    user test
}
</code>```

In this schema the fields are not being parsed correctly, there should be two fields namely:
(FIELDNAME: id, FIELDTYPE: test) and (FIELDNAME: user, FIELDTYPE: test) however it doesn't parse those, this is the tree I get in result:

Besides that I am not really sure when to use fragments and when not in the lexer.

I hope anyone can help me in finding/solving the issue! Thanks in advance

I have tried modifying my lexer so such that: OPENMODEL   : OPEN -> pushMode(MODELMODE) ; and tried many different small changes in both the parser and lexer, the attempt in above code was the one where I got the closest to the result I want to achieve, namely that the modelbody has the modelfields all separately parsed without any errors occurring.

Body:
I'm trying to make a grammar to parse easy schema in a structure like the prisma orm uses. After trying a lot of different things it still doesn't parse it properly and I am not sure where the issue lies.

This is the lexer I have written:

lexer grammar OrmLexer;

MODEL: 'model';
MODELNAME : LETTERS+;
OPEN : '{' NEWLINE?;

OPENMODEL   : MODEL MODELNAME OPEN -> pushMode(MODELMODE) ;

WHITESPACE : ' ' -> skip ;
NEWLINE: '\r' '\n' | '\n' | '\r';

mode MODELMODE ;
FIELD: FIELDNAME FIELDTYPE NEWLINE;
FIELDNAME   : LETTERS+;
FIELDTYPE   : LETTERS+;
CLOSE: '}' -> popMode ;

fragment LETTERS  : [a-zA-Z] ;

This is the parser I have written:

parser grammar OrmParser;

options { tokenVocab=OrmLexer; }

start: root | EOF ;
root: model*;

model : modelstart modelbody modelend;
modelbody: modelfield*;
modelstart : MODEL MODELNAME OPEN ;
modelfield : FIELDNAME FIELDTYPE NEWLINE ;
modelend: CLOSE ;

I am testing the grammar on an example schema which looks like:

model test {
    id test
    user test
}

In this schema the fields are not being parsed correctly, there should be two fields namely:
(FIELDNAME: id, FIELDTYPE: test) and (FIELDNAME: user, FIELDTYPE: test) however it doesn't parse those, this is the tree I get in result:

Besides that I am not really sure when to use fragments and when not in the lexer.

I hope anyone can help me in finding/solving the issue! Thanks in advance

I have tried modifying my lexer so such that: OPENMODEL   : OPEN -> pushMode(MODELMODE) ; and tried many different small changes in both the parser and lexer, the attempt in above code was the one where I got the closest to the result I want to achieve, namely that the modelbody has the modelfields all separately parsed without any errors occurring.


问:
Adding content to a FireStore database and I want to access recently added content
I am currently working on a google chrome extension to collect images, text, pages, and Youtube videos into folders and subfolders created by the user. The user can also invite other users to their folders.

I am adding content to a FireStore database and I want to access recently added content without creating a "Recently Added" collection inside the database (to avoid duplicated content and populate it into a Chrome Extension Popup UI named "Recently Added".

At the moment the  UI only displays 1 recently added content from each folder. example. The user has 3 folders and added 3 images into folder 1 and 3 images into folder 2. However in the  "Recently Added UI"  It only dhows two of the images. Only 1 form folder 1 and only one from folder 2.

Is there a way I can populate multiple content recently added from the folders  into the UI without making another FireStore collection?

```<code>const playlistRef = collection(db, "playlists");
    const subFolderRef = collection(db, "SubFolder")
    const q = query(playlistRef, where("lastUpdated", "!=", "undefined"), orderBy("lastUpdated", "desc"));
    const r = query(subFolderRef, where("lastUpdated", "!=", "undefined"), orderBy("lastUpdated", "desc"))

    const querySnapshotMain = await getDocs(q);
    const result: any[] = [];
    console.log("Get recently added")

    const querySnapshotSubFolder = await getDocs(r);

    querySnapshotMain.forEach((doc) => {

      if(doc.data().createdBy != userid){
        return;
      }
      let current = doc.data().content
      result.push(current[current.length - 1])

      //let playlistDoc = doc.data();
      //playlistDoc.id = doc.id;
      //let playlistDoc = { id: doc.id, data: doc.data() };
      //result.push(playlistDoc);
      //result.push(doc.data())
    });

    querySnapshotSubFolder.forEach((doc) => {

        if(doc.data().createdBy != userid){
          return;
        }
        let current = doc.data().content
        result.push(current[current.length - 1])
</code>```

Body:
I am currently working on a google chrome extension to collect images, text, pages, and Youtube videos into folders and subfolders created by the user. The user can also invite other users to their folders.

I am adding content to a FireStore database and I want to access recently added content without creating a "Recently Added" collection inside the database (to avoid duplicated content and populate it into a Chrome Extension Popup UI named "Recently Added".

At the moment the  UI only displays 1 recently added content from each folder. example. The user has 3 folders and added 3 images into folder 1 and 3 images into folder 2. However in the  "Recently Added UI"  It only dhows two of the images. Only 1 form folder 1 and only one from folder 2.

Is there a way I can populate multiple content recently added from the folders  into the UI without making another FireStore collection?

const playlistRef = collection(db, "playlists");
    const subFolderRef = collection(db, "SubFolder")
    const q = query(playlistRef, where("lastUpdated", "!=", "undefined"), orderBy("lastUpdated", "desc"));
    const r = query(subFolderRef, where("lastUpdated", "!=", "undefined"), orderBy("lastUpdated", "desc"))

    const querySnapshotMain = await getDocs(q);
    const result: any[] = [];
    console.log("Get recently added")

    const querySnapshotSubFolder = await getDocs(r);

    querySnapshotMain.forEach((doc) => {

      if(doc.data().createdBy != userid){
        return;
      }
      let current = doc.data().content
      result.push(current[current.length - 1])

      //let playlistDoc = doc.data();
      //playlistDoc.id = doc.id;
      //let playlistDoc = { id: doc.id, data: doc.data() };
      //result.push(playlistDoc);
      //result.push(doc.data())
    });

    querySnapshotSubFolder.forEach((doc) => {

        if(doc.data().createdBy != userid){
          return;
        }
        let current = doc.data().content
        result.push(current[current.length - 1])


问:
Using $(call ....) in a makefile recipe
So I have a really nice make macro that creates me a pretty message during compilation that is done in such a way that the destination of the message can be implemented externally.

It uses the $(shell ) make function something like this.

```<code>send_msg = $(shell $do_send_msg "$1")
</code>```

Where do_send_msg can be expanded to be echo, wall, email, etc.

I use this lots in the makefiles.

I'd like to be able to use the same macro in recipes as the result of the recipe may change what is needed to be sent, dependent on some test made to the result of an external program.

However variables in recipes are expanded by make entirely before the lines in the recipe are called one at a time.

So if I write (e.g.)

if test_prog; then \
    $(call send_msg,PASS);\
else \
    $(call send_msg,FAIL);\
fi
```
<p>Effectively this becomes (not strictly true syntax, but close enough):</p>
<pre class="lang-bash prettyprint-override"><code>(bash -c 'echo "PASS"') &
(bash -c 'echo "FAIL"') &
(bash -c 'if test_prog; then \
    \
else \
    \
fi)'
</code>```

This of course will not work, it will run test_prog and, separately, regardless of the exit status both send_msg lines will expand and be executed.

So it will print both PASS and FAIL as the two subshells are run independently and in parallel by make.

I don't want to 'cheat' and use another variable in the $(call ) function or even worse a global that, ok, would allow an if some_var ... in the send_msg implementation but would reduce it's flexability as the implementation would have to understand that variable in all cases.

Another way would be to just have two different send_msg macros, one with and one without the $(shell ) function. Simple, but not elegant.

Right now I am using a 'hack' and calling the same makefile with a variable. If that variable is set then it sends it's contents otherwise does nothing. This works fine but to me it seems clunky and wrong, there must be a better way.....
e.g.

if test_prog; then \
    MESSAGE=PASS $(MAKE) message;\
else \
    MESSAGE=FAIL $(MAKE) message;\
fi
```
<p>Where the <code>Makefile</code> says (and this is an abreviated version to convey the idea)</p>
```ifneq ($(MESSAGE),)
message:
    $(call send_msg,$(MESSAGE))
else:
message:

endif
```
<p><strong>Question:</strong>
How would I make (<em>make</em>) detect if the macro is being expanded inside a Makefile recipe or inside the Makefile body and effectively keep or remove the <code>$(shell )</code> call that wraps how the work is done?</p>
<p>e.g. (if <code>make_or_shell</code> existed)</p>
```ifdef some_test
$(make_or_shell send_msg,"Message from Make")
endif

goal:
    $(make_or_shell send_msg,"Message from Recipe")
```

Title: Using $(call ....) in a makefile recipe

Body:
So I have a really nice make macro that creates me a pretty message during compilation that is done in such a way that the destination of the message can be implemented externally.

It uses the $(shell ) make function something like this.

send_msg = $(shell $do_send_msg "$1")

Where do_send_msg can be expanded to be echo, wall, email, etc.

I use this lots in the makefiles.

I'd like to be able to use the same macro in recipes as the result of the recipe may change what is needed to be sent, dependent on some test made to the result of an external program.

However variables in recipes are expanded by make entirely before the lines in the recipe are called one at a time.

So if I write (e.g.)

if test_prog; then \
    $(call send_msg,PASS);\
else \
    $(call send_msg,FAIL);\
fi

Effectively this becomes (not strictly true syntax, but close enough):

(bash -c 'echo "PASS"') &
(bash -c 'echo "FAIL"') &
(bash -c 'if test_prog; then \
    \
else \
    \
fi)'

This of course will not work, it will run test_prog and, separately, regardless of the exit status both send_msg lines will expand and be executed.

So it will print both PASS and FAIL as the two subshells are run independently and in parallel by make.

I don't want to 'cheat' and use another variable in the $(call ) function or even worse a global that, ok, would allow an if some_var ... in the send_msg implementation but would reduce it's flexability as the implementation would have to understand that variable in all cases.

Another way would be to just have two different send_msg macros, one with and one without the $(shell ) function. Simple, but not elegant.

Right now I am using a 'hack' and calling the same makefile with a variable. If that variable is set then it sends it's contents otherwise does nothing. This works fine but to me it seems clunky and wrong, there must be a better way.....
e.g.

if test_prog; then \
    MESSAGE=PASS $(MAKE) message;\
else \
    MESSAGE=FAIL $(MAKE) message;\
fi

Where the Makefile says (and this is an abreviated version to convey the idea)

ifneq ($(MESSAGE),)
message:
    $(call send_msg,$(MESSAGE))
else:
message:

endif

Question:
How would I make (make) detect if the macro is being expanded inside a Makefile recipe or inside the Makefile body and effectively keep or remove the $(shell ) call that wraps how the work is done?

e.g. (if make_or_shell existed)

ifdef some_test
$(make_or_shell send_msg,"Message from Make")
endif

goal:
    $(make_or_shell send_msg,"Message from Recipe")


问:
How does Linux kernel automatically migrate threads (to balance load or otherwise)?
I looked at this Q&A How does Linux kernel migrate the process among multiple cores?
and I guess it's somewhat clear how the tasks are migrated to different cores via sched_setaffinity()

But I am right that the scheduler may decide to migrate a given task to some core at any tick?

I looked here https://elixir.bootlin.com/linux/v6.0/source/kernel/sched/core.c and I don't see where something like stop_one_core is called from

It's called by sched_exec but that is... for exec syscalls only, right?..

It's also called by migrate_task_to but that's under an ifdef for NUMA...

So where's the usual scheduler migration path? Or am I wrong and such usual periodic migration is not performed by the scheduler but... by migration threads ([migration/X]) maybe?


问:
WARNING:tensorflow:5 out of the last 5 calls to <function _BaseOptimizer._update_step_xla at 0x7f9cb53574c0> triggered tf.function retracing
I am working on a project with tensorflow, and my code keep warning WARNING:tensorflow:5 out of the last 5 calls to <function _BaseOptimizer._update_step_xla at 0x7ff7d01cbaf0> triggered tf.function retracing,  and WARNING:tensorflow:6 out of the last 6 calls to <function _BaseOptimizer._update_step_xla at 0x7ff7d01cbaf0> triggered tf.function retracing. As shown in picture:

warning

Here is the replicable part of code that causes the problem

```<code>
    import tensorflow as tf

    class Conv(tf.keras.layers.Layer):

        def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1):
            super(Conv, self).__init__()
            self.dilations = dilation
            init = tf.keras.initializers.HeNormal()

            self.kernel = tf.Variable(init([kernel_size, in_channels, out_channels], dtype=tf.float32),trainable=True)
            self.bias = tf.Variable(tf.zeros([1, 1, out_channels], dtype=tf.float32),trainable=True)

        def call(self, x):
            conv = tf.nn.conv1d(tf.transpose(x,perm = [0,2,1]), self.kernel, 1, padding='SAME', dilations=self.dilations)
            out = tf.transpose(conv + self.bias,perm = [0,2,1])

            return out

    class Imputer(tf.keras.Model):

        def __init__(self, in_channels, res_channels, skip_channels, out_channels):
            super(Imputer, self).__init__()
            self.init_conv = Conv(in_channels, res_channels, kernel_size=1)
            self.final_conv1 = Conv(skip_channels, skip_channels, kernel_size=1)
            self.final_conv2 = Conv(skip_channels, out_channels,kernel_size = 1)

        def call(self, x):
            x = tf.nn.relu(self.init_conv(x))
            y = self.final_conv2(tf.nn.relu(self.final_conv1(x)))

            return y

    model = Imputer(4,4,4,4)
    input_data = tf.random.uniform([4,4,4],minval=0,maxval=3,dtype=tf.dtypes.float32,seed=1)
    myloss = tf.keras.losses.MeanSquaredError()
    z = tf.random.normal(shape = [4,4,4],mean = 0,stddev=1)
    optimizer = tf.keras.optimizers.Adam(learning_rate= 0.001)
    with tf.GradientTape() as tape:
        predicition = model(input_data)
        loss = myloss(z, predicition)

    gradients = tape.gradient(loss, model.trainable_variables)
    print(optimizer.build(model.trainable_variables))
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

</code>```

I think I do not have the possible problems as indicated by warning and the warning is related to I call Conv layer multiple times, my question is why the warning is caused and how to properly deal with the situation that I have to call a custom layer multiple times?

Body:
I am working on a project with tensorflow, and my code keep warning WARNING:tensorflow:5 out of the last 5 calls to <function _BaseOptimizer._update_step_xla at 0x7ff7d01cbaf0> triggered tf.function retracing,  and WARNING:tensorflow:6 out of the last 6 calls to <function _BaseOptimizer._update_step_xla at 0x7ff7d01cbaf0> triggered tf.function retracing. As shown in picture:

warning

Here is the replicable part of code that causes the problem

    import tensorflow as tf

    class Conv(tf.keras.layers.Layer):

        def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1):
            super(Conv, self).__init__()
            self.dilations = dilation
            init = tf.keras.initializers.HeNormal()

            self.kernel = tf.Variable(init([kernel_size, in_channels, out_channels], dtype=tf.float32),trainable=True)
            self.bias = tf.Variable(tf.zeros([1, 1, out_channels], dtype=tf.float32),trainable=True)

        def call(self, x):
            conv = tf.nn.conv1d(tf.transpose(x,perm = [0,2,1]), self.kernel, 1, padding='SAME', dilations=self.dilations)
            out = tf.transpose(conv + self.bias,perm = [0,2,1])

            return out

    class Imputer(tf.keras.Model):

        def __init__(self, in_channels, res_channels, skip_channels, out_channels):
            super(Imputer, self).__init__()
            self.init_conv = Conv(in_channels, res_channels, kernel_size=1)
            self.final_conv1 = Conv(skip_channels, skip_channels, kernel_size=1)
            self.final_conv2 = Conv(skip_channels, out_channels,kernel_size = 1)

        def call(self, x):
            x = tf.nn.relu(self.init_conv(x))
            y = self.final_conv2(tf.nn.relu(self.final_conv1(x)))

            return y

    model = Imputer(4,4,4,4)
    input_data = tf.random.uniform([4,4,4],minval=0,maxval=3,dtype=tf.dtypes.float32,seed=1)
    myloss = tf.keras.losses.MeanSquaredError()
    z = tf.random.normal(shape = [4,4,4],mean = 0,stddev=1)
    optimizer = tf.keras.optimizers.Adam(learning_rate= 0.001)
    with tf.GradientTape() as tape:
        predicition = model(input_data)
        loss = myloss(z, predicition)

    gradients = tape.gradient(loss, model.trainable_variables)
    print(optimizer.build(model.trainable_variables))
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))

I think I do not have the possible problems as indicated by warning and the warning is related to I call Conv layer multiple times, my question is why the warning is caused and how to properly deal with the situation that I have to call a custom layer multiple times?


问:
How to run a fetch inside a Vite Plugin
Am creating a vite plugin which will enable me to generate a sitemap for my website but am not finding how to make a fetch request using one of their many hooks. Am using simplecrawler module to run the fetch inside the plugin but it doesn't seem to work.

import type { Plugin, ResolvedConfig } from "vite";
import crawler from "simplecrawler";

const crawl = async (port:number): Promise<string[]> => {
    return new Promise((resolve)=> {
        const links: Set<string> = new Set();
        const Crawler = new crawler(`http://localhost:${port}`);
        Crawler.on("fetchcomplete", (queueItem, _responseBody, response) => {
            if (response.headers["content-type"] === "text/html") {
                links.add(queueItem.url);
            }
        });

        Crawler.on("complete", () => {
            const paths = [...links].map((link) => {
                return new URL(link).pathname;
            });
            resolve(paths);
        });

        Crawler.start()
    });
};

const plugin = ():Plugin =>{
    const moduleId = `virtual:sitemap`;
    const resolvedModuleId = `\0${moduleId}`;
    let config: ResolvedConfig;

    return {
        name: "vite-plugin-svelte-sitemap",
        resolveId: id => {
            if (id === moduleId){
                return resolvedModuleId
            }
            return id
        },
        configResolved: resolvedConfig => {
            config = resolvedConfig;

        },
        buildStart: ()=>{
            return async ()=>{
                let port = config.server.port !== undefined ? config.server.port : (config.mode === "development" ? 5173 : 4173);
                let urls = await crawl(port);
                console.log(urls);
            }
        }

    }
}

export default plugin;

```

So far, this is what I have been able to come up with

Title: How to run a fetch inside a Vite Plugin

Body:
Am creating a vite plugin which will enable me to generate a sitemap for my website but am not finding how to make a fetch request using one of their many hooks. Am using simplecrawler module to run the fetch inside the plugin but it doesn't seem to work.

import type { Plugin, ResolvedConfig } from "vite";
import crawler from "simplecrawler";

const crawl = async (port:number): Promise<string[]> => {
    return new Promise((resolve)=> {
        const links: Set<string> = new Set();
        const Crawler = new crawler(`http://localhost:${port}`);
        Crawler.on("fetchcomplete", (queueItem, _responseBody, response) => {
            if (response.headers["content-type"] === "text/html") {
                links.add(queueItem.url);
            }
        });

        Crawler.on("complete", () => {
            const paths = [...links].map((link) => {
                return new URL(link).pathname;
            });
            resolve(paths);
        });

        Crawler.start()
    });
};

const plugin = ():Plugin =>{
    const moduleId = `virtual:sitemap`;
    const resolvedModuleId = `\0${moduleId}`;
    let config: ResolvedConfig;

    return {
        name: "vite-plugin-svelte-sitemap",
        resolveId: id => {
            if (id === moduleId){
                return resolvedModuleId
            }
            return id
        },
        configResolved: resolvedConfig => {
            config = resolvedConfig;

        },
        buildStart: ()=>{
            return async ()=>{
                let port = config.server.port !== undefined ? config.server.port : (config.mode === "development" ? 5173 : 4173);
                let urls = await crawl(port);
                console.log(urls);
            }
        }

    }
}

export default plugin;

So far, this is what I have been able to come up with


问:
Laravel Queues/Horizon - Distribute jobs evenly across multiple worker servers
Overview

I have a Laravel 9.x application which has a multiple different job classes that run on Horizon. These jobs are very resource intensive and so I am exploring different approaches on to how to scale my queue worker force horizontally. Currently, I have 3 dedicated worker servers that run Horizon and are all connected to the same central Redis instance to poll for jobs.

My Problem

Say I have a job class called ProcessDocumentJob. I also have 3 instances of Horizon running per my 3 worker servers. All 3 worker servers are listening to the same queue, document-processing. My issue is that if I where to dispatch the ProcessDocumentJob 3 times to the document-processing queue, there is no guarantee that all 3 of my worker servers would be utilized for maximum performance. What happens most of the time is one of the three worker servers picks up all three jobs and tries to process them while the other two worker servers are idle. What I would like to happen is for the jobs to be distributed evenly (load balanced via a round robin approach) across all my worker servers.

My Current Solution

My current solution to distribute jobs evenly across my worker servers is to set a WORKER_QUEUE env var specific to each server. So for my 3 worker servers there would be 3 different queues I would deploy the ProcessDocumentJob to (worker-queue-1, worker-queue-2, worker-queue-3). Additionally, I'm also using the HORIZON_ENV env var (set to "worker") to specify the correct environment.

Here's a snippet of what my horizon.php config file looks like for this:

'environments' => [
        'worker' => [
            'worker-supervisor' => [
                'connection' => 'redis',
                'queue' => [env('WORKER_QUEUE')],
                'balance' => 'simple',
                'maxProcesses' => 10,
                'maxJobs' => 0,
                'memory' => 512,
                'tries' => 3,
                'nice' => 0,
                'timeout' => 600,
            ],
        ],
```
<p>The constructor of my <code>ProcessDocumentJob</code> job class looks like this:</p>
<pre class="lang-php prettyprint-override"><code>public function __construct(Document $document)
{
    $this->onQueue(Worker::bestPick());

    $this->document = $document;
}

</code>```

The Worker::bestPick() method is my approach to a round robin equivalent of dispatching jobs. It knows how many worker servers are available, each worker server's corresponding queue name and which queue was last used so that when another ProcessDocumentJob job comes in, it knows which server worker queue is next in the chain to assign it too.

The Drawback

This solution works well for the most part and all my jobs are distributed evenly across my worker servers. However, if one of my three worker servers goes down, this solution would not work unless I implemented some sort of uptime check into my Worker::bestPick() method.

Additionally, I've also explored Redis's atomic locks and limiting the maxJobs field in my config file in an attempt to achieve what I'm after but had no success.

Questions

How do I distribute jobs evenly across all my worker servers similar to how a load balancer would distribute traffic via Round Robin to web servers?

Am I on the right path with attempting to horizontally scale my worker servers with peak performance in mind? Or is there a more Laravel friendly way of handling this?

And yes, I know these things

Queue systems are first-in, first-out.

The balance field can be set to "simple", "auto" and "false" and these values do not appear to help solve my problem.

Yes, I've read the Laravel docs on Horizon and Queues.

TL;DR

I get that time is money... but don't be lazy. Read the whole thing ^

Body:
Overview

I have a Laravel 9.x application which has a multiple different job classes that run on Horizon. These jobs are very resource intensive and so I am exploring different approaches on to how to scale my queue worker force horizontally. Currently, I have 3 dedicated worker servers that run Horizon and are all connected to the same central Redis instance to poll for jobs.

My Problem

Say I have a job class called ProcessDocumentJob. I also have 3 instances of Horizon running per my 3 worker servers. All 3 worker servers are listening to the same queue, document-processing. My issue is that if I where to dispatch the ProcessDocumentJob 3 times to the document-processing queue, there is no guarantee that all 3 of my worker servers would be utilized for maximum performance. What happens most of the time is one of the three worker servers picks up all three jobs and tries to process them while the other two worker servers are idle. What I would like to happen is for the jobs to be distributed evenly (load balanced via a round robin approach) across all my worker servers.

My Current Solution

My current solution to distribute jobs evenly across my worker servers is to set a WORKER_QUEUE env var specific to each server. So for my 3 worker servers there would be 3 different queues I would deploy the ProcessDocumentJob to (worker-queue-1, worker-queue-2, worker-queue-3). Additionally, I'm also using the HORIZON_ENV env var (set to "worker") to specify the correct environment.

Here's a snippet of what my horizon.php config file looks like for this:

'environments' => [
        'worker' => [
            'worker-supervisor' => [
                'connection' => 'redis',
                'queue' => [env('WORKER_QUEUE')],
                'balance' => 'simple',
                'maxProcesses' => 10,
                'maxJobs' => 0,
                'memory' => 512,
                'tries' => 3,
                'nice' => 0,
                'timeout' => 600,
            ],
        ],

The constructor of my ProcessDocumentJob job class looks like this:

public function __construct(Document $document)
{
    $this->onQueue(Worker::bestPick());

    $this->document = $document;
}

The Worker::bestPick() method is my approach to a round robin equivalent of dispatching jobs. It knows how many worker servers are available, each worker server's corresponding queue name and which queue was last used so that when another ProcessDocumentJob job comes in, it knows which server worker queue is next in the chain to assign it too.

The Drawback

This solution works well for the most part and all my jobs are distributed evenly across my worker servers. However, if one of my three worker servers goes down, this solution would not work unless I implemented some sort of uptime check into my Worker::bestPick() method.

Additionally, I've also explored Redis's atomic locks and limiting the maxJobs field in my config file in an attempt to achieve what I'm after but had no success.

Questions

How do I distribute jobs evenly across all my worker servers similar to how a load balancer would distribute traffic via Round Robin to web servers?

Am I on the right path with attempting to horizontally scale my worker servers with peak performance in mind? Or is there a more Laravel friendly way of handling this?

And yes, I know these things

Queue systems are first-in, first-out.

The balance field can be set to "simple", "auto" and "false" and these values do not appear to help solve my problem.

Yes, I've read the Laravel docs on Horizon and Queues.

TL;DR

I get that time is money... but don't be lazy. Read the whole thing ^


问:
ResNet fluctuates on validation set and poor on test set
I'm trying to use ResNet50(pretrained) to classify CFP images(448*448), unfortunately some strange phenomenon occurred:

The model showed a nice curve of training loss, but the validation loss fluctuated massively.
5-cross validation loss map

The kappa and accuracy showed huge difference against train and validation stage, while the curve is full of spikes.
5-cross validation accuracy map
5-cross validation kappa map

Here are my training settings.
optimizer:SGD
lr:1e-3
lr_decay:0.9
lr_decay_start:2
tolerance_iter_num:5
lr_min:1e-5
momentum:0.9
weight_decay:1e-4
max_epoch:30

The attempt I've made:**

Change Learning rate(1e-3~1e-5).

Change the depth of ResNet(18, 34, 50, 152).

Different kinds of data augmentation.

5-cross validation.

Rearrange the distribution of the dataset. The original set has 100 images(3 labels) and was out of distribution, so I expanded the train set to 320 images with a distribution of 2:1:1. Now the test set has 100 images and validation set has 20 images， both of them share a distribution with train set.

I've searched some potential solutions like freeze the BN layer, but the problem still exists.
What should I do?**


问:
How to make a popup with GET/POST request ASP NET CORE
I have a map, with n numbers of markers with a unique ID. When I click on them a custom popup for that marker appears (using JS and CSS). Every time I click on one of the markers, I want it to send a POST request that will change the URL from ~/reports/index to ~report/index/custom_Id. I need it to be with a custom id in the URL because I need to load some popups from another page using GET request.

My code:

Load map:

```<code><script type="text/javascript">

    var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];

    var map = new ol.Map({
        target: 'map',
        view: new ol.View({
            zoom: 5,
            center: [166326, 5992663]
        }),
        interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
        layers: layers
    });

    const options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };

    function togglePopup(id) { //The function that revals the popup
        document.getElementById("overlay-container-" + id).classList.toggle("active");
    }

    // Vector Feature Popup logic
    map.on('click', function (e) { //The "sensor" that detects if a marker has been clicked.
        map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {

        togglePopup(feature.getId());
        resetCurrent();
        handleImages(feature.getId());
    })
})
</code>```

Add markers (this is inside a bigger for loop):

```<code><script type="text/javascript">
    markers = new ol.layer.Vector({
    source: new ol.source.Vector(),
    style: new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.5, 1],
            src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
            })
        })
    });

    map.addLayer(markers);

    var marker = new ol.Feature(new ol.geom.Point([parseFloat(@_Data.coordLat), parseFloat(@_Data.coordLong)]));
    marker.setId(@_Data.Id);
    markers.getSource().addFeature(marker);
</script>
</code>```

I know that if it was a HTML button for something like that I could have add asp-route-id=@_Data.Id or something but this is JS. How can I make it?

Body:
I have a map, with n numbers of markers with a unique ID. When I click on them a custom popup for that marker appears (using JS and CSS). Every time I click on one of the markers, I want it to send a POST request that will change the URL from ~/reports/index to ~report/index/custom_Id. I need it to be with a custom id in the URL because I need to load some popups from another page using GET request.

My code:

Load map:

I know that if it was a HTML button for something like that I could have add asp-route-id=@_Data.Id or something but this is JS. How can I make it?


问:
command to update the jir file for a sentinel doesn't seem to change anything in jac
I've been running into trouble managing sentinels on our jaseci server. The command to update the jir file for a sentinel doesn't seem to change anything when I run it, and so my current workflow is to delete all previously used sentinels and graphs and create new ones when I wish to change any part of the jaseci code. I imagine there must be an easier way to do this, and I think I must be misunderstanding something about how sentinels work.</p>