问:
Flask And discord Bot ValueError: signal only works in main thread
I am trying to run a discord bot and flask server in one file, I thought it worked but the flask server does nothing so I checked with debug options True, now I get this error:

```<code>$ python main.py
Traceback (most recent call last):
  File "main.py", line 262, in <module>
    run()
  File "main.py", line 260, in run
 * Serving Flask app 'main'
 * Debug mode: on
    Tools().discordbot()
  File "main.py", line 204, in discordbot
    threading.Thread(target=loopy.run_forever).start()
NameError: name 'loopy' is not defined
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8080
 * Running on http://198.54.114.12:8080
Press CTRL+C to quit
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/opt/alt/python38/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/opt/alt/python38/lib64/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "main.py", line 213, in __init__
    self.RunApi()
  File "main.py", line 254, in RunApi
    app.run(host="0.0.0.0",port=8080, debug=True)
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/flask/app.py", line 1188, in run
    run_simple(t.cast(str, host), port, self, **options)
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/serving.py", line 1090, in run_simple
    run_with_reloader(
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/_reloader.py", line 427, in run_with_reloader
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  File "/opt/alt/python38/lib64/python3.8/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
</code>```

my contains this to start the discord bot which works fine:

```<code>        myLoop.start()
        threading.Thread(target=loopy.run_forever).start()
        loop = asyncio.get_event_loop()
        loop.create_task(self.bot.start(self.BotToken))
        threading.Thread(target=loop.run_forever).start()
</code>```

but the flask server does not work, the run command I use for it is this:

```<code>class ApiBot:
    def __init__(self) -> None:
        self.RunApi()

    def RunApi(self):
        app = Flask(__name__)

        @app.route('/auth')
        def auth():
            code = request.args.get("code")

            if (code != None):
                if AntiSql(code) == True:
                    return jsonify({"error":"1004"})

                discord = Discordx()
                res = discord.ExchangeCode(code)
                try:
                    access_token = res['access_token']
                    refresh_token = res['refresh_token']
                    info = discord.GetInfo(access_token)
                    username = info['username']
                    avatar = info['avatar']
                    userid = info['id']
                except:
                    return jsonify({"error":"1005"})
                data = {
                    "access_token": access_token,
                    "refresh_token": refresh_token,
                    "username":username,
                    "avatar":avatar,
                    "userid":userid,
                    "ip":request.remote_addr
                }

                if Memberdb.CheckIfUserIsInDb(data) == False:
                    Memberdb.AddNewMember(data)

                ListToSend.append(data)
                return "<script>window.close();</script>"
            else:
                return jsonify({"error":"1002"})

        app.run(host="0.0.0.0",port=8080, debug=True)

def run():
    threading.Thread(target=ApiBot).start()
</code>```

can someone help me? thanks in advance

Body:
I am trying to run a discord bot and flask server in one file, I thought it worked but the flask server does nothing so I checked with debug options True, now I get this error:

$ python main.py
Traceback (most recent call last):
  File "main.py", line 262, in <module>
    run()
  File "main.py", line 260, in run
 * Serving Flask app 'main'
 * Debug mode: on
    Tools().discordbot()
  File "main.py", line 204, in discordbot
    threading.Thread(target=loopy.run_forever).start()
NameError: name 'loopy' is not defined
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8080
 * Running on http://198.54.114.12:8080
