问:
"zip file closed" when deploying Spring Boot application to AWS/railway.app/docker
I face that problem everytime i want to deploy my Spring Boot application which opens webserver at localhost:8080. It works at localhost.

2023-01-10T12:40:42.326Z  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-01-10T12:40:42.326Z  INFO 1 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.4]
2023-01-10T12:40:42.605Z ERROR 1 --- [           main] org.apache.catalina.core.ContainerBase   : A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na]
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:923) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:886) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1383) ~[tomcat-embed-core-10.1.4.jar!/:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:252) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:430) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:926) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:485) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.(TomcatWebServer.java:104) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:486) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:210) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:183) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:161) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:578) ~[spring-context-6.0.3.jar!/:6.0.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar!/:3.0.1]
at com.example.RappersInfo.demo.RappersInfo.main(RappersInfo.java:19) ~[classes!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[demo-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:95) ~[demo-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[demo-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65) ~[demo-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1383) ~[tomcat-embed-core-10.1.4.jar!/:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) ~[tomcat-embed-core-10.1.4.jar!/:na]
37 common frames omitted
Caused by: java.lang.IllegalStateException: zip file closed
at java.base/java.util.zip.ZipFile.ensureOpen(ZipFile.java:831) ~[na:na]
at java.base/java.util.zip.ZipFile.getManifestName(ZipFile.java:1057) ~[na:na]
at java.base/java.util.zip.ZipFile$1.getManifestName(ZipFile.java:1100) ~[na:na]
at java.base/java.util.jar.JarFile.getManEntry(JarFile.java:937) ~[na:na]
at java.base/java.util.jar.JarFile.checkForSpecialAttributes(JarFile.java:1000) ~[na:na]
at java.base/java.util.jar.JarFile.isMultiRelease(JarFile.java:389) ~[na:na]
at org.apache.tomcat.util.scan.JarFileUrlJar.(JarFileUrlJar.java:68) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.tomcat.util.scan.JarFactory.newInstance(JarFactory.java:41) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:393) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.tomcat.util.scan.StandardJarScanner.processURLs(StandardJarScanner.java:328) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.tomcat.util.scan.StandardJarScanner.doScanClassPath(StandardJarScanner.java:271) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:234) ~[tomcat-embed-core-10.1.4.jar!/:11.0.0-M1]
at org.apache.jasper.servlet.TldScanner.scanJars(TldScanner.java:262) ~[tomcat-embed-jasper-11.0.0-M1.jar!/:11.0.0-M1]
at org.apache.jasper.servlet.TldScanner.scan(TldScanner.java:104) ~[tomcat-embed-jasper-11.0.0-M1.jar!/:11.0.0-M1]
at org.apache.jasper.servlet.JasperInitializer.onStartup(JasperInitializer.java:83) ~[tomcat-embed-jasper-11.0.0-M1.jar!/:11.0.0-M1]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5144) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
43 common frames omitted
2023-01-10T12:40:42.615Z ERROR 1 --- [           main] org.apache.catalina.core.ContainerBase   : A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na]
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:923) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:252) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:430) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:926) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-10.1.4.jar!/:na]`
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:485) ~[tomcat-embed-core-10.1.4.jar!/:na]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-3.0.1.jar!/:3.0.1]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.(TomcatWebServer.java:104) ~[spring-boot-3.0.1.jar!/:3.0.1]

What can i do?

I tried changing it to war and it deploys sucessfully to docker image but it doesnt work for AWS and railway.app or any other cloud.

And general question, somehow related to this one:

How can i deploy my app in other way which is good-practice for the future? I mean should I maybe try other way than deploying it to cloud, for example running it on my PC and then changing some ports in my router?

I want my app to be visible in public domain.

I also have Raspberry Pi so it could be my server.


来源: stackexchange

问:
Preview selected image on HTML, Flask app
I'm trying to make a product upload page were we upload a product photo along with its details. However I want to preview the photo on upload page through the image container in html before saving it.

Following is the Fileupload code in app.py:

` ` `

```<code>if file and allowed_file(file.filename):
            filename = generate_custom_name(file.filename)
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            photourl = filename
            if description and title and age and condition and photourl and price != "":
                cur = mysql.connection.cursor()
                cur.execute("""INSERT INTO products (pid,title,pdescription,page,pcondition,pavailability,sellertype,price,sellername,photourl,sellerid) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                            (pid, title, description, age, condition, availability, sellertype, int(price), sellername, photourl, int(sellerid)))
                mysql.connection.commit()
                cur.close()
                flash("Product Added Successfully!", "info")
</code>```

` ` `

donate.html

` ` `

```<code> <div class="fileup">
            <h1>Upload Product Photo</h1>
            <img src="static/uplaods/#" id="photo">
            <form method="post" enctype="multipart/form-data">
            <div class="upload">
                <input type="file" id="file" name="file">
            <label for="file" id="uploadBtn"> Choose Photo</label>
            </div>
        </div>
</code>```

` ` `

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a product upload page were we upload a product photo along with its details. However I want to preview the photo on upload page through the image container in html before saving it.

Following is the Fileupload code in app.py:

` ` `

