问:
python-telegram-bot stops working after 5 min
I have created a telegram bot that sends screenshots of the browser webpage. I have used python-selenium package in order to connect browser with telegram-bot but each time my bot stops working after 5min, here is the full log

ERROR:telegram.ext.dispatcher:No error handlers are registered, logging exception.
Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 402, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 398, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read
    return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 259, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 68, in request
    return self.request_encode_body(method, url, fields=fields,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 347, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\packages\six.py", line 686, in reraise
    raise value
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 404, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 321, in _raise_timeout
    raise exc_cls(*args)
telegram.vendor.ptb_urllib3.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=5.0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\ext\utils\promise.py", line 96, in run
    self._result = self.pooled_function(*self.args, **self.kwargs)
  File "C:\Users\Evilreborn\Desktop\tmp\test.py", line 53, in status
    context.bot.send_chat_action(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 130, in decorator
    result = func(*args, **kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 2023, in send_chat_action
    result = self._post('sendChatAction', data, timeout=timeout, api_kwargs=api_kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 295, in _post
    return self.request.post(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 356, in post
    result = self._request_wrapper(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 261, in _request_wrapper
    raise TimedOut() from error
telegram.error.TimedOut: Timed out
```
<p>variable USER_ID contains my userid so that no one else can use the bot.</p>
<p><strong>My program:</strong></p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
import os
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram import ChatAction

BOT_TOKEN = 504XXXXXX:AAGXXXXXXXXXXXXXXXXXXXXXXX
USER_ID = 123456

options = webdriver.ChromeOptions()
browser = webdriver.Chrome(options=options)

updater = Updater(token=BOT_TOKEN, use_context=True)
dp = updater.dispatcher

def status(update, context):
    user = update.message.from_user
    if user["id"] == int(USER_ID):
        browser.save_screenshot("snapshot.png")
        context.bot.send_chat_action(
            chat_id=USER_ID, action=ChatAction.UPLOAD_PHOTO, timeout=100)
        context.bot.send_photo(
            chat_id=USER_ID, photo=open("snapshot.png", "rb"), timeout=100
        )
        os.remove("snapshot.png")
    else:
        update.message.reply_text(
            "You are not authorized to use this bot"
        )

def main():
    browser.get("https://google.com")
    dp.add_handler(CommandHandler("status", status, run_async=True))

    updater.start_polling(timeout=100)
    #updater.idle()

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

Packages used:

```<code>python_telegram_bot==13.7
selenium==3.141.0
</code>```

What I have tried till now:

I have tried to increase the timeout but still, the problem persists.

I have gone through all preexisting questions on StackOverflow but none of them works for me.

Removed if user["id"] == int(USER_ID): this if-else block

context.bot.send_chat_action(chat_id=USER_ID, action=ChatAction.UPLOAD_PHOTO, timeout=100) removed the line where the error occured but still facing the same issue

There is no problem with respect to internet connection

Bot crashes when I send "/status" (after 5 min from startup). if I keep on sending "/status" in less than 5min intervals it runs smoothly but if there is no activity for 5min it starts sending this error.

The problem is not with respect to the internet connection.  Since I thought it might be an issue so created a Virtual Machine/RDP/VPS on Azure platform of 16GB RAM and tested it on but still, it didn't work. Also, I have tried increasing the timeout of context.bot.send_chat_action but it didn't work.

One more thing which I have observed is that after getting this error if I send /status it works (even after 5 min) if I send again after 5 min it doesn't work, so it works in an alternative manner one time it throws the error and the next time it works.

I'm having this issue for the past 8 days, if anyone can help me, please help.

thankyou for giving your valuable time to my issue,
thanking you

Note: This question was forwarded to both the python-telegram-bot user group and the issue tracker

答:
You increased the timeout for the call to context.bot.send_photo, but the traceback indicates that the timeout happens for the call to context.bot.send_chat_action.
If you have frequent timeout problems, I suggest to try & stabilize your internet connection. Please also have a look at this wiki page on handling network exception.

Disclaimer: I'm currently the maintainer of python-telegram-bot

Body:
I have created a telegram bot that sends screenshots of the browser webpage. I have used python-selenium package in order to connect browser with telegram-bot but each time my bot stops working after 5min, here is the full log

ERROR:telegram.ext.dispatcher:No error handlers are registered, logging exception.
Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 402, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 398, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read
    return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 259, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 68, in request
    return self.request_encode_body(method, url, fields=fields,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 347, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\packages\six.py", line 686, in reraise
    raise value
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 404, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout,
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 321, in _raise_timeout
    raise exc_cls(*args)
telegram.vendor.ptb_urllib3.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=5.0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\ext\utils\promise.py", line 96, in run
    self._result = self.pooled_function(*self.args, **self.kwargs)
  File "C:\Users\Evilreborn\Desktop\tmp\test.py", line 53, in status
    context.bot.send_chat_action(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 130, in decorator
    result = func(*args, **kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 2023, in send_chat_action
    result = self._post('sendChatAction', data, timeout=timeout, api_kwargs=api_kwargs)
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\bot.py", line 295, in _post
    return self.request.post(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 356, in post
    result = self._request_wrapper(
  File "C:\Users\Evilreborn\AppData\Local\Programs\Python\Python310\lib\site-packages\telegram\utils\request.py", line 261, in _request_wrapper
    raise TimedOut() from error
telegram.error.TimedOut: Timed out

variable USER_ID contains my userid so that no one else can use the bot.

My program:

from selenium import webdriver
import os
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram import ChatAction

BOT_TOKEN = 504XXXXXX:AAGXXXXXXXXXXXXXXXXXXXXXXX
USER_ID = 123456

options = webdriver.ChromeOptions()
browser = webdriver.Chrome(options=options)

updater = Updater(token=BOT_TOKEN, use_context=True)
dp = updater.dispatcher

def status(update, context):
    user = update.message.from_user
    if user["id"] == int(USER_ID):
        browser.save_screenshot("snapshot.png")
        context.bot.send_chat_action(
            chat_id=USER_ID, action=ChatAction.UPLOAD_PHOTO, timeout=100)
        context.bot.send_photo(
            chat_id=USER_ID, photo=open("snapshot.png", "rb"), timeout=100
        )
        os.remove("snapshot.png")
    else:
        update.message.reply_text(
            "You are not authorized to use this bot"
        )

def main():
    browser.get("https://google.com")
    dp.add_handler(CommandHandler("status", status, run_async=True))

    updater.start_polling(timeout=100)
    #updater.idle()

if __name__ == "__main__":
    main()

Packages used:

python_telegram_bot==13.7
selenium==3.141.0

What I have tried till now:

I have tried to increase the timeout but still, the problem persists.

I have gone through all preexisting questions on StackOverflow but none of them works for me.

Removed if user["id"] == int(USER_ID): this if-else block

context.bot.send_chat_action(chat_id=USER_ID, action=ChatAction.UPLOAD_PHOTO, timeout=100) removed the line where the error occured but still facing the same issue

There is no problem with respect to internet connection

Bot crashes when I send "/status" (after 5 min from startup). if I keep on sending "/status" in less than 5min intervals it runs smoothly but if there is no activity for 5min it starts sending this error.

The problem is not with respect to the internet connection.  Since I thought it might be an issue so created a Virtual Machine/RDP/VPS on Azure platform of 16GB RAM and tested it on but still, it didn't work. Also, I have tried increasing the timeout of context.bot.send_chat_action but it didn't work.

One more thing which I have observed is that after getting this error if I send /status it works (even after 5 min) if I send again after 5 min it doesn't work, so it works in an alternative manner one time it throws the error and the next time it works.

I'm having this issue for the past 8 days, if anyone can help me, please help.

thankyou for giving your valuable time to my issue,
thanking you

Note: This question was forwarded to both the python-telegram-bot user group and the issue tracker


来源: stackexchange

问:
In Redisgraph, how can I store the numeric value of 0?
I'm using Redisgraph. I'm using this query:

```<code>MERGE (p:Person { age: 0 } )
RETURN p
</code>```

But what I get is age: "".

If I query:

```<code>MERGE (p:Person { age: 12 } )
RETURN p
</code>```

This correctly store age: 12 (without quotes).

How can I store the numeric value of 0?
Thank you!

答:
A minimal example which create a node with an attribute with the value 0 and retrieves it using redisgraph.js

const RedisGraph = require("redisgraph.js").Graph;
let graph = new RedisGraph("G");

(async () =>{
        await graph.query("CREATE (:L {v:0})");
        let res = await graph.query("MATCH (a) RETURN a, a.v");
        while (res.hasNext()) {
            let record = res.next();
            console.log(record.get("a"));
            console.log(record.get("a.v"));
        }

        graph.deleteGraph();
        graph.close();

    })();
```
<p>Output:</p>
```Node { id: 1, label: undefined, properties: { v: 0 } }
0
```

@albertoSpinella would you mind sharing a reproducible snippet?

ContentLicense: CC BY-SA 4.0

Body:
I'm using Redisgraph. I'm using this query:

MERGE (p:Person { age: 0 } )
RETURN p

But what I get is age: "".

If I query:

MERGE (p:Person { age: 12 } )
RETURN p

This correctly store age: 12 (without quotes).

How can I store the numeric value of 0?
Thank you!

Body:
A minimal example which create a node with an attribute with the value 0 and retrieves it using redisgraph.js

const RedisGraph = require("redisgraph.js").Graph;
let graph = new RedisGraph("G");

(async () =>{
        await graph.query("CREATE (:L {v:0})");
        let res = await graph.query("MATCH (a) RETURN a, a.v");
        while (res.hasNext()) {
            let record = res.next();
            console.log(record.get("a"));
            console.log(record.get("a.v"));
        }

        graph.deleteGraph();
        graph.close();

    })();

Output:

Node { id: 1, label: undefined, properties: { v: 0 } }
0

@albertoSpinella would you mind sharing a reproducible snippet?


问:
Syntax for outputting raw with 'using'
I'm implementing AuthorizeNet into my site and as per [this posting] I am to use something like:

```<code>@using (Html.BeginSIMForm("http://...", 1.99M, "...", "...", true))
{
    @Html.CheckoutFormInputs(true);
    @Html.Hidden("order_id", "1234");
    <input type = "submit" value = "Pay" />
}
</code>```

the trouble is that the BeginSIMForm method outputs HTML which, of course, gets escaped by Razor, so I need to output raw.

I've tried:

```<code>@Html.Raw(using(html.BeginSIMForm()) { ... })
</code>```

but that's no good.  I can't quite get the syntax right.  is there a way to tell Razor to generate raw output between certain markers?

* update *

I missed something which was in the posting.  what I need to do is wrap the call to .CheckoutFormInputs() like this:

```<code>@Html.Raw(Html.CheckoutFormInputs(true));
</code>```

and that produces the right output... however, the call to .BeginSIMForm() produces output (a form) at the very top of my page and breaks everything.  grr...

答: Based on the thread you referenced, it seems like that component is not implemented correctly with respect to how it writes the output. You should contact the authors of that library and verify that it supports MVC 3 including the Razor view engine.</p>

ContentLicense: CC BY-SA 3.0

Title: Syntax for outputting raw with 'using'

Body:
I'm implementing AuthorizeNet into my site and as per [this posting] I am to use something like:

@using (Html.BeginSIMForm("http://...", 1.99M, "...", "...", true))
{
    @Html.CheckoutFormInputs(true);
    @Html.Hidden("order_id", "1234");
    <input type = "submit" value = "Pay" />
}

the trouble is that the BeginSIMForm method outputs HTML which, of course, gets escaped by Razor, so I need to output raw.

I've tried:

@Html.Raw(using(html.BeginSIMForm()) { ... })

but that's no good.  I can't quite get the syntax right.  is there a way to tell Razor to generate raw output between certain markers?

* update *

I missed something which was in the posting.  what I need to do is wrap the call to .CheckoutFormInputs() like this:

@Html.Raw(Html.CheckoutFormInputs(true));

and that produces the right output... however, the call to .BeginSIMForm() produces output (a form) at the very top of my page and breaks everything.  grr...


问:
How to add button in scroll View using script in unity
I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;</p>
```<code>public string allNames;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            Debug.Log(separatedNames[i]);
            //make buttons here and attach them to scroll View
        }
    }
}
</code>```

答:
I found a video that applied @ShafqatJamilKhan suggestion. Posting my code here for reference.</p>
```<code>//content reference of scroll view
[SerializeField] Transform contentPanel;

[SerializeField] GameObject buttonPrefab;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        string allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

       // prefab button y position and yPosition should be the same.
        float yPosition = 115;

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            GameObject button = (GameObject)Instantiate(buttonPrefab);
            string name = separatedNames[i];
            button.GetComponentInChildren<Text>().text = name;

            button.GetComponent<Button>().onClick.AddListener(
                // your function whatever you want to do
                () => { customFunction(name); });

            // applying y positions so the buttons dont overlap

            button.transform.SetPositionAndRotation(new Vector3(0.0f, yPosition, 0.0f), new Quaternion(0.0f, 0.0f, 0.0f,0.0f));
            button.transform.SetParent(contentPanel,false);
            yPosition -= 35;
        }
    }
}
</code>```

Body:
I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;

public string allNames;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            Debug.Log(separatedNames[i]);
            //make buttons here and attach them to scroll View
        }
    }
}

Body:
I found a video that applied @ShafqatJamilKhan suggestion. Posting my code here for reference.

//content reference of scroll view
[SerializeField] Transform contentPanel;

[SerializeField] GameObject buttonPrefab;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        string allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

       // prefab button y position and yPosition should be the same.
        float yPosition = 115;

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            GameObject button = (GameObject)Instantiate(buttonPrefab);
            string name = separatedNames[i];
            button.GetComponentInChildren<Text>().text = name;

            button.GetComponent<Button>().onClick.AddListener(
                // your function whatever you want to do
                () => { customFunction(name); });

            // applying y positions so the buttons dont overlap

            button.transform.SetPositionAndRotation(new Vector3(0.0f, yPosition, 0.0f), new Quaternion(0.0f, 0.0f, 0.0f,0.0f));
            button.transform.SetParent(contentPanel,false);
            yPosition -= 35;
        }
    }
}