Press CTRL+C to quit
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/opt/alt/python38/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/opt/alt/python38/lib64/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "main.py", line 213, in __init__
    self.RunApi()
  File "main.py", line 254, in RunApi
    app.run(host="0.0.0.0",port=8080, debug=True)
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/flask/app.py", line 1188, in run
    run_simple(t.cast(str, host), port, self, **options)
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/serving.py", line 1090, in run_simple
    run_with_reloader(
  File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/werkzeug/_reloader.py", line 427, in run_with_reloader
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  File "/opt/alt/python38/lib64/python3.8/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

my contains this to start the discord bot which works fine:

        myLoop.start()
        threading.Thread(target=loopy.run_forever).start()
        loop = asyncio.get_event_loop()
        loop.create_task(self.bot.start(self.BotToken))
        threading.Thread(target=loop.run_forever).start()

but the flask server does not work, the run command I use for it is this:

class ApiBot:
    def __init__(self) -> None:
        self.RunApi()

    def RunApi(self):
        app = Flask(__name__)

        @app.route('/auth')
        def auth():
            code = request.args.get("code")

            if (code != None):
                if AntiSql(code) == True:
                    return jsonify({"error":"1004"})

                discord = Discordx()
                res = discord.ExchangeCode(code)
                try:
                    access_token = res['access_token']
                    refresh_token = res['refresh_token']
                    info = discord.GetInfo(access_token)
                    username = info['username']
                    avatar = info['avatar']
                    userid = info['id']
                except:
                    return jsonify({"error":"1005"})
                data = {
                    "access_token": access_token,
                    "refresh_token": refresh_token,
                    "username":username,
                    "avatar":avatar,
                    "userid":userid,
                    "ip":request.remote_addr
                }

                if Memberdb.CheckIfUserIsInDb(data) == False:
                    Memberdb.AddNewMember(data)

                ListToSend.append(data)
                return ""
            else:
                return jsonify({"error":"1002"})

        app.run(host="0.0.0.0",port=8080, debug=True)

def run():
    threading.Thread(target=ApiBot).start()

can someone help me? thanks in advance


来源: stackexchange

问:
Using contextlib.redirect_stdout in an async function redirects output of other tasks
I want to redirect the output of a few lines in my code that I don't have control over, but the outputs are not relevant. I've been able to use contextlib.redirect_stdout(io.StringIO()) in a synchronous function to successfully redirect the lines I want, but I can't do it with an async function

This is what I have so far

import asyncio
import contextlib
import sys

async def long_function(val: int, semaphore: asyncio.Semaphore, file_out, old_stdout=sys.stdout):

    # Only let two tasks start at a time
    await semaphore.acquire()
    print(f"{val}: Starting")

    # Redirect stdout of ONLY the lines within this context manager
    with contextlib.redirect_stdout(file_out):
        await asyncio.sleep(3)  # long-running task that prints output I can't control, but is not useful to me
        print(f"{val}: Finished redirect")
    contextlib.redirect_stdout(old_stdout)

    print(f"{val}: Done")
    semaphore.release()

async def main():
    # I want to limit the number of concurrent tasks to 2
    semaphore: asyncio.Semaphore = asyncio.Semaphore(2)

    # Create a list of tasks to perform
    file_out = open("file.txt", "w")
    tasks = []
    for i in range(0, 9):
        tasks.append(long_function(i, semaphore, file_out))

    # Gather/run the tasks
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    asyncio.run(main())
```

When running this, however, the output of other tasks is also placed into the "file.txt" file. I only want the "Finished redirect" to be placed into the file

I see the following in the Python docs

Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts.

Is there any other way to go about this, or do I just have to live with the output as-is?

Thanks for any help!

ContentLicense: CC BY-SA 4.0

Body:
I want to redirect the output of a few lines in my code that I don't have control over, but the outputs are not relevant. I've been able to use contextlib.redirect_stdout(io.StringIO()) in a synchronous function to successfully redirect the lines I want, but I can't do it with an async function

This is what I have so far

import asyncio
import contextlib
import sys

async def long_function(val: int, semaphore: asyncio.Semaphore, file_out, old_stdout=sys.stdout):

    # Only let two tasks start at a time
    await semaphore.acquire()
    print(f"{val}: Starting")

    # Redirect stdout of ONLY the lines within this context manager
    with contextlib.redirect_stdout(file_out):
        await asyncio.sleep(3)  # long-running task that prints output I can't control, but is not useful to me
        print(f"{val}: Finished redirect")
    contextlib.redirect_stdout(old_stdout)

    print(f"{val}: Done")
    semaphore.release()

async def main():
    # I want to limit the number of concurrent tasks to 2
    semaphore: asyncio.Semaphore = asyncio.Semaphore(2)

    # Create a list of tasks to perform
    file_out = open("file.txt", "w")
    tasks = []
    for i in range(0, 9):
        tasks.append(long_function(i, semaphore, file_out))

    # Gather/run the tasks
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    asyncio.run(main())

When running this, however, the output of other tasks is also placed into the "file.txt" file. I only want the "Finished redirect" to be placed into the file

I see the following in the Python docs

Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts.

Is there any other way to go about this, or do I just have to live with the output as-is?

Thanks for any help!


问:
Is it possible to wait until multiprocessing.Value changes?
I have a simple bool value to tell subprocess to clean up and gracefully exit:

```<code>self.mem_manager = multiprocessing.Manager()
self.exiting = self..mem_manager.Value(ctypes.c_byte, False)
</code>```

Now I have a bunch of threads doing the actual work, so right now at the end of my run() method for my process there was basically this:

```<code>while not self.exiting.value:
    time.sleep(1)
self.terminate_threads()
return
</code>```

This is really ugly. Whenever I was dealing with that, there was a condition variable to wait on.

But I have another condition for quitting already - failure in either thread. So I now have a condition variable:

```<code>error_condition = threading.Condition()
... threads have access to this and will notify on error and stop ...

... more code ...

while not self.exiting.value:
    with error_condition:
        error_condition.wait(1)
        if self.errors_happened():
            ... handle errors ...
            break
self.terminate_threads()
return
</code>```

I would prefer of course:

```<code>while not self.exiting.value:
    wait_for_either(error_contition, changed_condition(self.exiting))
</code>```

Can I do that somehow?

Body:
I have a simple bool value to tell subprocess to clean up and gracefully exit:

self.mem_manager = multiprocessing.Manager()
self.exiting = self..mem_manager.Value(ctypes.c_byte, False)

Now I have a bunch of threads doing the actual work, so right now at the end of my run() method for my process there was basically this:

while not self.exiting.value:
    time.sleep(1)
self.terminate_threads()
return

This is really ugly. Whenever I was dealing with that, there was a condition variable to wait on.

But I have another condition for quitting already - failure in either thread. So I now have a condition variable:

error_condition = threading.Condition()
... threads have access to this and will notify on error and stop ...

... more code ...

while not self.exiting.value:
    with error_condition:
        error_condition.wait(1)
        if self.errors_happened():
            ... handle errors ...
            break
self.terminate_threads()
return

I would prefer of course:

while not self.exiting.value:
    wait_for_either(error_contition, changed_condition(self.exiting))

Can I do that somehow?


问:
What could queue up FireQueuedTimerCompletion work items?
We have a windows service with legacy code involving WCF, Webapi, SignalR and more. On rare occasions this service hangs and we do a memory dump and see the following when listing queued tasks:

tpq

```<code>...
31115 Work  System.Threading.TimerQueue.FireQueuedTimerCompletion
</code>```

Is this only triggered by Timers we create manually or does any built-in parts of WCF, WebApi or SignalR use timers and could be the root cause of this?

Body:
We have a windows service with legacy code involving WCF, Webapi, SignalR and more. On rare occasions this service hangs and we do a memory dump and see the following when listing queued tasks:

tpq

...
31115 Work  System.Threading.TimerQueue.FireQueuedTimerCompletion

Is this only triggered by Timers we create manually or does any built-in parts of WCF, WebApi or SignalR use timers and could be the root cause of this?


问:
misses second and third conditions
```<code>month = input()
nights_count = int(input())

studio_pr = 0
apartment_pr = 0

if month == "May" or "October":
    studio_pr = nights_count * 50
    apartment_pr = nights_count * 65
    if 14 == nights_count > 7:
        studio_pr = studio_pr * 0.95
    elif nights_count > 14:
        studio_pr = studio_pr * 0.70
        apartment_pr = apartment_pr * 0.9
elif month == "June" or "September":
    studio_pr = nights_count * 75.20
    apartment_pr = nights_count * 68.70
    if nights_count > 14:
        studio_pr = studio_pr * 0.8
        apartment_pr = apartment_pr * 0.9
elif month == "July" or "August":
    studio_pr = nights_count * 76
    apartment_pr = nights_count * 77
    if nights_count > 14:
        apartment_pr = apartment_pr * 0.9
print(f"Apartment: {apartment_pr:.2f}")
print(f"Studio: {studio_pr:.2f}")

</code>```

The code calculate the first condition, even if the month is August or June
Some help here :D

I expected this:
Input:June 14  Output:  Apartment: 961.80 lv. Studio: 1052.80 lv.
but the code outputs the result for May 14

Title: misses second and third conditions

Body:
month = input()
nights_count = int(input())

studio_pr = 0
apartment_pr = 0

if month == "May" or "October":
    studio_pr = nights_count * 50
    apartment_pr = nights_count * 65
    if 14 == nights_count > 7:
        studio_pr = studio_pr * 0.95
    elif nights_count > 14:
        studio_pr = studio_pr * 0.70
        apartment_pr = apartment_pr * 0.9
elif month == "June" or "September":
    studio_pr = nights_count * 75.20
    apartment_pr = nights_count * 68.70
    if nights_count > 14:
        studio_pr = studio_pr * 0.8
        apartment_pr = apartment_pr * 0.9
elif month == "July" or "August":
    studio_pr = nights_count * 76
    apartment_pr = nights_count * 77
    if nights_count > 14:
        apartment_pr = apartment_pr * 0.9
print(f"Apartment: {apartment_pr:.2f}")
print(f"Studio: {studio_pr:.2f}")

The code calculate the first condition, even if the month is August or June
Some help here :D

I expected this:
Input:June 14  Output:  Apartment: 961.80 lv. Studio: 1052.80 lv.
but the code outputs the result for May 14


问:
Rails 7 Javascript not working on first page load
I have a Rails 7 app, where users can upload photos to a post. I've used Javascript (client side) to create the drag and drop upload file upload field, but it doesn't work when the page is loaded the first time. If you refresh the page, it works as expected.

I think this is something to do with Turbo, but I don't know how to fix it. I have tried adding <meta name="turbo-visit-control" content="reload"> but with no success.

Any help would be appreciated.

my file upload form and javascript:

```<code><p class="text-2xl font-bold mb-4 text-blue-600 xl:pl-9">Add Some Photos</p>
            <p class="text-l font-semibold mb-7 xl:pl-9">You can upload up to ten photos of your item.</p>
            <article aria-label="File Upload Modal" class="xl:h-2/5 relative flex flex-col bg-white shadow-xl rounded-md xl:m-7" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);" ondragleave="dragLeaveHandler(event);" ondragenter="dragEnterHandler(event);">
              <div id="overlay" class="w-full h-full absolute top-0 left-0 pointer-events-none z-50 flex flex-col items-center justify-center rounded-md">
                <i>
                  <svg class="fill-current w-12 h-12 mb-3 text-blue-700" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                    <path d="M19.479 10.092c-.212-3.951-3.473-7.092-7.479-7.092-4.005 0-7.267 3.141-7.479 7.092-2.57.463-4.521 2.706-4.521 5.408 0 3.037 2.463 5.5 5.5 5.5h13c3.037 0 5.5-2.463 5.5-5.5 0-2.702-1.951-4.945-4.521-5.408zm-7.479-1.092l4 4h-3v4h-2v-4h-3l4-4z" />
                  </svg>
                </i>
                <p class="text-lg text-blue-700">Drop files to upload</p>
              </div>

              <section class="h-full overflow-auto p-8 w-full h-full flex flex-col">
                <header class="border-dashed border-2 border-gray-400 py-12 flex flex-col justify-center items-center">
                  <p class="mb-3 font-semibold flex flex-wrap justify-center">
                    <span>Drag and drop your</span> <span>files anywhere or</span>
                  </p>
                  <%= f.file_field :photos, multiple: true, class: "hidden", id: "hidden-input", name: "part[photos][]" %>
                  <button id="button" type="button" class="mt-2 rounded-lg px-3 py-1 bg-blue-600 hover:bg-blue-700 font-bold text-white focus:shadow-outline focus:outline-none">
                    Upload a file
                  </button>
                </header>

                <h1 class="pt-8 pb-3 font-semibold sm:text-lg text-blue-600">
                  To Upload
                </h1>

                <ul id="gallery" class="flex flex-1 flex-wrap -m-1">
                  <li id="empty" class="h-full w-full text-center flex flex-col items-center justify-center items-center">
                    <img class="mx-auto w-32" src="https://user-images.githubusercontent.com/507615/54591670-ac0a0180-4a65-11e9-846c-e55ffce0fe7b.png" alt="no data" />
                    <span class="text-small">No files selected.</span>
                  </li>
                </ul>
              </section>
            </article>

            <template id="file-template">
              <li class="block p-1 w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/6 xl:w-1/8 h-24">
                <article tabindex="0" class="group w-full h-full rounded-md focus:outline-none focus:shadow-outline elative bg-gray-100 cursor-pointer relative shadow-sm">
                  <img alt="upload preview" class="img-preview hidden w-full h-full sticky object-cover rounded-md bg-fixed" />

                  <section class="flex flex-col rounded-md text-xs break-words w-full h-full z-20 absolute top-0 py-2 px-3">
                    <h1 class="flex-1 group-hover:text-blue-800"></h1>
                    <div class="flex">
                      <span class="p-1 text-blue-800">
                        <i>
                          <svg class="fill-current w-4 h-4 ml-auto pt-1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                            <path d="M15 2v5h5v15h-16v-20h11zm1-2h-14v24h20v-18l-6-6z" />
                          </svg>
                        </i>
                      </span>
                      <p class="p-1 size text-xs text-gray-700"></p>
                      <button class="delete ml-auto focus:outline-none hover:bg-gray-300 p-1 rounded-md text-gray-800">
                        <svg class="pointer-events-none fill-current w-4 h-4 ml-auto" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                          <path class="pointer-events-none" d="M3 6l3 18h12l3-18h-18zm19-4v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.316c0 .901.73 2 1.631 2h5.711z" />
                        </svg>
                      </button>
                    </div>
                  </section>
                </article>
              </li>
            </template>

            <template id="image-template">
              <li class="block p-1 w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/6 xl:w-1/8 h-24">
                <article tabindex="0" class="group hasImage w-full h-full rounded-md focus:outline-none focus:shadow-outline bg-gray-100 cursor-pointer relative text-transparent hover:text-white shadow-sm">
                  <img alt="upload preview" class="img-preview w-full h-full sticky object-cover rounded-md bg-fixed" />

                  <section class="flex flex-col rounded-md text-xs break-words w-full h-full z-20 absolute top-0 py-2 px-3">
                    <h1 class="flex-1"></h1>
                    <div class="flex">
                      <span class="p-1">
                        <i>
                          <svg class="fill-current w-4 h-4 ml-auto pt-" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                            <path d="M5 8.5c0-.828.672-1.5 1.5-1.5s1.5.672 1.5 1.5c0 .829-.672 1.5-1.5 1.5s-1.5-.671-1.5-1.5zm9 .5l-2.519 4-2.481-1.96-4 5.96h14l-5-8zm8-4v14h-20v-14h20zm2-2h-24v18h24v-18z" />
                          </svg>
                        </i>
                      </span>

                      <p class="p-1 size text-xs"></p>
                      <button class="delete ml-auto focus:outline-none hover:bg-gray-300 p-1 rounded-md">
                        <svg class="pointer-events-none fill-current w-4 h-4 ml-auto" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                          <path class="pointer-events-none" d="M3 6l3 18h12l3-18h-18zm19-4v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.316c0 .901.73 2 1.631 2h5.711z" />
                        </svg>
                      </button>
                    </div>
                  </section>
                </article>
              </li>
            </template>

            <script>
              const photos = [];

              // Get a reference to the file input element
              const fileInput = document.getElementById('hidden-input');

              // Listen for changes to the file input element
              fileInput.addEventListener('change', function() {
                // Get the list of selected files
                const files = fileInput.files;

                // Loop through the selected files
                for (let i = 0; i < files.length; i++) {
                  // Add the file to the photos array
                  photos.push(files[i]);
                }
              });

              const fileTempl = document.getElementById("file-template"),
                imageTempl = document.getElementById("image-template"),
                empty = document.getElementById("empty");

              // use to store pre selected files
              let FILES = {};

              // check if file is of type image and prepend the initialied
              // template to the target element
              function addFile(target, file) {
                const isImage = file.type.match("image.*"),
                  objectURL = URL.createObjectURL(file);

                const clone = isImage
                  ? imageTempl.content.cloneNode(true)
                  : fileTempl.content.cloneNode(true);

                clone.querySelector("h1").textContent = file.name;
                clone.querySelector("li").id = objectURL;
                clone.querySelector(".delete").dataset.target = objectURL;
                clone.querySelector(".size").textContent =
                  file.size > 1024
                    ? file.size > 1048576
                      ? Math.round(file.size / 1048576) + "mb"
                      : Math.round(file.size / 1024) + "kb"
                    : file.size + "b";

                isImage &&
                  Object.assign(clone.querySelector("img"), {
                    src: objectURL,
                    alt: file.name
                  });

                empty.classList.add("hidden");
                target.prepend(clone);

                FILES[objectURL] = file;
              }

              const gallery = document.getElementById("gallery"),
                overlay = document.getElementById("overlay");

              // click the hidden input of type file if the visible button is clicked
              // and capture the selected files
              const hidden = document.getElementById("hidden-input");
              document.getElementById("button").onclick = () => hidden.click();
              hidden.onchange = (e) => {
                for (const file of e.target.files) {
                  addFile(gallery, file);
                }
              };

              // use to check if a file is being dragged
              const hasFiles = ({ dataTransfer: { types = [] } }) =>
                types.indexOf("Files") > -1;

              // use to drag dragenter and dragleave events.
              // this is to know if the outermost parent is dragged over
              // without issues due to drag events on its children
              let counter = 0;

              // reset counter and append file to gallery when file is dropped
              function dropHandler(ev) {
                ev.preventDefault();
                for (const file of ev.dataTransfer.files) {
                  addFile(gallery, file);
                  overlay.classList.remove("draggedover");
                  counter = 0;
                }
              }

              // only react to actual files being dragged
              function dragEnterHandler(e) {
                e.preventDefault();
                if (!hasFiles(e)) {
                  return;
                }
                ++counter && overlay.classList.add("draggedover");
              }

              function dragLeaveHandler(e) {
                1 > --counter && overlay.classList.remove("draggedover");
              }

              function dragOverHandler(e) {
                if (hasFiles(e)) {
                  e.preventDefault();
                }
              }

              // event delegation to caputre delete events
              // fron the waste buckets in the file preview cards
              gallery.onclick = ({ target }) => {
                if (target.classList.contains("delete")) {
                  const ou = target.dataset.target;
                  document.getElementById(ou).remove(ou);
                  gallery.children.length === 1 && empty.classList.remove("hidden");
                  delete FILES[ou];
                }
              };

              function addFilesToPhotosArray() {
                // Get the gallery element
                const gallery = document.getElementById("gallery");

                // Get the selected files from the gallery
                const selectedFiles = gallery.querySelectorAll(".selected");

                // Get the photos array from the input field
                const photosArray = document.getElementById("hidden-input").value;

                // Add the selected files to the photos array
                for (const selectedFile of selectedFiles) {
                  photosArray.push(selectedFile);
                }

                // Update the input field with the new photos array
                document.getElementById("hidden-input").value = photosArray;
              }

              // clear entire selection
              document.getElementById("cancel").onclick = () => {
                while (gallery.children.length > 0) {
                  gallery.lastChild.remove();
                }
                FILES = {};
                empty.classList.remove("hidden");
                gallery.append(empty);
              };
            </script>
          </div>