if file and allowed_file(file.filename):
            filename = generate_custom_name(file.filename)
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            photourl = filename
            if description and title and age and condition and photourl and price != "":
                cur = mysql.connection.cursor()
                cur.execute("""INSERT INTO products (pid,title,pdescription,page,pcondition,pavailability,sellertype,price,sellername,photourl,sellerid) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
                            (pid, title, description, age, condition, availability, sellertype, int(price), sellername, photourl, int(sellerid)))
                mysql.connection.commit()
                cur.close()
                flash("Product Added Successfully!", "info")

` ` `

donate.html

` ` `

Upload Product Photo

            <form method="post" enctype="multipart/form-data">

                <input type="file" id="file" name="file">
             Choose Photo

` ` `


问:
SPL file missing the PJL commands when sent from mac
I am printing a document from mac to a windows shared print queue. The spooled file reaches to the print queue but it's missing the PJL commands in the SPL file ? My application needs to read the PJL comments and job attributes.

How the SPL file generated in windows print queue is different from mac ?


问:
Animations blinks when hovered
I created a simple animation where an array of words roll one after the other in an infinite loop.

function App() {
  const words = ['word1', 'word2', 'word3', 'word4', 'word5', 'word1'];

  return (

  sometime, "word1" blinks for no apparent reason (hover on it if it doesn't happen)

        {words.map((word) => {
          return
 {word}
;
        })}

  );
}
ReactDOM.render( < App / > , document.getElementById("root"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container-rollingText {
  overflow-y: hidden;
  height: 140px;
  width: fit-content;
}

.singleWord {
  font-size: 65px;
  animation: roll-up 8s infinite;

  height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes roll-up {
  20% {
    transform: translateY(-100%);
  }
  40% {
    transform: translateY(-200%);
  }
  60% {
    transform: translateY(-300%);
  }
  80% {
    transform: translateY(-400%);
  }
  100% {
    transform: translateY(-500%);
  }
}</code>```

 ```

https://stackblitz.com/edit/react-ts-pk2xui?file=App.tsx,style.css

It works fine, except that sometime, it blinks once when the animation starts a new loop.

It feels random, and I can't figure out a cause. It seems to happen when I hover on the div containing the rolling words, though there is no hover effect built in my code.

Could someone guide me on what provokes this blink, and maybe suggest a solution?

Title: Animations blinks when hovered

Body:
I created a simple animation where an array of words roll one after the other in an infinite loop.

function App() {
  const words = ['word1', 'word2', 'word3', 'word4', 'word5', 'word1'];

  return (

  sometime, "word1" blinks for no apparent reason (hover on it if it doesn't happen)

        {words.map((word) => {
          return
 {word}
;
        })}

  );
}
ReactDOM.render( < App / > , document.getElementById("root"));

.container-rollingText {
  overflow-y: hidden;
  height: 140px;
  width: fit-content;
}

.singleWord {
  font-size: 65px;
  animation: roll-up 8s infinite;

  height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes roll-up {
  20% {
    transform: translateY(-100%);
  }
  40% {
    transform: translateY(-200%);
  }
  60% {
    transform: translateY(-300%);
  }
  80% {
    transform: translateY(-400%);
  }
  100% {
    transform: translateY(-500%);
  }
}

https://stackblitz.com/edit/react-ts-pk2xui?file=App.tsx,style.css

It works fine, except that sometime, it blinks once when the animation starts a new loop.

It feels random, and I can't figure out a cause. It seems to happen when I hover on the div containing the rolling words, though there is no hover effect built in my code.

Could someone guide me on what provokes this blink, and maybe suggest a solution?


问:
Why is FusionReactor not working with tomcat?
I have tired to add FusionReactor  agent to my tomcat on the linux server, but it was failed.
First, i have created a directory where are located files of FusionReactor  then into  JAVA_OPTS(for tomcat) variable has added the next equery:

```<code>-javaagent:/opt/fusionreactor/instance/tomcat/fusionreactor.jar=address=8080 -agentpath:/opt/fusionreactor/instance/tomcat/libfrjvmti_x64.so
</code>```

After the server was restarted. I have expected thatit will be successfully launched, but actially it was finished with the next error

```<code>FusionReactor JVMTI Revision: 9.1.0 Build: 1837.391d431697a9fcba6366edbd202476ca511a1fbb.9.1.0
Warning:  Could not initialize the framework - FusionReactor may be unavailable: No such file or directory
Warning:  Could not initialize the framework - FusionReactor may be unavailable: No such file or directory
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1023)
at com.intergral.fusionreactor.agent.frameworkhostmanager.FrameworkHostManager.init(FrameworkHostManager.java:82)
at com.intergral.fusionreactor.agent.Agent.startup(Agent.java:525)
at com.intergral.fusionreactor.agent.Agent.access$100(Agent.java:40)
at com.intergral.fusionreactor.agent.Agent$2.run(Agent.java:272)
at java.lang.Thread.run(Thread.java:750)
org.apache.catalina.startup.ClassLoaderFactory validateFile
</code>```

Why this error has occurred?

I have add all grants for  libfrjvmti_x64.so, fusionreactor.jar, but it looks like unavailable.

Body:
I have tired to add FusionReactor  agent to my tomcat on the linux server, but it was failed.
First, i have created a directory where are located files of FusionReactor  then into  JAVA_OPTS(for tomcat) variable has added the next equery:

-javaagent:/opt/fusionreactor/instance/tomcat/fusionreactor.jar=address=8080 -agentpath:/opt/fusionreactor/instance/tomcat/libfrjvmti_x64.so

After the server was restarted. I have expected thatit will be successfully launched, but actially it was finished with the next error

FusionReactor JVMTI Revision: 9.1.0 Build: 1837.391d431697a9fcba6366edbd202476ca511a1fbb.9.1.0
Warning:  Could not initialize the framework - FusionReactor may be unavailable: No such file or directory
Warning:  Could not initialize the framework - FusionReactor may be unavailable: No such file or directory
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1023)
at com.intergral.fusionreactor.agent.frameworkhostmanager.FrameworkHostManager.init(FrameworkHostManager.java:82)
at com.intergral.fusionreactor.agent.Agent.startup(Agent.java:525)
at com.intergral.fusionreactor.agent.Agent.access$100(Agent.java:40)
at com.intergral.fusionreactor.agent.Agent$2.run(Agent.java:272)
at java.lang.Thread.run(Thread.java:750)
org.apache.catalina.startup.ClassLoaderFactory validateFile

Why this error has occurred?

I have add all grants for  libfrjvmti_x64.so, fusionreactor.jar, but it looks like unavailable.


问:
Pivot Table Filter issue based on calculated date field
I have a workbook which analyses exported data and summarizes results from previous work week. I do the export every week start of Monday. The export has all the sales data from 2016 up until now. I plug the export into my workbook and after every row of records I have some very simple formulas, one is that checks if the sale has happened previous week. Just a calculated date field that works fine, if so the formula generates "YES". Based on that I have a pivot table with a filter set like “Sale in previous week” = YES.

Another filter checks if the sale record is for my department being department 1 (“Dep1”). There is a total of 5 departments. So, second filter is set to “Dep1” = YES; with “Dep1” = NO shows then all the sales of departments 2 to 5.
Sometimes, there no sale for my department 1. So, with my filter “Sale in previous week” = YES and Dep1 = YES I get an empty pivot table with Grand Total = 0. This is how it should be (Field Settings = Show items with no data). Issue is that sometimes there is no sale for any department. Meaning that if I plug in the new export data and do a Refresh All with no sale in previous week the result of the pivot table is “Sale in previous week” = NO  meaning there is no “YES” in my table for any record and the pivot table filter has no other option then NO, thus showing all results. For my department it happens a lot that there is no sale, but there always a sale for the other departments. That’s why I’m able to view the pivot table as empty (meaning 0 as in no sale). But sometimes there is no sale at all for any departments.

Note this is a simplified representation of a big workbook with dashboards and a lot of formulas and calculations, but I’m afraid that occasionally the workbook fails just by the way I have set up the initial previous work week calculation and filters. Is there work around for this, or maybe some other suggestions?

I was testing with adding a dummy record in Excel which always has "Sale in previous week" = YES. Issue is that every week there is a new export clearing previous records and the source database does not (and may not) have a dummy record. I can manually change some things, but I'm moving on and colleagues are taking over this task. 99/100 it just export, plug in Excel and Refresh All and it's ok. But as described above it sometimes fails.


问:
Send Sensor data to local serverr
I use an esp8266 that sends me sensor data, the sensor is mounted on a water meter and is supposed to determine the liter consumption.

Unfortunately, the WiFi connection often breaks, so that I lose data from several periods.

with micropython i was thinking about running two parallel threads, the first one (async def count():) can count the pulses and the send one (def SendData()) is sending them to local server when there is a wifi connection.

i want to hand over the arguments to MqttApp() on SendData() but i coudnt make that work well..

for now im getting this :

```<code>Traceback (most recent call last):
  File "<stdin>", line 113
SyntaxError: invalid syntax

line 113 : client = SendData(target = MqttApp, args = (client_id='Mono', server="10.28.1.119", port=1883, keepalive=30, count_func=pulse2liter, topic="Mono"))
</code>```

from machine import ADC, Pin, time_pulse_us
from time import sleep
from umqttsimple import MQTTClient
import uasyncio

# send 1 when one liter is consumed
class Pulse2Liter:
    def __init__(self, pin):
        self.pin = pin

    def __call__(self):
        result = time_pulse_us(self.pin, 1500000)
        if result in (-1, -2):
            return 0
        # alles was kürzer als 400 ms ist
        return 1 if result <= 400000 else 0
        return 10 if result >= 3000000 else 0

# send the data to local server when wifi is activ

async def SendData():
    class MqttApp(MQTTClient):
        def __init__(self, *args, topic, count_func, **kwargs):
            """
            topic:= Topic der Nachricht
            count_func:= Zählerfunktion
            """
            super().__init__(*args, **kwargs)
            self.countall = 0
            self.topic = topic
            self.count_func = count_func

        def safe_connect(self):
            """
            Versuch eine Verbindung aufzubauen und erst bei
            Erfolg wird die Methode verlassen.
            """
            while True:
                try:
                    if self.connect() == 0:
                        # Kein Erfolg
                        return
                except OSError:
                    # Kein Erfolg
                    pass
                else:
                    # Erfolg
                    return
                    # immer warten, wenn kein Erfolg
                sleep(1)

        def send(self, count):
            """
            Sendet eine Nachricht.
            Falls die Verbindung unterbrochen wird,
            blockiert die Methode so lange, bis eine Verbindung wieder
            hergestellt ist und versucht erneut die Nachricht zu senden.
            """
            while True:
                try:
                    self.publish(self.topic, str(count), qos=1)
                except OSError:
                    print("Lost connection.")
                    self.safe_connect()
                else:
                    return

        self.safe_connect()
        while True:
            if len(DataQueue) > 0:
                self.send(DataQueue[0])
                sleep(3)
                DataQueue.clear()
            sleep(0.05)

# COUNT THE PULSES
async def count():
    class run(self):
        print('1')
        """
        Starte Zählschleife.
        """
        global DataQueue
        x = 1
        startzeit = time.time()
        self.countall = 0
        Gruen = Pin(5, Pin.OUT)
        while True:
            Gruen.on()
            count = self.count_func()
            count = 1
            if count > 0:
                self.countall = self.countall + count
                print(self.countall)
                sleep(0.2)
            if time.time() > startzeit + x*3600:
                DataQueue.append(self.countall)
                self.countall = 0
                sleep(0.05)

trigger_pin = Pin(12, Pin.IN, Pin.PULL_UP)
DataQueue = []

pulse2liter = Pulse2Liter(trigger_pin)

async def runBothThreads():
    uasyncio.create_task(count())
    client = SendData(target = MqttApp, args = (client_id='Mono', server="10.28.1.119", port=1883,    keepalive=30, count_func=pulse2liter, topic="Mono"))
    uasyncio.create_task(SendData())
    client.run()
    while True:
        await uasyncio.sleep_ms(100)

uasyncio.run(runBothThreads())
```

Title: Send Sensor data to local serverr

Body:
I use an esp8266 that sends me sensor data, the sensor is mounted on a water meter and is supposed to determine the liter consumption.

Unfortunately, the WiFi connection often breaks, so that I lose data from several periods.

with micropython i was thinking about running two parallel threads, the first one (async def count():) can count the pulses and the send one (def SendData()) is sending them to local server when there is a wifi connection.

i want to hand over the arguments to MqttApp() on SendData() but i coudnt make that work well..

for now im getting this :

Traceback (most recent call last):
  File "<stdin>", line 113
SyntaxError: invalid syntax

line 113 : client = SendData(target = MqttApp, args = (client_id='Mono', server="10.28.1.119", port=1883, keepalive=30, count_func=pulse2liter, topic="Mono"))

from machine import ADC, Pin, time_pulse_us
from time import sleep
from umqttsimple import MQTTClient
import uasyncio

# send 1 when one liter is consumed
class Pulse2Liter:
    def __init__(self, pin):
        self.pin = pin

    def __call__(self):
        result = time_pulse_us(self.pin, 1500000)
        if result in (-1, -2):
            return 0
        # alles was kürzer als 400 ms ist
        return 1 if result <= 400000 else 0
        return 10 if result >= 3000000 else 0

# send the data to local server when wifi is activ

async def SendData():
    class MqttApp(MQTTClient):
        def __init__(self, *args, topic, count_func, **kwargs):
            """
            topic:= Topic der Nachricht
            count_func:= Zählerfunktion
            """
            super().__init__(*args, **kwargs)
            self.countall = 0
            self.topic = topic
            self.count_func = count_func

        def safe_connect(self):
            """
            Versuch eine Verbindung aufzubauen und erst bei
            Erfolg wird die Methode verlassen.
            """
            while True:
                try:
                    if self.connect() == 0:
                        # Kein Erfolg
                        return
                except OSError:
                    # Kein Erfolg
                    pass
                else:
                    # Erfolg
                    return
                    # immer warten, wenn kein Erfolg
                sleep(1)

        def send(self, count):
            """
            Sendet eine Nachricht.
            Falls die Verbindung unterbrochen wird,
            blockiert die Methode so lange, bis eine Verbindung wieder
            hergestellt ist und versucht erneut die Nachricht zu senden.
            """
            while True:
                try:
                    self.publish(self.topic, str(count), qos=1)
                except OSError:
                    print("Lost connection.")
                    self.safe_connect()
                else:
                    return

        self.safe_connect()
        while True:
            if len(DataQueue) > 0:
                self.send(DataQueue[0])
                sleep(3)
                DataQueue.clear()
            sleep(0.05)

# COUNT THE PULSES
async def count():
    class run(self):
        print('1')
        """
        Starte Zählschleife.
        """
        global DataQueue
        x = 1
        startzeit = time.time()
        self.countall = 0
        Gruen = Pin(5, Pin.OUT)
        while True:
            Gruen.on()
            count = self.count_func()
            count = 1
            if count > 0:
                self.countall = self.countall + count
                print(self.countall)
                sleep(0.2)
            if time.time() > startzeit + x*3600:
                DataQueue.append(self.countall)
                self.countall = 0
                sleep(0.05)

trigger_pin = Pin(12, Pin.IN, Pin.PULL_UP)
DataQueue = []

pulse2liter = Pulse2Liter(trigger_pin)

async def runBothThreads():
    uasyncio.create_task(count())
    client = SendData(target = MqttApp, args = (client_id='Mono', server="10.28.1.119", port=1883,    keepalive=30, count_func=pulse2liter, topic="Mono"))
    uasyncio.create_task(SendData())
    client.run()
    while True:
        await uasyncio.sleep_ms(100)

uasyncio.run(runBothThreads())


问:
elasticsearch "_doc" replaces my own "testType"
I am new at ElasticSearch, so maybe it's very obvious..

I have a class in the API with basic methods like refreshIndeces, checkIfExists, createIndex, addDocument, etc.

According to the manuals, I decided that my elastic requests should consist of URL, indexName, type, and other parameters. I specified "indexName" when creating an instance of the class, that is, it is always the same in all tests, I also specified "type" in the code.

I have an API where the date is returned in a certain format, with certain fields, and written to elastic.

I recently duplicated another copy of the API and changed the data format and field names.

After that, my "testType" type is automatically changed to "_doc" when sending requests everywhere (like it record data with "_doc" instead "testType" in parameter and it does search also by switching to "_doc" and ignores "testType").

I'm not sure since it came after changing the format/fields that is the reason, but I did tests with one more copy of the API. At first, the copy with the old fields worked well, then when I changed the code and fields, it again changed the "_doc" itself and changed my hardcoded "testType" to "_doc".

I thought maybe the reason is that elastic stores only one schema in one index. And since the new API returns a different format, does it automatically debug it and put it in "doc _"?

Or could there be something else?

And if I delete the entire index with data, and write the new format first, will it work normally and stop redirecting to "_doc"?


问:
Is there a way to add a class to an element on click - while removing every other case of that class on an entire page?
I have something mocked up, but it isn't working as desired. The clicked elements aren't siblings, they are links nested within siblings:

```<code>$(".btn").click(function() {
    $('.btn').removeClass('btn-clicked');
    $(this).addClass('btn-clicked');
});
</code>```

I've also tried this to no avail:

```<code>$('.btn').click(function () {
    $(this).addClass('btn-clicked');
    $('.btn').not(this).removeClass('btn-clicked');
});
</code>```

Any ideas? Thanks!

Body:
I have something mocked up, but it isn't working as desired. The clicked elements aren't siblings, they are links nested within siblings:

$(".btn").click(function() {
    $('.btn').removeClass('btn-clicked');
    $(this).addClass('btn-clicked');
});

I've also tried this to no avail:

$('.btn').click(function () {
    $(this).addClass('btn-clicked');
    $('.btn').not(this).removeClass('btn-clicked');
});

Any ideas? Thanks!


问:
How do I post JavaScript added input values in Razor? (No MVC)
I'm working on a Razor Page web application (no MVC) and currently trying to create a page where an admin (basicly an user) can create an Exam with certain inputs and questions.

However the questions section is dynamic. There are 3 question types and the user must select an option and press the button 'Add Question' before the inputs are shown (because each question type has different inputs). The user can add as many questions to the exam as he/she likes.
Question inputs example

My Exam class

```<code>public class Exam
    {
        public Exam()
        {
            this.Id = 0;
            this.Name = "";
            this.Users = new List<ApplicationUser>();
            this.Record = new List<Record>();
            this.CreatedByUserId = "";
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public List<ApplicationUser> Users { get; set; }
        public ICollection<Question> Questions { get; set; }
        public List<Record> Record { get; set; }
        public string CreatedByUserId { get; set; }
    }
</code>```

My Razor page

```<code>@page
@using iD_Develops.Models
@model iD_Develops.Pages.Examination.MyExams.CreateModel

<div class="container-md">
    <h2>Creating new exam</h2>
    <p><span class="text-danger">*</span> is a required field</p>
    <div class="col-md-6 mb-3">
        <div class="form-floating">
            <input type="text" class="form-control" id="floatingInput" placeholder="text">
            <label for="floatingInput">Exam name<span class="text-danger">*</span></label>
        </div>
    </div>
    <div class="col-md-6 mb-3">
        <div class="form-floating">
            <select class="form-select" id="floatingSelect">
                <option selected>-</option>
                <option value="1">English course - Beginner</option>
                <option value="2">English course - Intermediate</option>
                <option value="3">English course - Advanced</option>
                <option value="4">Dutch course - Beginner</option>
                <option value="5">Dutch course - Intermediate</option>
                <option value="6">Dutch course - Advanced</option>
            </select>
            <label for="floatingSelect">Add to course</label>
        </div>
    </div>
    <div class="col-md-6 mb-3">
        <div class="input-group" style="max-width: 300px;">
            <input type="number" class="form-control" style="min-width: 130px;" placeholder="Exam time length" min="0" aria-label="Exam time length" aria-describedby="basic-addon2">
            <div class="input-group-append">
                <span class="input-group-text" id="basic-addon2">minutes</span>
            </div>
        </div>
        <div>
            <span>Leave blank or fill 0 for no time length.</span>
        </div>
    </div>
    <div class="col-md-6 mb-3">
        <div class="form-floating">
            <input type="text" class="form-control" id="floatingInput" placeholder="text">
            <label for="floatingInput">Rules<span class="text-danger">*</span></label>
        </div>
    </div>
    <h4>Settings</h4>
    <div class="form-check">
        <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
        <label class="form-check-label" for="flexCheckDefault">
            Enable summary after submitting exam
        </label>
    </div>
    <h4>Questions</h4>
    <div class="col-md-6 mb-3" id="empty-exam">
        <p>There are currently no questions...</p>
    </div>
    <div class="col-md-6 mb-3" id="add-question-btn">
        <div class="input-group mb-3" style="max-width: 300px;">
            <select class="form-select" style="min-width: 130px;" id="inputQuestionSelect">
                <option selected value="openquestion">Open question</option>
                <option value="multiplechoice">Multiple choice</option>
                <option value="trueorfalse">True or false</option>
            </select>
            <div class="input-group-append">
                <button class="btn btn-outline-secondary" type="button" onclick="javascript:addQuestion()">Add question</button>
            </div>
        </div>
    </div>
    <a class="btn btn-primary" asp-page="/Examination/MyExams/Index" role="button">Save</a>
</div>
</code>```

In the div where id="add-question-btn" I call a JavaScript function that adds inputs according to the selected value of the .

Part of my js code:

```<code>var questionCount = 0;
function addQuestion() {
    var emptyQuestions = document.getElementById('empty-exam');
    if (emptyQuestions.style.display != 'none') {
        emptyQuestions.style.display = 'none';
    }
    var select = document.getElementById('inputQuestionSelect');
    var questionType = select.options[select.selectedIndex].value;

    switch (questionType) {
        case 'openquestion':
            addOpenQuestion();
            break;
        case 'multiplechoice':
            addMultipleChoiceQuestion();
            break;
        case 'trueorfalse':
            addTrueOrFalseQuestion();
            break;
    }
}

function addOpenQuestion() {
    var addQuestionBtn = document.getElementById('add-question-btn');
    var parentDiv = addQuestionBtn.parentNode;

    if (addQuestionBtn) {
        var questionNumber = document.createElement('h3');
        questionNumber.innerHTML = 'Question ' + (questionCount + 1);

        //Scenario input
        var colScenarioDiv = document.createElement('div');
        colScenarioDiv.className = 'col-md-6 mb-3';
        var scenarioInputDiv = createInputsDiv("Scenario text", true);

        //Question input
        var colQuestionTextDiv = document.createElement('div');
        colQuestionTextDiv.className = 'col-md-6 mb-3';
        var questionInputDiv = createInputsDiv("Question text", true);

        //Answer input
        var colAnswerDiv = document.createElement('div');
        colAnswerDiv.className = 'col-md-6 mb-3';
        var answerInputDiv = createInputsDiv("Correct answer", false);

        //Points input
        var colPointsDiv = document.createElement('div');
        colPointsDiv.className = 'col-md-6 mb-3';
        var pointsDiv = createPointsDiv();

        // Error check
        if (questionNumber && colScenarioDiv && colQuestionTextDiv && colAnswerDiv && colPointsDiv)    {
            parentDiv.insertBefore(questionNumber, addQuestionBtn);

            colScenarioDiv.appendChild(scenarioInputDiv);
            parentDiv.insertBefore(colScenarioDiv, addQuestionBtn);

            colQuestionTextDiv.appendChild(questionInputDiv);
            parentDiv.insertBefore(colQuestionTextDiv, addQuestionBtn);

            colAnswerDiv.appendChild(answerInputDiv);
            parentDiv.insertBefore(colAnswerDiv, addQuestionBtn);

            colPointsDiv.appendChild(pointsDiv);
            parentDiv.insertBefore(colPointsDiv, addQuestionBtn);

            questionCount++;
        }
    }
}
function createInputsDiv(inputText, required) {
    var divElement = document.createElement('div');
    divElement.className = "form-floating";

    var inputElement = document.createElement('input');
    inputElement.type = 'text';
    inputElement.className = 'form-control';
    inputElement.id = 'floatingInput';
    inputElement.placeholder = 'text';

    var labelElement = document.createElement('label');
    labelElement.htmlFor = 'floatingInput';
    if (required) {
        ;
        labelElement.innerHTML = inputText;

        var spanElement = document.createElement('span');
        spanElement.className = 'text-danger';
        spanElement.innerHTML = '*'

        $(spanElement).appendTo(labelElement);
    }
    else {
        labelElement.innerHTML = inputText;
    }

    if (divElement && inputElement && labelElement) {
        divElement.appendChild(inputElement);
        divElement.appendChild(labelElement);
    }
    return divElement;
}
</code>```

My struggle here is to 'Post' these dynamically added inputs from JavaScript to my OnPost() function in the PageModel class because I can't figure out how to send them as parameters.

Ultimately, I'd like to post ALL of the inputs (including the exam inputs such as exam name, etc) together to the database upon pressing the Save button.

I've tried to use the exam model in a foreach loop with a switch case and work with updating the model so I didn't need to use JavaScript.
HTML

```<code><h4>Questions</h4>
    @if (Model.NewExam.Questions.Count > 0)
    {
        foreach (var q in Model.NewExam.Questions)
        {
            switch (q)
            {
                case OpenQuestion o:
                    //Show inputs here for open question
                    break;
                case MultipleChoiceQuestion m:
                    //Show inputs here for multiple choice
                    break;
                case TrueOrFalseQuestion t:
                    //Show inputs here for true or false
                    break;
            }
        }
    }
    else
    {
        <div class="col-md-6 mb-3" id="empty-exam">
            <p>There are currently no questions...</p>
        </div>
    }
</code>```

PageModel

```<code>public class CreateModel : PageModel
    {
        [BindProperty]
        public Exam NewExam { get; set; }
        [BindProperty]
        public string QuestionTypeOption { get; set; }
        public void OnGet()
        {
            NewExam = new Exam
            {
                Id = 25,
                Questions = new List<Question>()
            };
        }
        public IActionResult OnPostAddQuestion()
        {
            switch (QuestionTypeOption)
            {
                case "openquestion":
                    NewExam.Questions.Add(new OpenQuestion());
                    break;
                case "multiplechoice":
                    NewExam.Questions.Add(new MultipleChoiceQuestion());
                    break;
                case "trueorfalse":
                    NewExam.Questions.Add(new TrueOrFalseQuestion());
                    break;
            }
            return RedirectToPage("Create", this.NewExam);
        }
    }
</code>```

When I click the Add question button it executes the OnPostAddQuestion() in the PageModel.
However the 'NewExam' empties as going through the OnPost function and giving me object reference not set to an instance of an object error because a new instance of the PageModel class is created upon each request.
I could've worked this out by saving this to the database but I think executing a database query after adding each question (which isn't definitive) is requiring a lot of resources.

Body:
I'm working on a Razor Page web application (no MVC) and currently trying to create a page where an admin (basicly an user) can create an Exam with certain inputs and questions.

However the questions section is dynamic. There are 3 question types and the user must select an option and press the button 'Add Question' before the inputs are shown (because each question type has different inputs). The user can add as many questions to the exam as he/she likes.
Question inputs example

My Exam class

public class Exam
    {
        public Exam()
        {
            this.Id = 0;
            this.Name = "";
            this.Users = new List<ApplicationUser>();
            this.Record = new List<Record>();
            this.CreatedByUserId = "";
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public List<ApplicationUser> Users { get; set; }
        public ICollection<Question> Questions { get; set; }
        public List<Record> Record { get; set; }
        public string CreatedByUserId { get; set; }
    }

My Razor page

@page
@using iD_Develops.Models
@model iD_Develops.Pages.Examination.MyExams.CreateModel

Creating new exam

* is a required field

            <input type="text" class="form-control" id="floatingInput" placeholder="text">
            Exam name*

            <select class="form-select" id="floatingSelect">
                <option selected>-</option>
                <option value="1">English course - Beginner</option>
                <option value="2">English course - Intermediate</option>
                <option value="3">English course - Advanced</option>
                <option value="4">Dutch course - Beginner</option>
                <option value="5">Dutch course - Intermediate</option>
                <option value="6">Dutch course - Advanced</option>
            </select>
            Add to course

            <input type="number" class="form-control" style="min-width: 130px;" placeholder="Exam time length" min="0" aria-label="Exam time length" aria-describedby="basic-addon2">

                minutes

            Leave blank or fill 0 for no time length.

            <input type="text" class="form-control" id="floatingInput" placeholder="text">
            Rules*

Settings

        <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">

            Enable summary after submitting exam

Questions

There are currently no questions...

            <select class="form-select" style="min-width: 130px;" id="inputQuestionSelect">
                <option selected value="openquestion">Open question</option>
                <option value="multiplechoice">Multiple choice</option>
                <option value="trueorfalse">True or false</option>
            </select>

                <button class="btn btn-outline-secondary" type="button" onclick="javascript:addQuestion()">Add question</button>

    Save

In the div where id="add-question-btn" I call a JavaScript function that adds inputs according to the selected value of the .

Part of my js code:

var questionCount = 0;
function addQuestion() {
    var emptyQuestions = document.getElementById('empty-exam');
    if (emptyQuestions.style.display != 'none') {
        emptyQuestions.style.display = 'none';
    }
    var select = document.getElementById('inputQuestionSelect');
    var questionType = select.options[select.selectedIndex].value;

    switch (questionType) {
        case 'openquestion':
            addOpenQuestion();
            break;
        case 'multiplechoice':
            addMultipleChoiceQuestion();
            break;
        case 'trueorfalse':
            addTrueOrFalseQuestion();
            break;
    }
}

function addOpenQuestion() {
    var addQuestionBtn = document.getElementById('add-question-btn');
    var parentDiv = addQuestionBtn.parentNode;

    if (addQuestionBtn) {
        var questionNumber = document.createElement('h3');
        questionNumber.innerHTML = 'Question ' + (questionCount + 1);

        //Scenario input
        var colScenarioDiv = document.createElement('div');
        colScenarioDiv.className = 'col-md-6 mb-3';
        var scenarioInputDiv = createInputsDiv("Scenario text", true);

        //Question input
        var colQuestionTextDiv = document.createElement('div');
        colQuestionTextDiv.className = 'col-md-6 mb-3';
        var questionInputDiv = createInputsDiv("Question text", true);

        //Answer input
        var colAnswerDiv = document.createElement('div');
        colAnswerDiv.className = 'col-md-6 mb-3';
        var answerInputDiv = createInputsDiv("Correct answer", false);

        //Points input
        var colPointsDiv = document.createElement('div');
        colPointsDiv.className = 'col-md-6 mb-3';
        var pointsDiv = createPointsDiv();

        // Error check
        if (questionNumber && colScenarioDiv && colQuestionTextDiv && colAnswerDiv && colPointsDiv)    {
            parentDiv.insertBefore(questionNumber, addQuestionBtn);

            colScenarioDiv.appendChild(scenarioInputDiv);
            parentDiv.insertBefore(colScenarioDiv, addQuestionBtn);

            colQuestionTextDiv.appendChild(questionInputDiv);
            parentDiv.insertBefore(colQuestionTextDiv, addQuestionBtn);

            colAnswerDiv.appendChild(answerInputDiv);
            parentDiv.insertBefore(colAnswerDiv, addQuestionBtn);

            colPointsDiv.appendChild(pointsDiv);
            parentDiv.insertBefore(colPointsDiv, addQuestionBtn);

            questionCount++;
        }
    }
}
function createInputsDiv(inputText, required) {
    var divElement = document.createElement('div');
    divElement.className = "form-floating";

    var inputElement = document.createElement('input');
    inputElement.type = 'text';
    inputElement.className = 'form-control';
    inputElement.id = 'floatingInput';
    inputElement.placeholder = 'text';

    var labelElement = document.createElement('label');
    labelElement.htmlFor = 'floatingInput';
    if (required) {
        ;
        labelElement.innerHTML = inputText;

        var spanElement = document.createElement('span');
        spanElement.className = 'text-danger';
        spanElement.innerHTML = '*'

        $(spanElement).appendTo(labelElement);
    }
    else {
        labelElement.innerHTML = inputText;
    }

    if (divElement && inputElement && labelElement) {
        divElement.appendChild(inputElement);
        divElement.appendChild(labelElement);
    }
    return divElement;
}

My struggle here is to 'Post' these dynamically added inputs from JavaScript to my OnPost() function in the PageModel class because I can't figure out how to send them as parameters.

Ultimately, I'd like to post ALL of the inputs (including the exam inputs such as exam name, etc) together to the database upon pressing the Save button.

I've tried to use the exam model in a foreach loop with a switch case and work with updating the model so I didn't need to use JavaScript.
HTML

Questions

    @if (Model.NewExam.Questions.Count > 0)
    {
        foreach (var q in Model.NewExam.Questions)
        {
            switch (q)
            {
                case OpenQuestion o:
                    //Show inputs here for open question
                    break;
                case MultipleChoiceQuestion m:
                    //Show inputs here for multiple choice
                    break;
                case TrueOrFalseQuestion t:
                    //Show inputs here for true or false
                    break;
            }
        }
    }
    else
    {

There are currently no questions...

    }

PageModel

public class CreateModel : PageModel
    {
        [BindProperty]
        public Exam NewExam { get; set; }
        [BindProperty]
        public string QuestionTypeOption { get; set; }
        public void OnGet()
        {
            NewExam = new Exam
            {
                Id = 25,
                Questions = new List<Question>()
            };
        }
        public IActionResult OnPostAddQuestion()
        {
            switch (QuestionTypeOption)
            {
                case "openquestion":
                    NewExam.Questions.Add(new OpenQuestion());
                    break;
                case "multiplechoice":
                    NewExam.Questions.Add(new MultipleChoiceQuestion());
                    break;
                case "trueorfalse":
                    NewExam.Questions.Add(new TrueOrFalseQuestion());
                    break;
            }
            return RedirectToPage("Create", this.NewExam);
        }
    }

When I click the Add question button it executes the OnPostAddQuestion() in the PageModel.
However the 'NewExam' empties as going through the OnPost function and giving me object reference not set to an instance of an object error because a new instance of the PageModel class is created upon each request.
I could've worked this out by saving this to the database but I think executing a database query after adding each question (which isn't definitive) is requiring a lot of resources.


问:
unable to read data(csv) using pandas in pycharm
My code is:-

```<code>   import pandas as pd
   import numpy as np
   import plotly.express as px
   import plotly.graph_objects as go
   import plotly.io as pio
   import os

    print(os.getcwd())
    os.chdir("//Users//apple//Desktop//Employedata")
    print(os.getcwd())
   pio.templates.default = "plotly_white"
   data = pd.read_csv("/Users/apple/Desktop/Employedata/EmployeeSampleData.csv")
   print(data)
</code>```

It is showing error as follows in the console:-

```<code>    /Users/apple/PycharmProjects/pythonProject4/venv/bin/python /Users/apple     /PycharmProjects/pythonProject4/main.py
    /Users/apple/PycharmProjects/pythonProject4
    /Users/apple/Desktop/Employedata

   Traceback (most recent call last):
   File "/Users/apple/PycharmProjects/pythonProject4/main.py", line 12, in <module>
   data = pd.read_csv("/Users/apple/Desktop/Employedata/EmployeeSampleData.csv")
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/util/_decorators.py", line 211, in wrapper
    return func(*args, **kwargs)
       ^^^^^^^^^^^^^^^^^^^^^
    File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/util/_decorators.py", line 331, in wrapper
      return func(*args, **kwargs)
       ^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 950, in read_csv
      return _read(filepath_or_buffer, kwds)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 605, in _read
        parser = TextFileReader(filepath_or_buffer, **kwds)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1442, in __init__
       self._engine = self._make_engine(f, self.engine)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1753, in _make_engine
     return mapping[engine](f, **self.options)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 79, in __init__
     self._reader = parsers.TextReader(src, **kwds)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "pandas/_libs/parsers.pyx", line 547, in     pandas._libs.parsers.TextReader.__cinit__
     File "pandas/_libs/parsers.pyx", line 636, in       pandas._libs.parsers.TextReader._get_header
    File "pandas/_libs/parsers.pyx", line 852, in pandas._libs.parsers.TextReader._tokenize_rows
    File "pandas/_libs/parsers.pyx", line 1965, in pandas._libs.parsers.raise_parser_error
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 14194:    invalid start byte

   Process finished with exit code 1
</code>```

I unable to resolve it. I do not know what to do.
I am using PyCharm 2022.2.3 with Python 3.11. Also, using mac. If you need further information, please do kindly message me

Thanks.

Body:
My code is:-

   import pandas as pd
   import numpy as np
   import plotly.express as px
   import plotly.graph_objects as go
   import plotly.io as pio
   import os

    print(os.getcwd())
    os.chdir("//Users//apple//Desktop//Employedata")
    print(os.getcwd())
   pio.templates.default = "plotly_white"
   data = pd.read_csv("/Users/apple/Desktop/Employedata/EmployeeSampleData.csv")
   print(data)

It is showing error as follows in the console:-

    /Users/apple/PycharmProjects/pythonProject4/venv/bin/python /Users/apple     /PycharmProjects/pythonProject4/main.py
    /Users/apple/PycharmProjects/pythonProject4
    /Users/apple/Desktop/Employedata

   Traceback (most recent call last):
   File "/Users/apple/PycharmProjects/pythonProject4/main.py", line 12, in <module>
   data = pd.read_csv("/Users/apple/Desktop/Employedata/EmployeeSampleData.csv")
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/util/_decorators.py", line 211, in wrapper
    return func(*args, **kwargs)
       ^^^^^^^^^^^^^^^^^^^^^
    File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/util/_decorators.py", line 331, in wrapper
      return func(*args, **kwargs)
       ^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 950, in read_csv
      return _read(filepath_or_buffer, kwds)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 605, in _read
        parser = TextFileReader(filepath_or_buffer, **kwds)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1442, in __init__
       self._engine = self._make_engine(f, self.engine)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1753, in _make_engine
     return mapping[engine](f, **self.options)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/Users/apple/PycharmProjects/pythonProject4/venv/lib/python3.11/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 79, in __init__
     self._reader = parsers.TextReader(src, **kwds)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "pandas/_libs/parsers.pyx", line 547, in     pandas._libs.parsers.TextReader.__cinit__
     File "pandas/_libs/parsers.pyx", line 636, in       pandas._libs.parsers.TextReader._get_header
    File "pandas/_libs/parsers.pyx", line 852, in pandas._libs.parsers.TextReader._tokenize_rows
    File "pandas/_libs/parsers.pyx", line 1965, in pandas._libs.parsers.raise_parser_error
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 14194:    invalid start byte

   Process finished with exit code 1

I unable to resolve it. I do not know what to do.
I am using PyCharm 2022.2.3 with Python 3.11. Also, using mac. If you need further information, please do kindly message me

Thanks.


问:
Why am I not getting iOS 16.1 as an option for simulator in XCode(13.4.1)? How can I get it?
Simulator options available on Xcode

I'm not able to find anything relatable to this on internet.


问:
Cannot setup the envirorment for ROS2 and try the example
After following the installation tutorial on ROS website (huble hawksbill version) step by step i'm trying to setup the environment for ROS2, but when i run the command
call C:\dev\ros2_humble\local_setup.bat

The answer is this:

"[rti_connext_dds_cmake_module][warning] RTI Connext DDS environment script not found (\resource\scripts\rtisetenv_x64Win64VS2017.bat). RTI Connext DDS will not be available at runtime, unless you already configured PATH manually."

I tried to install RTI Connext DDS separately but the result is the same


问:
Parse data in multiple rows of json strings in Spark Dataframe
I have for example three json's as a string inside a dataframe column:

```<code>df = spark.createDataFrame(
    [
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":[{"key":"value"},{"key":"value"}]}, "data_B" : {"a":"1"}}"""]
        ,
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":{"key":"value"}}, "data_B" : null}"""]
        ,
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":[{"key":"value"},{"key":"value"}]}, "data_B" : [{"a":"1"}, {"a":"2"}]}"""]
    ], ['payload']
)
</code>```

As you can see, the data can have multiple values inside data_A and data_B but can sometimes have nothing (null) or only one value. How to get this data inside one dataframe with a generic schema?

When trying code in this linkit will result in a null because it cannot insert one value inside an arraytype.
https://i.stack.imgur.com/O3Tlu.png

I tried using the solution within this link but it's not working.
Unify schema across multiple rows of json strings in Spark Dataframe

Desired result is to have a column with the 'payload' as a struct field so we can navigate through the data.

```<code>payload:struct
---data_B:array
------element:struct
---------a:string
---header:struct
------name:string
------title:string
---results:struct
------data_A:array
---------element:struct
------------key:string
------elt:array
---------element:struct
------------key:string
---------------test:struct
------------------test2:struct
---------------------elt:array
------------------------element:struct
---------------------------A:long
---------------------------B:long
------test:struct
---------a:struct
------------elt:array
---------------element:array
------------------element:struct
---------------------ab:long
---------b:string
</code>```

Body:
I have for example three json's as a string inside a dataframe column:

df = spark.createDataFrame(
    [
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":[{"key":"value"},{"key":"value"}]}, "data_B" : {"a":"1"}}"""]
        ,
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":{"key":"value"}}, "data_B" : null}"""]
        ,
        ["""{"header":{"title":"ABC123","name":"test"},"results":{"data_A":[{"key":"value"},{"key":"value"}]}, "data_B" : [{"a":"1"}, {"a":"2"}]}"""]
    ], ['payload']
)

As you can see, the data can have multiple values inside data_A and data_B but can sometimes have nothing (null) or only one value. How to get this data inside one dataframe with a generic schema?

When trying code in this linkit will result in a null because it cannot insert one value inside an arraytype.
https://i.stack.imgur.com/O3Tlu.png

I tried using the solution within this link but it's not working.
Unify schema across multiple rows of json strings in Spark Dataframe

Desired result is to have a column with the 'payload' as a struct field so we can navigate through the data.

payload:struct
---data_B:array
------element:struct
---------a:string
---header:struct
------name:string
------title:string
---results:struct
------data_A:array
---------element:struct
------------key:string
------elt:array
---------element:struct
------------key:string
---------------test:struct
------------------test2:struct
---------------------elt:array
------------------------element:struct
---------------------------A:long
---------------------------B:long
------test:struct
---------a:struct
------------elt:array
---------------element:array
------------------element:struct
---------------------ab:long
---------b:string


问:
am i terminating my jsx in my fetch() function the right way?
this is the error i'm getting : " Line 10:78:  Parsing error: Unterminated JSX contents. (10:78)"
i thought it was a bracket missing but to me it looks right , im doing a project for a organisation and this is keeping me behind .

```<code>import React, { createContext, useState } from 'react';