问:
Kernel space write a file
I'm trying to write a file /proc/test/enable in kernel 5.10 C code.

I can write it in user space by calling fwrite.

When I using kernel_write in kernel C code, I will get the error kernel write not supported for file test/enable and error code 22.

```<code>struct file *filp;
char context[] = "test";
filp = filp_open("/proc/test/enable", O_WRONLY, 0);
int err = kernel_write(filp, (void *)context, sizeof(context), &filp->f_pos);
dev_info(afe->dev, "%s(), DONE, code = %d", __func__, err);
</code>```

I can't understand why kernel_write can't get proc file write function, but userspace fwrite can

答:
For support "normal" write (from userspace), a file may define .write or .write_iter operations (in its struct file_operations).

But writing from the kernel can use only .write_iter operation.
For support writing your file from the kernel, you need to define .write_iter operation for the file instead of .write one.

The failed check for your case is

```<code>    /*
     * Also fail if ->write_iter and ->write are both wired up as that
     * implies very convoluted semantics.
     */
    if (unlikely(!file->f_op->write_iter || file->f_op->write))
        return warn_unsupported(file, "write");
</code>```

Title: Kernel space write a file

Body:
I'm trying to write a file /proc/test/enable in kernel 5.10 C code.

I can write it in user space by calling fwrite.

When I using kernel_write in kernel C code, I will get the error kernel write not supported for file test/enable and error code 22.

struct file *filp;
char context[] = "test";
filp = filp_open("/proc/test/enable", O_WRONLY, 0);
int err = kernel_write(filp, (void *)context, sizeof(context), &filp->f_pos);
dev_info(afe->dev, "%s(), DONE, code = %d", __func__, err);

I can't understand why kernel_write can't get proc file write function, but userspace fwrite can

Body:
For support "normal" write (from userspace), a file may define .write or .write_iter operations (in its struct file_operations).