</code>```

Body:
I have a Rails 7 app, where users can upload photos to a post. I've used Javascript (client side) to create the drag and drop upload file upload field, but it doesn't work when the page is loaded the first time. If you refresh the page, it works as expected.

I think this is something to do with Turbo, but I don't know how to fix it. I have tried adding <meta name="turbo-visit-control" content="reload"> but with no success.

Any help would be appreciated.

my file upload form and javascript:

Add Some Photos

You can upload up to ten photos of your item.

                  <svg class="fill-current w-12 h-12 mb-3 text-blue-700" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                    <path d="M19.479 10.092c-.212-3.951-3.473-7.092-7.479-7.092-4.005 0-7.267 3.141-7.479 7.092-2.57.463-4.521 2.706-4.521 5.408 0 3.037 2.463 5.5 5.5 5.5h13c3.037 0 5.5-2.463 5.5-5.5 0-2.702-1.951-4.945-4.521-5.408zm-7.479-1.092l4 4h-3v4h-2v-4h-3l4-4z" />
                  </svg>

Drop files to upload

                    Drag and drop your files anywhere or

                  <%= f.file_field :photos, multiple: true, class: "hidden", id: "hidden-input", name: "part[photos][]" %>
                  <button id="button" type="button" class="mt-2 rounded-lg px-3 py-1 bg-blue-600 hover:bg-blue-700 font-bold text-white focus:shadow-outline focus:outline-none">
                    Upload a file
                  </button>

                  To Upload

                    No files selected.

            <template id="file-template">

                          <svg class="fill-current w-4 h-4 ml-auto pt-1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                            <path d="M15 2v5h5v15h-16v-20h11zm1-2h-14v24h20v-18l-6-6z" />
                          </svg>

                      <button class="delete ml-auto focus:outline-none hover:bg-gray-300 p-1 rounded-md text-gray-800">
                        <svg class="pointer-events-none fill-current w-4 h-4 ml-auto" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                          <path class="pointer-events-none" d="M3 6l3 18h12l3-18h-18zm19-4v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.316c0 .901.73 2 1.631 2h5.711z" />
                        </svg>
                      </button>

            </template>

            <template id="image-template">

                          <svg class="fill-current w-4 h-4 ml-auto pt-" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                            <path d="M5 8.5c0-.828.672-1.5 1.5-1.5s1.5.672 1.5 1.5c0 .829-.672 1.5-1.5 1.5s-1.5-.671-1.5-1.5zm9 .5l-2.519 4-2.481-1.96-4 5.96h14l-5-8zm8-4v14h-20v-14h20zm2-2h-24v18h24v-18z" />
                          </svg>

                      <button class="delete ml-auto focus:outline-none hover:bg-gray-300 p-1 rounded-md">
                        <svg class="pointer-events-none fill-current w-4 h-4 ml-auto" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                          <path class="pointer-events-none" d="M3 6l3 18h12l3-18h-18zm19-4v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.316c0 .901.73 2 1.631 2h5.711z" />
                        </svg>
                      </button>

            </template>


问:
Integrity constraint violation: column cannot be null, variable error
Im working on a project where I need to submit new data to a mysql database. However after inserting the data and click the submit button an error appears saying the value cannot be null... but they aren´t because the values inserted appear with an echo. I dont know if the variables are declared correctly. If someone can help I´ll be gratefull :).
This is my code:
enter image description here
enter image description here

enter image description here


问:
How to direct vue-cli to build different entrypoints into different directories? (Vue.js 3 and Ionic 6)
I would like to split my website build with Vue.js 3 and Ionic 6 and I would like to split the built site into into 2 folders (public, private) or 3 folders (public, private, common) but I'm not sure of what steps to take...

Just to be clear, so far I have 2 entrypoints configured:

```<code>module.exports = {
  pages: {
    publicSide: {
      entry: 'src/main.ts',
      template: 'public/index.html',
      filename: 'index.html',
      title: 'Public Page'
    },
    privateSide: {
      entry: 'src/private.ts',
      template: 'private/index.html',
      filename: 'private.html',
      title: 'Private Page'
    }
  }
}
</code>```

And I would like to be able to export the built site into:

```<code>dist
\public (includes common)
\private
</code>```

What extra configuration do I need?

Thanks in advance...

Body:
I would like to split my website build with Vue.js 3 and Ionic 6 and I would like to split the built site into into 2 folders (public, private) or 3 folders (public, private, common) but I'm not sure of what steps to take...

Just to be clear, so far I have 2 entrypoints configured:

module.exports = {
  pages: {
    publicSide: {
      entry: 'src/main.ts',
      template: 'public/index.html',
      filename: 'index.html',
      title: 'Public Page'
    },
    privateSide: {
      entry: 'src/private.ts',
      template: 'private/index.html',
      filename: 'private.html',
      title: 'Private Page'
    }
  }
}

And I would like to be able to export the built site into:

dist
\public (includes common)
\private

What extra configuration do I need?

Thanks in advance...


问:
RTK query disable cache
I have three buttons and text near it

[button item_count]

[red 1] - [blue 2] - [yellow 3]

item 1

item 2
...

item 123

When we click on each button we see different items.

I fetch everything using rtk-query, so the response from the server is(for example, red is clicked):

```<code>{
    red : 1,
    blue : 2,
    yellow : 3,
    data : [...]
}
</code>```

On every button click I get the newest data;

The problem:

On page load:

[red 1] - [blue 2] - [yellow 3]

In Database, I add new item to red section

I select blue button the buttons will be:
[red 2] - [blue 2] - [yellow 3] - because I re-fetched everything when selected blue button and count increased for red;

BUT

When I click red, for a second I see old count 1; I see [red 1] then when it stops fetching data I see [red 2]

THE SOLUTION I CAME UP:

The solution is to use keepUnusedDataFor:0

I think the problem is with the cache. Also, my endpoint uses refetchOnMountOrArgChange : true

Maybe there is a better solution for this problem?

Title: RTK query disable cache

Body:
I have three buttons and text near it

[button item_count]

[red 1] - [blue 2] - [yellow 3]

item 1

item 2
...

item 123

When we click on each button we see different items.

I fetch everything using rtk-query, so the response from the server is(for example, red is clicked):

{
    red : 1,
    blue : 2,
    yellow : 3,
    data : [...]
}

On every button click I get the newest data;

The problem:

On page load:

[red 1] - [blue 2] - [yellow 3]

In Database, I add new item to red section

I select blue button the buttons will be:
[red 2] - [blue 2] - [yellow 3] - because I re-fetched everything when selected blue button and count increased for red;

BUT

When I click red, for a second I see old count 1; I see [red 1] then when it stops fetching data I see [red 2]

THE SOLUTION I CAME UP:

The solution is to use keepUnusedDataFor:0

I think the problem is with the cache. Also, my endpoint uses refetchOnMountOrArgChange : true

Maybe there is a better solution for this problem?


问:
Jupyter notebook cannot find location of file
screenshot of the error

For some reason jupyter cannot find the file even tho it clearly exists. I have used the exact same code on another notebook and had 0 issues.

I check to make sure there's no space in 'train' but there isn't. Tried googling the issue but I cannot a solution.

 If anyone knows whats going on please let me know. All help is appreciated


问:
MongoDb Update one field using BulkWriteAsync
I am trying to add one property in some of my documents (later I will be updating it).
My code looks like below:

```<code>    public async Task<bool> InsertTagsToPeople(IEnumerable<People> toInsert)
    {
        var collection = _mongoClient.GetPeopleDetailsCollection();
        try
        {
            var updates = new List<WriteModel<People>>();

            foreach (var doc in toInsert)
            {
                var filter = Builders<People>.Filter.And(
                                Builders<People>.Filter.Eq(x => x.Address, doc.Address),
                                Builders<People>.Filter.Eq(x => x.Type, doc.Type));
                var update = Builders<People>.Update.Set(x => x.Tags, doc.Tags);
                updates.Add(new UpdateOneModel<People>(filter, update){IsUpsert = false});
            }

            var result = await collection.BulkWriteAsync(updates);
            return true;
        }
    }