const UserContext = createContext();

const UserProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  const fetch = async (user_name, password) => {

      // Make a request to the login endpoint with the username and password
      const response = await fetch('http://localhost:3500/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_name, password }),
      })
      const data = await response.json();
      if (response.ok) {
        // If the login was successful, set the user in the state.
        setUser(data);
      } else {
        // If the login was unsuccessful, throw an error
        throw new Error(data.message);

      }

  };

  return (
    <UserContext.Provider value={{ user, fetch }}>
      {children}
    </UserContext.Provider>
  );
};

export default { UserContext, UserProvider };
</code>```

this is the code for the login form :

```<code>import React from 'react';
import {useContext, useState} from 'react';
import {Formik} from 'formik';
import {UserContext} from '../../Context/UserContext';
 import {  useNavigate } from 'react-router-dom';

const LoginForm = () => {

    const { fetch } = useContext(UserContext);

    const [user_name, setUsername] = useState('');
    const [password, setPassword] = useState('');

      const handleSubmit = (values, { setSubmitting}) => {
        fetch(values.user_name, values.password);
        setSubmitting(false);
        navigate('/MainGrid')
      };
    const navigate = useNavigate();

    const handleForgotClick = () => {
          navigate('/LoginMessage')
    }

  return (
    <Formik
    initialValues={{user_name: '', password: ''}}
    onSubmit={handleSubmit}
    >
      {({values, isSubmitting, handleChange}) => (
        <section id="loginUser" className="sanctuary-auth-form">
        <div className="row">
          <div className="col p-3 border rounded shadow-sm">
            <div className="sanctuary-auth-form-icon">
              <img className="img-thumbnail rounded-circle mx-auto d-block" src="assets/icons/organisations/icon_organisation_oasis.png" alt="Sancturay Guardian logo"></img>
            </div>
            <h4>Login</h4>
            <form   onSubmit={handleSubmit} style={{minWidth: '30em', maxWidth: '30em'}} >
              <div className="form-floating mb-3">
                <input
                type="text"
                className="form-control form-control"
                name="user_name"
                value={user_name}
                onChange={setUsername(handleChange)}
                required></input>
                <label htmlFor="user_name" aria-label=".form-control">username</label>
              </div>
              <div className="form-floating mb-3">
                <input
                type="password"
                className="form-control form-control"
                name="password"
                value={password}
                onChange={setPassword(handleChange)}
                required>
                </input>
                <label htmlFor="password" aria-label=".form-control">Password</label>
              </div>
              <div className="mb-3 text-end">
                <a className="link-danger" onClick={handleForgotClick} >Forgot login details</a>
              </div>
              <div className="d-grid text-end">
                <button className="btn btn-primary" type="submit" disabled={isSubmitting} >Login</button>
              </div>
            </form>
          </div>
        </div>
      </section>
      )}

  </Formik>

  )
}