But writing from the kernel can use only .write_iter operation.
For support writing your file from the kernel, you need to define .write_iter operation for the file instead of .write one.

The failed check for your case is

    /*
     * Also fail if ->write_iter and ->write are both wired up as that
     * implies very convoluted semantics.
     */
    if (unlikely(!file->f_op->write_iter || file->f_op->write))
        return warn_unsupported(file, "write");


问:
Javascript Textbox "Scrubber"
I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.

I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.

答:
Is there a set of keywords? And can be they be combined only in a certain fashion?

Looks like couple of regex patterns will be able to do the trick.

e.g: to match "9030 OUT FU [1234 TEST]" regex would be: /\d{4} OUT FU \[\d{4}\]/.

OUT FU and can be substituted with \w{3} and \w{2} respectively (unless you do not want any word to be allowed).

Title: Javascript Textbox "Scrubber"


问:
VSCode Remote SSH to Linux - Connecting was canceled
I am trying to connect from my Windows 10 machine to my Ubuntu Linux server (16.04.6) using Remote SSH.
To do this I've read many different tutorials but have no success.

I am able to connect from my Windows 10 command prompt to the Ubuntu Linux server via ssh without any problems. I even used ssh-keygen to generate a private and a public key and copied the public key to the appropriate directory on the Linux Server (.ssh).

In VsCode I installed the extension Remote-SSH added my host to my configuration file c:\user.ssh\config:

```<code>Host <ip-address>
  HostName <ip-address>
  User <username>
</code>```

Then I clicked in VSCode the button bottom left "Open a remote Window" and chosed my host. A new windows opens and VSCode is trying to connect. Then I see a window with the error message: "Could not establish connection to . Connection was canceled". This is the log.

```<code>[11:53:17.573] Log Level: 2
[11:53:17.582] remote-ssh@0.51.0
[11:53:17.583] win32 x64
[11:53:17.586] SSH Resolver called for "ssh-remote+<ip-address>", attempt 1
[11:53:17.587] SSH Resolver called for host: <ip-address>
[11:53:17.587] Setting up SSH remote "<ip-address>"
[11:53:17.648] Using commit id "5763d909d5f12fe19f215cbfdd29a91c0fa9208a" and quality "stable" for server
[11:53:17.650] Install and start server if needed
[11:53:18.624] getPlatformForHost was canceled
[11:53:18.625] Resolver error: Connecting was canceled
[11:53:18.640] ------
</code>```

Again, I can connect to the same linux server via ssh from my local machine (Win 10) without any problems.

答:
I tried the following that worked for me:

Click on View > Command Palette  (alternatively press CTRL + Shift + P)

Start typing:

Remote SSH: Kill

Click on the first option that says: Remote-SSH: kill VS Code Server on Host...

From the options, click on the server you are having trouble connecting to. This will kill that VScode server.

Now just try to reconnect:
a. View > Command Palette  (alternatively press CTRL + Shift + P)
b. Start typing:
SSH Remote-SSH: Connect to host...
c. Select the server.

Body:
I am trying to connect from my Windows 10 machine to my Ubuntu Linux server (16.04.6) using Remote SSH.
To do this I've read many different tutorials but have no success.

I am able to connect from my Windows 10 command prompt to the Ubuntu Linux server via ssh without any problems. I even used ssh-keygen to generate a private and a public key and copied the public key to the appropriate directory on the Linux Server (.ssh).

In VsCode I installed the extension Remote-SSH added my host to my configuration file c:\user.ssh\config:

Host <ip-address>
  HostName <ip-address>
  User <username>

Then I clicked in VSCode the button bottom left "Open a remote Window" and chosed my host. A new windows opens and VSCode is trying to connect. Then I see a window with the error message: "Could not establish connection to . Connection was canceled". This is the log.

[11:53:17.573] Log Level: 2
[11:53:17.582] remote-ssh@0.51.0
[11:53:17.583] win32 x64
[11:53:17.586] SSH Resolver called for "ssh-remote+<ip-address>", attempt 1
[11:53:17.587] SSH Resolver called for host: <ip-address>
[11:53:17.587] Setting up SSH remote "<ip-address>"
[11:53:17.648] Using commit id "5763d909d5f12fe19f215cbfdd29a91c0fa9208a" and quality "stable" for server
[11:53:17.650] Install and start server if needed
[11:53:18.624] getPlatformForHost was canceled
[11:53:18.625] Resolver error: Connecting was canceled
[11:53:18.640] ------

Again, I can connect to the same linux server via ssh from my local machine (Win 10) without any problems.


问:
How to round robin by UUID in SQL database?
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query
```

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)

答:
You can combine two queries where the second is only run if the first one didn't return anything:

```<code>with next_agent as (
  SELECT id
  FROM agents
  WHERE id > $1 -- the last ID retrieved or NULL if it's the first
  ORDER BY id
  limit 1
)
select *
from next_agent
union all
(
  select *
  from agents
  where not exists (select * from next_agent)
  order by id
  limit 1
)
</code>```

So if $1 is null (first call) or 'uuid4' the next_agent CTE will not return anything. And in that case the second part of the UNION in the outer query will be run picking the "first" row

Body:
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)

Body:
You can combine two queries where the second is only run if the first one didn't return anything:

with next_agent as (
  SELECT id
  FROM agents
  WHERE id > $1 -- the last ID retrieved or NULL if it's the first
  ORDER BY id
  limit 1
)
select *
from next_agent
union all
(
  select *
  from agents
  where not exists (select * from next_agent)
  order by id
  limit 1
)

So if $1 is null (first call) or 'uuid4' the next_agent CTE will not return anything. And in that case the second part of the UNION in the outer query will be run picking the "first" row


问:
Laravel Spatial error on save or retrieve
My code was working fine and all of the sudden I'm getting a real strange error. (really all of the sudden! I didn't change a line of code! Only my mac got updated to latest version which I honestly don't see how that could be an issue!)

When I try to save or retrieve any entity that has a point data type in it I get this exception:

PHP Fatal error:  During inheritance of JsonSerializable: Uncaught ErrorException: Return type of Grimzy\LaravelMysqlSpatial\Types\Point::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/amirpeivandi/Projects/nwrewards/vendor/grimzy/laravel-mysql-spatial/src/Types/Point.php:93

Any idea what this could be?

Amir

答:
I believe this error is caused by failing to add the spatial trait and  protected spatial field to the model.

```<code>use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;

class User
{
    use SpatialTrait;

    protected $spatialFields = [
        'location',
    ];
}
</code>```

You can read about this requirement on GitHub here.

Body:
I believe this error is caused by failing to add the spatial trait and  protected spatial field to the model.

use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;

class User
{
    use SpatialTrait;

    protected $spatialFields = [
        'location',
    ];
}

You can read about this requirement on GitHub here.


问:
Need to pass tuples to subclass to draw triangle
I want to draw a triangle from a class, so I call the function

```<code>pygame.draw.polygon()
</code>```

Now, the problem is that I need to pass the points in a manner that will allow me to calculate the centre of the triangle.

I was trying to pass the tuples one by one in this way

```<code>self.first_point = (int, int)
self.second_point = (int, int)
self.third_point = (int, int)
</code>```

so that I can then access the single tuple values.

Then pass the three points like this

```<code>self.position = [self.first_point, self.second_point, self.third_point]
</code>```

But for some reason, it doesn't work.

This is the error I get

```<code>File "C:/Users/oricc/PycharmProjects/designAChessboardChallange/display.py", line 178, in <module>
    white_archer_3 = Archer(white, [(100, 100), (200, 200), (300, 300)])
[(100, 100), (200, 200), (300, 300)]
  File "C:/Users/oricc/PycharmProjects/designAChessboardChallange/display.py", line 132, in __init__
    self.triangle = pygame.draw.polygon(game_window, colour, self.position)