</code>```

Problem with this code is that it is not setting Tags property. Nothing on Database is changing.
In result object I have properties like this:

When I change IsUpsert = true it throws error

Category : "DuplicateKey", Code : 11000, Message : "E11000 duplicate
key error collection:

I don`t understand why it is trying to update whole model instead just one property. But I suppose that IsUpsert do not matter here. Update.Set should do the work.

Body:
I am trying to add one property in some of my documents (later I will be updating it).
My code looks like below:

    public async Task<bool> InsertTagsToPeople(IEnumerable<People> toInsert)
    {
        var collection = _mongoClient.GetPeopleDetailsCollection();
        try
        {
            var updates = new List<WriteModel<People>>();

            foreach (var doc in toInsert)
            {
                var filter = Builders<People>.Filter.And(
                                Builders<People>.Filter.Eq(x => x.Address, doc.Address),
                                Builders<People>.Filter.Eq(x => x.Type, doc.Type));
                var update = Builders<People>.Update.Set(x => x.Tags, doc.Tags);
                updates.Add(new UpdateOneModel<People>(filter, update){IsUpsert = false});
            }

            var result = await collection.BulkWriteAsync(updates);
            return true;
        }
    }

Problem with this code is that it is not setting Tags property. Nothing on Database is changing.
In result object I have properties like this:

When I change IsUpsert = true it throws error

Category : "DuplicateKey", Code : 11000, Message : "E11000 duplicate
key error collection:

I don`t understand why it is trying to update whole model instead just one property. But I suppose that IsUpsert do not matter here. Update.Set should do the work.


问:
How to solve Split_bundle 15?
Hi Developers at Ministerio de Telecomunicaciones Ecuador,
Per last email, your app FirmaEC (ec.gob.firmadigital.firmaec_app) has been rejected from Google Play for not resolving the previously communicated policy issue (copied below for your reference). To resolve this issue and get your app changes published on Google Play, please address the issues highlighted in the earlier email and resubmit the app.

Publishing Status

App Status: Rejected
Your app has been rejected and wasn't published due to the policy issue(s) listed below. If you submitted an update, the previous version of your app is still available on Google Play.

Issue found: Permission use is not directly related to your app's core purpose.
We found that your app is not compliant with how REQUEST_INSTALL_PACKAGES permission is allowed to be used. Specifically, the use of the permission is not directly related to the core purpose of the app.

Issue details

We found an issue in the following area(s):

SPLIT_BUNDLE 15
Additionally, follow these steps to bring your app into compliance:

Please remove the use of REQUEST_INSTALL_PACKAGES permission from your app.
About the Request Install Packages Permission
The REQUEST_INSTALL_PACKAGES permission allows an application to request the installation of app packages. To use this permission, your app’s core functionality must include:

Sending or receiving app packages, AND
Enabling user-initiated installation of app packages.
Permitted functionalities include any of the following:

Web browsing or search
Communication services that support attachments
File sharing, transfer or management
Enterprise device management
Backup and restore
Device migration / phone transfer
The REQUEST_INSTALL_PACKAGES permission may not be used to perform self updates, modifications, or the bundling of other APKs in the asset file unless for device management purposes. All updates or installing of packages must abide by Google Play’s Device and Network Abuse policy and must be initiated and driven by the user.

For more help addressing this issue, read more in our Help Center.
Action required: Submit an updated app for review
Here's what to do to help get your app on Google Play:
Make sure to read the applicable policies or requirements listed below:
Request Install Packages Permission
Make appropriate changes to your app (if possible), and be sure to address the issue described above. You may also want to check your app's store listing for compliance, if applicable.
Double check that your app is compliant with all other Developer Program Policies.
If you made changes to your app bundle, store listing, or APK, please sign in to your Play Console and submit the update(s).
Contact support
If you've reviewed the policy and feel our decision may have been in error, please reach out to our policy support team. We'll get back to you within 2 business days.

try:
App is not compliant with how REQUEST_INSTALL_PACKAGES permission is allowed

Title: How to solve Split_bundle 15?


问:
"I'm not a Robot" Recaptcha is not working as expected -Selenium WebDriver(Java)
Steps to Produce:

I am trying to handle "Recaptcha" through manual intervention using Selenium Web Driver (Java) in Firefox Browser

In the demosite,"https://demoqa.com/register", I am trying to automate "Recaptcha" through manual intervention

I am switching into "I'm not a Robot" frame and trying to click on the checkbox and then use "Explicit Wait" till I manually click on "Verify" button

Then I am switching out of the iframe to the default content and trying to click "Register"

Issue:

My code works till switching into "I'm not a Robot" frame and the random image tiles open, then it doesn't work

My Code:

```<code>//Check "I'm not a Robot"
    driver.switchTo().frame(7);
    driver.findElement(By.xpath("//span[@id='recaptcha-anchor']/div")).click();

   WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(
            By.xpath("//iframe[starts-with(@name, 'a-4fg5nocuvnax') and starts-with(@src, 'https://www.google.com/recaptcha')]")));

    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#recaptcha-verify-button"))).click();
    driver.switchTo().defaultContent();
</code>```

Help me and correct if I am wrong .

```<code>

</code>```

Body:
Steps to Produce:

I am trying to handle "Recaptcha" through manual intervention using Selenium Web Driver (Java) in Firefox Browser

In the demosite,"https://demoqa.com/register", I am trying to automate "Recaptcha" through manual intervention

I am switching into "I'm not a Robot" frame and trying to click on the checkbox and then use "Explicit Wait" till I manually click on "Verify" button

Then I am switching out of the iframe to the default content and trying to click "Register"

Issue:

My code works till switching into "I'm not a Robot" frame and the random image tiles open, then it doesn't work

My Code:

//Check "I'm not a Robot"
    driver.switchTo().frame(7);
    driver.findElement(By.xpath("//span[@id='recaptcha-anchor']/div")).click();

   WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(
            By.xpath("//iframe[starts-with(@name, 'a-4fg5nocuvnax') and starts-with(@src, 'https://www.google.com/recaptcha')]")));

    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#recaptcha-verify-button"))).click();
    driver.switchTo().defaultContent();

Help me and correct if I am wrong .


问:
How to mock a protected class whos instance is used by the tested method in Java?
I have a public POJO class whos constructor is protected & its setters are protected/private as well.
The only thing that is public is the getters.

```<code>public class RequestInfo {

    private String user;
    private String date;
    private String action;

    protected RequestInfo(String user, String date, String action) {
        this.user = user;
        this.date = date;
        this.action = action;
    }

    public String getUser(){
        return user;
    }
    ...
    ...
    private void setUser(String user){
        this.user = user;
    }
    ..
    ..
}
</code>```

I want to write a JUnit test which tests a method, that gets as a parameter an instance of the POJO class I have mentioned in the beginning.

```<code>public String getReport(RequestInfo requestInfo){
    String requestUser = requestInfo.getUser();
    String requestDate = requestInfo.getDate();
    String requestAction = requestInfo.getAction();
    ....
    ....
}
</code>```

This complicates things for me, because I want to mock this instance in order to test the method as needed, but I can't mock it because:

I can't just create a new instance of the class and insert my mocked values because the constructor is protected.

```<code>@Test
public void getReportTest(){
    RequestInfo requestInfo = new RequestInfo("john", "12DEC22", "addUser");
    String report = ReportsManager.getReport(requestInfo);
    assertEquals(.......)
    .....
}
</code>```

I can't mock it using Mockito.mock(RequestInfo.Class) because although it will create a mock of the class, but everything inside of it (fields) will be nulled, so the tested method, which relies on the info that the instance stores, will fail.

I can make the constructor public, but I wrote it as protected for a reason, and I don't want to break my design just because of one or two tests.

I have wrote the codes as an example to clarify my needs, please address to the general idea and not for these specific code samples

I'll be glad to get tips,
thanks.

Body:
I have a public POJO class whos constructor is protected & its setters are protected/private as well.
The only thing that is public is the getters.

public class RequestInfo {

    private String user;
    private String date;
    private String action;

    protected RequestInfo(String user, String date, String action) {
        this.user = user;
        this.date = date;
        this.action = action;
    }

    public String getUser(){
        return user;
    }
    ...
    ...
    private void setUser(String user){
        this.user = user;
    }
    ..
    ..
}

I want to write a JUnit test which tests a method, that gets as a parameter an instance of the POJO class I have mentioned in the beginning.

public String getReport(RequestInfo requestInfo){
    String requestUser = requestInfo.getUser();
    String requestDate = requestInfo.getDate();
    String requestAction = requestInfo.getAction();
    ....
    ....
}

This complicates things for me, because I want to mock this instance in order to test the method as needed, but I can't mock it because:

I can't just create a new instance of the class and insert my mocked values because the constructor is protected.

@Test
public void getReportTest(){
    RequestInfo requestInfo = new RequestInfo("john", "12DEC22", "addUser");
    String report = ReportsManager.getReport(requestInfo);
    assertEquals(.......)
    .....
}

I can't mock it using Mockito.mock(RequestInfo.Class) because although it will create a mock of the class, but everything inside of it (fields) will be nulled, so the tested method, which relies on the info that the instance stores, will fail.

I can make the constructor public, but I wrote it as protected for a reason, and I don't want to break my design just because of one or two tests.

I have wrote the codes as an example to clarify my needs, please address to the general idea and not for these specific code samples

I'll be glad to get tips,
thanks.


问:
I am unable to install netmiko in pyscript
I have already installed netmiko in my pc, but it doesnt run in pyscript.
The error I get is
Loading runtime...
Runtime created...
Initializing components</p>
```<code>
<html>
    <head>
        <title>Educative PyScript Answers</title>

        <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

        <py-env>
            - matplotlib
            - netmiko
        </py-env>
    </head>
    <body>
        <h1> Plotting a graph </h1>
        <div id="lineplot"> </div>

        <py-script>
            import netmiko

            print('hello world')

        </py-script>
    </body>
</html>