export default LoginForm
</code>```

i don't even know why the error is being throwed , some clarity on the why the error is being generated would help me for future reference

Body:
this is the error i'm getting : " Line 10:78:  Parsing error: Unterminated JSX contents. (10:78)"
i thought it was a bracket missing but to me it looks right , im doing a project for a organisation and this is keeping me behind .

import React, { createContext, useState } from 'react';

const UserContext = createContext();

const UserProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  const fetch = async (user_name, password) => {

      // Make a request to the login endpoint with the username and password
      const response = await fetch('http://localhost:3500/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_name, password }),
      })
      const data = await response.json();
      if (response.ok) {
        // If the login was successful, set the user in the state.
        setUser(data);
      } else {
        // If the login was unsuccessful, throw an error
        throw new Error(data.message);

      }

  };

  return (
    <UserContext.Provider value={{ user, fetch }}>
      {children}
    </UserContext.Provider>
  );
};

export default { UserContext, UserProvider };

this is the code for the login form :

import React from 'react';
import {useContext, useState} from 'react';
import {Formik} from 'formik';
import {UserContext} from '../../Context/UserContext';
 import {  useNavigate } from 'react-router-dom';

const LoginForm = () => {

    const { fetch } = useContext(UserContext);

    const [user_name, setUsername] = useState('');
    const [password, setPassword] = useState('');

      const handleSubmit = (values, { setSubmitting}) => {
        fetch(values.user_name, values.password);
        setSubmitting(false);
        navigate('/MainGrid')
      };
    const navigate = useNavigate();

    const handleForgotClick = () => {
          navigate('/LoginMessage')
    }

  return (
    <Formik
    initialValues={{user_name: '', password: ''}}
    onSubmit={handleSubmit}
    >
      {({values, isSubmitting, handleChange}) => (

Login

            <form   onSubmit={handleSubmit} style={{minWidth: '30em', maxWidth: '30em'}} >

                <input
                type="text"
                className="form-control form-control"
                name="user_name"
                value={user_name}
                onChange={setUsername(handleChange)}
                required></input>
                username

                <input
                type="password"
                className="form-control form-control"
                name="password"
                value={password}
                onChange={setPassword(handleChange)}
                required>
                </input>
                Password

                Forgot login details

                <button className="btn btn-primary" type="submit" disabled={isSubmitting} >Login</button>

            </form>

      )}

  </Formik>

  )
}

export default LoginForm

i don't even know why the error is being throwed , some clarity on the why the error is being generated would help me for future reference


问:
Reduce spacing between two x axes
I am trying to produce a graph with an x axis that has two values on each tick. One is a percentage and the other is an absolute. I can do this quite easily by passing in a tuple array into the labels key for an axis.

```<code>const options = {
  ...
  ...
  scales: {
    x: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 700,
      },
      ...
    },
  },
};
</code>```

However, I want these two values to have different font weights, so it seems to me the only way I can achieve this is by having two axes, one underneath the other like so:

```<code>const options = {
  ...
  ...
  scales: {
    x1: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 700,
      },
      ...
    },
    x2: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 400,
      },
      ...
    },
  },
};
</code>```

The only issue now is that the two axes have quite a large gap between them, even when setting the padding of each to 0. With negative padding, it starts to cut off parts of the label text.

Is there any way to reduce the space between these two axes that are side-by-side?

Title: Reduce spacing between two x axes

Body:
I am trying to produce a graph with an x axis that has two values on each tick. One is a percentage and the other is an absolute. I can do this quite easily by passing in a tuple array into the labels key for an axis.

const options = {
  ...
  ...
  scales: {
    x: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 700,
      },
      ...
    },
  },
};

However, I want these two values to have different font weights, so it seems to me the only way I can achieve this is by having two axes, one underneath the other like so:

const options = {
  ...
  ...
  scales: {
    x1: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 700,
      },
      ...
    },
    x2: {
      ...
      labels: ["foo", "bar"],
      ticks: {
        weight: 400,
      },
      ...
    },
  },
};

The only issue now is that the two axes have quite a large gap between them, even when setting the padding of each to 0. With negative padding, it starts to cut off parts of the label text.

Is there any way to reduce the space between these two axes that are side-by-side?


问:
How to get the full error Message from Elasticsearch using Python?
i am trying to get some queries done in Python. However iam getting an runtime error no matter what i try.

I think the full error might be very helpful.
I have read people retrieving the full error message from elasticserach with curl, is there a way to do it with python?


问:
How to exit threads in python program?
How  to exit 2 threads I create using python code? I'm trying to end the program when I type "break" but it doesn't work for me here.

```<code>import socket
import threading
import time