TypeError: points must be number pairs
</code>```

By number of pairs, the Pygame documentation gives as an example

e.g. [(x1, y1), (x2, y2), (x3, y3)]

In fact, when I print the position I pass I get, as you can see from the error above

```<code>[(100, 100), (200, 200), (300, 300)]
</code>```

Anyone can help with this?
Is there another manner to calculate the centre without accessing the xs and ys like that?

Full code here

```<code>import pygame
import sys
from coordinator import coordinator

# set up the display
pygame.init()
window_size = (800, 800)
game_window = pygame.display.set_mode(size=window_size)
pygame.display.set_caption('My Game')

# defines classes and related methods

class WhiteSquare:
    def __init__(self):
        self.height = int(window_size[0] / 8)
        self.width = int(window_size[1] / 8)
        self.white_square = pygame.Surface((self.height, self.width))
        self.white_square.fill((255, 255, 255))

class BlackSquare:
    def __init__(self):
        self.height = int(window_size[0] / 8)
        self.width = int(window_size[1] / 8)
        self.black_square = pygame.Surface((self.height, self.width))
        self.black_square.fill((0, 0, 0))

class ChessBoard:
    def __init__(self):
        self.ws = ws
        self.bs = bs
        self.white_columns = white_columns
        self.black_columns = black_columns

    def draw(self):
        for w_columns in self.white_columns:
            game_window.blit(self.ws.white_square, w_columns)

        for b_columns in self.black_columns:
            game_window.blit(self.bs.black_square, b_columns)

# declare letters and numbers
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8']

# create coordinates
coordinates = []
for item_letter in letters:
    letter = item_letter
    for item_number in numbers:
        number = item_number
        coordinates.append(letter + number)

# create coordinates values components
x_values = []
for number in range(0, 800, 100):
    x = number
    x_values.append(x)

y_values = []
for number in range(0, 800, 100):
    y = number
    y_values.append(y)

# create coordinate values
coordinate_values = []
for x in x_values:
    for y in y_values:
        coordinate_values.append((x, y))

# assign values to coordinates
squares_coordinates = dict(zip(coordinates, coordinate_values))

# Background for units
class CircleSurface:
    def __init__(self):
        self.circle_surface = pygame.Surface((100, 100), flags=pygame.SRCALPHA)
        pygame.draw.circle(self.circle_surface, (255, 0, 0), (50, 50), 45)

# define colours
black = (0, 0, 0)
white = (255, 255, 255)
gold = (153, 153, 0)

class Unit:
    def __init__(self, colour, position):

        # define Unit colour
        self.colour = colour

        # define Unit position
        self.position = position

class Knight(Unit):
    def __init__(self, colour, position):

        # draw circle, inline, and outline
        super().__init__(colour, position)
        self.center_x = position[0]
        self.center_y = position[1]
        self.colour = colour
        self.position = position
        circle_radius = 40
        self.circle = pygame.draw.circle(game_window, colour, self.position, circle_radius)
        self.circle_outline = pygame.draw.circle(game_window, gold, self.position, circle_radius, 5)
        self.circle_inline = pygame.draw.circle(game_window, gold, self.position, (circle_radius - 10), 5)

        # draw letter
        pygame.font.init()
        my_font_size = 50
        my_font = pygame.font.SysFont('Time New Roman', my_font_size)
        text_surface = my_font.render('K', 1, gold)
        center_text = text_surface.get_rect(center=(self.center_x, self.center_y))
        game_window.blit(text_surface, center_text)

class Archer(Unit):
    def __init__(self, colour, position):
        super().__init__(colour, position)
        self.first_point = (int, int)
        self.second_point = (int, int)
        self.third_point = (int, int)
        self.position = [self.first_point, self.second_point, self.third_point]
        print(position)
        self.triangle = pygame.draw.polygon(game_window, colour, self.position)
        self.triangle_outline = pygame.draw.polygon(game_window, gold, self.position, 5)
        self.triangle_inline = pygame.draw.polygon(game_window, gold, self.position, 5)

        # draw letter
        # pygame.font.init()
        # my_font_size = 50
        # my_font = pygame.font.SysFont('Time New Roman', my_font_size)
        # text_surface = my_font.render('A', 1, gold)
        # center_text = text_surface.get_rect(center=(self.center_x, self.center_y))
        # game_window.blit(text_surface, center_text)

# Sets and gets the coordinates for black and white squares

coordinator = coordinator()

black_columns = coordinator[2] + coordinator[3]
white_columns = coordinator[0] + coordinator[1]

# Creates needed objects

ws = WhiteSquare()
bs = BlackSquare()
cb = ChessBoard()
cs = CircleSurface()

# Event loop (outer)
while 1:

    # Event loop (inner)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # Draws the chessboard
    cb.draw()

    # Draws white pieces in their initial position
    white_knight_1 = Knight(white, (150, 650))
    white_knight_2 = Knight(white, (650, 650))
    white_archer_3 = Archer(white, [(100, 100), (200, 200), (300, 300)])

    pygame.display.update()
