问:
ImportError: cannot import name 'COMError' from '_ctypes' (Speak function)
I have been trying to create a desktop assistant and trying to get it to speak. How can this error be fixed?
I have also tried commands like:
pip3 install pyttsx3
pip3 uninstall pyttsx3
pip3 install pyttsx3=.6
pip3 install pypiwin32

but nothing seemed to work

```<code>  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
          ~~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/weakref.py", line 136, in __getitem__
    o = self.data[key]()
        ~~~~~~~~~^^^^^
KeyError: 'sapi5'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/simrankataria/Desktop/test.py", line 2, in <module>
    Assistant= pyttsx3.init('sapi5')
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/drivers/sapi5.py", line 1, in <module>
    import comtypes.client  # Importing comtypes.client will make the gen subpackage
    ^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/comtypes/__init__.py", line 28, in <module>
    from _ctypes import COMError
ImportError: cannot import name 'COMError' from '_ctypes' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload/_ctypes.cpython-311-darwin.so)
</code>```

I am trying to create an AI but I am stuck with this error.
my code:

```<code>import pyttsx3
Assistant= pyttsx3.init('sapi5')
voices = Assistant.getProperty('voices')
print(voices)
Assistant.setProperty('voices',voices[1].id)

def Speak(audio):
    print("  ")
    Assistant.say(audio)
    print("  ")
    Assistant.runAndWait()

Speak("Blah")
</code>```

Body:
I have been trying to create a desktop assistant and trying to get it to speak. How can this error be fixed?
I have also tried commands like:
pip3 install pyttsx3
pip3 uninstall pyttsx3
pip3 install pyttsx3=.6
pip3 install pypiwin32

but nothing seemed to work

  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
          ~~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/weakref.py", line 136, in __getitem__
    o = self.data[key]()
        ~~~~~~~~~^^^^^
KeyError: 'sapi5'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/simrankataria/Desktop/test.py", line 2, in <module>
    Assistant= pyttsx3.init('sapi5')
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyttsx3/drivers/sapi5.py", line 1, in <module>
    import comtypes.client  # Importing comtypes.client will make the gen subpackage
    ^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/comtypes/__init__.py", line 28, in <module>
    from _ctypes import COMError
ImportError: cannot import name 'COMError' from '_ctypes' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload/_ctypes.cpython-311-darwin.so)

I am trying to create an AI but I am stuck with this error.
my code:

import pyttsx3
Assistant= pyttsx3.init('sapi5')
voices = Assistant.getProperty('voices')
print(voices)
Assistant.setProperty('voices',voices[1].id)

def Speak(audio):
    print("  ")
    Assistant.say(audio)
    print("  ")
    Assistant.runAndWait()

Speak("Blah")


来源: stackexchange

问:
How to make a cube in Jimp?
I am using Jimp and I would like to know if it is possible to make a cube like the one in the image.

Here's an image of what I want to have

I haven't tried anything because I don't know where to start.

ContentLicense: CC BY-SA 4.0

Title: How to make a cube in Jimp?


问:
after deploy, fcm alert function is not working... java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified
I made alert service using FCM, it works fine in my local server. but after I deployed my server in ec2, trying alert function on ec2 app gives me this error :

```<code>[ient-SecureIO-1] o.a.t.websocket.pojo.PojoEndpointBase    : No error handling configured for [springboot.utils.WebsocketClientEndpoint] and the following error occurred

java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified
</code>```

Reading the error message, i guess that there's no token in my server.

In notification.js, I'm trying to get token and request POST to '/register'

```<code>const firebaseModule = (function () {
    async function init() {
        // Your web app's Firebase configuration
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('/firebase-messaging-sw.js')
                    .then(registration => {
                        var firebaseConfig = {
                              configuration Information

                        };

                        // Initialize Firebase
                        console.log("firebase Initialization");
                        firebase.initializeApp(firebaseConfig);

                        // Show Notification Dialog
                        const messaging = firebase.messaging();
                        messaging.requestPermission()
                        .then(function() {
                            console.log("Permission granted to get token");
                            return messaging.getToken();
                        })
                        .then(async function(token) {
                            console.log("Token: ", token);
                            await fetch('/register', { method: 'post', body: token })
                            messaging.onMessage(payload => {
                                const title = payload.notification.title
                                const options = {
                                    body : payload.notification.body
                                }
                                navigator.serviceWorker.ready.then(registration => {
                                    registration.showNotification(title, options);
                                })
                            })
                        })
                        .catch(function(err) {
                            console.log("Error Occured : " +err );
                        })
                    })
            })
        }
    }
</code>```

And by debugging it by console.log(), I found out that code is stopped before "if ('serviceWorker' in navigator) {"

So I need to make it proceed. But to be honest, it's been a while since i made this function, and I don't know almost anything about Javascript. I don't even know what navigator means(I googled it, but couldn't find clear answer) I'm having trouble figuring out what is wrong and how can I fix it. Can someone help me??

Body:
I made alert service using FCM, it works fine in my local server. but after I deployed my server in ec2, trying alert function on ec2 app gives me this error :

[ient-SecureIO-1] o.a.t.websocket.pojo.PojoEndpointBase    : No error handling configured for [springboot.utils.WebsocketClientEndpoint] and the following error occurred

java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified

Reading the error message, i guess that there's no token in my server.

In notification.js, I'm trying to get token and request POST to '/register'

const firebaseModule = (function () {
    async function init() {
        // Your web app's Firebase configuration
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('/firebase-messaging-sw.js')
                    .then(registration => {
                        var firebaseConfig = {
                              configuration Information

                        };

                        // Initialize Firebase
                        console.log("firebase Initialization");
                        firebase.initializeApp(firebaseConfig);

                        // Show Notification Dialog
                        const messaging = firebase.messaging();
                        messaging.requestPermission()
                        .then(function() {
                            console.log("Permission granted to get token");
                            return messaging.getToken();
                        })
                        .then(async function(token) {
                            console.log("Token: ", token);
                            await fetch('/register', { method: 'post', body: token })
                            messaging.onMessage(payload => {
                                const title = payload.notification.title
                                const options = {
                                    body : payload.notification.body
                                }
                                navigator.serviceWorker.ready.then(registration => {
                                    registration.showNotification(title, options);
                                })
                            })
                        })
                        .catch(function(err) {
                            console.log("Error Occured : " +err );
                        })
                    })
            })
        }
    }

And by debugging it by console.log(), I found out that code is stopped before "if ('serviceWorker' in navigator) {"

So I need to make it proceed. But to be honest, it's been a while since i made this function, and I don't know almost anything about Javascript. I don't even know what navigator means(I googled it, but couldn't find clear answer) I'm having trouble figuring out what is wrong and how can I fix it. Can someone help me??


问:
Indexed records are getting deleted in solr. What could be the reason?
Indexed records are getting deleted in Solr 7.7.2 version. This is happening only in 1 instance.
There is no specific pattern when it is getting deleted. In 18000 records, sometimes around 2000 or 8000 are remaining after deletion. Physical memory is 95% used. No out of memory error.
No programmatical scheduler or activity is happening during this deletion. Please suggest

I tried re-indexing multiple times, but again getting deleted at unknown time. Sometimes it is 1 day, sometimes it is 3 days or more and no specific pattern.
Tried checking logs, nothing found suspicious (no memory error)


问:
PyInstaller Error Loading Python DLL: ~python27.dll (error code 14001)
My program uses "Pyinstaller" to build .py files via generator (Similar structure to auto-py-to-exe)

However, the version I use to make my program work on windows xp is low.

```<code>python 2.7.18
pyinstaller 3.2.1
</code>```

On my PC it creates and runs fine. But the problem is it doesn't run on other PCs (e.g. VMs).
On the other PC the generator runs fine and the spawn function works fine.

Program information:

Generator (.exe)

python 27, Eel

Build with Pyinstaller 3.2.1

program (.exe)

python 27, pyside 1.2.2

Built with Pyinstaller 3.2.1 and Pyarmor 7.6.0

Program flow:

Generator > build program.py with pyarmor (+ third party program(.exe), config file etc) > generate program (.exe)

Build Command

```<code>pyarmor pack --clean -O ./output -e " --icon some.ico -w --onefile --add-data xxx;xx --paths '..\venv\Lib\site-packages'" -n program program.py
</code>```

When executing the created program.exe, the following error occurs.

```<code>Error loading Python DLL:
c:\~~~\AppData\Local\Temp\_MEIXXX\python27.dll (error code 14001)
</code>```

Can you tell me what you know about this error or why it is happening? (I can't figure out why it happens, so I can't solve it.)

Body:
My program uses "Pyinstaller" to build .py files via generator (Similar structure to auto-py-to-exe)

However, the version I use to make my program work on windows xp is low.

python 2.7.18
pyinstaller 3.2.1

On my PC it creates and runs fine. But the problem is it doesn't run on other PCs (e.g. VMs).
On the other PC the generator runs fine and the spawn function works fine.

Program information:

Generator (.exe)

python 27, Eel

Build with Pyinstaller 3.2.1

program (.exe)

python 27, pyside 1.2.2

Built with Pyinstaller 3.2.1 and Pyarmor 7.6.0

Program flow:

Generator > build program.py with pyarmor (+ third party program(.exe), config file etc) > generate program (.exe)

Build Command

pyarmor pack --clean -O ./output -e " --icon some.ico -w --onefile --add-data xxx;xx --paths '..\venv\Lib\site-packages'" -n program program.py

When executing the created program.exe, the following error occurs.

Error loading Python DLL:
c:\~~~\AppData\Local\Temp\_MEIXXX\python27.dll (error code 14001)

Can you tell me what you know about this error or why it is happening? (I can't figure out why it happens, so I can't solve it.)


问:
Visual studio server explorer server name could not be found
Found the feature, watched some guides and decided to start using data connections in my app. The problem is that db server is on the remote machine, and I can't connect to my server using ip address.

When I try to add new server it just says: server name "192.168.1.3" could not be found.

Really can't find much infomration about how does server connections works. I assume it uses ssh to connect(correct me if i'm wrong).

The server is 100% responding, can do ssh connection. Credentials are also fine.
Maybe the format is wrong, check this out:
image

Tried fiddler to figure out what's wrong, but it doesn't capture the requests.
Tried wireshark, found 2 pings of port 137, request size doesn't change depending on input data length, so it's nothing like login.