IP = "127.0.0.1"
PORT = 25565

server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind((IP, PORT))
server_sock.listen()
conn, addr = server_sock.accept()

def recv():
    while True:
        income_message = conn.recv(1024)
        print("client: " + income_message.decode())

def send():
    while True:
        message =input("")
        conn.send(message.encode())
        if message == "break":
            break

def main():
    x = threading.Thread(target=recv, args=())
    x.start()
    y = threading.Thread(target=send, args=())
    y.start()

    print("started threads!")
    if not send():
        x.join()
        y.join()
        server_sock.close()
        print("stop")

if __name__ == "__main__":
    main()
</code>```

I thought it will end the program when I type "break" but it still running.

Title: How to exit threads in python program?

Body:
How  to exit 2 threads I create using python code? I'm trying to end the program when I type "break" but it doesn't work for me here.

import socket
import threading
import time

IP = "127.0.0.1"
PORT = 25565

server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind((IP, PORT))
server_sock.listen()
conn, addr = server_sock.accept()

def recv():
    while True:
        income_message = conn.recv(1024)
        print("client: " + income_message.decode())

def send():
    while True:
        message =input("")
        conn.send(message.encode())
        if message == "break":
            break

def main():
    x = threading.Thread(target=recv, args=())
    x.start()
    y = threading.Thread(target=send, args=())
    y.start()

    print("started threads!")
    if not send():
        x.join()
        y.join()
        server_sock.close()
        print("stop")

if __name__ == "__main__":
    main()

I thought it will end the program when I type "break" but it still running.


问:
How to write unit test for BigQuery Java code
Can you help me write the Java unit test cases for increasing the coverage for the below Java code which retrieves the data from the BigQuery using the given query ?

BigQuery bigQueryInst =
                BigQueryOptions.newBuilder().setProjectId(projectId).setCredentials(googleCred.generateCred()).build()
                        .getService();

        String queryResp  = /* Query to be executed */;

        QueryJobConfiguration queryJobConfiguration =                     QueryJobConfiguration.newBuilder(carbonAgriRawDataRespQuery)
                .addPositionalParameter(QueryParameterValue.string(nodeID)).build();

        Job queryJob = bigQueryInst.create(JobInfo.newBuilder(queryJobConfiguration).build());
        queryJob = queryJob.waitFor();

        if (queryJob == null) {
            throw new Exception("Job no longer exists for Carbon Agriculture Raw Data");
        }

        if (queryJob.getStatus().getError() != null) {
            throw new Exception(queryJob.getStatus().getError().toString());
        }

        TableResult result = queryJob.getQueryResults();

        for (FieldValueList row : result.iterateAll()) {

        }
```