</code>```

Thank you

答:
you could also do this: self.first_point = (int(0), int(0)) as int is not a placeholder but to declare that a variable is an integer str('0') will print '0' you could also input this

```<code>zero = 0
str(zero) #'0'
int(zero) #0
</code>```

and you dont need to put rgb tupels because you can store them in a variable like this

```<code>black = (0, 0, 0)
Display = pygame.display.set_mode((800, 600))
Display.fill(black)
</code>```

Body:
I want to draw a triangle from a class, so I call the function

pygame.draw.polygon()

Now, the problem is that I need to pass the points in a manner that will allow me to calculate the centre of the triangle.

I was trying to pass the tuples one by one in this way

self.first_point = (int, int)
self.second_point = (int, int)
self.third_point = (int, int)

so that I can then access the single tuple values.

Then pass the three points like this

self.position = [self.first_point, self.second_point, self.third_point]

But for some reason, it doesn't work.

This is the error I get

File "C:/Users/oricc/PycharmProjects/designAChessboardChallange/display.py", line 178, in <module>
    white_archer_3 = Archer(white, [(100, 100), (200, 200), (300, 300)])
[(100, 100), (200, 200), (300, 300)]
  File "C:/Users/oricc/PycharmProjects/designAChessboardChallange/display.py", line 132, in __init__
    self.triangle = pygame.draw.polygon(game_window, colour, self.position)
TypeError: points must be number pairs

By number of pairs, the Pygame documentation gives as an example

e.g. [(x1, y1), (x2, y2), (x3, y3)]

In fact, when I print the position I pass I get, as you can see from the error above

[(100, 100), (200, 200), (300, 300)]

Anyone can help with this?
Is there another manner to calculate the centre without accessing the xs and ys like that?

Full code here

import pygame
import sys
from coordinator import coordinator

# set up the display
pygame.init()
window_size = (800, 800)
game_window = pygame.display.set_mode(size=window_size)
pygame.display.set_caption('My Game')

# defines classes and related methods

class WhiteSquare:
    def __init__(self):
        self.height = int(window_size[0] / 8)
        self.width = int(window_size[1] / 8)
        self.white_square = pygame.Surface((self.height, self.width))
        self.white_square.fill((255, 255, 255))

class BlackSquare:
    def __init__(self):
        self.height = int(window_size[0] / 8)
        self.width = int(window_size[1] / 8)
        self.black_square = pygame.Surface((self.height, self.width))
        self.black_square.fill((0, 0, 0))

class ChessBoard:
    def __init__(self):
        self.ws = ws
        self.bs = bs
        self.white_columns = white_columns
        self.black_columns = black_columns

    def draw(self):
        for w_columns in self.white_columns:
            game_window.blit(self.ws.white_square, w_columns)

        for b_columns in self.black_columns:
            game_window.blit(self.bs.black_square, b_columns)

# declare letters and numbers
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
numbers = ['1', '2', '3', '4', '5', '6', '7', '8']

# create coordinates
coordinates = []
for item_letter in letters:
    letter = item_letter
    for item_number in numbers:
        number = item_number
        coordinates.append(letter + number)

# create coordinates values components
x_values = []
for number in range(0, 800, 100):
    x = number
    x_values.append(x)

y_values = []
for number in range(0, 800, 100):
    y = number
    y_values.append(y)

# create coordinate values
coordinate_values = []
for x in x_values:
    for y in y_values:
        coordinate_values.append((x, y))

# assign values to coordinates
squares_coordinates = dict(zip(coordinates, coordinate_values))

# Background for units
class CircleSurface:
    def __init__(self):
        self.circle_surface = pygame.Surface((100, 100), flags=pygame.SRCALPHA)
        pygame.draw.circle(self.circle_surface, (255, 0, 0), (50, 50), 45)

# define colours
black = (0, 0, 0)
white = (255, 255, 255)
gold = (153, 153, 0)

class Unit:
    def __init__(self, colour, position):

        # define Unit colour
        self.colour = colour

        # define Unit position
        self.position = position

class Knight(Unit):
    def __init__(self, colour, position):

        # draw circle, inline, and outline
        super().__init__(colour, position)
        self.center_x = position[0]
        self.center_y = position[1]
        self.colour = colour
        self.position = position
        circle_radius = 40
        self.circle = pygame.draw.circle(game_window, colour, self.position, circle_radius)
        self.circle_outline = pygame.draw.circle(game_window, gold, self.position, circle_radius, 5)
        self.circle_inline = pygame.draw.circle(game_window, gold, self.position, (circle_radius - 10), 5)

        # draw letter
        pygame.font.init()
        my_font_size = 50
        my_font = pygame.font.SysFont('Time New Roman', my_font_size)
        text_surface = my_font.render('K', 1, gold)
        center_text = text_surface.get_rect(center=(self.center_x, self.center_y))
        game_window.blit(text_surface, center_text)

class Archer(Unit):
    def __init__(self, colour, position):
        super().__init__(colour, position)
        self.first_point = (int, int)
        self.second_point = (int, int)
        self.third_point = (int, int)
        self.position = [self.first_point, self.second_point, self.third_point]
        print(position)
        self.triangle = pygame.draw.polygon(game_window, colour, self.position)
        self.triangle_outline = pygame.draw.polygon(game_window, gold, self.position, 5)
        self.triangle_inline = pygame.draw.polygon(game_window, gold, self.position, 5)

        # draw letter
        # pygame.font.init()
        # my_font_size = 50
        # my_font = pygame.font.SysFont('Time New Roman', my_font_size)
        # text_surface = my_font.render('A', 1, gold)
        # center_text = text_surface.get_rect(center=(self.center_x, self.center_y))
        # game_window.blit(text_surface, center_text)

# Sets and gets the coordinates for black and white squares

coordinator = coordinator()

black_columns = coordinator[2] + coordinator[3]
white_columns = coordinator[0] + coordinator[1]

# Creates needed objects

ws = WhiteSquare()
bs = BlackSquare()
cb = ChessBoard()
cs = CircleSurface()

# Event loop (outer)
while 1:

    # Event loop (inner)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # Draws the chessboard
    cb.draw()

    # Draws white pieces in their initial position
    white_knight_1 = Knight(white, (150, 650))
    white_knight_2 = Knight(white, (650, 650))
    white_archer_3 = Archer(white, [(100, 100), (200, 200), (300, 300)])

    pygame.display.update()

Thank you

Body:
you could also do this: self.first_point = (int(0), int(0)) as int is not a placeholder but to declare that a variable is an integer str('0') will print '0' you could also input this

zero = 0
str(zero) #'0'
int(zero) #0

and you dont need to put rgb tupels because you can store them in a variable like this

black = (0, 0, 0)
Display = pygame.display.set_mode((800, 600))
Display.fill(black)


问:
Search for closes index on SQL table
I have a hypothetical SQL table "EVENTS", with two columns, a UUID index column, and a DateTime column,
The table is populated with values ranging from 1900-01-01 to today, it is not ordered, there are numerous dates missing.

The query that I have to run is basically 'retrieve all events that happened at the requested date (start to the end of the day) or the closest previous date'

If I were looking for all events in a day that I know that exists in the database it would be something as simple as:

```<code>SELECT * FROM Events e
WHERE
e.date BETWEEN $START_OF_DAY AND $END_OF_DAY;
</code>```

But if that date doesn't exist I must retrieve the latest date up to the requested date.

答:
Calculate the most recent date, and do a self join. Although I'm using MYSQL, I believe this is the most generic workaround

CREATE TABLE d0207Event (ID INT ,EventDateTime DATETIME)

INSERT INTO d0207Event
VALUES
(1,'2022-01-01 08:00')
,(2,'2022-01-01 09:00')
,(3,'2022-01-01 10:00')
,(4,'2022-01-03 12:00')

INSERT INTO d0207Event
VALUES
(5, '2021-12-12 08:00');

select t1.*
  from d0207Event t1,
  (
    select min(t1.dat) mindat
      from (
        select t1.*,
               DATEDIFF('2022-01-02', cast(t1.EventDateTime as date)) dat
          from d0207Event t1
    ) t1
     where t1.dat >= 0
 ) t2
 where DATEDIFF('2022-01-02', cast(t1.EventDateTime as date)) = t2.mindat
;
```
<p>There are also many advanced syntaxes that can solve this problem better, depending on which DB you use and your specific application scenario</p>
<p>It seems that you can also choose a database with more syntax, then using an analytic function usually solves the efficiency problem well, since the EVENT table only needs to be queried once.</p>
<pre class="lang-sql prettyprint-override"><code>
CREATE TABLE Event (
ID MEDIUMINT NOT NULL AUTO_INCREMENT
,EventDateTime DATETIME
,PRIMARY KEY (ID));

INSERT INTO Event (EventDateTime)
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00');

select *
  from (
    select t1.*,
           first_value(cast(t1.EventDateTime as date))
                over(order by cast(t1.EventDateTime as date) desc) fv
      from event t1
     where cast(t1.EventDateTime as date) <= '2022-01-03'
) t1
 where cast(t1.EventDateTime as date) = fv
</code>```

Creating a functional index cast(t1.EventDateTime as date), or creating a virtual column directly can make the query easier, otherwise using date_add() is a good way

Title: Search for closes index on SQL table

Body:
I have a hypothetical SQL table "EVENTS", with two columns, a UUID index column, and a DateTime column,
The table is populated with values ranging from 1900-01-01 to today, it is not ordered, there are numerous dates missing.

The query that I have to run is basically 'retrieve all events that happened at the requested date (start to the end of the day) or the closest previous date'

If I were looking for all events in a day that I know that exists in the database it would be something as simple as:

SELECT * FROM Events e
WHERE
e.date BETWEEN $START_OF_DAY AND $END_OF_DAY;

But if that date doesn't exist I must retrieve the latest date up to the requested date.

Body:
Calculate the most recent date, and do a self join. Although I'm using MYSQL, I believe this is the most generic workaround

CREATE TABLE d0207Event (ID INT ,EventDateTime DATETIME)

INSERT INTO d0207Event
VALUES
(1,'2022-01-01 08:00')
,(2,'2022-01-01 09:00')
,(3,'2022-01-01 10:00')
,(4,'2022-01-03 12:00')

INSERT INTO d0207Event
VALUES
(5, '2021-12-12 08:00');

select t1.*
  from d0207Event t1,
  (
    select min(t1.dat) mindat
      from (
        select t1.*,
               DATEDIFF('2022-01-02', cast(t1.EventDateTime as date)) dat
          from d0207Event t1
    ) t1
     where t1.dat >= 0
 ) t2
 where DATEDIFF('2022-01-02', cast(t1.EventDateTime as date)) = t2.mindat
;

There are also many advanced syntaxes that can solve this problem better, depending on which DB you use and your specific application scenario

It seems that you can also choose a database with more syntax, then using an analytic function usually solves the efficiency problem well, since the EVENT table only needs to be queried once.

CREATE TABLE Event (
ID MEDIUMINT NOT NULL AUTO_INCREMENT
,EventDateTime DATETIME
,PRIMARY KEY (ID));

INSERT INTO Event (EventDateTime)
VALUES
('2022-01-01 08:00')
,('2022-01-01 09:00')
,('2022-01-01 10:00')
,('2022-01-03 12:00');

select *
  from (
    select t1.*,
           first_value(cast(t1.EventDateTime as date))
                over(order by cast(t1.EventDateTime as date) desc) fv
      from event t1
     where cast(t1.EventDateTime as date) <= '2022-01-03'
) t1
 where cast(t1.EventDateTime as date) = fv

Creating a functional index cast(t1.EventDateTime as date), or creating a virtual column directly can make the query easier, otherwise using date_add() is a good way


问:
removeElementsInSetDecrementsSize test not going through with HashTable
I have one test that is not going through in this testclass. I have implemented the code that I have tried, however it is not working. I dont know what I am doing wrong. I think that my Hashtable code is correct however, this test does not work.

//TODO: How should I write this test in the testclass.

The message I get is :

```<code>java.lang.AssertionError:
Expected: <7>
     but: was <0>