packages screenshot
(only 1 ping, second is similar)

Am I doing something wrong? Maybe there are some alternatives? I can and do connect to my db using regular connection string, but seems like data connections in vs adds more flexibility.


问:
How to run runnable cells in vscode on a remote instance (GCP instance in my case)
I am trying to run a runnable cell in vs code, which is connected currently to a GCP instance. When I try to run a runnable cell in local, it works fine, but not on any remote instance. I get the same error while trying to run a jupyter notebook in vscode with remote instance (when not running on the browser)

I tried making a runnable cell in vscode in Python with #%% but it doesn't do anything.
I tried typing code in the interactive window and it gives me the error:
Failed to start the Kernel. View Jupyter log for further details.


问:
Kafka java.lang.ClassNotFoundException: io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe
Have problem with Kafka, error

05-Jan-2023 11:19:47.532 SEVERE [http-nio-8080-exec-32] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jpublish] in context with path [/DS] threw exception [Servlet execution threw an exception] with root cause java.lang.ClassNotFoundException:
io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe

```<code>Properties props = new Properties();
props.put("bootstrap.servers", url);
props.put("linger.ms", 1);
props.put("max.block.ms", 10000);
props.put("group.id", "group");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSchemaSerializer.class.getName());
props.put(KafkaJsonSchemaSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081");

Producer<String, Payment> producer = new KafkaProducer<String, Payment>(props);
ProducerRecord<String, Payment> record = new ProducerRecord<String, Payment>(topic, uuid, message);

producer.send(record);

producer.close();
</code>```

lib kafka on project

class io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe i can import and no error

any suggest ?

already tried including kafka-serde-tools from link, but not working

Body:
Have problem with Kafka, error

05-Jan-2023 11:19:47.532 SEVERE [http-nio-8080-exec-32] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jpublish] in context with path [/DS] threw exception [Servlet execution threw an exception] with root cause java.lang.ClassNotFoundException:
io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe

Properties props = new Properties();
props.put("bootstrap.servers", url);
props.put("linger.ms", 1);
props.put("max.block.ms", 10000);
props.put("group.id", "group");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaJsonSchemaSerializer.class.getName());
props.put(KafkaJsonSchemaSerializerConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081");

Producer<String, Payment> producer = new KafkaProducer<String, Payment>(props);
ProducerRecord<String, Payment> record = new ProducerRecord<String, Payment>(topic, uuid, message);

producer.send(record);

producer.close();

lib kafka on project

class io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe i can import and no error

any suggest ?

already tried including kafka-serde-tools from link, but not working


问:
Dynamic Form created from Combobox that chooses between two queries related to two tables
I have a form for a driver where the driver picks up students at home and drops students off at school in any order:

Picks up Student1
Drops off Student 1
Picks up Student 2
Picks up Student 3
Drops off Students 2 and 3 at the same school.

What I am trying to do is have a combobox1 that makes a choice between a student or choice of school.  The choice relates to a record set from 1 of 2 tables - Student or School.

If student is chosen combobox2 allows a search of all students by their last name and related records and fills attached txtfields

If school is chosen combobox2 allows a search of all schools and related records and fills related txtfields.

In the picture the top half is working correctly other than the choice made for student in the combobox in the upper left hand corner.  The bottom half isn't working at all.  Can anyone help me with the selection of a query that populates a second combobox?  I have done a lot of research, but I haven't been able to put it together even in an example with a very small database and a form with only a few txtboxes.

Thanks for your consideration,

Aaron J

I tried using If statements with Access SQL.  If combobox 1 = "Student" Then Select Values From tblStudent  Elseif combobox1 = "School" Then Select Values From tblSchool.


问:
YAML header not producing desired HTML output
My YAML header syntax is not producing the HTML output I'm trying to achieve: a floating table of contents and the cerulean theme. Also, my output shows the actual YAML code. In addition, I need to insert a space before the first set of dashes, but I don't know why. I'm trying to follow other examples to no success.   I'm new to R and need help. Thank you!

This is the syntax I am using:

---
title: "Cyclistic Bike-Share Analysis Case Study"
author: "Elaine Sanchez Wilber"
date: "December 2022"
output:
  html_document:
    toc: TRUE
    toc_float: TRUE
    theme: cerulean
---
```

output page looks like this

Body:
My YAML header syntax is not producing the HTML output I'm trying to achieve: a floating table of contents and the cerulean theme. Also, my output shows the actual YAML code. In addition, I need to insert a space before the first set of dashes, but I don't know why. I'm trying to follow other examples to no success.   I'm new to R and need help. Thank you!

This is the syntax I am using:

---
title: "Cyclistic Bike-Share Analysis Case Study"
author: "Elaine Sanchez Wilber"
date: "December 2022"
output:
  html_document:
    toc: TRUE
    toc_float: TRUE
    theme: cerulean
---

output page looks like this


问:
power bi data flow refresh failed Error: An internal error occurred
I have been trying to refresh my dataflow which consists of 6 million rows and around 500 columns I am a premium user this data flow takes around 2 hours and 20 min and then gets failed error mentioned below  my data source is MySQL
Error: An internal error occurred.. RootActivityId = 01290be1-c38e-4bad-8a49-d80c0000ab75.Param1 = Access to the path 'C:\WINDOWS\ServiceProfiles\PBIEgwService\AppData\Local\Microsoft\On-premises data gateway\Spooler\2f6805d9-bbd9-47f4-9fdc-32f67123cc48.1999' is denied. [DM_ErrorDetailNameCode_UnderlyingErrorMessage]=Access to the path 'C:\WINDOWS\ServiceProfiles\PBIEgwService\AppData\Local\Microsoft\On-premises data gateway\Spooler\2f6805d9-bbd9-47f4-9fdc-32f67123cc48.1999' is denied. [DM_ErrorDetailNameCode_UnderlyingHResult]=-2147024891 [InnerType]=UnauthorizedAccessException Access to the path 'C:\WINDOWS\ServiceProfiles\PBIEgwService\AppData\Local\Microsoft\On-premises data gateway\Spooler\2f6805d9-bbd9-47f4-9fdc-32f67123cc48.1999' is denied. [GatewayPipelineErrorCode]=DM_GWPipeline_UnknownError [ErrorShortName]=GatewayClientErrorResponseException[GatewayId=1832410]/Wrapped(UnauthorizedAccessException)[HResult=-2147024891] [ExceptionErrorShortName]=GatewayClientErrorResponseException[GatewayId=1832410] Request ID: 2687c3bc-f535-7f31-fd7c-327b08268155.</p>


问:
kafka brokers cannot start because of EventHandler fail with create partition topic
i'm running with kafka 3.2.0 with kraft mode
when i restart the kafka brokers, the brokers keep fatal start up
it keep throwing the same error log

```<code>2023-01-05 04:36:00,267 - ERROR [EventHandler:Logging@76] - [BrokerMetadataPublisher id=1] Error publishing broker metadata at OffsetAndEpoch(offset=1284527, epoch=5864)
org.apache.kafka.common.errors.InconsistentTopicIdException: Tried to assign topic ID aCqb9NV2QJOd7_4ELWo4pg to log for topic partition public.task_assignment-2,but log already contained topic ID 5iPMzQEuTXCk1-RHLyrRig
2023-01-05 04:36:00,268 - INFO  [main:Logging@66] - [BrokerServer id=1] Transition from STARTING to STARTED
2023-01-05 04:36:00,285 - ERROR [main:MarkerIgnoringBase@159] - [BrokerServer id=1] Fatal error during broker startup. Prepare to shutdown
java.util.concurrent.ExecutionException:org.apache.kafka.common.errors.InconsistentTopicIdException: Tried to assign topic ID aCqb9NV2QJOd7_4ELWo4pg to log for topic partition public.task_assignment-2,but log already contained topic ID 5iPMzQEuTXCk1-RHLyrRig
    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
    at kafka.server.BrokerServer.startup(BrokerServer.scala:426)
    at kafka.server.KafkaRaftServer.$anonfun$startup$2(KafkaRaftServer.scala:114)
    at kafka.server.KafkaRaftServer.$anonfun$startup$2$adapted(KafkaRaftServer.scala:114)
    at scala.Option.foreach(Option.scala:437)
    at kafka.server.KafkaRaftServer.startup(KafkaRaftServer.scala:114)
    at kafka.Kafka$.main(Kafka.scala:109)
    at kafka.Kafka.main(Kafka.scala)

</code>```

expect that kafka brokers can start up as normal

edit: i deleted the topic public.task_assignment before
edit: it seem relay the topic metadata

```<code>2023-01-05 11:04:48,234 - ERROR [EventHandler:EventQueue$FailureLoggingEvent@60] - [BrokerMetadataListener id=1] Unexpected error handling HandleCommitsEvent
java.lang.RuntimeException: Unable to delete topic with id MXaqZEBbQDOl5zzVOL3ILw: no such topic found.
    at org.apache.kafka.image.TopicsDelta.replay(TopicsDelta.java:104)
    at org.apache.kafka.image.MetadataDelta.replay(MetadataDelta.java:250)
    at org.apache.kafka.image.MetadataDelta.replay(MetadataDelta.java:186)
    at kafka.server.metadata.BrokerMetadataListener.$anonfun$loadBatches$3(BrokerMetadataListener.scala:212)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at kafka.server.metadata.BrokerMetadataListener.kafka$server$metadata$BrokerMetadataListener$$loadBatches(BrokerMetadataListener.scala:204)
    at kafka.server.metadata.BrokerMetadataListener$HandleCommitsEvent.run(BrokerMetadataListener.scala:111)
    at org.apache.kafka.queue.KafkaEventQueue$EventContext.run(KafkaEventQueue.java:121)
    at org.apache.kafka.queue.KafkaEventQueue$EventHandler.handleEvents(KafkaEventQueue.java:200)
    at org.apache.kafka.queue.KafkaEventQueue$EventHandler.run(KafkaEventQueue.java:173)
    at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

my current kafka broker config with kraft mode

```<code>############################# Server Basics #############################

process.roles=broker,controller
node.id=1

# The connect string for the controller quorum
controller.quorum.voters=1@kafka-0.kafka-svc-headless.kafka-ns.svc.cluster.local:9093,2@kafka-1.kafka-svc-headless.kafka-ns.svc.cluster.local:9093,3@kafka-2.kafka-svc-headless.kafka-ns.svc.cluster.local:9093

############################# Socket Server Settings #############################

listeners=PLAINTEXT://10.72.9.205:9092,CONTROLLER://10.72.9.205:9093
inter.broker.listener.name=PLAINTEXT
advertised.listeners=PLAINTEXT://10.72.9.205:9092
controller.listener.names=CONTROLLER

listener.security.protocol.map=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/kafka/data/1

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Flush Policy #############################

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################
log.retention.hours=168

#log.retention.bytes=1073741824
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000

svc.service.port.voter=9093
url.path=kafka/3.2.0/kafka_2.13-3.2.0.tgz
exporter.kafka.service.port.metrics=9308
ui.port=tcp://10.76.7.168:80
svc.port.9093.tcp=tcp://10.76.6.196:9093
exporter.kafka.port=tcp://10.76.0.48:9308
ui.port.80.tcp=tcp://10.76.7.168:80
svc.service.port.client=9092
svc.port.9092.tcp=tcp://10.76.6.196:9092
ui.port.80.tcp.addr=10.76.7.168
svc.port.9092.tcp.proto=tcp
connect.service.host=10.76.0.215
replica.fetch.max.bytes=10485760
exporter.kafka.port.9308.tcp=tcp://10.76.0.48:9308
exporter.kafka.port.9308.tcp.addr=10.76.0.48
exporter.kafka.port.9308.tcp.proto=tcp
svc.port.9092.tcp.port=9092
ui.port.80.tcp.proto=tcp
ui.service.host=10.76.7.168
heap.opts=-Xms768M -Xmx768M
svc.service.host=10.76.6.196
message.max.bytes=10485760
svc.port.9093.tcp.proto=tcp
connect.port.8083.tcp=tcp://10.76.0.215:8083
connect.service.port.client=8083
svc.port.9093.tcp.addr=10.76.6.196
connect.port=tcp://10.76.0.215:8083
exporter.kafka.service.port=9308
svc.port.9093.tcp.port=9093
connect.port.8083.tcp.proto=tcp
zookeeper.connect=
ui.service.port=80
exporter.kafka.port.9308.tcp.port=9308
ui.service.port.http=80
svc.service.port=9092
exporter.kafka.service.host=10.76.0.48
auto.create.topics.enable=false
connect.port.8083.tcp.port=8083
svc.port=tcp://10.76.6.196:9092
data=/kafka/data
connect.port.8083.tcp.addr=10.76.0.215
connect.service.port=8083
ui.port.80.tcp.port=80
svc.port.9092.tcp.addr=10.76.6.196
broker.id=1
</code>```

Body:
i'm running with kafka 3.2.0 with kraft mode
when i restart the kafka brokers, the brokers keep fatal start up
it keep throwing the same error log

2023-01-05 04:36:00,267 - ERROR [EventHandler:Logging@76] - [BrokerMetadataPublisher id=1] Error publishing broker metadata at OffsetAndEpoch(offset=1284527, epoch=5864)
org.apache.kafka.common.errors.InconsistentTopicIdException: Tried to assign topic ID aCqb9NV2QJOd7_4ELWo4pg to log for topic partition public.task_assignment-2,but log already contained topic ID 5iPMzQEuTXCk1-RHLyrRig
2023-01-05 04:36:00,268 - INFO  [main:Logging@66] - [BrokerServer id=1] Transition from STARTING to STARTED
2023-01-05 04:36:00,285 - ERROR [main:MarkerIgnoringBase@159] - [BrokerServer id=1] Fatal error during broker startup. Prepare to shutdown
java.util.concurrent.ExecutionException:org.apache.kafka.common.errors.InconsistentTopicIdException: Tried to assign topic ID aCqb9NV2QJOd7_4ELWo4pg to log for topic partition public.task_assignment-2,but log already contained topic ID 5iPMzQEuTXCk1-RHLyrRig
    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
    at kafka.server.BrokerServer.startup(BrokerServer.scala:426)
    at kafka.server.KafkaRaftServer.$anonfun$startup$2(KafkaRaftServer.scala:114)
    at kafka.server.KafkaRaftServer.$anonfun$startup$2$adapted(KafkaRaftServer.scala:114)
    at scala.Option.foreach(Option.scala:437)
    at kafka.server.KafkaRaftServer.startup(KafkaRaftServer.scala:114)
    at kafka.Kafka$.main(Kafka.scala:109)
    at kafka.Kafka.main(Kafka.scala)

expect that kafka brokers can start up as normal

edit: i deleted the topic public.task_assignment before
edit: it seem relay the topic metadata

2023-01-05 11:04:48,234 - ERROR [EventHandler:EventQueue$FailureLoggingEvent@60] - [BrokerMetadataListener id=1] Unexpected error handling HandleCommitsEvent
java.lang.RuntimeException: Unable to delete topic with id MXaqZEBbQDOl5zzVOL3ILw: no such topic found.
    at org.apache.kafka.image.TopicsDelta.replay(TopicsDelta.java:104)
    at org.apache.kafka.image.MetadataDelta.replay(MetadataDelta.java:250)
    at org.apache.kafka.image.MetadataDelta.replay(MetadataDelta.java:186)
    at kafka.server.metadata.BrokerMetadataListener.$anonfun$loadBatches$3(BrokerMetadataListener.scala:212)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at kafka.server.metadata.BrokerMetadataListener.kafka$server$metadata$BrokerMetadataListener$$loadBatches(BrokerMetadataListener.scala:204)
    at kafka.server.metadata.BrokerMetadataListener$HandleCommitsEvent.run(BrokerMetadataListener.scala:111)
    at org.apache.kafka.queue.KafkaEventQueue$EventContext.run(KafkaEventQueue.java:121)
    at org.apache.kafka.queue.KafkaEventQueue$EventHandler.handleEvents(KafkaEventQueue.java:200)
    at org.apache.kafka.queue.KafkaEventQueue$EventHandler.run(KafkaEventQueue.java:173)
    at java.base/java.lang.Thread.run(Thread.java:829)

my current kafka broker config with kraft mode

############################# Server Basics #############################

process.roles=broker,controller
node.id=1

# The connect string for the controller quorum
controller.quorum.voters=1@kafka-0.kafka-svc-headless.kafka-ns.svc.cluster.local:9093,2@kafka-1.kafka-svc-headless.kafka-ns.svc.cluster.local:9093,3@kafka-2.kafka-svc-headless.kafka-ns.svc.cluster.local:9093

############################# Socket Server Settings #############################

listeners=PLAINTEXT://10.72.9.205:9092,CONTROLLER://10.72.9.205:9093
inter.broker.listener.name=PLAINTEXT
advertised.listeners=PLAINTEXT://10.72.9.205:9092
controller.listener.names=CONTROLLER

listener.security.protocol.map=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

num.network.threads=3

num.io.threads=8

socket.send.buffer.bytes=102400

socket.receive.buffer.bytes=102400

socket.request.max.bytes=104857600

############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/kafka/data/1

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Flush Policy #############################

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################
log.retention.hours=168

#log.retention.bytes=1073741824
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000

svc.service.port.voter=9093
url.path=kafka/3.2.0/kafka_2.13-3.2.0.tgz
exporter.kafka.service.port.metrics=9308
ui.port=tcp://10.76.7.168:80
svc.port.9093.tcp=tcp://10.76.6.196:9093
exporter.kafka.port=tcp://10.76.0.48:9308
ui.port.80.tcp=tcp://10.76.7.168:80
svc.service.port.client=9092
svc.port.9092.tcp=tcp://10.76.6.196:9092
ui.port.80.tcp.addr=10.76.7.168
svc.port.9092.tcp.proto=tcp
connect.service.host=10.76.0.215
replica.fetch.max.bytes=10485760
exporter.kafka.port.9308.tcp=tcp://10.76.0.48:9308
exporter.kafka.port.9308.tcp.addr=10.76.0.48
exporter.kafka.port.9308.tcp.proto=tcp
svc.port.9092.tcp.port=9092
ui.port.80.tcp.proto=tcp
ui.service.host=10.76.7.168
heap.opts=-Xms768M -Xmx768M
svc.service.host=10.76.6.196
message.max.bytes=10485760
svc.port.9093.tcp.proto=tcp
connect.port.8083.tcp=tcp://10.76.0.215:8083
connect.service.port.client=8083
svc.port.9093.tcp.addr=10.76.6.196
connect.port=tcp://10.76.0.215:8083
exporter.kafka.service.port=9308
svc.port.9093.tcp.port=9093
connect.port.8083.tcp.proto=tcp
zookeeper.connect=
ui.service.port=80
exporter.kafka.port.9308.tcp.port=9308
ui.service.port.http=80
svc.service.port=9092
exporter.kafka.service.host=10.76.0.48
auto.create.topics.enable=false
connect.port.8083.tcp.port=8083
svc.port=tcp://10.76.6.196:9092
data=/kafka/data
connect.port.8083.tcp.addr=10.76.0.215
connect.service.port=8083
ui.port.80.tcp.port=80
svc.port.9092.tcp.addr=10.76.6.196
broker.id=1


问:
PDF.JS - convert Pixels to Points
I am rendering a PDF on a webpage within a Canvas using PDF.JS

I am using my mouse to Drag Objects on my PDF, this way i can get the client's X (MouseX) position using javascript

```<code>var rect = canvas.getBoundingClientRect();
return e.clientX - rect.left
</code>```

Above returns the result in pixels,

Now i am using a javascript Library (PDF.JS) to Render that shape within PDF. That library requires X position to be in "PDF Points" . All I have is the X position of my mouse within the rendered PDF in canvas. here is a sample to render object within PDF

```<code>const button = form.createTextField("ctrl_22");
button.addToPage( firstPage, {
    x: 200 // This needs to be in POINTS
  })
</code>```

So is there a way i can capture the clientX of mouse and convert it into points?

Title: PDF.JS - convert Pixels to Points

Body:
I am rendering a PDF on a webpage within a Canvas using PDF.JS

I am using my mouse to Drag Objects on my PDF, this way i can get the client's X (MouseX) position using javascript

var rect = canvas.getBoundingClientRect();
return e.clientX - rect.left

Above returns the result in pixels,

Now i am using a javascript Library (PDF.JS) to Render that shape within PDF. That library requires X position to be in "PDF Points" . All I have is the X position of my mouse within the rendered PDF in canvas. here is a sample to render object within PDF

const button = form.createTextField("ctrl_22");
button.addToPage( firstPage, {
    x: 200 // This needs to be in POINTS
  })

So is there a way i can capture the clientX of mouse and convert it into points?


问:
Slower training per epoch with increasing number of GPUs for a DNN model - Tensorflow / Keras
So I have a Sequantial keras model with say, 3 Dense layers with 1024, 512 and 256 nodes between the input and output layers. I can create a MirroredStrategy using 1 - 2 and 4 GPUs. The model is defined as :

with strategy.scope(): model = self.build_model(xtrain) opt = self.optimizer(learning_rate) model.compile(loss="mse", optimizer=opt)

where

strategy = tf.distribute.MirroredStrategy(GPUS)

The batch size is :
32* strategy.num_replicas_in_sync

Now, for each epoch, if the model takes ~ 50 seconds with one GPU; with 2 GPUs, it's taking about 1.30 mins, i.e., ~ 90 seconds and about the same time with 4 GPUs.

My training data is custom data for a specific problem I am working on and is fed to model.fit as numpy arrays.

Could someone explain why I am seeing something like this?

I was expecting to see a reduction in time for training each epoch instead of an increase!


问:
Get google sheet authentication by Replit env variables: key error
I am try to get google sheet api authentication using pygsheets in the Replit. I saved the credentials json content into the "Secrets" function of Replit, the code is as below:

```<code>import pygsheets
import os
import json

creds = json.loads(os.environ.get('GDRIVE_API_CREDENTIALS'))
with open('gcreds.json', 'w') as fp:
    json.dump(creds, fp)
gc = pygsheets.authorize(service_account_env_var = 'gcreds.json')
</code>```

The 'GDRIVE_API_CREDENTIALS' is a below when i open the raw editor of Secrets:

```<code>"GDRIVE_API_CREDENTIALS": "{\"type\": \"service_account\", \"project_id\": \"xxx\", \"private_key_id\": \"xxx\", \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nxxx\\n-----END PRIVATE KEY-----\\n\", \"client_email\": \"xxx\", \"client_id\": \"xxx\", \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\", \"token_uri\": \"https://oauth2.googleapis.com/token\", \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\", \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/xxx.iam.gserviceaccount.com\"}"
</code>```

After running the .py file it gives me a KeyError: 'gcreds.json'

Body:
I am try to get google sheet api authentication using pygsheets in the Replit. I saved the credentials json content into the "Secrets" function of Replit, the code is as below:

import pygsheets
import os
import json

creds = json.loads(os.environ.get('GDRIVE_API_CREDENTIALS'))
with open('gcreds.json', 'w') as fp:
    json.dump(creds, fp)
gc = pygsheets.authorize(service_account_env_var = 'gcreds.json')

The 'GDRIVE_API_CREDENTIALS' is a below when i open the raw editor of Secrets:

"GDRIVE_API_CREDENTIALS": "{\"type\": \"service_account\", \"project_id\": \"xxx\", \"private_key_id\": \"xxx\", \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nxxx\\n-----END PRIVATE KEY-----\\n\", \"client_email\": \"xxx\", \"client_id\": \"xxx\", \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\", \"token_uri\": \"https://oauth2.googleapis.com/token\", \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\", \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/xxx.iam.gserviceaccount.com\"}"

After running the .py file it gives me a KeyError: 'gcreds.json'


问:
Predicting/Extrapolating Where a Rolling Ball will come to Rest
I have sample data of velocities over time of a ball rolling across a floor and want to estimate/predict when the ball will come to rest. Is there a function that predicts or extrapolates the sampled data?

Right now I am using numpy's polyfit function to find a second order least squares polynomial fit for the sampled data. The problem is this approach doesn't seem to be the best way to extrapolate a rolling ball coming to rest since the polynomial reaches a minimum and starts to increase again.

```<code>time = [1.18412275 1.21747832 1.25083389 1.28418946 1.31754503 1.38425617 1.43428953 1.4676451  1.50100067 1.53435624 1.56771181 1.6844563 1.76784523 1.82621748 1.9179453 ]
velocities = [5.5060043  5.39964001 4.87463784 4.67891974 4.13837197 3.8205219 3.66008049 3.52023226 3.67126291 3.52283502 3.45253548 3.40862858 3.22339027 3.05700499 2.9310785 ]
polynomial = [5.38169746 5.12811296 4.88910675 4.66467883 4.4548292  4.07886481 3.83515953 3.6909122  3.56124317 3.44615243 3.34563998 3.10865043 3.04870937 3.06096364 3.17042352]
plt.scatter(time, velocities)
plt.plot(time, polynomial)
plt.xlabel("time (seconds)")
plt.ylabel("speed (feet/sec)")
plt.show()
</code>```

Velocity of Rolling Ball over time with a second order polynomial fit

Body:
I have sample data of velocities over time of a ball rolling across a floor and want to estimate/predict when the ball will come to rest. Is there a function that predicts or extrapolates the sampled data?

Right now I am using numpy's polyfit function to find a second order least squares polynomial fit for the sampled data. The problem is this approach doesn't seem to be the best way to extrapolate a rolling ball coming to rest since the polynomial reaches a minimum and starts to increase again.

time = [1.18412275 1.21747832 1.25083389 1.28418946 1.31754503 1.38425617 1.43428953 1.4676451  1.50100067 1.53435624 1.56771181 1.6844563 1.76784523 1.82621748 1.9179453 ]
velocities = [5.5060043  5.39964001 4.87463784 4.67891974 4.13837197 3.8205219 3.66008049 3.52023226 3.67126291 3.52283502 3.45253548 3.40862858 3.22339027 3.05700499 2.9310785 ]
polynomial = [5.38169746 5.12811296 4.88910675 4.66467883 4.4548292  4.07886481 3.83515953 3.6909122  3.56124317 3.44615243 3.34563998 3.10865043 3.04870937 3.06096364 3.17042352]
plt.scatter(time, velocities)
plt.plot(time, polynomial)
plt.xlabel("time (seconds)")
plt.ylabel("speed (feet/sec)")
plt.show()

Velocity of Rolling Ball over time with a second order polynomial fit


问:
Cmd Line read terminal color
What I want is a from the prompt command line that will tell me what the screen background color is.
If it's black, then I will make the foreground (in .bashrc) an appropriate color and if white background then I can make the foreground a different color.

I want a single .bashrc script that I can use in different places and the script "handles" the foreground text color based on the background default screen color for that given Linux VM.  (I have hundreds of different Linux VMs and I build and tear down VMS almost daily.)

This way I could have if term_background is black then foreground text is yellow.....

Thanks in advance for your help.....

Prof Scott

I have different lines in my .bashrc to manage this, but it requires intervention to switch....

Title: Cmd Line read terminal color


问:
Issue with taking input from the COM port
I am trying to make it so that when a certain number comes through the COM port it updates a value within my sql table as can be seen in the code below

```<code>import sqlite3
import serial

def get_attendance_status():
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Select all rows from the 'students' table
  c.execute("SELECT * FROM students")

  # Fetch all rows from the cursor
  rows = c.fetchall()

  # Close the connection to the database
  conn.close()

  # Return the rows
  return rows

def mark_student_present(serial_number):
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Update the attendance status for the student with the given serial number
  c.execute("UPDATE students SET attendance_status = 'present' WHERE serial_number = ?", (serial_number,))

  # Commit the changes to the database
  conn.commit()

  # Close the connection to the database
  conn.close()

def create_database_and_table():
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Create the table if it doesn't already exist
  c.execute('''CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY,
    serial_number CHAR(10) UNIQUE,
    name VARCHAR(255),
    attendance_status VARCHAR(255)
  )''')

  # Reset the attendance status of all students to 'absent'
  c.execute("UPDATE students SET attendance_status = 'absent'")

  # Add the students to the table if they don't already exist
  c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (1, 'Declan', 'absent'))
  c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (2, 'Milan', 'absent'))

  # Commit the changes to the database
  conn.commit()

  # Close the connection to the database
  conn.close()

def main():
  # Create the database and table if they don't already exist
  create_database_and_table()

# Open the serial port
ser = serial.Serial('COM5', 115200)

# Continuously read serial numbers from the serial port and mark the corresponding students as present
while True:
  # Read a line of input from the serial port
  serial_number = ser.readline()

  # Check if the user entered "exit" on the command line
  if serial_number.lower() == 'exit':
    break

  # Mark the student as present
  mark_student_present(serial_number)

  # Get the attendance status for all students
  rows = get_attendance_status()

  # Print the attendance status for each student
  for row in rows:
    serial_number = row[1]
    name = row[2]
    attendance_status = row[3]
    print(f'{name} ({serial_number}): {attendance_status}')

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

However when I run the scrip I get this error

```<code>TypeError: mark_student_present() missing 1 required positional argument: 'serial_number'

[Done] exited with code=1 in 0.113 seconds
</code>```

I want it to continuously check the com port to see if the numbers relating to the sql table are recieved. If they are recieved it should then change the attendance_status value.

Body:
I am trying to make it so that when a certain number comes through the COM port it updates a value within my sql table as can be seen in the code below

import sqlite3
import serial

def get_attendance_status():
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Select all rows from the 'students' table
  c.execute("SELECT * FROM students")

  # Fetch all rows from the cursor
  rows = c.fetchall()

  # Close the connection to the database
  conn.close()

  # Return the rows
  return rows

def mark_student_present(serial_number):
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Update the attendance status for the student with the given serial number
  c.execute("UPDATE students SET attendance_status = 'present' WHERE serial_number = ?", (serial_number,))

  # Commit the changes to the database
  conn.commit()

  # Close the connection to the database
  conn.close()

def create_database_and_table():
  # Connect to the database
  conn = sqlite3.connect('attendance.db')
  c = conn.cursor()

  # Create the table if it doesn't already exist
  c.execute('''CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY,
    serial_number CHAR(10) UNIQUE,
    name VARCHAR(255),
    attendance_status VARCHAR(255)
  )''')

  # Reset the attendance status of all students to 'absent'
  c.execute("UPDATE students SET attendance_status = 'absent'")

  # Add the students to the table if they don't already exist
  c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (1, 'Declan', 'absent'))
  c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (2, 'Milan', 'absent'))

  # Commit the changes to the database
  conn.commit()

  # Close the connection to the database
  conn.close()

def main():
  # Create the database and table if they don't already exist
  create_database_and_table()

# Open the serial port
ser = serial.Serial('COM5', 115200)

# Continuously read serial numbers from the serial port and mark the corresponding students as present
while True:
  # Read a line of input from the serial port
  serial_number = ser.readline()

  # Check if the user entered "exit" on the command line
  if serial_number.lower() == 'exit':
    break

  # Mark the student as present
  mark_student_present(serial_number)

  # Get the attendance status for all students
  rows = get_attendance_status()

  # Print the attendance status for each student
  for row in rows:
    serial_number = row[1]
    name = row[2]
    attendance_status = row[3]
    print(f'{name} ({serial_number}): {attendance_status}')

if __name__ == '__main__':
  main()

However when I run the scrip I get this error

TypeError: mark_student_present() missing 1 required positional argument: 'serial_number'

[Done] exited with code=1 in 0.113 seconds

I want it to continuously check the com port to see if the numbers relating to the sql table are recieved. If they are recieved it should then change the attendance_status value.


问:
Why do I fail to install Maps on my mediawiki? and what should I do?
mediawiki version information
official installation documentation

error information
I figure out that I didn't have composer.local.json in my computer,but I have composer.local.json-sample under the directory of mediawiki.
What should I do next?


问:
Select2 not working properly on multiple select
My HTML

```<code><div class="form-group" id="diagnosaearlycheckinDiv">
   <label for="diagnosaLabelEarlycheckinDiv">Early Diagnose <code class="text-danger">*</code></label>
   <div class="select2-purple" id="diagnosaLabelEarlycheckinDiv">
      <select class="form-control select2" name="diagnosaearlyclaimcheckinTxt[]" id="diagnosaearlyclaimcheckinIDs" multiple="multiple" data-placeholder="Select Early Diagnose" data-dropdown-css-class="select2-purple" required></select>
   </div>
</div>
</code>```

My JS

```<code>    diagnosaEarlyCheckIN.select2({
        placeholder: '--- Select Diagnose ---',
        minimumInputLength: 3,
        theme: 'bootstrap4',
        allowClear: true,
        tags: [],
        multiple: true,
        ajax: {
          url: function (params) {
            return 'claim/edit/diagnose/' + params.term;
          },
          dataType: 'json',
          delay: 100,
          processData: false,
          contentType: false,
          xhrFields: {
            withCredentials: true
          },
          processResults: function (data) {
            return {
              results: $.map(data, function (item) {
                return {
                  text: item.text,
                  id: item.id
                }
              })
            };
          },
        }
    });
</code>```

My result:

```<code>[
    {
        "id": "622",
        "text": "Repair of retinal tear by photocoagulation of unspecified type"
    },
    {
        "id": "775",
        "text": "Type ii tympanoplasty"
    }
]
</code>```

I have input select2 to get multi diagnose, but i want set minimum 3 digit character to get data diagnose.
When set to single select, works perfect. Whats wrong? Any idea?

My expectation, I can select multiple diagnose.

Body:
My HTML

   Early Diagnose *

      <select class="form-control select2" name="diagnosaearlyclaimcheckinTxt[]" id="diagnosaearlyclaimcheckinIDs" multiple="multiple" data-placeholder="Select Early Diagnose" data-dropdown-css-class="select2-purple" required></select>

My JS

    diagnosaEarlyCheckIN.select2({
        placeholder: '--- Select Diagnose ---',
        minimumInputLength: 3,
        theme: 'bootstrap4',
        allowClear: true,
        tags: [],
        multiple: true,
        ajax: {
          url: function (params) {
            return 'claim/edit/diagnose/' + params.term;
          },
          dataType: 'json',
          delay: 100,
          processData: false,
          contentType: false,
          xhrFields: {
            withCredentials: true
          },
          processResults: function (data) {
            return {
              results: $.map(data, function (item) {
                return {
                  text: item.text,
                  id: item.id
                }
              })
            };
          },
        }
    });

My result:

[
    {
        "id": "622",
        "text": "Repair of retinal tear by photocoagulation of unspecified type"
    },
    {
        "id": "775",
        "text": "Type ii tympanoplasty"
    }
]

I have input select2 to get multi diagnose, but i want set minimum 3 digit character to get data diagnose.
When set to single select, works perfect. Whats wrong? Any idea?

My expectation, I can select multiple diagnose.


问:
While using Colab or Jupyter notebook is it possible to download the model and use it later on without starting from the top?
I am training a model with a huge dataset and creating it every time is a huge hassel so I was wondering if there is a way to download the model and reuse it rather than creating and running it repeatedly everytime i use it. (i am a beginner)

i am expecting to download this model and use it multiple times rather than start from scratch then build and train it.


问:
How to set an env var containing a special character in powershell?
In python, it's valid to have env vars that have "|" in them. but in powershell, its not possible to set these. eg:

```<code>$env:OVERRIDEPARM_|out|serverworkdir = "something"
</code>```

Produces this error:

```<code>out: The term 'out' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
</code>```

Would I use a function instead to do that somehow?  Or is there another way?
Note: I'm not talking about system env vars.

I recognise this question below is similar, but doesn't ask the same thing since I'm not talking about the help function, and it doesn't come up in search, so my question will help other searching for this specific problem - PowerShell, the syntax of help-function

Body:
In python, it's valid to have env vars that have "|" in them. but in powershell, its not possible to set these. eg:

$env:OVERRIDEPARM_|out|serverworkdir = "something"

Produces this error:

out: The term 'out' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Would I use a function instead to do that somehow?  Or is there another way?
Note: I'm not talking about system env vars.

I recognise this question below is similar, but doesn't ask the same thing since I'm not talking about the help function, and it doesn't come up in search, so my question will help other searching for this specific problem - PowerShell, the syntax of help-function


问:
Convert FFMpegCore Bitmap to Stream on Linux
I have a DotNet Core 7 app, which utilises the rather wonderful FFMpegCore by Malte Rosenbjerg to get snapshots of video using FFMpeg. I'm converting my app to run on Linux, but the FFMpeg.Snapshot function returns a System.Drawing.Bitmap, and the only way I can find to Save() it to a stream comes with a warning:

This call site is reachable on all platforms. 'Image.Save(Stream, ImageFormat)' is supported only on 'windows'

I'm using ImageSharp for other graphic manipulations, and it feels like the right thing to do is use that to read the in-memory bitmap and save it down to a stream, but I can't get it to load the resulting Bitmap.

The code is simply:

```<code>(await FFMpeg.SnapshotAsync(responseFile,
   new System.Drawing.Size(100, 100),
   TimeSpan.FromSeconds(frameSecond)))
   .Save(stream, System.Drawing.Imaging.ImageFormat.Png);
</code>```

What is the best way to return my bitmap as a stream without running on Windows?

I've also tried ImageConverter (windows-only), and various Image.Load(...) and Image.LoadPixelData as mentioned here

Body:
I have a DotNet Core 7 app, which utilises the rather wonderful FFMpegCore by Malte Rosenbjerg to get snapshots of video using FFMpeg. I'm converting my app to run on Linux, but the FFMpeg.Snapshot function returns a System.Drawing.Bitmap, and the only way I can find to Save() it to a stream comes with a warning:

This call site is reachable on all platforms. 'Image.Save(Stream, ImageFormat)' is supported only on 'windows'

I'm using ImageSharp for other graphic manipulations, and it feels like the right thing to do is use that to read the in-memory bitmap and save it down to a stream, but I can't get it to load the resulting Bitmap.

The code is simply:

(await FFMpeg.SnapshotAsync(responseFile,
   new System.Drawing.Size(100, 100),
   TimeSpan.FromSeconds(frameSecond)))
   .Save(stream, System.Drawing.Imaging.ImageFormat.Png);

What is the best way to return my bitmap as a stream without running on Windows?

I've also tried ImageConverter (windows-only), and various Image.Load(...) and Image.LoadPixelData as mentioned here


问:
How to get webhook data in python
I have a webhook url from messagebird, and post requests are being sent from the LINE Messaging API to that url when some events occur. I need to get the data of those webhooks (JSON data). I'm using Python (it's a Django app).

How can I get the data from the webhook?

Title: How to get webhook data in python


问:
We want to create a database in Notion to store health lab tests such as RBC, HDL, LDL etc
I need expert's advice so that I can design a simple database for my client. Problem - Attributes of database - Date, test value(such as Haemoglobin - 12)(variable), range(such as 12-16) (constant), Description of test, and location of lab/doctor name. My client has lab test data from 1995.

Test database in Notion

I tried creating this database in notion but it won't work because some tests doesn't have any report type. But not all tests comes under reports. We want to create a simple database which let us input test value, date of test. Description, and Range will be pre-filled and one time entry.


问:
Set permission AWS s3 to only creator
Is there a way to set access permissions (READ/WRITE) to only the creators of the buckets/objects?

We are working on a project that requires storing the data only for specific users. (I know about setting permissions to the specific groups - Admin, Developers. etc. but it's not the case here, as some other Developers are not allowed to view the items either).

Is it possible to perform it via policy?

Or it's just not possible to do so.

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AWSConfigBucketPermissionsCheck",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:GetBucketAcl",
      "Resource": "arn:aws:s3:::targetBucketName",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    },
    {
      "Sid": "AWSConfigBucketExistenceCheck",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::targetBucketName",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    },
    {
      "Sid": "AWSConfigBucketDelivery",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::targetBucketName/[optional] prefix/AWSLogs/sourceAccountID/Config/*",
      "Condition": {
        "StringEquals": {
          "s3:x-amz-acl": "bucket-owner-full-control",
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    }
  ]
}
</code>```

Title: Set permission AWS s3 to only creator

Body:
Is there a way to set access permissions (READ/WRITE) to only the creators of the buckets/objects?

We are working on a project that requires storing the data only for specific users. (I know about setting permissions to the specific groups - Admin, Developers. etc. but it's not the case here, as some other Developers are not allowed to view the items either).

Is it possible to perform it via policy?

Or it's just not possible to do so.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AWSConfigBucketPermissionsCheck",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:GetBucketAcl",
      "Resource": "arn:aws:s3:::targetBucketName",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    },
    {
      "Sid": "AWSConfigBucketExistenceCheck",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::targetBucketName",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    },
    {
      "Sid": "AWSConfigBucketDelivery",
      "Effect": "Allow",
      "Principal": {
        "Service": "config.amazonaws.com"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::targetBucketName/[optional] prefix/AWSLogs/sourceAccountID/Config/*",
      "Condition": {
        "StringEquals": {
          "s3:x-amz-acl": "bucket-owner-full-control",
          "AWS:SourceAccount": "sourceAccountID"
        }
      }
    }
  ]
}


问:
Get buffer of generated qr code via qrCode in node.js
I need some way to get the buffer of a qr code using qrCode.
Here is the code:</p>
```<code>qrGen.toDataURL(crypto.randomUUID(), function (err, url) {
  console.log(url)
  console.log(url.buffer)
});```
</code>```

Body:
I need some way to get the buffer of a qr code using qrCode.
Here is the code:

qrGen.toDataURL(crypto.randomUUID(), function (err, url) {
  console.log(url)
  console.log(url.buffer)
});```


问:
contextmenu event not working in webview [Electron]
I'm using Electron with React+Typescript but this can be tested using just Electron+Javascript. The dom-ready event is working, I can see it in the console, but the contextmenu event is not triggered when I right click.

```<code>export default Main() {
  const browserRef = useRef<WebViewProps>(null);

  useEffect(() => {
    const domReady = () => {
      console.log("Dom is ready!");
    };
    const contextMenu = () => {
      console.log("Context menu is working!");
    };

    if(browserRef.current) {
      browserRef.current.addEventListener("dom-ready", domReady);
      browserRef.current.addEventListener("contextmenu", contextMenu);
    };

    return () => {
      if (browserRef.current) {
        browserRef.current?.removeEventListener("dom-ready", domReady);
        browserRef.current?.removeEventListener("contextmenu", contextMenu);
      };
    };
  }, []);

  return (
    <webview ref={browserRef} src="https://www.google.com/" />
  );
};
</code>```

My contextmenu is not being called when I right click, this makes me think it doesn't fire when I right click but i don't know...

Body:
I'm using Electron with React+Typescript but this can be tested using just Electron+Javascript. The dom-ready event is working, I can see it in the console, but the contextmenu event is not triggered when I right click.

export default Main() {
  const browserRef = useRef<WebViewProps>(null);

  useEffect(() => {
    const domReady = () => {
      console.log("Dom is ready!");
    };
    const contextMenu = () => {
      console.log("Context menu is working!");
    };

    if(browserRef.current) {
      browserRef.current.addEventListener("dom-ready", domReady);
      browserRef.current.addEventListener("contextmenu", contextMenu);
    };

    return () => {
      if (browserRef.current) {
        browserRef.current?.removeEventListener("dom-ready", domReady);
        browserRef.current?.removeEventListener("contextmenu", contextMenu);
      };
    };
  }, []);

  return (
    <webview ref={browserRef} src="https://www.google.com/" />
  );
};

My contextmenu is not being called when I right click, this makes me think it doesn't fire when I right click but i don't know...


问:
The page you requested was not found in login 404
i have a script login using php and codeigniter 3

this my controller with name Auth.php

```<code>private function _login()
    {
        $username = $this->input->post('username', true);
        $password = $this->input->post('password', true);

        $user = $this->Auth_m->get_where('users', ['username' => $username])->row_array();
        if ($user != null) {
            if (sha1($password) == $user['password']) {
                $data = [
                    'username' => $user['username'],
                    'id_user' => $user['id_user']
                ];
                $this->session->set_userdata($data);
                redirect('admin/dashboard');
            } else {
                $this->session->set_flashdata('pesan', '<div class="alert alert-danger" role="alert">Password Salah!.</div>');
                redirect('auth');
            }
        } else {
            $this->session->set_flashdata('pesan', '<div class="alert alert-danger" role="alert">Akun Belum Terdaftar!.</div>');
            redirect('auth');
        }
    }
</code>```

this my model with name Auth_m.php

```<code>class Auth_m extends CI_Model
{
    public function get_where($table, $where)
    {
        return $this->db->get_where($table, $where);
    }
}
</code>```

this my view with name login.php

```<code><form class="form-signin" action="<?= base_url('auth'); ?>" method="post">
          <h1 class="h3 mb-3 font-weight-normal">Pembayaran SPP Sekolah</h1>
          <br>

          <?= $this->session->flashdata('pesan'); ?>
          <div class="form-group">
            <label for="username" class="sr-only">Username</label>
            <input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus>
            <small class="muted text-danger"><?= form_error('username'); ?></small>
          </div>
          <div class="form-group">
            <label for="password" class="sr-only">Password</label>
            <input type="password" name="password" id="password" class="form-control" placeholder="Password">
            <small class="muted text-danger"><?= form_error('password'); ?></small>
          </div>
          <div class="form-group">
            <button class="btn btn-lg btn-primary btn-block" type="submit">Masuk</button>
          </div>
          <p class="mt-5 mb-3 text-muted">© <?= date('Y'); ?></p>
        </form>
</code>```

i was change redirect page and another script cannot find a problem, please help me

Body:
i have a script login using php and codeigniter 3

this my controller with name Auth.php

private function _login()
    {
        $username = $this->input->post('username', true);
        $password = $this->input->post('password', true);

        $user = $this->Auth_m->get_where('users', ['username' => $username])->row_array();
        if ($user != null) {
            if (sha1($password) == $user['password']) {
                $data = [
                    'username' => $user['username'],
                    'id_user' => $user['id_user']
                ];
                $this->session->set_userdata($data);
                redirect('admin/dashboard');
            } else {
                $this->session->set_flashdata('pesan', '
Password Salah!.
');
                redirect('auth');
            }
        } else {
            $this->session->set_flashdata('pesan', '
Akun Belum Terdaftar!.
');
            redirect('auth');
        }
    }

this my model with name Auth_m.php

class Auth_m extends CI_Model
{
    public function get_where($table, $where)
    {
        return $this->db->get_where($table, $where);
    }
}

this my view with name login.php

<form class="form-signin" action="<?= base_url('auth'); ?>" method="post">

Pembayaran SPP Sekolah

          <?= $this->session->flashdata('pesan'); ?>

            Username
            <input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus>
            <?= form_error('username'); ?>

            Password
            <input type="password" name="password" id="password" class="form-control" placeholder="Password">
            <?= form_error('password'); ?>

            <button class="btn btn-lg btn-primary btn-block" type="submit">Masuk</button>

© <?= date('Y'); ?>

        </form>

i was change redirect page and another script cannot find a problem, please help me


问:
What's wrong with this code? Replacing blank cells in excel to 0 in Python
I have asked this question and I would to seek an opinion from other experts as well on how to resolve the issue. Basically, what the script does is it checks the Column A from Source.xlsx and if the value matches, the value in Column Count will be written to Column Count of Test.xlsx. If the value of Column Count in Source.xlsx is blank, the script should write 0 in Column Count of Test.xlsx. I was advised to use this code daily_data.fillna(0, inplace=True) but so far it has no errors however it doesn't convert the blank values in Column Count of Test.xlsx to 0.

Your opinion or suggestion is highly appreciated. Thank you very much.

```<code>import pandas as pd
import os
import openpyxl

daily_data = openpyxl.load_workbook('C:/Test.xlsx')
master_data = openpyxl.load_workbook('C:/Source.xlsx')

daily_sheet = daily_data['WorkSheet']
master_sheet = master_data['WorkSheet']

for i in daily_sheet.iter_rows():
Column_A = i[0].value
row_number = i[0].row
for j in master_sheet.iter_rows():
    if j[0].value == Column_A:
        daily_sheet.cell(row=row_number, column=6).value = j[1].value

        #print(j[1].value)

daily_data.save('C:/Test.xlsx')
daily_data = pd.read_excel('C:/Test.xlsx')
daily_data.fillna(0, inplace=True)
</code>```

Body:
I have asked this question and I would to seek an opinion from other experts as well on how to resolve the issue. Basically, what the script does is it checks the Column A from Source.xlsx and if the value matches, the value in Column Count will be written to Column Count of Test.xlsx. If the value of Column Count in Source.xlsx is blank, the script should write 0 in Column Count of Test.xlsx. I was advised to use this code daily_data.fillna(0, inplace=True) but so far it has no errors however it doesn't convert the blank values in Column Count of Test.xlsx to 0.

Your opinion or suggestion is highly appreciated. Thank you very much.

import pandas as pd
import os
import openpyxl

daily_data = openpyxl.load_workbook('C:/Test.xlsx')
master_data = openpyxl.load_workbook('C:/Source.xlsx')

daily_sheet = daily_data['WorkSheet']
master_sheet = master_data['WorkSheet']

for i in daily_sheet.iter_rows():
Column_A = i[0].value
row_number = i[0].row
for j in master_sheet.iter_rows():
    if j[0].value == Column_A:
        daily_sheet.cell(row=row_number, column=6).value = j[1].value

        #print(j[1].value)

daily_data.save('C:/Test.xlsx')
daily_data = pd.read_excel('C:/Test.xlsx')
daily_data.fillna(0, inplace=True)


问:
Error running stored procedure as non-sa user: EXECUTE permission was denied on the object 'sp_start_job'
I'm trying to run a stored procedure which starts up a job. When I run it as myself (as a sysadmin), it runs without a hitch, but when I run it as a custom SQL Server user ("SQLAgentUser" -- mapped to a SQL Server login), it gives the error:

EXECUTE permission was denied on the object 'sp_start_job', database 'msdb', schema 'dbo'.

SQLAgentUser is a member of all the following roles in msdb:

SQLAgentOperatorRole

SQLAgentReaderRole

SQLAgentUserRole

In addition, SQLAgentUser has the following explicit permissions granted in MSDB:

GRANT EXECUTE on sp_start_job (and when I look at effective permissions in SSMS, it says it has Execute permissions)

GRANT EXECUTE on sp_stop_job (same as above)

In MyDb (not its actual name), SQLAgentUser has EXECUTE permissions to the sqladm schema, as well as DELETE, INSERT, SELECT, and UPDATE permissions to sqladm.AgentJobsLastRun.

According to everything I found online, this SHOULD be all that's needed, but I'm still getting the error when executing as SQLAgentUser.

Here's the erroring code:

```<code>USE [MyDb]
GO

DECLARE @RC int
EXECUTE AS USER = 'SQLAgentUser'

UPDATE [sqladm].[AgentJobsLastRun]
SET RunDate = NULL
WHERE JobName = 'MonthlyJobs'

EXECUTE @RC = [sqladm].[udp_DailyJob]

REVERT
GO
</code>```

If I comment out, "EXECUTE AS USER = 'SQLAgentUser'," it runs without a hitch.

...and the code inside [sqladm].[udp_DailyJob]:

```<code>SET NOCOUNT ON;

-- Insert statements for procedure here
-- First check that the monthly job has run this month (should have run at 2 AM on the first). If not, manually run the job.
DECLARE @AgentJobNameSys nvarchar(128) = N'MonthlyJobs'
DECLARE @LastRunDate datetime = COALESCE((SELECT [RunDate] FROM [sqladm].[AgentJobsLastRun] WHERE JobName = @AgentJobNameSys),DATEADD(month,-1,getdate()))

IF @LastRunDate < DATEFROMPARTS(YEAR(getdate()),MONTH(getdate()),1)
BEGIN
    EXEC msdb.dbo.sp_start_job @AgentJobNameSys;
END
</code>```

Running SQL Server 2019 Developer Edition on my local computer.
Many thanks! :)

Body:
I'm trying to run a stored procedure which starts up a job. When I run it as myself (as a sysadmin), it runs without a hitch, but when I run it as a custom SQL Server user ("SQLAgentUser" -- mapped to a SQL Server login), it gives the error:

EXECUTE permission was denied on the object 'sp_start_job', database 'msdb', schema 'dbo'.

SQLAgentUser is a member of all the following roles in msdb:

SQLAgentOperatorRole

SQLAgentReaderRole

SQLAgentUserRole

In addition, SQLAgentUser has the following explicit permissions granted in MSDB:

GRANT EXECUTE on sp_start_job (and when I look at effective permissions in SSMS, it says it has Execute permissions)

GRANT EXECUTE on sp_stop_job (same as above)

In MyDb (not its actual name), SQLAgentUser has EXECUTE permissions to the sqladm schema, as well as DELETE, INSERT, SELECT, and UPDATE permissions to sqladm.AgentJobsLastRun.

According to everything I found online, this SHOULD be all that's needed, but I'm still getting the error when executing as SQLAgentUser.

Here's the erroring code:

USE [MyDb]
GO

DECLARE @RC int
EXECUTE AS USER = 'SQLAgentUser'

UPDATE [sqladm].[AgentJobsLastRun]
SET RunDate = NULL
WHERE JobName = 'MonthlyJobs'

EXECUTE @RC = [sqladm].[udp_DailyJob]

REVERT
GO

If I comment out, "EXECUTE AS USER = 'SQLAgentUser'," it runs without a hitch.

...and the code inside [sqladm].[udp_DailyJob]:

SET NOCOUNT ON;

-- Insert statements for procedure here
-- First check that the monthly job has run this month (should have run at 2 AM on the first). If not, manually run the job.
DECLARE @AgentJobNameSys nvarchar(128) = N'MonthlyJobs'
DECLARE @LastRunDate datetime = COALESCE((SELECT [RunDate] FROM [sqladm].[AgentJobsLastRun] WHERE JobName = @AgentJobNameSys),DATEADD(month,-1,getdate()))

IF @LastRunDate < DATEFROMPARTS(YEAR(getdate()),MONTH(getdate()),1)
BEGIN
    EXEC msdb.dbo.sp_start_job @AgentJobNameSys;
END

Running SQL Server 2019 Developer Edition on my local computer.
Many thanks! :)


问:
Many to Many Mapping Spring JPA when saving one record at a time
I am implementing a functionality where a user can win the reward once in a day.He will spin the wheel in app and will earn a reward.The table structure to store all the reward details and all the rewards won is shown below.

Rewards Table Model

```<code>@Table(name="spin_win_rewards_details")
@EntityListeners(AuditingEntityListener.class)
public class SpinWinRewardsDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

private String label;

private String description;

private String voucherCode;

private String status;

</code>```

}

RewardsWonByUser Entity class

```<code>@Table(name="spin_win_rewards_won")
@EntityListeners(AuditingEntityListener.class)
public class SpinWinRewardsWon {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    @JsonIgnore
    private Long id;

    private String shortId;

    @Transient
    private String rewardLabel;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity = SpinWinRewardsDetails.class)
    @JoinColumn(name = "reward_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private SpinWinRewardsDetails spinWinRewardDetails;

    @JsonIgnore
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at", nullable = false, updatable = false)
    @CreatedDate
    private Date createdAt;

}
</code>```

One Reward can be won by many users and one user can win many rewards but he can win only one reward in a day,so my question is ,is this the right mapping or do I need to go for ManytoMany mapping. But many to many mapping I am thinking is not required because when we create a reward won  then user can only win one reward at a time and not many rewards at a time.

SpinWinController

```<code>    @PostMapping(value = "/createReward")
    public ResponseEntity<?> createReward(@RequestBody SpinWinRewardsDetails spinWinRewardsDetails) {
        log.info("Inside spin win createReward..!!");
        if (spinWinRewardsDetails != null) {
            SpinWinRewardsDetails spinWinRewards = spinAndWinService.saveRewardsDetails(spinWinRewardsDetails);
                if (spinWinRewards != null) {
                    log.info("SpinWinRewardsDetails is created");
                    return new ResponseEntity<SpinWinRewardsDetails>(spinWinRewards, HttpStatus.CREATED);
                } else {
                    String message = "SpinWinRewardsDetails is not created properly";
                    log.info(message);
                    return getErrorMessage(new Exception(), message);
                }

        }
        return getErrorMessage(new Exception(), "invalid request body");
    }

@PostMapping(value = "/rewardWon")
public ResponseEntity<?> createWinningReward(@RequestBody SpinWinRewardsWon spinWinRewardsWon) {
    log.info("Inside createWinningReward..!!");
    if (spinWinRewardsWon != null) {

        String userShortId = spinWinRewardsWon.getShortId();
        String rewardWon = spinWinRewardsWon.getRewardLabel();

        log.info("User" +userShortId + "won the reward"+ rewardWon);
        Optional<SpinWinRewardsDetails> spinWinRewardsDetails = spinAndWinService.findByLabel(rewardWon);
        if(spinWinRewardsDetails.isPresent()){
            spinWinRewardsWon.setSpinWinRewardDetails(spinWinRewardsDetails.get());
            log.info("Saving WinningReward in DB!!");
            SpinWinRewardsWon spinWinRewardsWonResp = spinAndWinService.saveRewardsWon(spinWinRewardsWon);
            if (spinWinRewardsWonResp != null) {
                log.info("Saved successfully WinningReward in DB!!");
                return new ResponseEntity<SpinWinRewardsWon>(spinWinRewardsWonResp, HttpStatus.CREATED);
            } else {
                String message = "Winning Reward is not created properly";
                log.info(message);
                return getErrorMessage(new Exception(), message);
            }
        }

    }
    return getErrorMessage(new Exception(), "invalid request body");
}
</code>```

Body:
I am implementing a functionality where a user can win the reward once in a day.He will spin the wheel in app and will earn a reward.The table structure to store all the reward details and all the rewards won is shown below.

Rewards Table Model

@Table(name="spin_win_rewards_details")
@EntityListeners(AuditingEntityListener.class)
public class SpinWinRewardsDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

private String label;

private String description;

private String voucherCode;

private String status;

}

RewardsWonByUser Entity class

@Table(name="spin_win_rewards_won")
@EntityListeners(AuditingEntityListener.class)
public class SpinWinRewardsWon {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    @JsonIgnore
    private Long id;

    private String shortId;

    @Transient
    private String rewardLabel;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity = SpinWinRewardsDetails.class)
    @JoinColumn(name = "reward_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private SpinWinRewardsDetails spinWinRewardDetails;

    @JsonIgnore
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at", nullable = false, updatable = false)
    @CreatedDate
    private Date createdAt;

}

One Reward can be won by many users and one user can win many rewards but he can win only one reward in a day,so my question is ,is this the right mapping or do I need to go for ManytoMany mapping. But many to many mapping I am thinking is not required because when we create a reward won  then user can only win one reward at a time and not many rewards at a time.

SpinWinController

    @PostMapping(value = "/createReward")
    public ResponseEntity<?> createReward(@RequestBody SpinWinRewardsDetails spinWinRewardsDetails) {
        log.info("Inside spin win createReward..!!");
        if (spinWinRewardsDetails != null) {
            SpinWinRewardsDetails spinWinRewards = spinAndWinService.saveRewardsDetails(spinWinRewardsDetails);
                if (spinWinRewards != null) {
                    log.info("SpinWinRewardsDetails is created");
                    return new ResponseEntity<SpinWinRewardsDetails>(spinWinRewards, HttpStatus.CREATED);
                } else {
                    String message = "SpinWinRewardsDetails is not created properly";
                    log.info(message);
                    return getErrorMessage(new Exception(), message);
                }

        }
        return getErrorMessage(new Exception(), "invalid request body");
    }

@PostMapping(value = "/rewardWon")
public ResponseEntity<?> createWinningReward(@RequestBody SpinWinRewardsWon spinWinRewardsWon) {
    log.info("Inside createWinningReward..!!");
    if (spinWinRewardsWon != null) {

        String userShortId = spinWinRewardsWon.getShortId();
        String rewardWon = spinWinRewardsWon.getRewardLabel();

        log.info("User" +userShortId + "won the reward"+ rewardWon);
        Optional<SpinWinRewardsDetails> spinWinRewardsDetails = spinAndWinService.findByLabel(rewardWon);
        if(spinWinRewardsDetails.isPresent()){
            spinWinRewardsWon.setSpinWinRewardDetails(spinWinRewardsDetails.get());
            log.info("Saving WinningReward in DB!!");
            SpinWinRewardsWon spinWinRewardsWonResp = spinAndWinService.saveRewardsWon(spinWinRewardsWon);
            if (spinWinRewardsWonResp != null) {
                log.info("Saved successfully WinningReward in DB!!");
                return new ResponseEntity<SpinWinRewardsWon>(spinWinRewardsWonResp, HttpStatus.CREATED);
            } else {
                String message = "Winning Reward is not created properly";
                log.info(message);
                return getErrorMessage(new Exception(), message);
            }
        }

    }
    return getErrorMessage(new Exception(), "invalid request body");
}


问:
Nodejs (Windows Script Host ) ERROR , I tried searching about it but still can't understand
I realized something is wrong with my node.js environment few days ago.I went to command prompt and typed

```<code>node -v
</code>```

to check the version, surprisingly I encountered an error which says -

```<code>Script :
line :1
char 1
error : object expected
code : 800A138F
source : Microsoft JScript runtime error
</code>```

Since then I have even uninstalled node but this error keeps on showing. Now that I have uninstalled node, shouldn't this be replaced by

is not recognized as an internal or external command,
operable program or batch file.

I have an upcoming project evaluation on 8th, any help would be appreciated.Thankyou!

Body:
I realized something is wrong with my node.js environment few days ago.I went to command prompt and typed

node -v

to check the version, surprisingly I encountered an error which says -

Script :
line :1
char 1
error : object expected
code : 800A138F
source : Microsoft JScript runtime error

Since then I have even uninstalled node but this error keeps on showing. Now that I have uninstalled node, shouldn't this be replaced by

is not recognized as an internal or external command,
operable program or batch file.

I have an upcoming project evaluation on 8th, any help would be appreciated.Thankyou!


问:
How can remove anonymous event listener function in javascript
Basically i am using Stripe react package for getting card element. But as per requirement i need card holder name. when click 1.(as per attachment) then cursor automatically go down on 2.(as per attachment). Finally i get the click listener 3(as per attachment). if i remove the click listener i hope it will work perfectly. but how i can remove anonymous event function from DOM. or any built in method disabling the focus event in @stripe/react-stripe-js npm package.
Advanced thanks for helping me.

```<code>const options = {
  style: {
    iconStyle: "solid",
    base: {
      fontSize: "16px",
      color: "#424770",
      letterSpacing: "0.025em",
      fontFamily: "Source Code Pro, monospace",
      "::placeholder": {
        color: "#aab7c4",
      },
    },
    invalid: {
      color: "#9e2146",
    },
  },
}

 <CardNumberElement className="ant-input stripe-custom-card-number" options={options} />
</code>```

Body:
Basically i am using Stripe react package for getting card element. But as per requirement i need card holder name. when click 1.(as per attachment) then cursor automatically go down on 2.(as per attachment). Finally i get the click listener 3(as per attachment). if i remove the click listener i hope it will work perfectly. but how i can remove anonymous event function from DOM. or any built in method disabling the focus event in @stripe/react-stripe-js npm package.
Advanced thanks for helping me.

const options = {
  style: {
    iconStyle: "solid",
    base: {
      fontSize: "16px",
      color: "#424770",
      letterSpacing: "0.025em",
      fontFamily: "Source Code Pro, monospace",
      "::placeholder": {
        color: "#aab7c4",
      },
    },
    invalid: {
      color: "#9e2146",
    },
  },
}

 <CardNumberElement className="ant-input stripe-custom-card-number" options={options} />


问:
AVPlayerviewController controls are not visible on tvOS
My project is currently using SwiftUI but for a feature I need to use AVPlayerviewController to play a video. The code I provided below works well on iOS but on tvOS the player controls are not visible/focusable. What am I doing wrong?

```<code> struct ContentView: View {
    var videoUrl = Bundle.main.url(forResource: "test", withExtension: "mp4")!

    var body: some View {
       AVPlayerView(videoURL: videoUrl)
    }
 }

 struct AVPlayerView: UIViewControllerRepresentable {
    var videoURL: URL

    func updateUIViewController(_ playerController: AVPlayerViewController, context: Context) {

    }

    func makeUIViewController(context: Context) -> AVPlayerViewController {
       let item = AVPlayerItem(url: videoURL)
       let player = AVPlayer(playerItem: item)

       let playerController = AVPlayerViewController()
       playerController.player = player
       playerController.showsPlaybackControls = true

       player.play()

       return playerController
   }
}
</code>```

I also tried VideoPlayer(player: AVPLayer) from SwiftUI but same result. On the other hand, if I create a UIKit project from scratch with AVPlayerviewController, everything works fine on both iOS/tvOS. AVplayerItem is not an option for me as I want to utilize Apple default controls. Is there a focus or layout issue? I do see some autlayout logs from the console:

```<code>2023-01-04 21:02:07.254670-0800 rfrfrf[58048:622274] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600001fbfde0 H:|-(95)-[UIStackView:0x7f79ecc091c0]   (active, names: '|':UIView:0x7f79ecc06d80 )>",
    "<NSLayoutConstraint:0x600001fbfd90 UIStackView:0x7f79ecc091c0.trailing == UIView:0x7f79ecc06d80.trailing - 95   (active)>",
    "<NSLayoutConstraint:0x600001ffc870 H:|-(0)-[UIView:0x7f79ecc06d80]   (active, names: '|':_AVFocusContainerView:0x7f79ec907ed0 )>",
    "<NSLayoutConstraint:0x600001ffc8c0 UIView:0x7f79ecc06d80.trailing == _AVFocusContainerView:0x7f79ec907ed0.trailing   (active)>",
    "<NSLayoutConstraint:0x600001ffa120 '_UITemporaryLayoutWidth' _AVFocusContainerView:0x7f79ec907ed0.width == 0   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001fbfd90 UIStackView:0x7f79ecc091c0.trailing == UIView:0x7f79ecc06d80.trailing - 95   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
</code>```

Body:
My project is currently using SwiftUI but for a feature I need to use AVPlayerviewController to play a video. The code I provided below works well on iOS but on tvOS the player controls are not visible/focusable. What am I doing wrong?

 struct ContentView: View {
    var videoUrl = Bundle.main.url(forResource: "test", withExtension: "mp4")!

    var body: some View {
       AVPlayerView(videoURL: videoUrl)
    }
 }

 struct AVPlayerView: UIViewControllerRepresentable {
    var videoURL: URL

    func updateUIViewController(_ playerController: AVPlayerViewController, context: Context) {

    }

    func makeUIViewController(context: Context) -> AVPlayerViewController {
       let item = AVPlayerItem(url: videoURL)
       let player = AVPlayer(playerItem: item)

       let playerController = AVPlayerViewController()
       playerController.player = player
       playerController.showsPlaybackControls = true

       player.play()

       return playerController
   }
}

I also tried VideoPlayer(player: AVPLayer) from SwiftUI but same result. On the other hand, if I create a UIKit project from scratch with AVPlayerviewController, everything works fine on both iOS/tvOS. AVplayerItem is not an option for me as I want to utilize Apple default controls. Is there a focus or layout issue? I do see some autlayout logs from the console:

2023-01-04 21:02:07.254670-0800 rfrfrf[58048:622274] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600001fbfde0 H:|-(95)-[UIStackView:0x7f79ecc091c0]   (active, names: '|':UIView:0x7f79ecc06d80 )>",
    "<NSLayoutConstraint:0x600001fbfd90 UIStackView:0x7f79ecc091c0.trailing == UIView:0x7f79ecc06d80.trailing - 95   (active)>",
    "<NSLayoutConstraint:0x600001ffc870 H:|-(0)-[UIView:0x7f79ecc06d80]   (active, names: '|':_AVFocusContainerView:0x7f79ec907ed0 )>",
    "<NSLayoutConstraint:0x600001ffc8c0 UIView:0x7f79ecc06d80.trailing == _AVFocusContainerView:0x7f79ec907ed0.trailing   (active)>",
    "<NSLayoutConstraint:0x600001ffa120 '_UITemporaryLayoutWidth' _AVFocusContainerView:0x7f79ec907ed0.width == 0   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001fbfd90 UIStackView:0x7f79ecc091c0.trailing == UIView:0x7f79ecc06d80.trailing - 95   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.


问:
How to update a field of a nested object in Firestore array field with React?
I have the following collection:

collection firebase

And within this collection (0) I have nested modules -> videos as shown below:

enter image description here

What I want to achieve is that in the section, for example: modules[0].videos[0], the property finishedState = true. I am trying as follows:

```<code>try {
      const cursos = doc(firebase.db, "misCursos", "7eIHn6FtYIOcFEWq2mXE");

      await updateDoc(cursos, {
        "0.modulos.0.videos.0.videoFinalizado": true,
      });
    } catch (error) {
      console.log(error);

}
</code>```

But this removes all other modules with their videos and leaves me only **modules[0] -> videos[0] -> **finishState: true

My question is, how can I do to modify ONLY the property that belongs to that section?

Body:
I have the following collection:

collection firebase

And within this collection (0) I have nested modules -> videos as shown below:

enter image description here

What I want to achieve is that in the section, for example: modules[0].videos[0], the property finishedState = true. I am trying as follows:

try {
      const cursos = doc(firebase.db, "misCursos", "7eIHn6FtYIOcFEWq2mXE");

      await updateDoc(cursos, {
        "0.modulos.0.videos.0.videoFinalizado": true,
      });
    } catch (error) {
      console.log(error);

}

But this removes all other modules with their videos and leaves me only **modules[0] -> videos[0] -> **finishState: true

My question is, how can I do to modify ONLY the property that belongs to that section?


问:
trying to implement a render-as-you-type markdown input box, how do I save previous rendering results?
So I've been trying to create a simple table component like the one notion have, where you could use simple markdown syntax to create bold text or code. Most importantly, unlike most demo of markdown libraries, it renders on the input field itself.

Here is my demo: https://codesandbox.io/s/priceless-smoke-jxgf7v?file=/src/App.js

You could try to input something like *hello* world and the hello would become italics. However, if I now put a pair of `` around world, the style of hello would be cleared. The reason is that I am feeding the node.innerText to the markdown parser every time I determined there is a markdown match (like a pair of * has been typed). And since there is no markdown indicators around hello, there is no way the previous style can be pertained.

How do I keep previous rendering results?

I've tried to convert the innerHTML back to markdown first, but it would escape characters like *.