</code>```

Body:
I have already installed netmiko in my pc, but it doesnt run in pyscript.
The error I get is
Loading runtime...
Runtime created...
Initializing components

        <title>Educative PyScript Answers</title>

        <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />

        <py-env>
            - matplotlib
            - netmiko
        </py-env>

 Plotting a graph

        <py-script>
            import netmiko

            print('hello world')

        </py-script>


问:
Group columns and separate in R
I have a dataset, where I want to group 2 columns together (Proc Right and Days to Proc Right) and separate it from the next group of 2 columns (Proc Left and Days to Proc Left). During separation, I want to separate based on chronology of days to procedure, and assign 0 and NA to the other 2 columns which chronologically are later. I then want to create a new column pulling only the days to procedure.

To summarise:

Have this:

ID
Proc ID
Proc Right
Days to Proc Right
Proc Left
Days to Proc Left

1
108
4
41
4
168

1
105
4
169
4
42

1
101
3
270
0
NA

Want this:

ID
Proc ID
Proc Right
Days to Proc Right
Proc Left
Days to Proc Left
Days to Proc

1
108
4
41
0
NA
41

1
108
0
NA
4
168
168

1
105
0
NA
4
42
42

1
105
4
169
0
NA
169

1
101
3
270
0
NA
270

Would appreciate any help. Thanks

I have tried unite and cSplit, which separates the column groups, but doesn't help me assign 0 and NA to the other columns.

Title: Group columns and separate in R


问:
Issue with R-Script populating required content in excel
This script outputs excel spreadsheets of different region. However, since I included a column "Later", changed the corresponding template to also include the column "Later" and increased the number on this line  "df <- subset(clist[,c(1:18, 20:29)" from 28 to 29 (given the increased column). The output on the column "group" has come back with its content, but with quotation mark and some instance with CHAR(10).
Is there anyway I can edit this script to have column "group" outcome its content without the quotation marks. Please help!! help! I have struggled with this since.  See script below

NB changes made to the original script are as follows

inclusion of later in the sqlcode

changing the df <- subset(clist[,c(1:18, 20:28)" to df <- subset(clist[,c(1:18, 20:29)

Changing the second df <- subset(clist[,c(1:17, 19:28)] to df <- subset(clist[,c(1:18, 20:29)]

```<code>#####Constants#####

requiredpackages <- c("XLConnect", "RPostgreSQL", "svDialogs", "getPass")
reqpackages <- function(requiredpackages){
  for( i in requiredpackages ){
    if( ! require( i , character.only = TRUE ) ) {
      install.packages( i , dependencies = TRUE )
      library( i , character.only = TRUE )
    }
  }
}

# set the version to 1.0.5

packageurl <- "https://cran.r-project.org/src/contrib/Archive/XLConnect/XLConnect_1.0.5.tar.gz"
install.packages(packageurl, repos=NULL, type="source")

library(XLConnect)
library(RPostgreSQL)
library(svDialogs)
library(getPass)

source("N:/Ana/Code/Analysiss/Rational/R SQL working/postgresql-avd.R")

#####Retrieve data from analysis server#####