Expected :<7>
Actual   :<0>
</code>```
```<code>/**
 * An interface describing a generic set. Duplicates are not allowed.
 */
public interface Set<T> {

    boolean add(T elem);

    boolean remove(T elem);

    boolean contains(T elem);

    int size();
}

</code>```
```<code>import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.hash;

/**
 * A hash table-based implementation of the Set interface.
 */
public class HashSet<T> implements Set<T> {
   private List<T>[] table;
    private int size;
    private int capacity;
    private int index;

     /**
     * Creates a hash table with the given capacity (amount of buckets).
     *
     * @throws IllegalArgumentException if capacity <= 0.
     */
    public HashSet(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException(
                "capacity must be a positive, non-zero value! Provided: " + capacity);
        }
     @SuppressWarnings("unchecked") // for this declaration only
      List<T>[] t = new LinkedList[capacity];
      table = t;
      size = 0;
    }

    /**
     * Adds the given element to the set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to add to the set.
     * @return true if the set did not contain the element, otherwise false.
     */
    @Override
    public boolean add(T elem) {
    if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash]== null){
            table[hash] = new LinkedList<T>();
            table[hash].add(elem);
            size ++;
            return true;
        }
        if (table[hash].contains(elem)){
            return false;
        }else{
            table[hash].add(elem);
            size++;
            return true;
        }
    }

    /**
     * Removes the given element from the dictionary, if it is present.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to remove from the set.
     * @return true if the set contained the element, false otherwise.
     */
    @Override
    public boolean remove(T elem) {
        if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            table[hash].remove(elem);
            size --;
            return true;
        }else{
            return false;
        }
    }

    /**
     * Check if an element is in the Set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to look for.
     * @return true if the element is in the set, false otherwise.
     */
    @Override
    public boolean contains(T elem) {
        if (elem == null || elem .equals("")){
            return false;
        }
        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashSet<?> hashSet = (HashSet<?>) o;
        return capacity == hashSet.capacity && size == hashSet.size && index == hashSet.index && Objects.equals(table, hashSet.table);
    }

    @Override
    public int hashCode() {
        return hash(capacity, size, index, table);
    }

    /**
     * Returns the number of elements in this set.
     *
     * Complexity: O(1) expected time.
     *
     * @return The amount of elements in this set.
     */
    @Override
    public int size() {
        return size;
    }
}

</code>```
```<code>import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;

import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.stream.IntStream;
/**
 * Abstract test class for Set implementations.
 *
 * Implementing test classes must override the getIntegerSet method.
 *
 */
public abstract class SetTest {
    @Rule public Timeout globalTimeout = Timeout.seconds(5); // 5 seconds max per method tested

    private Set<Integer> set;
    private final int CAPACITY = 20;
    private int[] uniqueSetElements;
    private int[] elementsNotInSet;

    /**
     * Returns an implementation of Set that can hold at least 'minCapacity'
     * Integers.
     *
     * @param minCapacity The least amount of elements the Set must be able to
     * hold.
     * @return An implementation of Set.
     */
    protected abstract Set<Integer> getIntegerSet(int minCapacity);

    @Before
    public void setUp() {
        // Arrange
        set = getIntegerSet(CAPACITY);
        uniqueSetElements =
            new int[] {-234, 32, 443, Integer.MAX_VALUE, Integer.MIN_VALUE, 0, -231};
        // Works because all elements in uniqueSetElements are more than 2 values apart
        // -2 as Integer.MIN_VALUE - 1 == Integer.MAX_VALUE because of underflow
        elementsNotInSet = Arrays.stream(uniqueSetElements).map(elem -> elem - 2).toArray();

        for (int elem : uniqueSetElements) {
            set.add(elem);
        }
    }

    @Test
    public void removeElementsInSetDecrementsSize() { //TEST
        int expectedSize = uniqueSetElements.length;
        for (int elem : uniqueSetElements) {
            // Act
            set.remove(elem);
        }
        assertThat(set.size(), equalTo(expectedSize));
    }
}
</code>```

答:
You are removing all elements from the set and still expecting the size to be the original size. Set expectedSize to 0 and it would be fine.

@Test
    public void removeElementsInSetDecrementsSize() { //TEST
        int expectedSize = 0;
        for (int elem : uniqueSetElements) {
            // Act
            set.remove(elem);
        }
        assertThat(set.size(), equalTo(expectedSize));
    }
```

Body:
I have one test that is not going through in this testclass. I have implemented the code that I have tried, however it is not working. I dont know what I am doing wrong. I think that my Hashtable code is correct however, this test does not work.

//TODO: How should I write this test in the testclass.

The message I get is :

java.lang.AssertionError:
Expected: <7>
     but: was <0>
Expected :<7>
Actual   :<0>

/**
 * An interface describing a generic set. Duplicates are not allowed.
 */
public interface Set<T> {

    boolean add(T elem);

    boolean remove(T elem);

    boolean contains(T elem);

    int size();
}

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.hash;

/**
 * A hash table-based implementation of the Set interface.
 */
public class HashSet<T> implements Set<T> {
   private List<T>[] table;
    private int size;
    private int capacity;
    private int index;

     /**
     * Creates a hash table with the given capacity (amount of buckets).
     *
     * @throws IllegalArgumentException if capacity <= 0.
     */
    public HashSet(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException(
                "capacity must be a positive, non-zero value! Provided: " + capacity);
        }
     @SuppressWarnings("unchecked") // for this declaration only
      List<T>[] t = new LinkedList[capacity];
      table = t;
      size = 0;
    }

    /**
     * Adds the given element to the set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to add to the set.
     * @return true if the set did not contain the element, otherwise false.
     */
    @Override
    public boolean add(T elem) {
    if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash]== null){
            table[hash] = new LinkedList<T>();
            table[hash].add(elem);
            size ++;
            return true;
        }
        if (table[hash].contains(elem)){
            return false;
        }else{
            table[hash].add(elem);
            size++;
            return true;
        }
    }

    /**
     * Removes the given element from the dictionary, if it is present.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to remove from the set.
     * @return true if the set contained the element, false otherwise.
     */
    @Override
    public boolean remove(T elem) {
        if (elem == null || elem.equals("")){
            return false;
        }

        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            table[hash].remove(elem);
            size --;
            return true;
        }else{
            return false;
        }
    }

    /**
     * Check if an element is in the Set.
     *
     * Complexity: O(1) expected time.
     *
     * @param elem An element to look for.
     * @return true if the element is in the set, false otherwise.
     */
    @Override
    public boolean contains(T elem) {
        if (elem == null || elem .equals("")){
            return false;
        }
        int hash = Math.abs(elem.hashCode() % table.length);

        if (table[hash] != null && table[hash].contains(elem)){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashSet<?> hashSet = (HashSet<?>) o;
        return capacity == hashSet.capacity && size == hashSet.size && index == hashSet.index && Objects.equals(table, hashSet.table);
    }

    @Override
    public int hashCode() {
        return hash(capacity, size, index, table);
    }

    /**
     * Returns the number of elements in this set.
     *
     * Complexity: O(1) expected time.
     *
     * @return The amount of elements in this set.
     */
    @Override
    public int size() {
        return size;
    }
}

import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;