I tried to mock the BigQuery instance, Job configuration instance, and Job instance using the key.json. But it resulted in a null pointer exception.

I am expecting a way to do the Unit Testing coverage for the mentioned Java code.

Body:
Can you help me write the Java unit test cases for increasing the coverage for the below Java code which retrieves the data from the BigQuery using the given query ?

BigQuery bigQueryInst =
                BigQueryOptions.newBuilder().setProjectId(projectId).setCredentials(googleCred.generateCred()).build()
                        .getService();

        String queryResp  = /* Query to be executed */;

        QueryJobConfiguration queryJobConfiguration =                     QueryJobConfiguration.newBuilder(carbonAgriRawDataRespQuery)
                .addPositionalParameter(QueryParameterValue.string(nodeID)).build();

        Job queryJob = bigQueryInst.create(JobInfo.newBuilder(queryJobConfiguration).build());
        queryJob = queryJob.waitFor();

        if (queryJob == null) {
            throw new Exception("Job no longer exists for Carbon Agriculture Raw Data");
        }

        if (queryJob.getStatus().getError() != null) {
            throw new Exception(queryJob.getStatus().getError().toString());
        }

        TableResult result = queryJob.getQueryResults();

        for (FieldValueList row : result.iterateAll()) {

        }

I tried to mock the BigQuery instance, Job configuration instance, and Job instance using the key.json. But it resulted in a null pointer exception.