sqlcode <- paste("SELECT concat_ws(';',datacompletion,sortprovider) as datacompletion,ba,outstandingdata,provider,summary,
m,m_hos,m_sur,m_for,m_dob,ed,
bkhos,delhos,
pregnancy,b_d,
b,b_na,
group,groupsw,later,estimated,
screening,date,screening2,
booking,city,use,con,water
FROM common.etl_chasing
where ((date::text like '%",tperiod,"%' or date::text like '%",cperiod,"%')
and (anomalygroup like '%Down%' or group like '%Edwards%' or group like '%Patau%'))
or eddfyear like '%", fperiod,"%' or cleanyear like '%", cperiod, "%'", sep='')

con <- createConnection()
clist <- dbGetQuery(con, sqlcode)
dbDisconnect(con)

#####Create new folder on PID drive to output chasing lists to#####

dirname <- paste("P:/Data/Antenatal/Testing/", Sys.Date(),sep='')
dir.create(dirname)

#####Export CSV of all data#####

write.csv(clist,paste(dirname,"/masterlist.csv",sep=''))

#####Copy template for all individual providers#####

sortproviders <- unique(clist$sortprovider)
inpath <- "P:/Data/National/Antenatal/Template17b.xlsx"
for (i in seq_along(sortproviders)) {
  outpath <- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
  file.copy(from = inpath, to = outpath)
}

#####Populate templates for individual providers#####

swpatterns <- c("68 - ", "70 - ", "72 - ", "73 - ", "84 - ", "93 - ", "94 - ", "95 - ", "96 - ", "99 - ")

#grepl(paste(swpatterns, collapse = "|"), sortproviders\[1\])
#otherpatterns \<- c("72 - ", "96 - ", "73 - ", "93 - ", "94 - ", "72 - ", "99 - ")
#swsortproviders \<- unique(grep(paste(swpatterns, collapse = "|"), sortproviders, value = TRUE))
#restsortprividers \<- unique(grep(paste(otherpatterns, collapse = "|"), sortproviders, value = TRUE))

for (i in seq_along(sortproviders)) {
  outpath \<- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
  if (grepl(paste(swpatterns, collapse = "|"), sortproviders\[i\]) == FALSE) {
    df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
    dfformulacol <- as.vector(df$anomalygroup)
    df <- cbind(df, df)
    XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")

    wb <- loadWorkbook(filename = outpath, create = FALSE)

    for (j in seq_along(dfformulacol)) {
      setCellFormula(wb, "trust list", j+3, 18, dfformulacol[j])
    }

    for (k in seq_along(dfformulacol)) {
      setCellFormula(wb, "trust list", k+3, 45, dfformulacol[k])
    }
    saveWorkbook(wb)
    rm(wb)
  } else {
    df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
    df <- cbind(df, df)
    XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")

    wb <- loadWorkbook(filename = outpath, create = FALSE)
    saveWorkbook(wb)
    rm(wb)
  }
rm(df)
xlcFreeMemory()
}

#####################################
</code>```

Body:
This script outputs excel spreadsheets of different region. However, since I included a column "Later", changed the corresponding template to also include the column "Later" and increased the number on this line  "df <- subset(clist[,c(1:18, 20:29)" from 28 to 29 (given the increased column). The output on the column "group" has come back with its content, but with quotation mark and some instance with CHAR(10).
Is there anyway I can edit this script to have column "group" outcome its content without the quotation marks. Please help!! help! I have struggled with this since.  See script below

NB changes made to the original script are as follows

inclusion of later in the sqlcode

changing the df <- subset(clist[,c(1:18, 20:28)" to df <- subset(clist[,c(1:18, 20:29)

Changing the second df <- subset(clist[,c(1:17, 19:28)] to df <- subset(clist[,c(1:18, 20:29)]

#####Constants#####

requiredpackages <- c("XLConnect", "RPostgreSQL", "svDialogs", "getPass")
reqpackages <- function(requiredpackages){
  for( i in requiredpackages ){
    if( ! require( i , character.only = TRUE ) ) {
      install.packages( i , dependencies = TRUE )
      library( i , character.only = TRUE )
    }
  }
}

# set the version to 1.0.5

packageurl <- "https://cran.r-project.org/src/contrib/Archive/XLConnect/XLConnect_1.0.5.tar.gz"
install.packages(packageurl, repos=NULL, type="source")

library(XLConnect)
library(RPostgreSQL)
library(svDialogs)
library(getPass)

source("N:/Ana/Code/Analysiss/Rational/R SQL working/postgresql-avd.R")

#####Retrieve data from analysis server#####

sqlcode <- paste("SELECT concat_ws(';',datacompletion,sortprovider) as datacompletion,ba,outstandingdata,provider,summary,
m,m_hos,m_sur,m_for,m_dob,ed,
bkhos,delhos,
pregnancy,b_d,
b,b_na,
group,groupsw,later,estimated,
screening,date,screening2,
booking,city,use,con,water
FROM common.etl_chasing
where ((date::text like '%",tperiod,"%' or date::text like '%",cperiod,"%')
and (anomalygroup like '%Down%' or group like '%Edwards%' or group like '%Patau%'))
or eddfyear like '%", fperiod,"%' or cleanyear like '%", cperiod, "%'", sep='')

con <- createConnection()
clist <- dbGetQuery(con, sqlcode)
dbDisconnect(con)

#####Create new folder on PID drive to output chasing lists to#####

dirname <- paste("P:/Data/Antenatal/Testing/", Sys.Date(),sep='')
dir.create(dirname)

#####Export CSV of all data#####

write.csv(clist,paste(dirname,"/masterlist.csv",sep=''))

#####Copy template for all individual providers#####

sortproviders <- unique(clist$sortprovider)
inpath <- "P:/Data/National/Antenatal/Template17b.xlsx"
for (i in seq_along(sortproviders)) {
  outpath <- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
  file.copy(from = inpath, to = outpath)
}

#####Populate templates for individual providers#####

swpatterns <- c("68 - ", "70 - ", "72 - ", "73 - ", "84 - ", "93 - ", "94 - ", "95 - ", "96 - ", "99 - ")

#grepl(paste(swpatterns, collapse = "|"), sortproviders\[1\])
#otherpatterns \<- c("72 - ", "96 - ", "73 - ", "93 - ", "94 - ", "72 - ", "99 - ")
#swsortproviders \<- unique(grep(paste(swpatterns, collapse = "|"), sortproviders, value = TRUE))
#restsortprividers \<- unique(grep(paste(otherpatterns, collapse = "|"), sortproviders, value = TRUE))

for (i in seq_along(sortproviders)) {
  outpath \<- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
  if (grepl(paste(swpatterns, collapse = "|"), sortproviders\[i\]) == FALSE) {
    df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
    dfformulacol <- as.vector(df$anomalygroup)
    df <- cbind(df, df)
    XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")

    wb <- loadWorkbook(filename = outpath, create = FALSE)

    for (j in seq_along(dfformulacol)) {
      setCellFormula(wb, "trust list", j+3, 18, dfformulacol[j])
    }

    for (k in seq_along(dfformulacol)) {
      setCellFormula(wb, "trust list", k+3, 45, dfformulacol[k])
    }
    saveWorkbook(wb)
    rm(wb)
  } else {
    df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
    df <- cbind(df, df)
    XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")

    wb <- loadWorkbook(filename = outpath, create = FALSE)
    saveWorkbook(wb)
    rm(wb)
  }
rm(df)
xlcFreeMemory()
}

#####################################


问:
Using the Bing Ads Python SDK, is there a way to pull back all Ad Data related to an account with the AdGroup and Campaign ids?
Right now, I'm currently using the Bing Ads Python SDK to ingest data in csv format using the Bulk Service Client on version 13. For this example, I'll include 'Ads' as the only download entity with  no LastSyncTime variable set to collect all of the available data from the Bulk Service Endpoint for Ads. After creating the proper request and downloading the csv file from the appropriate URL, I'm returned a csv file with about 418 rows (most of which are empty which is correct), and two columns named 'AdGroup' and 'Campaign'. However, those two columns are simply the name of the AdGroup and Campaign rather than the ID. Is there a way to return the ID's of the AdGroup or Campaign rather than just the names?

Quick Note: I'm wanting to use the bulk_service_manager as it allows for the option of windowing the data that has been updated since a certain time. The history and the changes over time are required for Ads, AdGroups, and Campaigns.

Below is quick walkthrough of how I'm using the SDK right now. In this example, I'm wanting to pull back the 'Ads' object and its respective data. After creating the 'bulk_request' object, I'm waiting for the job to be completed before downloading the CSV file from the response URL. Regardless, the CSV returns the Ad Id, but the AdGroup and Campaign names rather than IDS.

```<code>from bingads.service_client import ServiceClient
from bingads.v13.reporting import *
from bingads.authorization import AuthorizationData, OAuthDesktopMobileAuthCodeGrant

authorization_data = AuthorizationData(
        account_id = ACCOUNT_ID,
        customer_id = CUSTOMER_ID,
        developer_token = DEVELOPER_TOKEN,
        authentication = None,
    )

    # authenticate authorization data through oAuth 2.0
    authenticate(authorization_data)

    # create the bulk service client
    bulk_service = ServiceClient(
        service='BulkService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT
    )

    # download the data related to each Ad
    download_entities = bulk_service.factory.create('ArrayOfDownloadEntity')
    download_entities.DownloadEntity = ['Ads']

    bulk_request = bulk_service.DownloadCampaignsByAccountIds(
        AccountIds={'long': [authorization_data.account_id] },
        DataScope=['EntityData', 'QualityScoreData', 'BidSuggestionsData'],
        DownloadEntities=download_entities,
        FormatVersion="6.0",
        LastSyncTimeInUTC=None
    )
</code>```

Body:
Right now, I'm currently using the Bing Ads Python SDK to ingest data in csv format using the Bulk Service Client on version 13. For this example, I'll include 'Ads' as the only download entity with  no LastSyncTime variable set to collect all of the available data from the Bulk Service Endpoint for Ads. After creating the proper request and downloading the csv file from the appropriate URL, I'm returned a csv file with about 418 rows (most of which are empty which is correct), and two columns named 'AdGroup' and 'Campaign'. However, those two columns are simply the name of the AdGroup and Campaign rather than the ID. Is there a way to return the ID's of the AdGroup or Campaign rather than just the names?

Quick Note: I'm wanting to use the bulk_service_manager as it allows for the option of windowing the data that has been updated since a certain time. The history and the changes over time are required for Ads, AdGroups, and Campaigns.

Below is quick walkthrough of how I'm using the SDK right now. In this example, I'm wanting to pull back the 'Ads' object and its respective data. After creating the 'bulk_request' object, I'm waiting for the job to be completed before downloading the CSV file from the response URL. Regardless, the CSV returns the Ad Id, but the AdGroup and Campaign names rather than IDS.

from bingads.service_client import ServiceClient
from bingads.v13.reporting import *
from bingads.authorization import AuthorizationData, OAuthDesktopMobileAuthCodeGrant

authorization_data = AuthorizationData(
        account_id = ACCOUNT_ID,
        customer_id = CUSTOMER_ID,
        developer_token = DEVELOPER_TOKEN,
        authentication = None,
    )

    # authenticate authorization data through oAuth 2.0
    authenticate(authorization_data)

    # create the bulk service client
    bulk_service = ServiceClient(
        service='BulkService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT
    )

    # download the data related to each Ad
    download_entities = bulk_service.factory.create('ArrayOfDownloadEntity')
    download_entities.DownloadEntity = ['Ads']

    bulk_request = bulk_service.DownloadCampaignsByAccountIds(
        AccountIds={'long': [authorization_data.account_id] },
        DataScope=['EntityData', 'QualityScoreData', 'BidSuggestionsData'],
        DownloadEntities=download_entities,
        FormatVersion="6.0",
        LastSyncTimeInUTC=None
    )


问:
LSTM multi-sequence input to one sequence output
I am new with neural networks and am currently trying to make an LSTM model that predicts an output sequence based on multiple parameters. Excuse my ignorance and dummyness in advance.

I have obtained training and validation datasets, which look somewhat like the following:

For every ID four rows are recorded, which uses columns holding certain parameters and the corresponding Y output. Practically, there are thus ~122,000 / 4 = ~30,500 samples (I mistakenly put 122,000 as ID, it is in fact the number of rows). Since the parameter values and the corresponding Y values follow temporal patterns, I am interested if a model such as LSTM improves the prediction.

I want to predict the Y in my validation dataset (~73,000/4 = ~18,000 samples), based on the temporal patterns of the parameters. But is this possible? Most tutorials I followed use a single sequence, for which an LSTM is used to extend a similar input sequence. I thus want an LSTM with 'multi-sequence' input, which outputs one sequence. How do I go about this?

I'm using PyTorch as framework. A simple LSTM model I created using a tutorial, which would not incorporate the parameters:

```<code>training_y = traindf.reset_index()['Y']
validation_y = traindf.reset_index()['Y']
</code>```

Then create a dataset for this:

```<code>class YDataset(Dataset):
  def __init__(self, data, seq_len = 100):
    self.data = data
    self.data = torch.from_numpy(data).float().view(-1)
    self.seq_len = seq_len

  def __len__(self):
    return len(self.data)-self.seq_len-1

  def __getitem__(self,index):
    return self.data[index : index+self.seq_len] , self.data[index+self.seq_len]

train_y = YDataset(training_y_df)
vali_y = YDataset(validation_y_df)
</code>```
```<code>batch_size = 64
train_dataloader = DataLoader(train_y, batch_size, drop_last=True)
vali_dataloader = DataLoader(vali_y, batch_size, drop_last=True)

device = "cuda" if torch.cuda.is_available() else "cpu"
</code>```

Then create the model:

```<code>class Lstm_model(nn.Module):
  def __init__(self, input_dim, hidden_size, num_layers):
    super(Lstm_model, self).__init__()
    self.num_layers = num_layers
    self.input_size = input_dim
    self.hidden_size = hidden_size
    self.lstm = nn.LSTM(input_size=input_dim, hidden_size = hidden_size, num_layers = num_layers)
    self.fc = nn.Linear(hidden_size, 1)

  def forward(self,x,hn,cn):
    out , (hn,cn) = self.lstm(x, (hn, cn))
    final_out = self.fc(out[-1])
    return final_out, hn,cn

  def predict(self,x):
    hn, cn = self.init()
    final_out = self.fc(out[-1])
    return final_out

  def init(self):
    h0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
    c0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
    return h0 , c0

input_dim = 1
hidden_size = 50
num_layers = 3

model = Lstm_model(input_dim , hidden_size , num_layers).to(device)
</code>```

Loss function and training loop (more or less same as for validation):

```<code>loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

def train(dataloader):
  hn, cn = model.init()
  model.train()
  for batch , item in enumerate(dataloader):
    x , y = item
    x = x.to(device)
    y = y.to(device)
    out , hn , cn = model(x.reshape(100,batch_size,1),hn,cn)
    loss = loss_fn(out.reshape(batch_size), y)
    hn = hn.detach()
    cn = cn.detach()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if batch == len(dataloader)-1:
      loss = loss.item
      print(f"train loss: {loss:>7f} ")

</code>```

Epochs and loss metrics:

```<code>epochs = 200 # Takes really long for me
for epoch in range(epochs):
  print(f"epoch {epoch} ")
  train(train_dataloader)
  test(vali_dataloader)

</code>```

Final metrics:

```<code>import math
from sklearn.metrics import mean_squared_error
import numpy as np
def calculate_metrics(data_loader):
  pred_arr = []
  y_arr = []
  with torch.no_grad():
    hn , cn = model.init()
    for batch , item = in enumerate(data_loader):
      x , y = item
      x , y = x.to(device) , y.to(device)
      x = x.view(100,64,1)
      pred = model(x, hn, cn)[0]
      pred = scalar.inverse_transform(pred.detach().cpu().numpy().reshape(-1))
      y = scalar.inverse_transform(y.detach().cpu().numpy().reshape(1,-1)).reshape(-1)
      pred_arr = pred_arr + list(pred)
      y_arr = y_arr + list(y)
    return math.sqrt(mean_squared_error(y_arr,pred_arr))
</code>```

I used this code more as an example of how LSTM would work. Nevertheless, I don't know if this is the right track for me. Does someone know what I should do or a tutorial that does work for my example? Thanks in advance!

Body:
I am new with neural networks and am currently trying to make an LSTM model that predicts an output sequence based on multiple parameters. Excuse my ignorance and dummyness in advance.

I have obtained training and validation datasets, which look somewhat like the following:

For every ID four rows are recorded, which uses columns holding certain parameters and the corresponding Y output. Practically, there are thus ~122,000 / 4 = ~30,500 samples (I mistakenly put 122,000 as ID, it is in fact the number of rows). Since the parameter values and the corresponding Y values follow temporal patterns, I am interested if a model such as LSTM improves the prediction.

I want to predict the Y in my validation dataset (~73,000/4 = ~18,000 samples), based on the temporal patterns of the parameters. But is this possible? Most tutorials I followed use a single sequence, for which an LSTM is used to extend a similar input sequence. I thus want an LSTM with 'multi-sequence' input, which outputs one sequence. How do I go about this?

I'm using PyTorch as framework. A simple LSTM model I created using a tutorial, which would not incorporate the parameters:

training_y = traindf.reset_index()['Y']
validation_y = traindf.reset_index()['Y']

Then create a dataset for this:

class YDataset(Dataset):
  def __init__(self, data, seq_len = 100):
    self.data = data
    self.data = torch.from_numpy(data).float().view(-1)
    self.seq_len = seq_len

  def __len__(self):
    return len(self.data)-self.seq_len-1

  def __getitem__(self,index):
    return self.data[index : index+self.seq_len] , self.data[index+self.seq_len]

train_y = YDataset(training_y_df)
vali_y = YDataset(validation_y_df)

batch_size = 64
train_dataloader = DataLoader(train_y, batch_size, drop_last=True)
vali_dataloader = DataLoader(vali_y, batch_size, drop_last=True)

device = "cuda" if torch.cuda.is_available() else "cpu"

Then create the model:

class Lstm_model(nn.Module):
  def __init__(self, input_dim, hidden_size, num_layers):
    super(Lstm_model, self).__init__()
    self.num_layers = num_layers
    self.input_size = input_dim
    self.hidden_size = hidden_size
    self.lstm = nn.LSTM(input_size=input_dim, hidden_size = hidden_size, num_layers = num_layers)
    self.fc = nn.Linear(hidden_size, 1)

  def forward(self,x,hn,cn):
    out , (hn,cn) = self.lstm(x, (hn, cn))
    final_out = self.fc(out[-1])
    return final_out, hn,cn

  def predict(self,x):
    hn, cn = self.init()
    final_out = self.fc(out[-1])
    return final_out

  def init(self):
    h0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
    c0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(device)
    return h0 , c0

input_dim = 1
hidden_size = 50
num_layers = 3

model = Lstm_model(input_dim , hidden_size , num_layers).to(device)

Loss function and training loop (more or less same as for validation):

loss_fn = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

def train(dataloader):
  hn, cn = model.init()
  model.train()
  for batch , item in enumerate(dataloader):
    x , y = item
    x = x.to(device)
    y = y.to(device)
    out , hn , cn = model(x.reshape(100,batch_size,1),hn,cn)
    loss = loss_fn(out.reshape(batch_size), y)
    hn = hn.detach()
    cn = cn.detach()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if batch == len(dataloader)-1:
      loss = loss.item
      print(f"train loss: {loss:>7f} ")

Epochs and loss metrics:

epochs = 200 # Takes really long for me
for epoch in range(epochs):
  print(f"epoch {epoch} ")
  train(train_dataloader)
  test(vali_dataloader)

Final metrics:

import math
from sklearn.metrics import mean_squared_error
import numpy as np
def calculate_metrics(data_loader):
  pred_arr = []
  y_arr = []
  with torch.no_grad():
    hn , cn = model.init()
    for batch , item = in enumerate(data_loader):
      x , y = item
      x , y = x.to(device) , y.to(device)
      x = x.view(100,64,1)
      pred = model(x, hn, cn)[0]
      pred = scalar.inverse_transform(pred.detach().cpu().numpy().reshape(-1))
      y = scalar.inverse_transform(y.detach().cpu().numpy().reshape(1,-1)).reshape(-1)
      pred_arr = pred_arr + list(pred)
      y_arr = y_arr + list(y)
    return math.sqrt(mean_squared_error(y_arr,pred_arr))

I used this code more as an example of how LSTM would work. Nevertheless, I don't know if this is the right track for me. Does someone know what I should do or a tutorial that does work for my example? Thanks in advance!


问:
How to key/unkey a radio and/or perform flow control through the VITA 49.2 standard
I've been looking at how to use the VITA 49.2 standard to key/unkey a radio and how to perform flow control.

I did not see something available in the existing attributes of the context/control packets for the items I mentioned.

Does this mean if I want to do keying or flow control through 49.2 I have to define these packets myself through extension packets?

I thought keying/unkeying a radio and performing flow control would be something commonly done with VITA 49.2, so I thought attributes for these items might have already existed in the standard.


问:
Laravel, Cannot get simple hasMany relationship to return results
I am trying to run a really simple model with relationship eloquent query. My code is below and as you can see, I am just outputting the results to the page for now:

ServiceController.php

    class ServiceController extends Controller
    {
        public function show(string $id): JsonResponse
        {
            $services = Service::with('transactions')->where('id', '=', $id)->first();

            echo '```';
            print_r($services->toArray());
            echo '```';
            exit;
        }
    }