import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.stream.IntStream;
/**
 * Abstract test class for Set implementations.
 *
 * Implementing test classes must override the getIntegerSet method.
 *
 */
public abstract class SetTest {
    @Rule public Timeout globalTimeout = Timeout.seconds(5); // 5 seconds max per method tested

    private Set<Integer> set;
    private final int CAPACITY = 20;
    private int[] uniqueSetElements;
    private int[] elementsNotInSet;

    /**
     * Returns an implementation of Set that can hold at least 'minCapacity'
     * Integers.
     *
     * @param minCapacity The least amount of elements the Set must be able to
     * hold.
     * @return An implementation of Set.
     */
    protected abstract Set<Integer> getIntegerSet(int minCapacity);

    @Before
    public void setUp() {
        // Arrange
        set = getIntegerSet(CAPACITY);
        uniqueSetElements =
            new int[] {-234, 32, 443, Integer.MAX_VALUE, Integer.MIN_VALUE, 0, -231};
        // Works because all elements in uniqueSetElements are more than 2 values apart
        // -2 as Integer.MIN_VALUE - 1 == Integer.MAX_VALUE because of underflow
        elementsNotInSet = Arrays.stream(uniqueSetElements).map(elem -> elem - 2).toArray();

        for (int elem : uniqueSetElements) {
            set.add(elem);
        }
    }

    @Test
    public void removeElementsInSetDecrementsSize() { //TEST
        int expectedSize = uniqueSetElements.length;
        for (int elem : uniqueSetElements) {
            // Act
            set.remove(elem);
        }
        assertThat(set.size(), equalTo(expectedSize));
    }
}


问:
how to return int. if int. is in range 10-19?
Here is my code so far. I want to return all sums, but if sum is in range of 10-19, return 20. Thank you! -Learning student</p>
```<code>def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

def find_sum(num1, num2):
    sum = num1 + num2
    if 10 <= sum <= 19:
        print(20)
    print(sum)

main()
</code>```

答:
[NOTE] this answer was added before OP edited the question to include an if statement in the find_sum method

you can check if a number is less than another value with

```<code>if a_number < some_other_big_number
</code>```

you can check if a number is greater than another number with

```<code>if a_number > some_other_small_number
</code>```

you can check if a number is between 2 numbers with

```<code>if some_other_small_number < a_number and a_number < some_other_big_number
</code>```

which python convieniently lets you rewrite as

```<code>if some_other_small_number < a_number < some_other_big_number
</code>```

using this knowledge you should be able to accomplish your task without problems

any if statement can also have a coresponding else that allows you to take an action if(and only if) the original condition is not met

```<code> if is_between_10_and_19(value):
    do_something(20)
 else:
    do_something(value)
</code>```

Body:
Here is my code so far. I want to return all sums, but if sum is in range of 10-19, return 20. Thank you! -Learning student

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

def find_sum(num1, num2):
    sum = num1 + num2
    if 10 <= sum <= 19:
        print(20)
    print(sum)

main()

Body:
[NOTE] this answer was added before OP edited the question to include an if statement in the find_sum method

you can check if a number is less than another value with

if a_number < some_other_big_number

you can check if a number is greater than another number with

if a_number > some_other_small_number

you can check if a number is between 2 numbers with

if some_other_small_number < a_number and a_number < some_other_big_number

which python convieniently lets you rewrite as

if some_other_small_number < a_number < some_other_big_number

using this knowledge you should be able to accomplish your task without problems

any if statement can also have a coresponding else that allows you to take an action if(and only if) the original condition is not met

 if is_between_10_and_19(value):
    do_something(20)
 else:
    do_something(value)


问:
Oxyplot application - Cannot find referencing error in xaml file
Am new to oxyplot and wish to use it with C# WPF with xaml. My .xaml file has the following code:

```<code><code>
<Window x:Class="CurveMaster.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CurveMaster"
    xmlns:oxy="http://oxyplot.org/wpf"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

<Grid>
    <oxy:Plot Title="{Binding Title}">
        <oxy:Plot.Series>
            <oxy:LineSeries ItemsSource="{Binding Points}"/>
        </oxy:Plot.Series>
    </oxy:Plot>
</Grid>

</Window>
</code>
</code>```

The .xaml.cs file is as follows:

```<code><code>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OxyPlot;
namespace CurveMaster
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class MainViewModel
{
    public MainViewModel()  //Constructor
    {
        this.Title = "My Graph";
        this.Points = new List<DataPoint>
        {
            new DataPoint (0,4),
            new DataPoint (10,13),
            new DataPoint (20,15),
        };
    }
    public string Title { get; private set; }
    public IList <DataPoint> Points { get; private set; }
 }
}

</code>
</code>```

So I'm just trying to run the above simple example but get the following error messages in the xaml file:

The type 'oxy:Plot' was not found. Verify that you are not missing an assembly reference.

The name "MainViewModel" does not exist in the namespace "clr-namespace:CurveMaster".

Now I installed the oxyplot Nuget package for WPF and installation was successful. However, above tells me that the above two issues are both referencing issues but I cannot figure out what the problem is. What additional oxyplot referencing is required once the package is installed?

Secondly why does it give me the MainViewModel does not exist message when in fact it does exist in the CurveMaster namespace?

Thanks in advance.

答:
If you (or someone else) still needs the answer - thats what helped me.
I also tried to install OxyPlot from Nuget and it gave referencing and non-existing errors. So I finally overpowered it with:

I have downloaded oxyplot from github, built it and took necessary DLL manually into my solution (OxyPlot.dll, OxyPlot.wpf.dll, OxyPlot.wpf.shared.dll)

I have changed

xmlns:oxy="http://oxyplot.codeplex.com"
```
<p>to</p>
<pre class="lang-xml prettyprint-override"><code>xmlns:oxy="http://oxyplot.org/wpf"
</code>```

in XAML.

Body:
Am new to oxyplot and wish to use it with C# WPF with xaml. My .xaml file has the following code:

<Window x:Class="CurveMaster.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CurveMaster"
    xmlns:oxy="http://oxyplot.org/wpf"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

<Grid>
    <oxy:Plot Title="{Binding Title}">
        <oxy:Plot.Series>
            <oxy:LineSeries ItemsSource="{Binding Points}"/>
        </oxy:Plot.Series>
    </oxy:Plot>
</Grid>

</Window>

The .xaml.cs file is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OxyPlot;
namespace CurveMaster
{
///
/// Interaction logic for MainWindow.xaml
///
public class MainViewModel
{
    public MainViewModel()  //Constructor
    {
        this.Title = "My Graph";
        this.Points = new List<DataPoint>
        {
            new DataPoint (0,4),
            new DataPoint (10,13),
            new DataPoint (20,15),
        };
    }
    public string Title { get; private set; }
    public IList <DataPoint> Points { get; private set; }
 }
}

So I'm just trying to run the above simple example but get the following error messages in the xaml file:

The type 'oxy:Plot' was not found. Verify that you are not missing an assembly reference.

The name "MainViewModel" does not exist in the namespace "clr-namespace:CurveMaster".

Now I installed the oxyplot Nuget package for WPF and installation was successful. However, above tells me that the above two issues are both referencing issues but I cannot figure out what the problem is. What additional oxyplot referencing is required once the package is installed?

Secondly why does it give me the MainViewModel does not exist message when in fact it does exist in the CurveMaster namespace?

Thanks in advance.

Body:
If you (or someone else) still needs the answer - thats what helped me.
I also tried to install OxyPlot from Nuget and it gave referencing and non-existing errors. So I finally overpowered it with:

I have downloaded oxyplot from github, built it and took necessary DLL manually into my solution (OxyPlot.dll, OxyPlot.wpf.dll, OxyPlot.wpf.shared.dll)

I have changed

xmlns:oxy="http://oxyplot.codeplex.com"

to

xmlns:oxy="http://oxyplot.org/wpf"

in XAML.


问:
Message received from background. Values reset
I'm sending post request from "angular->port 4200" to "expressjs server->port 8000".

As an example i'm folowing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

I'm getting two error :

1)undefined from Nodejs(data and req.body.text)

2)Message received from background. Values reset