I am expecting a way to do the Unit Testing coverage for the mentioned Java code.


问:
improve search in flutter firebase with multiple parameters (lowcase, contains, is greater than)
I have a search input to look up for my Firebase products.
At the moment it is only working if the Capital case or lower case in both products and search value are matched. It also work if I type only 1 character.
But I would like to improve it.

For example:

if the user does't write exactly the name,

or if the the products contains 2 words and user start to type the second word

How can i achieve that?

```<code>Container(
      height: MediaQuery.of(context).size.height*0.8,
      child: FutureBuilder<QuerySnapshot>(
          future: _services.userRef.doc(_services.getUserID()).collection('Categories')
              .doc(widget.catID).collection('products').orderBy('name')
          .startAt([_searchValue]).endAt(['$_searchValue\uf8ff']).get(),
          builder: (context, snapshot ){
            if (!snapshot.hasData )
              return Center(child: CircularProgressIndicator());{
              final document = snapshot.data?.docs;
              return ListView.builder(shrinkWrap: true,
                  itemCount: document?.length,
                  itemBuilder: (context, index) {
                    return Center(
                      child: Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: ListTile( title: Text(document![index]['name']),
                              onTap: () {
</code>```

Body:
I have a search input to look up for my Firebase products.
At the moment it is only working if the Capital case or lower case in both products and search value are matched. It also work if I type only 1 character.
But I would like to improve it.

For example:

if the user does't write exactly the name,

or if the the products contains 2 words and user start to type the second word

How can i achieve that?