```
<p>Service.php</p>
<pre class="lang-php prettyprint-override"><code>    class Service extends Model
    {
        public function transactions()
        {
            return $this->hasMany(Transaction::class);
        }
    }
</code>```

My transactions database tables contains the following columns:

transactions

| id | ... | service_id | created_at | updated_at | deleted_at |

I get no error when I run this, but the transactions relationship is empty. But only for some results. Some services have all the transactions returned correctly. Some have them missing.

What am I doing wrong?  It seems a simple setup. Surely I can't be missing something so big?

Edit
I have noticed that the missing relationship all belong to the same two services. All services return their transactions correctly except for these two services. Not sure if that means anything.

Body:
I am trying to run a really simple model with relationship eloquent query. My code is below and as you can see, I am just outputting the results to the page for now:

ServiceController.php

    class ServiceController extends Controller
    {
        public function show(string $id): JsonResponse
        {
            $services = Service::with('transactions')->where('id', '=', $id)->first();

            echo '
';
            print_r($services->toArray());
            echo '
';
            exit;
        }
    }

Service.php

    class Service extends Model
    {
        public function transactions()
        {
            return $this->hasMany(Transaction::class);
        }
    }

My transactions database tables contains the following columns:

transactions

| id | ... | service_id | created_at | updated_at | deleted_at |

I get no error when I run this, but the transactions relationship is empty. But only for some results. Some services have all the transactions returned correctly. Some have them missing.

What am I doing wrong?  It seems a simple setup. Surely I can't be missing something so big?

Edit
I have noticed that the missing relationship all belong to the same two services. All services return their transactions correctly except for these two services. Not sure if that means anything.


问:
Add custom shape object properties based on svg in react-three-fiber
I'm trying to render a map of a small room based on the svg image I have, just as shown in here. I can see every shape being listed and rendered properly, but since I want those objects to be interactive, I need to somehow relate them to the ids I have in the db. I'm aware that svgs can contain data-* properties, but is it possible to make them included in the objects listed? For example my custom data-id?</p>


问:
How to reduce GPU memory in PyTorch while avoiding in-place operations?
I am running out of GPU memory on a Transformer model I am using and I believe it is because I changed a number of in-place operations to out-of-place.

For example,
I changed b += something to b = b + something

where b and something are both PyTorch tensors.

I did this because the in-place operation (+=) breaks torch autograd and prevents me from perfroming back propogation. However, with out-of-place operations, I am duplicating data and I eventually run out of memory.

I tried manually deleting variables as follows:

```<code>b_new = b + something
del b
torch.cuda.empty_cache()
</code>```

But this does not free up any GPU memory as observed from torch.cuda.memory_allocated()

How can I reduce my GPU memory consumption here?

Here is a toy example to illustrate my problem. I wish to have the memory performance of using in-place operations, while still being able to perform back propagation.

```<code>from torch import nn
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

X = torch.rand([500, 500, 512], device=device)

class SimpleNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.linears = nn.ModuleList([nn.Linear(512, 512) for i in range(10)])
        self.mem_before = []
        self.mem_after = []

    def forward(self, x):
        for linear in self.linears:
            self.mem_before.append(torch.cuda.memory_allocated() /1024**2)
            # compare out-of-place versus in-place
            # x += linear(x)
            x = x + linear(x)
            self.mem_after.append(torch.cuda.memory_allocated() /1024**2)
        return x

model = SimpleNetwork()
model.to(device)

for epoch in range(10):
    output = model(X)
    # Calculate loss and do backward step
    # I can't do backward step with in-place operations
</code>```

Below I have plotted the GPU memory usage for each method.

Body:
I am running out of GPU memory on a Transformer model I am using and I believe it is because I changed a number of in-place operations to out-of-place.

For example,
I changed b += something to b = b + something

where b and something are both PyTorch tensors.

I did this because the in-place operation (+=) breaks torch autograd and prevents me from perfroming back propogation. However, with out-of-place operations, I am duplicating data and I eventually run out of memory.

I tried manually deleting variables as follows:

b_new = b + something
del b
torch.cuda.empty_cache()

But this does not free up any GPU memory as observed from torch.cuda.memory_allocated()

How can I reduce my GPU memory consumption here?

Here is a toy example to illustrate my problem. I wish to have the memory performance of using in-place operations, while still being able to perform back propagation.

from torch import nn
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

X = torch.rand([500, 500, 512], device=device)

class SimpleNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.linears = nn.ModuleList([nn.Linear(512, 512) for i in range(10)])
        self.mem_before = []
        self.mem_after = []

    def forward(self, x):
        for linear in self.linears:
            self.mem_before.append(torch.cuda.memory_allocated() /1024**2)
            # compare out-of-place versus in-place
            # x += linear(x)
            x = x + linear(x)
            self.mem_after.append(torch.cuda.memory_allocated() /1024**2)
        return x

model = SimpleNetwork()
model.to(device)

for epoch in range(10):
    output = model(X)
    # Calculate loss and do backward step
    # I can't do backward step with in-place operations

Below I have plotted the GPU memory usage for each method.


问:
Missing Argument Parameter #1 in Call for an expression with no parameters
I keep getting an error "Missing argument for parameter #1 in call" when i try to call a ForEach on a list of Workouts, and I don't know what Swift is confused about. I believe it has something to do with which ViewModel it is referencing, but im not sure how to explicitly tell it.

Here's my code of my View:

```<code>
struct WorkoutProgramView: View {
    @ObservedObject var workoutViewModel: WorkoutViewModel
    @StateObject var vm: WorkoutListViewModel = .init()
    @State var currentWeek: [Date] = []
    @State var currentDay: Date = Date()
    @State var selection: String? = nil
    let screenSize: CGRect = UIScreen.main.bounds
    let columns = [GridItem(.adaptive(minimum: 150, maximum: 400))]

var body: some View {

ScrollView{
                LazyVGrid(columns: columns){
                    ForEach(vm.workoutDays, id:\.id) { day in
                        if isSameDay(date1: currentDay, date2: day.date!){
                            ZStack{
                                RoundedRectangle(cornerRadius: 5).frame(width: .infinity).padding().foregroundColor(Color.black).opacity(0.1)
}
</code>```

I get the error on the ForEach row.

Here's my workoutViewModel and vm:

```<code>import SwiftUI
@MainActor
class WorkoutListViewModel: ObservableObject{
    @ObservedObject var workoutViewModel = WorkoutViewModel()
    @Published var workoutDays: [WorkoutDays] = []

    func loadWorkoutData() async throws{
        let svc = NestedFirestoreService(workoutViewModel: workoutViewModel)

        self.workoutDays = try await svc.retrieveWorkoutDays()
    }
}

class WorkoutViewModel: ObservableObject {
    let auth = Auth.auth()
    let user = Auth.auth().currentUser
    @Published var name: String = ""
    @Published var date: Date = Date()
    @Published var exercise: Double = 0.0
    @Published var workoutProgramList: [WorkoutProgramModel] = []
    @Published var todaysFoodList: [FoodItem] = []
    @Published var workoutProgramSelected: String = ""
    @Published var workoutDayData: [WorkoutDays] = []
    @Published var workoutDaySelected: String = ""
    @Published var exerciseData: [ExerciseModel] = []
    @Published var ExerciseSelected: String = ""
    @Published var loggedSet: Int = 0
    @Published var loggedReps: Int = 0
    @Published var loggedWeight: Int = 0
    @Published var notes: String = ""
    @Published var dayAndExerciseList: [newStrengthModel] = []
}
</code>```

And here's my WorkoutDays model":

```<code>struct WorkoutDays: Encodable, Decodable, Identifiable {
    @DocumentID var id: String?
    var name: String?
    var date: Date?
    var description: String?
    var timeToCompleteWarmup: Double?
    var timeToCompleteStrength: Double?
    var timeToCompleteMetcon: Double?
    var timeToCompleteAccessories: Double?
    var exercises: [ExerciseModel]?
}
</code>```
```<code>struct ExerciseModel: Encodable, Decodable, Hashable, Identifiable {
    @DocumentID var id: String?
    var workoutDayID: String?
    var name: String?
    var reps: [Int]?
    var percent: [Double]?
    var linkToVideo: String?
    var isCompleted: Bool?
    var description: String?
    var timeToComplete: Double?
    var type: String?
}

</code>```

Can anyone help out? Been stuck on this for days and its definitely bugging me lol.

Body:
I keep getting an error "Missing argument for parameter #1 in call" when i try to call a ForEach on a list of Workouts, and I don't know what Swift is confused about. I believe it has something to do with which ViewModel it is referencing, but im not sure how to explicitly tell it.

Here's my code of my View:

struct WorkoutProgramView: View {
    @ObservedObject var workoutViewModel: WorkoutViewModel
    @StateObject var vm: WorkoutListViewModel = .init()
    @State var currentWeek: [Date] = []
    @State var currentDay: Date = Date()
    @State var selection: String? = nil
    let screenSize: CGRect = UIScreen.main.bounds
    let columns = [GridItem(.adaptive(minimum: 150, maximum: 400))]

var body: some View {

ScrollView{
                LazyVGrid(columns: columns){
                    ForEach(vm.workoutDays, id:\.id) { day in
                        if isSameDay(date1: currentDay, date2: day.date!){
                            ZStack{
                                RoundedRectangle(cornerRadius: 5).frame(width: .infinity).padding().foregroundColor(Color.black).opacity(0.1)
}

I get the error on the ForEach row.

Here's my workoutViewModel and vm:

import SwiftUI
@MainActor
class WorkoutListViewModel: ObservableObject{
    @ObservedObject var workoutViewModel = WorkoutViewModel()
    @Published var workoutDays: [WorkoutDays] = []

    func loadWorkoutData() async throws{
        let svc = NestedFirestoreService(workoutViewModel: workoutViewModel)

        self.workoutDays = try await svc.retrieveWorkoutDays()
    }
}

class WorkoutViewModel: ObservableObject {
    let auth = Auth.auth()
    let user = Auth.auth().currentUser
    @Published var name: String = ""
    @Published var date: Date = Date()
    @Published var exercise: Double = 0.0
    @Published var workoutProgramList: [WorkoutProgramModel] = []
    @Published var todaysFoodList: [FoodItem] = []
    @Published var workoutProgramSelected: String = ""
    @Published var workoutDayData: [WorkoutDays] = []
    @Published var workoutDaySelected: String = ""
    @Published var exerciseData: [ExerciseModel] = []
    @Published var ExerciseSelected: String = ""
    @Published var loggedSet: Int = 0
    @Published var loggedReps: Int = 0
    @Published var loggedWeight: Int = 0
    @Published var notes: String = ""
    @Published var dayAndExerciseList: [newStrengthModel] = []
}

And here's my WorkoutDays model":

struct WorkoutDays: Encodable, Decodable, Identifiable {
    @DocumentID var id: String?
    var name: String?
    var date: Date?
    var description: String?
    var timeToCompleteWarmup: Double?
    var timeToCompleteStrength: Double?
    var timeToCompleteMetcon: Double?
    var timeToCompleteAccessories: Double?
    var exercises: [ExerciseModel]?
}

struct ExerciseModel: Encodable, Decodable, Hashable, Identifiable {
    @DocumentID var id: String?
    var workoutDayID: String?
    var name: String?
    var reps: [Int]?
    var percent: [Double]?
    var linkToVideo: String?
    var isCompleted: Bool?
    var description: String?
    var timeToComplete: Double?
    var type: String?
}

Can anyone help out? Been stuck on this for days and its definitely bugging me lol.


问:
How to query a geojson polygon from a POSTGres SQL db via Python
I would like to query a polygon from a POSTGRESQL database via Python using a geojson polygon.

Type:

cursor.execute("SELECT * FROM database_name WHERE in geojson)

Geojson file:

a = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates":

...

Many thanks in advance for your insights

I have tried classic SQL queries, and queries using @ but it does not work for me.


问:
Getting an array of test case ids to use to create a test run
I am trying to implement testrail integration using Testrail's API endpoint with Selenium C#. I have successfully created a test run with all tests in a test suite.

I now want to create a test run and include only the test cases that I have selected to run instead of all test cases in the suite (which is what is done by default).

I would like to get a list of the selected cases, add these to an array and then use that array to make the request.

Code:

Here are two attempts I have made.  Firstly I have manually assigned test case ids but I want to dynamically create this array when I run a selected number of test cases.  How could this be done?

```<code>        RestRequest newRequest = new
        RestRequest($"index.php?/api/v2/add_run/{project_id}", Method.Post);
        string authInfo = Base64StringConverter.GetBase64String("email:password");
        newRequest.AddHeader("Authorization", "Basic " + authInfo);
        newRequest.AddHeader("Content-Type", "application/json");
        newRequest.RequestFormat = DataFormat.Json;
        int[] arrayOfCases = new int [] {2342321, 2323242, 2234213};
        newRequest.AddJsonBody(new { assignedto_id = 1, suite_id = 1111, name = "API Test Run", refs = "API Auto Tests", description = "This is a description of the test", include_all = false, case_ids = new[] { arrayOfCases } });
        var newResponse = await restClient.ExecuteAsync(newRequest);
</code>```

Here I have created a test run including all test cases in the suite:

```<code>        RestRequest newRequest = new RestRequest($"index.php?/api/v2/add_run/{project_id}", Method.Post);
        string authInfo = Base64StringConverter.GetBase64String("email:password");
        newRequest.AddHeader("Authorization", "Basic " + authInfo);
        newRequest.AddHeader("Content-Type", "application/json");
        newRequest.RequestFormat = DataFormat.Json;
        newRequest.AddJsonBody(new { assignedto_id = 9, suite_id = 2506, name = "UI Nightly Regression Test Run", refs = "UI Auto Tests", description = "This is a description of the test", include_all = true });
        var newResponse = await restClient.ExecuteAsync(newRequest);
</code>```

Body:
I am trying to implement testrail integration using Testrail's API endpoint with Selenium C#. I have successfully created a test run with all tests in a test suite.

I now want to create a test run and include only the test cases that I have selected to run instead of all test cases in the suite (which is what is done by default).

I would like to get a list of the selected cases, add these to an array and then use that array to make the request.

Code:

Here are two attempts I have made.  Firstly I have manually assigned test case ids but I want to dynamically create this array when I run a selected number of test cases.  How could this be done?

        RestRequest newRequest = new
        RestRequest($"index.php?/api/v2/add_run/{project_id}", Method.Post);
        string authInfo = Base64StringConverter.GetBase64String("email:password");
        newRequest.AddHeader("Authorization", "Basic " + authInfo);
        newRequest.AddHeader("Content-Type", "application/json");
        newRequest.RequestFormat = DataFormat.Json;
        int[] arrayOfCases = new int [] {2342321, 2323242, 2234213};
        newRequest.AddJsonBody(new { assignedto_id = 1, suite_id = 1111, name = "API Test Run", refs = "API Auto Tests", description = "This is a description of the test", include_all = false, case_ids = new[] { arrayOfCases } });
        var newResponse = await restClient.ExecuteAsync(newRequest);

Here I have created a test run including all test cases in the suite:

        RestRequest newRequest = new RestRequest($"index.php?/api/v2/add_run/{project_id}", Method.Post);
        string authInfo = Base64StringConverter.GetBase64String("email:password");
        newRequest.AddHeader("Authorization", "Basic " + authInfo);
        newRequest.AddHeader("Content-Type", "application/json");
        newRequest.RequestFormat = DataFormat.Json;
        newRequest.AddJsonBody(new { assignedto_id = 9, suite_id = 2506, name = "UI Nightly Regression Test Run", refs = "UI Auto Tests", description = "This is a description of the test", include_all = true });
        var newResponse = await restClient.ExecuteAsync(newRequest);


问:
How to set specific variable types in config file
I just added the settings config file to my C# console application and I'm looking to store a list of byte arrays, however I'm unfamiliar. Is there any way to do this so that next time I launch my app it has the same values in the arrays in the list?</p>


问:
How can I use the sort method in Python to sort a list of dictionaries by a specific key in the dictionary?
To use the sort method in Python to sort a list of dictionaries by a specific key in the dictionary, you can pass a lambda function as the key parameter to the sort method. This lambda function should specify that the list should be sorted by the desired key in the dictionary.</p>
```<code>my_list = [    {'name': 'Alice', 'age': 25},    {'name': 'Bob', 'age': 27},    {'name': 'Charlie', 'age': 23},]
my_list.sort(key x: x['age'])
print(my_list)
</code>```

Body:
To use the sort method in Python to sort a list of dictionaries by a specific key in the dictionary, you can pass a lambda function as the key parameter to the sort method. This lambda function should specify that the list should be sorted by the desired key in the dictionary.

my_list = [    {'name': 'Alice', 'age': 25},    {'name': 'Bob', 'age': 27},    {'name': 'Charlie', 'age': 23},]
my_list.sort(key x: x['age'])
print(my_list)