Angular side:

```<code>  callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }
</code>```

expressjs side:

```<code>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');

app.all("/*", function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Nodejs`;
  req.body.text = `${req.body.text} from Nodejs`;
  res.send(req.body)
})

app.listen(8000, () => {
    console.log('server started');
})
</code>```

答:
Either you are not sending anything of there is no value in body.text

Try to console.log(req.body) instead of req.body.text.

Try to console.log(culture) and this.getLangCookie() on the client side to see if you are actually sending something.
You can also make use of the network tab in the browser to inspect the request that you are sending.

Body:
I'm sending post request from "angular->port 4200" to "expressjs server->port 8000".

As an example i'm folowing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

I'm getting two error :

1)undefined from Nodejs(data and req.body.text)

2)Message received from background. Values reset

Angular side:

  callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }

expressjs side:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');

app.all("/*", function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Nodejs`;
  req.body.text = `${req.body.text} from Nodejs`;
  res.send(req.body)
})

app.listen(8000, () => {
    console.log('server started');
})


问:
Apps Script Google Calendar API Integration String Class Error
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

```<code>function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}
</code>```

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D

答:
was able to solve the problem, turns out it was just linked to the wrong spreadsheet hence the issue! The code itself was working already. Appreciate the help!

However, there is something else I just noticed I may need some help with. I would also like for it to be able to update any edits I made to the spreadsheet but also not duplicate the events that were already made from the first run. I know it's got something to do with the GetID string but I'm not too sure how to go about it since this is my first time coding, would really appreciate it anyone can aid with that too? :'D

Body:
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D


问:
Bitbake stopped in do_fetch
I have been trying to create a Linux image for the VAR-SOM-MX8X. Its been a rough beginning, but I have managed to create the layers and so. I have bitbaked 2 days ago and left the system working, I already knew it was going to be a long way.

The problem is since yesterday at 23:26  the log inside of my tmp/buildstats/ shows me the build has been trying to download me this Git package,

```<code>git clone --branch imx_5.4.24_2.1.0  https://source.codeaurora.org/external/imx/linux-imx.git
</code>```

I have tried to download it by myself with git clone and it starts, its huge, but it downloads properly. The problem is the bitbake download doesn't look like its working, the progress bar has stayed all day long in 41% and it doesn't look like its working.

-- UPDATE

okey, I didn't know you could actually stop bitbake by Ctr+C twice, one first and another after the "wait for executiioning tasks" dialogue appears. Anyway my download has not gone far, my system stays downloading the same git path all the time and it doesnt make any change, once it has managed to go to 100% but then it has stopped there forever. Any idea why is this happening?

答:
I have finally managed to get the image, the problem may be about connectivity issue. First, I tried to do it in my work laptop in my office but it was too slow. Finally, trying to do it in my home PC I have managed to get the image, some recipes fail, but with

```<code>bitbake <image_name> -c cleanall
</code>```

I have managed to get everything done. Moreover, nodejs didnt compile properly, so I remove it out of my local.conf file and everythign worked fine.

Title: Bitbake stopped in do_fetch

Body:
I have been trying to create a Linux image for the VAR-SOM-MX8X. Its been a rough beginning, but I have managed to create the layers and so. I have bitbaked 2 days ago and left the system working, I already knew it was going to be a long way.

The problem is since yesterday at 23:26  the log inside of my tmp/buildstats/ shows me the build has been trying to download me this Git package,

git clone --branch imx_5.4.24_2.1.0  https://source.codeaurora.org/external/imx/linux-imx.git

I have tried to download it by myself with git clone and it starts, its huge, but it downloads properly. The problem is the bitbake download doesn't look like its working, the progress bar has stayed all day long in 41% and it doesn't look like its working.

-- UPDATE

okey, I didn't know you could actually stop bitbake by Ctr+C twice, one first and another after the "wait for executiioning tasks" dialogue appears. Anyway my download has not gone far, my system stays downloading the same git path all the time and it doesnt make any change, once it has managed to go to 100% but then it has stopped there forever. Any idea why is this happening?

Body:
I have finally managed to get the image, the problem may be about connectivity issue. First, I tried to do it in my work laptop in my office but it was too slow. Finally, trying to do it in my home PC I have managed to get the image, some recipes fail, but with

bitbake <image_name> -c cleanall

I have managed to get everything done. Moreover, nodejs didnt compile properly, so I remove it out of my local.conf file and everythign worked fine.


问:
How to convert date from react calendar in the dd/mm/yyyy format?
I am using react-calendar , Here I am getting a date in the following format

```<code>Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)
</code>```

Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?

Thanks.

答:
You could use the methods shown in this blogpost https://bobbyhadz.com/blog/javascript-format-date-dd-mm-yyyy from Borislav Hadzhiev.

You could a new date based on your calendar date and afterwards format it:

```<code>function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
  return [
    padTo2Digits(date.getDate()),
    padTo2Digits(date.getMonth() + 1),
    date.getFullYear(),
  ].join('/');
}

console.log(formatDate(new Date('Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)')));
</code>```

Body:
I am using react-calendar , Here I am getting a date in the following format

Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)

Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?

Thanks.

Body:
You could use the methods shown in this blogpost https://bobbyhadz.com/blog/javascript-format-date-dd-mm-yyyy from Borislav Hadzhiev.

You could a new date based on your calendar date and afterwards format it:

function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
  return [
    padTo2Digits(date.getDate()),
    padTo2Digits(date.getMonth() + 1),
    date.getFullYear(),
  ].join('/');
}

console.log(formatDate(new Date('Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)')));


问:
Working on an auto clicker with python and I can't open the file
Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.</p>
```<code>import mouse
import keyboard

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')

    if keyboard.is_pressed('.'):
        break
</code>```

答:
You should try structuring your loop like this:

```<code>while True:
    if keyboard.is_pressed(','):
        mouse.click('left')
    elif keyboard.is_pressed('.'):
        break
    elif ...
</code>```

And run your code from the terminal, if you are on Windows press Win+R, type cmd and go to the directory where your file resides (cd <directory name>).  Then you can open the file with Python by typing python <filename>.  If you see any errors, you should probably pip install the keyboard and mouse packages you are trying to import.

Body:
Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.

import mouse
import keyboard

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')

    if keyboard.is_pressed('.'):
        break

Body:
You should try structuring your loop like this:

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')
    elif keyboard.is_pressed('.'):
        break
    elif ...

And run your code from the terminal, if you are on Windows press Win+R, type cmd and go to the directory where your file resides (cd <directory name>).  Then you can open the file with Python by typing python <filename>.  If you see any errors, you should probably pip install the keyboard and mouse packages you are trying to import.


问:
Calculation bug in R
I noticed, that the following check is giving FALSE in R:

```<code>(1000*0.6/24)==(1000*(0.6/24))

[1] FALSE
</code>```

as follow up the floor function is giving different results:

```<code>floor(1000*0.6/24)
[1] 25

floor(1000*(0.6/24))
[1] 24
</code>```

This inconsistency is critical for my code.

Does somebody have an explanation and a tip on how to prevent this behavior?

Thank you.

Best regards,

John

答:
Thank you very much for your proposals.

My actual problem was that

```<code>floor(1000*(0.6/24))
[1] 24
</code>```

The issue can be solved by dividing/multiplicating both sides with enough big number.

Example with 100:

```<code>> floor(1000*100*(0.6/24/100))
[1] 25
</code>```

Title: Calculation bug in R

Body:
I noticed, that the following check is giving FALSE in R:

(1000*0.6/24)==(1000*(0.6/24))

[1] FALSE

as follow up the floor function is giving different results:

floor(1000*0.6/24)
[1] 25

floor(1000*(0.6/24))
[1] 24

This inconsistency is critical for my code.

Does somebody have an explanation and a tip on how to prevent this behavior?

Thank you.

Best regards,

John

Body:
Thank you very much for your proposals.

My actual problem was that

floor(1000*(0.6/24))
[1] 24

The issue can be solved by dividing/multiplicating both sides with enough big number.

Example with 100:

> floor(1000*100*(0.6/24/100))
[1] 25