Container(
      height: MediaQuery.of(context).size.height*0.8,
      child: FutureBuilder<QuerySnapshot>(
          future: _services.userRef.doc(_services.getUserID()).collection('Categories')
              .doc(widget.catID).collection('products').orderBy('name')
          .startAt([_searchValue]).endAt(['$_searchValue\uf8ff']).get(),
          builder: (context, snapshot ){
            if (!snapshot.hasData )
              return Center(child: CircularProgressIndicator());{
              final document = snapshot.data?.docs;
              return ListView.builder(shrinkWrap: true,
                  itemCount: document?.length,
                  itemBuilder: (context, index) {
                    return Center(
                      child: Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: ListTile( title: Text(document![index]['name']),
                              onTap: () {


问:
disable and remove pjax functionality fom limesurvey
is it possible to remove pjax functionality from limesurvey? it caused a lot of problems for me, I just want the page load normally</p>


Title: Read VMF1 grid file

Body:
What are the efficient ways to read vmf1 grid file (e.g. VMFG_20221231.H00) using python?

Below is first few lines of vmf1 grid file (VMFG_20221231.H00):

! Version:            1.0
! Source:             D. Landskron, TU Vienna (created: 2022-12-30)
! Data_types:         VMF3 (lat lon ah aw zhd zwd)
! Epoch:              2022 12 31 00 00  0.0
! Scale_factor:       1.e+00
! Range/resolution:   -89.5 89.5 0.5 359.5 1 1
! Comment:            vmf.geo.tuwien.ac.at/trop_products/GRID/1x1/VMF3/VMF3_FC/2022/
 89.5    0.5  0.00115662  0.00056181  2.2824  0.0297
 89.5    1.5  0.00115661  0.00056843  2.2824  0.0298
 89.5    2.5  0.00115661  0.00057441  2.2823  0.0298
 89.5    3.5  0.00115660  0.00057922  2.2823  0.0299
 89.5    4.5  0.00115661  0.00058348  2.2823  0.0299
 89.5    5.5  0.00115661  0.00058729  2.2822  0.0299
 89.5    6.5  0.00115661  0.00059052  2.2822  0.0300
 89.5    7.5  0.00115661  0.00059295  2.2822  0.0300
 89.5    8.5  0.00115662  0.00059456  2.2821  0.0300
 89.5    9.5  0.00115662  0.00059563  2.2821  0.0300
 89.5   10.5  0.00115662  0.00059638  2.2821  0.0300
 89.5   11.5  0.00115662  0.00059697  2.2820  0.0300
 89.5   12.5  0.00115662  0.00059671  2.2820  0.0300
 89.5   13.5  0.00115662  0.00059567  2.2820  0.0300
 89.5   14.5  0.00115663  0.00059444  2.2820  0.0300


问:
Woocommerce API documentation for Postman
Is there any Woocommerce API documentation that I can import to Postman with one click? I have this documentation Woo API but this is not possible to import in Postman.</p>


问:
scipy.optimize.minimize stop after n iterations without being better
I am looking to stop the minimization of scipy when there are no improvment in score after n iterations.

Like a counter that reset when the scipy minimization iteration find a best solution (minimum of score). When the counter go over a value, it stop searching and return the result.

There are the parameter maxiter in options but it take the total number of iterations insteed of number of iterations without progress.


问:
git : how to merge a file from another repo (with different file path)?
I created a NEW_REPO. Same code as OLD_REPO but with different arborescence.

I need to merge

old/path/to/my_file.txt from the OLD_REPO (my_branch) into

newly/added/folder/old/path/to/my_file.txt of the NEW_REPO (my_branch)

What I've done (from the NEW_REPO) :

```<code>git remote add OLD_REPO https://...
git fetch OLD_REPO <commit-sha>
git co -b my_branch
</code>```

and then

```<code>git checkout <commit-sha> -- my_file.txt

error: pathspec 'my_file.txt' did not match any file(s) known to git
</code>```

I guess I need to find a way to indicate the path to my_file but I don't know how to do it, hence this question.

So : How to merge a file from another repo, with different file path ?

Thanks !

Body:
I created a NEW_REPO. Same code as OLD_REPO but with different arborescence.

I need to merge

old/path/to/my_file.txt from the OLD_REPO (my_branch) into

newly/added/folder/old/path/to/my_file.txt of the NEW_REPO (my_branch)

What I've done (from the NEW_REPO) :

git remote add OLD_REPO https://...
git fetch OLD_REPO <commit-sha>
git co -b my_branch

and then

git checkout <commit-sha> -- my_file.txt

error: pathspec 'my_file.txt' did not match any file(s) known to git

I guess I need to find a way to indicate the path to my_file but I don't know how to do it, hence this question.

So : How to merge a file from another repo, with different file path ?

Thanks !


问:
JPackage Unable to Launch JVM - Circular loading of URL stream handler providers detected
After running jpackage on my JavaFX application using following command:

.\jpackage.exe
--input C:\Users\My\Documents\NetBeansProjects\MyFX\target\
--dest C:\Users\My\Documents\NetBeansProjects\MyFX\
--name "MyFX"
--main-jar C:\Users\My\Documents\NetBeansProjects\MyFX\target\MyFX-2.0.jar
--main-class my.myfx.App
--module-path 'C:\Program Files\Java\jmods\\'
--add-modules javafx.controls,javafx.fxml,java.sql --win-console
```
<p>I'm getting error on launching the program:
<code>Unable to launch JVM</code></p>
<p>Error on console:</p>
```Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.Error: Circular loading of URL stream handler providers detected
at java.base/java.net.URL.lookupViaProviders(Unknown Source)
at java.base/java.net.URL.getURLStreamHandler(Unknown Source)
at java.base/java.net.URL.<init>(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolveFile(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolve(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.parseClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.getClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getLoader(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$1.next(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$1.hasMoreElements(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader$1.hasNext(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader$1.hasMoreElements(Unknown Source)
at java.base/java.lang.CompoundEnumeration.next(Unknown Source)
at java.base/java.lang.CompoundEnumeration.hasMoreElements(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.nextProviderClass(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(Unknown Source)
at java.base/java.util.ServiceLoader$2.hasNext(Unknown Source)
at java.base/java.util.ServiceLoader$3.hasNext(Unknown Source)
at java.base/java.net.URL$1.getNext(Unknown Source)
at java.base/java.net.URL$1.hasNext(Unknown Source)
at java.base/java.net.URL$2.run(Unknown Source)
at java.base/java.net.URL$2.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at java.base/java.net.URL.lookupViaProviders(Unknown Source)
at java.base/java.net.URL.getURLStreamHandler(Unknown Source)
at java.base/java.net.URL.<init>(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolveFile(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolve(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.parseClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.getClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getLoader(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getResource(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
at java.base/sun.launcher.LauncherHelper.loadMainClass(Unknown Source)
at java.base/sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
```
<p>Failed to launch JVM</p>
<p>Are there any more libraries to add? any more JMods? What does "Circular loading of URL streams" have to do with this?</p>
<p>EDIT: <strong>MyFX.App</strong></p>
<pre class="lang-java prettyprint-override"><code>package my.myfx;
    public static javafx.scene.image.Image loadingImg,tickImg,appIconImg;
    public static javafx.scene.image.ImageView loading,tick,appIcon;
    private static javafx.scene.Scene scene;
    @Override
    public void start(javafx.stage.Stage stage) throws java.io.IOException {
        try{
            appIcon=new ImageView();
            appIconImg=new Image(getClass().getResource("icons/icon.png").toURI().toString());
            appIcon.setImage(appIconImg);
            loading=new ImageView();
            loadingImg=new Image(getClass().getResource("icons/loading.gif").toURI().toString());
            loading.setImage(loadingImg);
            javafx.concurrent.Task<Exception>work=new javafx.concurrent.Task<>(){
                @Override
                protected Exception call(){
                    try{
                        Thread.sleep(500);  //Simulate IO operation
                    }catch(Exception ex){
                        return ex;
                    }
                    return null;
                }
            };
            new Thread(work).start();
            scene = new javafx.scene.Scene(new javafx.fxml.FXMLLoader(getClass().getResource("fxml/main.fxml")).load(), 640, 480);
            stage.setScene(scene);
            stage.setMaximized(true);
            stage.setTitle("MyFX");
            stage.getIcons().add(appIconImg);
            stage.show();
            work.setOnSucceeded(e->{
                try{
                    if(work.get()==null){
                        System.out.println("Folders initialized");
                        tick=new ImageView();
                        tickImg=new Image(getClass().getResource("icons/tick.png").toURI().toString(),true);
                        tick.setImage(tickImg);
                    }else{
                       System.out.println(work.get());
                    }
                }catch(Exception ex){
                    System.out.println(ex);
                }
            });
            stage.setOnCloseRequest((javafx.stage.WindowEvent t) -> {
                Platform.exit();
                System.exit(0);
            });
        }catch(Exception ex){
            System.out.println(ex);
        }
    }

    public static void main(String[] args) {
        launch();
    }

    static void setRoot(){
        try{
            scene.setRoot(new javafx.fxml.FXMLLoader(App.class.getResource("fxml/main.fxml")).load());
        }catch(Exception ex){
            System.out.println(ex);
        }
    }
</code>```

This also contains some functions but they're mostly getters for other classes

Body:
After running jpackage on my JavaFX application using following command:

.\jpackage.exe
--input C:\Users\My\Documents\NetBeansProjects\MyFX\target\
--dest C:\Users\My\Documents\NetBeansProjects\MyFX\
--name "MyFX"
--main-jar C:\Users\My\Documents\NetBeansProjects\MyFX\target\MyFX-2.0.jar
--main-class my.myfx.App
--module-path 'C:\Program Files\Java\jmods\\'
--add-modules javafx.controls,javafx.fxml,java.sql --win-console

I'm getting error on launching the program:
Unable to launch JVM

Error on console:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.Error: Circular loading of URL stream handler providers detected
at java.base/java.net.URL.lookupViaProviders(Unknown Source)
at java.base/java.net.URL.getURLStreamHandler(Unknown Source)
at java.base/java.net.URL.<init>(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolveFile(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolve(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.parseClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.getClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getLoader(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$1.next(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$1.hasMoreElements(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader$1.hasNext(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader$1.hasMoreElements(Unknown Source)
at java.base/java.lang.CompoundEnumeration.next(Unknown Source)
at java.base/java.lang.CompoundEnumeration.hasMoreElements(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.nextProviderClass(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(Unknown Source)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(Unknown Source)
at java.base/java.util.ServiceLoader$2.hasNext(Unknown Source)
at java.base/java.util.ServiceLoader$3.hasNext(Unknown Source)
at java.base/java.net.URL$1.getNext(Unknown Source)
at java.base/java.net.URL$1.hasNext(Unknown Source)
at java.base/java.net.URL$2.run(Unknown Source)
at java.base/java.net.URL$2.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at java.base/java.net.URL.lookupViaProviders(Unknown Source)
at java.base/java.net.URL.getURLStreamHandler(Unknown Source)
at java.base/java.net.URL.<init>(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolveFile(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.tryResolve(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.parseClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath$JarLoader.getClassPath(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getLoader(Unknown Source)
at java.base/jdk.internal.loader.URLClassPath.getResource(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(Unknown Source)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
at java.base/sun.launcher.LauncherHelper.loadMainClass(Unknown Source)
at java.base/sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

Failed to launch JVM

Are there any more libraries to add? any more JMods? What does "Circular loading of URL streams" have to do with this?

EDIT: MyFX.App

package my.myfx;
    public static javafx.scene.image.Image loadingImg,tickImg,appIconImg;
    public static javafx.scene.image.ImageView loading,tick,appIcon;
    private static javafx.scene.Scene scene;
    @Override
    public void start(javafx.stage.Stage stage) throws java.io.IOException {
        try{
            appIcon=new ImageView();
            appIconImg=new Image(getClass().getResource("icons/icon.png").toURI().toString());
            appIcon.setImage(appIconImg);
            loading=new ImageView();
            loadingImg=new Image(getClass().getResource("icons/loading.gif").toURI().toString());
            loading.setImage(loadingImg);
            javafx.concurrent.Task<Exception>work=new javafx.concurrent.Task<>(){
                @Override
                protected Exception call(){
                    try{
                        Thread.sleep(500);  //Simulate IO operation
                    }catch(Exception ex){
                        return ex;
                    }
                    return null;
                }
            };
            new Thread(work).start();
            scene = new javafx.scene.Scene(new javafx.fxml.FXMLLoader(getClass().getResource("fxml/main.fxml")).load(), 640, 480);
            stage.setScene(scene);
            stage.setMaximized(true);
            stage.setTitle("MyFX");
            stage.getIcons().add(appIconImg);
            stage.show();
            work.setOnSucceeded(e->{
                try{
                    if(work.get()==null){
                        System.out.println("Folders initialized");
                        tick=new ImageView();
                        tickImg=new Image(getClass().getResource("icons/tick.png").toURI().toString(),true);
                        tick.setImage(tickImg);
                    }else{
                       System.out.println(work.get());
                    }
                }catch(Exception ex){
                    System.out.println(ex);
                }
            });
            stage.setOnCloseRequest((javafx.stage.WindowEvent t) -> {
                Platform.exit();
                System.exit(0);
            });
        }catch(Exception ex){
            System.out.println(ex);
        }
    }

    public static void main(String[] args) {
        launch();
    }

    static void setRoot(){
        try{
            scene.setRoot(new javafx.fxml.FXMLLoader(App.class.getResource("fxml/main.fxml")).load());
        }catch(Exception ex){
            System.out.println(ex);
        }
    }

This also contains some functions but they're mostly getters for other classes


问:
select midi device in java
In my program it is necessary to be able to select the midi device in java.
I have tried using another sequencer that i got from MidiSystem.getDevice().

Simply using setSequence() and starting the sequencer were without success however (i.e no sound).

I'm guessing that I somehow need to connect a Sequencer with a Synthesizer.

How can I do this properly?

ContentLicense: CC BY-SA 3.0

Title: select midi device in java