Title: MongoDB get last transaction per UCODE

Body:
I need to filter the records below but I need to return only the last transaction (the most recent transaction) by UCODE.

_id                        ucode                         value           createDate
-------------------------------------------------------------------------------------
63a997ac1    08905ba5-4188-4f5f-b982-123456789012          10        2020-02-10 09:00:00
398fdd112    08905ba5-4188-4f5f-b982-123456789012         647        2020-02-11 09:00:00
561e4c033    1beced7e-b0ad-43e7-bd8d-d3c7cf2a1234          99        2020-02-12 10:00:00
63a997ac4    08905ba5-4188-4f5f-b982-xxxxxa3b0396          10        2020-02-13 09:00:00
398fdd115    08905ba5-4188-4f5f-b982-xxxxxa3b0396         777        2020-02-14 09:00:00
561e4c036    1beced7e-b0ad-43e7-bd8d-d3c7cf2axxxx         234        2020-02-15 10:00:00
63a997ac7    08905ba5-4188-4f5f-b982-906d2a3baaaa         610        2020-02-16 09:00:00
398fdd118    08905ba5-4188-4f5f-b982-906d2a3baaaa         647        2020-02-17 09:00:00
561e4c039    1beced7e-b0ad-43e7-bd8d-d3c7cf2axxxx         999        2020-02-18 10:00:00

db.transaction.aggregate([
    { $match:
        {ucode: {$in:[:listOfUcode]},
        createDate: {
            "$gte": ISODate(:start),
            "$lte": ISODate(:end)
                }
        }
    },
    { $sort: { ucode: 1, createDate: -1 } },
])

This is the result I would like to get.

_id                        ucode                         value           createDate
-------------------------------------------------------------------------------------
398fdd112    08905ba5-4188-4f5f-b982-123456789012         647        2020-02-11 09:00:00
561e4c033    1beced7e-b0ad-43e7-bd8d-d3c7cf2a1234          99        2020-02-12 10:00:00
398fdd115    08905ba5-4188-4f5f-b982-xxxxxa3b0396         777        2020-02-14 09:00:00
398fdd118    08905ba5-4188-4f5f-b982-906d2a3baaaa         647        2020-02-17 09:00:00
561e4c039    1beced7e-b0ad-43e7-bd8d-d3c7cf2axxxx         999        2020-02-18 10:00:00

Someone could help me with the adjustment in the query?

.:SOLUTION:.

db.transaction.aggregate([
    { $match:
        {ucode: {$in:[:listOfUcode]},
        createDate: {
            "$gte": ISODate(:start),
            "$lte": ISODate(:end)
                }
        }
    },
    { $sort: { ucode: 1, createDate: -1 } },
    { $group:{
        _id: "$ucode",
        lastDateTransaction:{$first: "$createDate"},
        numberOfTransactionsInThePeriod: { $sum: 1 }
        }
    }
])


来源: stackexchange

问:
MySQL does not apply one-to-many relationship
I have the 2 dimension tables and 1 fact table. They look like this:

Dimension table 1: Investor_DM

Investor_nr
Investor_name

1
Jack

2
Kelly

Dimension table 2: Company_DM

Company_nr
Company_name

1
Apple

2
Microsoft

Fact table: Positions

Company_nr
Investor_nr
InvestmentDate
InvestmentSize

1
1
2022-jan-02
$1,000

2
1
2022-feb-03
$1,500

1
2
2022-jun-02
$7,000

2
2
2022-jul-03
$7,500

I assigned Investor_nr and Company_nr as PK's in their respective dimension tables, and assigned FK's in the fact table in which I refer to the PK's.

What I want is when I look for data WHERE Investor_nr = '1', I only get the investments in the fact table of investor 1, etc. However, I still get all investments even though I have created one-to-many relationships between the tables. Same goes for the company dimension table.

This is my

```<code>SELECT *
FROM Positions
WHERE Investor_nr = '1'
;

</code>```

query:

I would hope that if I SELECT * from all 3 tables, the Investor_nr's on each row correspond between the fact and dimension table, but this is not the case. Same goes for Company_nr.

What am I missing here? Am I using the wrong query, or are my relationships wrong?
I tried multiple queries, sometimes only on 1 table and sometimes 2 or 3 tables, but I always get data from investors I did not filter on.

Thanks!

ContentLicense: CC BY-SA 4.0

Body:
I have the 2 dimension tables and 1 fact table. They look like this:

Dimension table 1: Investor_DM

Investor_nr
Investor_name

1
Jack

2
Kelly

Dimension table 2: Company_DM

Company_nr
Company_name

1
Apple

2
Microsoft

Fact table: Positions

Company_nr
Investor_nr
InvestmentDate
InvestmentSize

1
1
2022-jan-02
$1,000

2
1
2022-feb-03
$1,500

1
2
2022-jun-02
$7,000

2
2
2022-jul-03
$7,500

I assigned Investor_nr and Company_nr as PK's in their respective dimension tables, and assigned FK's in the fact table in which I refer to the PK's.

What I want is when I look for data WHERE Investor_nr = '1', I only get the investments in the fact table of investor 1, etc. However, I still get all investments even though I have created one-to-many relationships between the tables. Same goes for the company dimension table.

This is my

SELECT *
FROM Positions
WHERE Investor_nr = '1'
;

query:

I would hope that if I SELECT * from all 3 tables, the Investor_nr's on each row correspond between the fact and dimension table, but this is not the case. Same goes for Company_nr.

What am I missing here? Am I using the wrong query, or are my relationships wrong?
I tried multiple queries, sometimes only on 1 table and sometimes 2 or 3 tables, but I always get data from investors I did not filter on.

Thanks!


问:
adding a message for the user in a custom django admin view
I have created a custom admin site and there is a view I'd like to be invoked with a custom button. This is my adminSite object:

```<code>class MyAdminSite(admin.AdminSite):
    site_header = 'My admin site'

    def get_urls(self):
        from django.urls import path
        urls = super().get_urls()
        urls += [
            path('appname/modelname/<int:pk>', self.admin_view(self.my_view), name='appname_modelname_view'),
        ]
        return urls

    def my_view(self, request, pk):
        #do something
        messages.info(request, 'some message')

</code>```

registering the model for which the view is invoked

```<code>my_admin = MyAdminSite()

class myModelAdmin(admin.ModelAdmin):
    change_form_template = 'admin/appname/change_form.html'

my_admin.register(myModel, myModelAdmin)
</code>```

change_form.html:

```<code>{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

{% block object-tools-items %}
    <li>
        <a href="{% url opts|admin_urlname:'myview' original.pk %}" class="someclass">Invoke</a>
    </li>
    <li>
        <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
    </li>
    {% if has_absolute_url %}
        <li>
            <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
        </li>
    {% endif %}
{% endblock %}
</code>```

When I click the "invoke" button, it should reload the the page and display the info message on top. However, the page simply reloads.

How do I make sure that the messages are displayed?

Thank you for your time...

Body:
I have created a custom admin site and there is a view I'd like to be invoked with a custom button. This is my adminSite object:

class MyAdminSite(admin.AdminSite):
    site_header = 'My admin site'

    def get_urls(self):
        from django.urls import path
        urls = super().get_urls()
        urls += [
            path('appname/modelname/<int:pk>', self.admin_view(self.my_view), name='appname_modelname_view'),
        ]
        return urls

    def my_view(self, request, pk):
        #do something
        messages.info(request, 'some message')

registering the model for which the view is invoked

my_admin = MyAdminSite()

class myModelAdmin(admin.ModelAdmin):
    change_form_template = 'admin/appname/change_form.html'

my_admin.register(myModel, myModelAdmin)

change_form.html:

{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}

{% if messages %}

    {% for message in messages %}

{{ message }}

    {% endfor %}

{% endif %}

{% block object-tools-items %}

        Invoke

        {% translate "History" %}

    {% if has_absolute_url %}

            {% translate "View on site" %}

    {% endif %}
{% endblock %}

When I click the "invoke" button, it should reload the the page and display the info message on top. However, the page simply reloads.

How do I make sure that the messages are displayed?

Thank you for your time...


问:
parameter hints still showing even when switched off
```<code>{
    "workbench.colorTheme": "Default Dark+",
    "editor.parameterHints.enabled": false,
    "editor.suggestOnTriggerCharacters": false,
    "editor.lightbulb.enabled": false,
    "editor.fontSize": 16,
    "terminal.integrated.fontSize": 18,
    "editor.accessibilitySupport": "off",
    "window.zoomLevel": -1,

}
</code>```

Those are all of my settings, as you can see I have them switched off, and my settings are saved. So how is this even happening?

Body:
{
    "workbench.colorTheme": "Default Dark+",
    "editor.parameterHints.enabled": false,
    "editor.suggestOnTriggerCharacters": false,
    "editor.lightbulb.enabled": false,
    "editor.fontSize": 16,
    "terminal.integrated.fontSize": 18,
    "editor.accessibilitySupport": "off",
    "window.zoomLevel": -1,

}

Those are all of my settings, as you can see I have them switched off, and my settings are saved. So how is this even happening?


问:
XR grab interactable object disappears when grabbed
I'm building a spaceship game for Oculus Quest. Inside the ship I added a lever to control its speed which has a rigidbody and an xr grab interactable component attached to it and a hinge joint as well.
The lever works well when the ship is stopped but if it's moving, when I grab the lever it immediately disappears.

Lever components

Scene hierarchy

Both "Ship" and "Ship bridge" objects have rigidbody attached with gravity turned off and kinematic turned on.

To move the ship I wrote this script and attached to the Ship object:

```<code>    private void FixedUpdate()
    {
        moveDirection = new Vector3(0, 0, -0.1f);
        transform.Translate(moveDirection, Space.World);
    }
</code>```

I tried turning on "retain transform parent" in the lever "xr grab interactable" component and I tried adding an interactable event to keep the lever as child of "Ship Bridge". None of those do anything.
(https://i.stack.imgur.com/h9vJd.png)

I don't understand why it disappears when the ship is moving.

Body:
I'm building a spaceship game for Oculus Quest. Inside the ship I added a lever to control its speed which has a rigidbody and an xr grab interactable component attached to it and a hinge joint as well.
The lever works well when the ship is stopped but if it's moving, when I grab the lever it immediately disappears.

Lever components

Scene hierarchy

Both "Ship" and "Ship bridge" objects have rigidbody attached with gravity turned off and kinematic turned on.

To move the ship I wrote this script and attached to the Ship object:

    private void FixedUpdate()
    {
        moveDirection = new Vector3(0, 0, -0.1f);
        transform.Translate(moveDirection, Space.World);
    }

I tried turning on "retain transform parent" in the lever "xr grab interactable" component and I tried adding an interactable event to keep the lever as child of "Ship Bridge". None of those do anything.
(https://i.stack.imgur.com/h9vJd.png)

I don't understand why it disappears when the ship is moving.


问:
How can I use multiple keys to do one thing in turtle
I am pretty much a beginner at Python and code altogether. I have a raspberry pi to mess around on and I recently got a Trilobot.

I'm trying to set it up so I can control it with a keyboard. I decided to use turtle and have been using things like the code below. I want to be able to go forward and right, but I don't know how to do both of them at the same time by holding w and d.

```<code>def forward():
     Bot.forward()
wn.onkeypress(forward, “w”)
</code>```

I don't know if any of that made sense. If it didn't, I'll gladly explain myself to get an answer.

Body:
I am pretty much a beginner at Python and code altogether. I have a raspberry pi to mess around on and I recently got a Trilobot.

I'm trying to set it up so I can control it with a keyboard. I decided to use turtle and have been using things like the code below. I want to be able to go forward and right, but I don't know how to do both of them at the same time by holding w and d.

def forward():
     Bot.forward()
wn.onkeypress(forward, “w”)

I don't know if any of that made sense. If it didn't, I'll gladly explain myself to get an answer.


问:
activate virtual environment in vs code in wsl2
I'm using vs code 1.74.2

I create my virtual environment in wsl2 in a directory like

```<code> usr@MainPC:~/projectA/projA $ source .tst/bin/activate
</code>```

then it becomes

```<code>(.tst) usr@MainPC:~/projectA/projA$ code .
</code>```

vs code will select .tst automatically

but if I exit and go to another directory

```<code>(.tst) usr@MainPC:~/projectB/projB$ code .
</code>```

I couldn't select .tst in vscode even if I use select interpreter and find the python in projectA/projA

Any idea?

Body:
I'm using vs code 1.74.2

I create my virtual environment in wsl2 in a directory like

 usr@MainPC:~/projectA/projA $ source .tst/bin/activate

then it becomes

(.tst) usr@MainPC:~/projectA/projA$ code .

vs code will select .tst automatically

but if I exit and go to another directory

(.tst) usr@MainPC:~/projectB/projB$ code .

I couldn't select .tst in vscode even if I use select interpreter and find the python in projectA/projA

Any idea?


问:
Power Automate Shopify API Connector and Export to Excel
I am trying to read my Shopify Products and Export them to an Excel file. So I was able to create a custom Connector and Get products, however I have an issue of exporting them into an excel. I need the list of SKUs, however it runs few minutes and throws me an error that job has timed out. Can you please help with the Power Automate step for getting data from GetProduct custom app and write into the excel. I actually tried to extract titles, and it worked, however when I go to the lower level to get sku, the job times-out.


问:
How do I make an item from my list disappear when it collides with my character?
I have no idea how to make my ggift dissapear. I think i need to acces the particular gift in the list but i can't figure out how. This is the part:

```<code> for ggift in GGift:
        if pygame.sprite.spritecollideany(personaj, ggift):
            GGift.remove(ggift)
            sunet_ciocnire.play()
</code>```

the full code:

```<code>from turtle import *
import pygame
import random
from pygame.locals import (
    RLEACCEL,
    K_UP,
    K_DOWN,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

latime_fereastra = 800
inaltime_fereastra = 600

class Avion(pygame.sprite.Sprite):
    def __init__(self):
        super(Avion, self).__init__()
        self.surf = pygame.image.load("santa.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect()

    def update(self, tasta_apasata):
        if tasta_apasata[K_UP]:
            self.rect.move_ip(0, -5)
            sunet_urcare.play()
        if tasta_apasata[K_DOWN]:
            self.rect.move_ip(0, 5)
            sunet_coborire.play()
        if tasta_apasata[K_LEFT]:
            self.rect.move_ip(-5, 0)
        if tasta_apasata[K_RIGHT]:
            self.rect.move_ip(5, 0)

        if self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > latime_fereastra:
            self.rect.right = latime_fereastra
        if self.rect.top <= 0:
            self.rect.top = 0
        elif self.rect.bottom >= inaltime_fereastra:
            self.rect.bottom = inaltime_fereastra

class WGift(pygame.sprite.Sprite):
    def __init__(self):
        super(WGift, self).__init__()
        self.surf = pygame.image.load("gift.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )
        self.speed = random.randint(5, 15)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

class GGift(pygame.sprite.Sprite):
    def __init__(self):
        super(GGift, self).__init__()
        self.surf = pygame.image.load("cadou.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )
        self.speed = random.randint(5, 15)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

class Norisor(pygame.sprite.Sprite):
    def __init__(self):
        super(Norisor, self).__init__()
        self.surf = pygame.image.load("nor.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )

    def update(self):
        self.rect.move_ip(-5, 0)
        if self.rect.right < 0:
            self.kill()

pygame.mixer.init()
pygame.init()

cronometru = pygame.time.Clock()
fereastra = pygame.display.set_mode((latime_fereastra, inaltime_fereastra))

adauga_wgift = pygame.USEREVENT + 1
pygame.time.set_timer(adauga_wgift, 500)

adauga_ggift = pygame.USEREVENT + 3
pygame.time.set_timer(adauga_ggift, 500)

adauga_norisor = pygame.USEREVENT + 2
pygame.time.set_timer(adauga_norisor, 1000)

personaj = Avion()

wgift = pygame.sprite.Group()
ggift = pygame.sprite.Group()

norisori = pygame.sprite.Group()
lista_cadre = pygame.sprite.Group()
lista_cadre.add(personaj)

pygame.mixer.music.load("muzica.mp3")
pygame.mixer.music.play(loops = -1)

sunet_urcare = pygame.mixer.Sound("sus.ogg")
sunet_coborire = pygame.mixer.Sound("jos.ogg")
sunet_ciocnire = pygame.mixer.Sound("ciocnire.ogg")

sunet_urcare.set_volume(0.5)
sunet_coborire.set_volume(0.5)
sunet_ciocnire.set_volume(0.5)

joc_activ = True

while joc_activ:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                joc_activ = False
        elif event.type == QUIT:
            joc_activ = False
        elif event.type == adauga_wgift:
            wgift_noua = WGift()
            wgift.add(wgift_noua)
            lista_cadre.add(wgift_noua)
        elif event.type == adauga_norisor:
            norisor_nou = Norisor()
            norisori.add(norisor_nou)
            lista_cadre.add(norisor_nou)
        elif event.type == adauga_ggift:
            ggift_noua = GGift()
            ggift.add(ggift_noua)
            lista_cadre.add(ggift_noua)

    tasta_apasata = pygame.key.get_pressed()
    personaj.update(tasta_apasata)

    wgift.update()
    ggift.update()
    norisori.update()

    fereastra.fill((42, 73, 122))

    for cadru in lista_cadre:
        fereastra.blit(cadru.surf, cadru.rect)

    if pygame.sprite.spritecollideany(personaj, wgift):
        personaj.kill()
        sunet_urcare.stop()
        sunet_coborire.stop()
        sunet_ciocnire.play()
        joc_activ = False

    for ggift in GGift:
        if pygame.sprite.spritecollideany(personaj, ggift):
            GGift.remove(ggift)
            sunet_ciocnire.play()

    pygame.display.flip()

    cronometru.tick(30)

pygame.mixer.music.stop()
pygame.mixer.quit()

</code>```

I need after personaj and that one ggift collide, just the ggift to dissapear

Body:
I have no idea how to make my ggift dissapear. I think i need to acces the particular gift in the list but i can't figure out how. This is the part:

 for ggift in GGift:
        if pygame.sprite.spritecollideany(personaj, ggift):
            GGift.remove(ggift)
            sunet_ciocnire.play()

the full code:

from turtle import *
import pygame
import random
from pygame.locals import (
    RLEACCEL,
    K_UP,
    K_DOWN,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

latime_fereastra = 800
inaltime_fereastra = 600

class Avion(pygame.sprite.Sprite):
    def __init__(self):
        super(Avion, self).__init__()
        self.surf = pygame.image.load("santa.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect()

    def update(self, tasta_apasata):
        if tasta_apasata[K_UP]:
            self.rect.move_ip(0, -5)
            sunet_urcare.play()
        if tasta_apasata[K_DOWN]:
            self.rect.move_ip(0, 5)
            sunet_coborire.play()
        if tasta_apasata[K_LEFT]:
            self.rect.move_ip(-5, 0)
        if tasta_apasata[K_RIGHT]:
            self.rect.move_ip(5, 0)

        if self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > latime_fereastra:
            self.rect.right = latime_fereastra
        if self.rect.top <= 0:
            self.rect.top = 0
        elif self.rect.bottom >= inaltime_fereastra:
            self.rect.bottom = inaltime_fereastra

class WGift(pygame.sprite.Sprite):
    def __init__(self):
        super(WGift, self).__init__()
        self.surf = pygame.image.load("gift.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )
        self.speed = random.randint(5, 15)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

class GGift(pygame.sprite.Sprite):
    def __init__(self):
        super(GGift, self).__init__()
        self.surf = pygame.image.load("cadou.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )
        self.speed = random.randint(5, 15)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

class Norisor(pygame.sprite.Sprite):
    def __init__(self):
        super(Norisor, self).__init__()
        self.surf = pygame.image.load("nor.png").convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(
            center=(
                random.randint(latime_fereastra + 20, latime_fereastra + 100),
                random.randint(0, inaltime_fereastra),
            )
        )

    def update(self):
        self.rect.move_ip(-5, 0)
        if self.rect.right < 0:
            self.kill()

pygame.mixer.init()
pygame.init()

cronometru = pygame.time.Clock()
fereastra = pygame.display.set_mode((latime_fereastra, inaltime_fereastra))

adauga_wgift = pygame.USEREVENT + 1
pygame.time.set_timer(adauga_wgift, 500)

adauga_ggift = pygame.USEREVENT + 3
pygame.time.set_timer(adauga_ggift, 500)

adauga_norisor = pygame.USEREVENT + 2
pygame.time.set_timer(adauga_norisor, 1000)

personaj = Avion()

wgift = pygame.sprite.Group()
ggift = pygame.sprite.Group()

norisori = pygame.sprite.Group()
lista_cadre = pygame.sprite.Group()
lista_cadre.add(personaj)

pygame.mixer.music.load("muzica.mp3")
pygame.mixer.music.play(loops = -1)

sunet_urcare = pygame.mixer.Sound("sus.ogg")
sunet_coborire = pygame.mixer.Sound("jos.ogg")
sunet_ciocnire = pygame.mixer.Sound("ciocnire.ogg")

sunet_urcare.set_volume(0.5)
sunet_coborire.set_volume(0.5)
sunet_ciocnire.set_volume(0.5)

joc_activ = True

while joc_activ:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                joc_activ = False
        elif event.type == QUIT:
            joc_activ = False
        elif event.type == adauga_wgift:
            wgift_noua = WGift()
            wgift.add(wgift_noua)
            lista_cadre.add(wgift_noua)
        elif event.type == adauga_norisor:
            norisor_nou = Norisor()
            norisori.add(norisor_nou)
            lista_cadre.add(norisor_nou)
        elif event.type == adauga_ggift:
            ggift_noua = GGift()
            ggift.add(ggift_noua)
            lista_cadre.add(ggift_noua)

    tasta_apasata = pygame.key.get_pressed()
    personaj.update(tasta_apasata)

    wgift.update()
    ggift.update()
    norisori.update()

    fereastra.fill((42, 73, 122))

    for cadru in lista_cadre:
        fereastra.blit(cadru.surf, cadru.rect)

    if pygame.sprite.spritecollideany(personaj, wgift):
        personaj.kill()
        sunet_urcare.stop()
        sunet_coborire.stop()
        sunet_ciocnire.play()
        joc_activ = False

    for ggift in GGift:
        if pygame.sprite.spritecollideany(personaj, ggift):
            GGift.remove(ggift)
            sunet_ciocnire.play()

    pygame.display.flip()

    cronometru.tick(30)

pygame.mixer.music.stop()
pygame.mixer.quit()

I need after personaj and that one ggift collide, just the ggift to dissapear


问:
vscode code gdb, how to halt, not stop debugging
In VS Code V1.73.1 - I am running GDB (actually a RISCV variant, debugging a target board vi jtag).

I"m also quite a bit confused and do not know if this is a VSCODE problem or a plugin problem, and there are multiple plugins involved,

If it is a plugin then I'm thinking it is the one that controls GDB... and other things are built upon that plugin. But - GDB is so much at the core that I think that the GDB component is actually part of the baseline VS-CODE package.

Background: I want to halt the cpu I am debugging so that i can inspect global variables and/or set breakpoints. I cannot seem to do that.

I normally go through the connect, load, then type continue. If I set a breakpoint before I type continue - it works.

My code is now running, I want to stop - add a breakpoint and continue.

To be clear - I do not mean disconnect and stop debugging, I want to stop or halt the cpu at its current location.

The normal method or action for GDB is to type Control_C in the GDB terminal but - this is VS Code, its not a normal terminal.

The question is how do I stop or halt the cpu under control of the debugger

Its not obvious, and no menu seems to find that selection.

if it was an local debug session I could do something like controlC in a console window or use KILL to send a signal, but - this is an embedded/remote GDB session so that is not possible.


问:
How do you keep authorization active when entering the docs in Fastapi?
I am using some basic oauth2 authentication in Python, fast api. I want to hide all of the swagger docs behind a login, and ideally I would want all the login logic to be handled by the oauth2scheme, such that when a user logs in to see the docs, they do not need to reauthenticate in order to test any of the endpoints.

The closest I have gotten to a solution is logging in the user by saving a cookie to the request, then overwriting the swagger ui to check the cookie and logout the user. The only functionality I am missing is having the user be automatically authenticated once entering the docs based on this cookie. Relevant code below:

```<code>@dbparse.get("/", include_in_schema=False, response_class=HTMLResponse)
async def login_page(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})
</code>```
```<code>@dbparse.post("/login", include_in_schema=False)
async def perform_login(
    request: Request,
    response: Response,
    username: Optional[str] = Form(None),
    password: Optional[str] = Form(None),
):
    try:
        if not (username and password):
            return RedirectResponse(
                "/?error=true", status_code=status.HTTP_303_SEE_OTHER
            )
        # Fake an oauth login form to route login attempts to previously written code
        form = OAuth2PasswordRequestForm(username=username, password=password, scope="")
        token = await generate_token(form)
        response = RedirectResponse("/docs", status_code=status.HTTP_302_FOUND)
        # Set the user's login cookie so that we can have them auth'd later
        response.set_cookie(
            key="Authorization",
            value=f"{token['token_type'].capitalize()} {token['access_token']}",
        )
        return response
    except:
        return RedirectResponse("/?error=true", status_code=status.HTTP_303_SEE_OTHER)
</code>```
```<code>@dbparse.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(request: Request):
    if request.cookies:
        try:
            token = await generate_token(None, request.cookies)
        except:
            response = RedirectResponse("/?expired=true", status_code=status.HTTP_303_SEE_OTHER)
            response.delete_cookie(key="Authorization")
            return response
    return get_swagger_ui_html(...)
</code>```
```<code>@dbparse.post("/token", include_in_schema=False)
async def generate_token(form_data: OAuth2PasswordRequestForm = Depends(), cached_token = None):
    print("==========================\nGENERATE_TOKEN()\n==========================")
    if cached_token:
        try:
            _, access_token = cached_token["Authorization"].split(" ")
            _ = decode_token(access_token)
            # Ensure that the token in cookies is working. (Confirmed to work as intended)
            return {"access_token": access_token, "token_type": "bearer"}
        except:
            raise
    user = authenticate(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username/password",
        )
    token = create_token(user)

    return {"access_token": token, "token_type": "bearer"}
</code>```

If there is an easier solution, I was unable to find it. The key functionality I am looking for is to use a cookie to authenticate the swagger docs for endpoint use. The endpoints need to require authentication, but ideally when you log in before seeing the docs, this authentication should carry over.

Body:
I am using some basic oauth2 authentication in Python, fast api. I want to hide all of the swagger docs behind a login, and ideally I would want all the login logic to be handled by the oauth2scheme, such that when a user logs in to see the docs, they do not need to reauthenticate in order to test any of the endpoints.

The closest I have gotten to a solution is logging in the user by saving a cookie to the request, then overwriting the swagger ui to check the cookie and logout the user. The only functionality I am missing is having the user be automatically authenticated once entering the docs based on this cookie. Relevant code below:

@dbparse.get("/", include_in_schema=False, response_class=HTMLResponse)
async def login_page(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})

@dbparse.post("/login", include_in_schema=False)
async def perform_login(
    request: Request,
    response: Response,
    username: Optional[str] = Form(None),
    password: Optional[str] = Form(None),
):
    try:
        if not (username and password):
            return RedirectResponse(
                "/?error=true", status_code=status.HTTP_303_SEE_OTHER
            )
        # Fake an oauth login form to route login attempts to previously written code
        form = OAuth2PasswordRequestForm(username=username, password=password, scope="")
        token = await generate_token(form)
        response = RedirectResponse("/docs", status_code=status.HTTP_302_FOUND)
        # Set the user's login cookie so that we can have them auth'd later
        response.set_cookie(
            key="Authorization",
            value=f"{token['token_type'].capitalize()} {token['access_token']}",
        )
        return response
    except:
        return RedirectResponse("/?error=true", status_code=status.HTTP_303_SEE_OTHER)

@dbparse.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(request: Request):
    if request.cookies:
        try:
            token = await generate_token(None, request.cookies)
        except:
            response = RedirectResponse("/?expired=true", status_code=status.HTTP_303_SEE_OTHER)
            response.delete_cookie(key="Authorization")
            return response
    return get_swagger_ui_html(...)

@dbparse.post("/token", include_in_schema=False)
async def generate_token(form_data: OAuth2PasswordRequestForm = Depends(), cached_token = None):
    print("==========================\nGENERATE_TOKEN()\n==========================")
    if cached_token:
        try:
            _, access_token = cached_token["Authorization"].split(" ")
            _ = decode_token(access_token)
            # Ensure that the token in cookies is working. (Confirmed to work as intended)
            return {"access_token": access_token, "token_type": "bearer"}
        except:
            raise
    user = authenticate(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username/password",
        )
    token = create_token(user)

    return {"access_token": token, "token_type": "bearer"}

If there is an easier solution, I was unable to find it. The key functionality I am looking for is to use a cookie to authenticate the swagger docs for endpoint use. The endpoints need to require authentication, but ideally when you log in before seeing the docs, this authentication should carry over.


问:
Why does Next.js scroll restoration not work during development but does work after build?
TLDR - Why does scroll restoration only work after build Next.js project.

When developing in Next.js, I want to reload the page and have the scroll position remain the same. This works after I run next build, but doesn't work with next dev - It just scrolls back to the top of the page. I have had random flukes where the scroll position is restored during development.

How to reproduce -

Create new next project

Create new page with the following

const MyComponent = () => {

    return (
        <>

asdf

asdf2

        </>
    )
}

export default MyComponent
```

run next dev, scroll down some and reload. Notice how it goes back to the top.

run next build and then next start. Scroll down again and reload. Notice it stays.

Body:
TLDR - Why does scroll restoration only work after build Next.js project.

When developing in Next.js, I want to reload the page and have the scroll position remain the same. This works after I run next build, but doesn't work with next dev - It just scrolls back to the top of the page. I have had random flukes where the scroll position is restored during development.

How to reproduce -

Create new next project

Create new page with the following

const MyComponent = () => {

    return (
        <>

asdf

asdf2

        </>
    )
}

export default MyComponent

run next dev, scroll down some and reload. Notice how it goes back to the top.

run next build and then next start. Scroll down again and reload. Notice it stays.


问:
RealityKit removing old 3D objects from scene before adding new 3D objects
I'm trying to play with Apple's RealityKit and some usdz files I got from their website.

I made a small app where I can load each 3D model at a time.

It works but with one issue. If I add a single 3D object is fine but when I load the new models they all get stuck upon each other. I can't seem to figure out how to remove the old 3D object before adding a different one.

Here is my code

My Model object

```<code>import Foundation
import UIKit
import RealityKit
import Combine

class Model {
    var modelName: String
    var image: UIImage
    var modelEntity: ModelEntity?

    private var cancellable: AnyCancellable? = nil

    var message: String = ""

    init(modelName: String){
        self.modelName = modelName

        self.image = UIImage(named: modelName)!

        let filename = modelName + ".usdz"

        self.cancellable = ModelEntity.loadModelAsync(named: filename)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    print("Model.swift -> DEBUG: Succesfully loaded \(self.modelName)")
                    break
                case .failure(let error):
                    print("Model.swift -> DEBUG: Unable to load : \(self.modelName)")
                    self.message = error.localizedDescription
                }

            }, receiveValue: { modelEntity in
                //get model entity
                self.modelEntity = modelEntity
            })
    }

}

</code>```

RealityKit and SwiftUI View

```<code>import SwiftUI
import RealityKit
import ARKit

struct ContentView : View {

    @State private var isPlacementEnabled = false
    @State private var selectedModel: Model?
    @State private var modelConfirmedForPlacement: Model?

    private var models: [Model] {

        //Dynamicaly get file names
        let filemanager = FileManager.default

        guard let path = Bundle.main.resourcePath,
              let files = try? filemanager.contentsOfDirectory(atPath: path)
        else {
            return []
        }

        var availableModels: [Model] = []

        for filename in files where filename.hasSuffix("usdz") {
            let modelName = filename.replacingOccurrences(of: ".usdz", with: "")

            let model = Model(modelName: modelName)

            availableModels.append(model)
        }

        return availableModels
    }

    var body: some View {
        ZStack(alignment: .bottom){
            ARViewContainer(modelConfirmedForPlacement: self.$modelConfirmedForPlacement)

            if self.isPlacementEnabled {
                PlacementButtonsView(isPlacementEnabled: self.$isPlacementEnabled,
                                     selectedModel: self.$selectedModel,
                                     modelConfirmedForPlacement: self.$modelConfirmedForPlacement
                )
            }
            else {
                ModelPickerView(models: self.models,
                                isPlacementEnabled: self.$isPlacementEnabled,
                                selectedModel: self.$selectedModel)
            }

        }
    }
}

struct ARViewContainer: UIViewRepresentable {

    @Binding var modelConfirmedForPlacement: Model?

    var anchorEntity = AnchorEntity(world: .init(x: 0, y: 0, z: 0))

    func makeUIView(context: Context) -> ARView {

        let arView = ARView(frame: .zero)

        let config = ARWorldTrackingConfiguration()

        config.planeDetection = [.horizontal, .vertical ]

        config.environmentTexturing = .automatic

        if ARWorldTrackingConfiguration.supportsSceneReconstruction(.mesh){
            config.sceneReconstruction = .mesh
        }
        arView.session.run(config)

        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) {

        //Here is where I try to remove the old 3D Model before loading the new one
        if self.modelConfirmedForPlacement?.modelEntity != nil {
            uiView.scene.anchors.first?.removeChild((self.modelConfirmedForPlacement?.modelEntity)!)
            anchorEntity.scene?.removeAnchor(anchorEntity)
            self.anchorEntity.removeChild((self.modelConfirmedForPlacement?.modelEntity)!)

        }

        if let model = self.modelConfirmedForPlacement{

            if model.modelEntity != nil {
                print("ARContainer -> DEBUG: adding model to scene - \(model.modelName)"  )
            }
            else{
                print("ARContainer -> DEBUG: Unable to load model entity for - \(model.modelName)"  )
            }

            DispatchQueue.main.async {

                let modelEntity = try? Entity.load( named: model.modelName + ".usdz")

                anchorEntity.addChild(modelEntity!)

                uiView.scene.addAnchor(anchorEntity)
            }
        }
    }
}

struct ModelPickerView: View {

    var models: [Model]
    @Binding var isPlacementEnabled: Bool
    @Binding var selectedModel: Model?

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false){
            HStack(spacing: 30){
                ForEach(0 ..< self.models.count , id: \.self){ index in
                    Button {
                        //                        print("DEBUG : selected model with name:  \(self.models[index].modelName)")
                        self.isPlacementEnabled = true
                        self.selectedModel = self.models[index]
                    } label: {
                        Image(uiImage: self.models[index].image)
                            .resizable()
                            .frame(height: 80 )
                            .aspectRatio(1/1, contentMode: .fit)
                            .background(Color.white)
                            .cornerRadius(12)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
        }
        .padding(20)
        .background(Color.black.opacity(0.5))

    }
}

struct PlacementButtonsView: View {

    @Binding var isPlacementEnabled: Bool
    @Binding var selectedModel: Model?
    @Binding  var modelConfirmedForPlacement: Model?

    var body: some View {

        HStack{

            //Cancel button
            Button {
                //                print("DEBUG: model ploacement cancelled")
                self.resetPlacementParameters()

            } label: {
                Image(systemName: "xmark")
                    .frame(width: 60, height: 60)
                    .font(.title)
                    .background(Color.white.opacity(0.75))
                    .cornerRadius(30)
                    .padding(20)
            }

            //Confirm button
            Button {
                //                print("DEBUG: model ploacement confirmed")
                self.modelConfirmedForPlacement = self.selectedModel
                self.resetPlacementParameters()

            } label: {
                Image(systemName: "checkmark")
                    .frame(width: 60, height: 60)
                    .font(.title)
                    .background(Color.white.opacity(0.75))
                    .cornerRadius(30)
                    .padding(20)
            }

        }
    }

    func resetPlacementParameters(){
        self.isPlacementEnabled = false
        self.selectedModel = nil
    }

}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
</code>```

Body:
I'm trying to play with Apple's RealityKit and some usdz files I got from their website.

I made a small app where I can load each 3D model at a time.

It works but with one issue. If I add a single 3D object is fine but when I load the new models they all get stuck upon each other. I can't seem to figure out how to remove the old 3D object before adding a different one.

Here is my code

My Model object

import Foundation
import UIKit
import RealityKit
import Combine

class Model {
    var modelName: String
    var image: UIImage
    var modelEntity: ModelEntity?

    private var cancellable: AnyCancellable? = nil

    var message: String = ""

    init(modelName: String){
        self.modelName = modelName

        self.image = UIImage(named: modelName)!

        let filename = modelName + ".usdz"

        self.cancellable = ModelEntity.loadModelAsync(named: filename)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    print("Model.swift -> DEBUG: Succesfully loaded \(self.modelName)")
                    break
                case .failure(let error):
                    print("Model.swift -> DEBUG: Unable to load : \(self.modelName)")
                    self.message = error.localizedDescription
                }

            }, receiveValue: { modelEntity in
                //get model entity
                self.modelEntity = modelEntity
            })
    }

}

RealityKit and SwiftUI View

import SwiftUI
import RealityKit
import ARKit

struct ContentView : View {

    @State private var isPlacementEnabled = false
    @State private var selectedModel: Model?
    @State private var modelConfirmedForPlacement: Model?

    private var models: [Model] {

        //Dynamicaly get file names
        let filemanager = FileManager.default

        guard let path = Bundle.main.resourcePath,
              let files = try? filemanager.contentsOfDirectory(atPath: path)
        else {
            return []
        }

        var availableModels: [Model] = []

        for filename in files where filename.hasSuffix("usdz") {
            let modelName = filename.replacingOccurrences(of: ".usdz", with: "")

            let model = Model(modelName: modelName)

            availableModels.append(model)
        }

        return availableModels
    }

    var body: some View {
        ZStack(alignment: .bottom){
            ARViewContainer(modelConfirmedForPlacement: self.$modelConfirmedForPlacement)

            if self.isPlacementEnabled {
                PlacementButtonsView(isPlacementEnabled: self.$isPlacementEnabled,
                                     selectedModel: self.$selectedModel,
                                     modelConfirmedForPlacement: self.$modelConfirmedForPlacement
                )
            }
            else {
                ModelPickerView(models: self.models,
                                isPlacementEnabled: self.$isPlacementEnabled,
                                selectedModel: self.$selectedModel)
            }

        }
    }
}

struct ARViewContainer: UIViewRepresentable {

    @Binding var modelConfirmedForPlacement: Model?

    var anchorEntity = AnchorEntity(world: .init(x: 0, y: 0, z: 0))

    func makeUIView(context: Context) -> ARView {

        let arView = ARView(frame: .zero)

        let config = ARWorldTrackingConfiguration()

        config.planeDetection = [.horizontal, .vertical ]

        config.environmentTexturing = .automatic

        if ARWorldTrackingConfiguration.supportsSceneReconstruction(.mesh){
            config.sceneReconstruction = .mesh
        }
        arView.session.run(config)

        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) {

        //Here is where I try to remove the old 3D Model before loading the new one
        if self.modelConfirmedForPlacement?.modelEntity != nil {
            uiView.scene.anchors.first?.removeChild((self.modelConfirmedForPlacement?.modelEntity)!)
            anchorEntity.scene?.removeAnchor(anchorEntity)
            self.anchorEntity.removeChild((self.modelConfirmedForPlacement?.modelEntity)!)

        }

        if let model = self.modelConfirmedForPlacement{

            if model.modelEntity != nil {
                print("ARContainer -> DEBUG: adding model to scene - \(model.modelName)"  )
            }
            else{
                print("ARContainer -> DEBUG: Unable to load model entity for - \(model.modelName)"  )
            }

            DispatchQueue.main.async {

                let modelEntity = try? Entity.load( named: model.modelName + ".usdz")

                anchorEntity.addChild(modelEntity!)

                uiView.scene.addAnchor(anchorEntity)
            }
        }
    }
}

struct ModelPickerView: View {

    var models: [Model]
    @Binding var isPlacementEnabled: Bool
    @Binding var selectedModel: Model?

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false){
            HStack(spacing: 30){
                ForEach(0 ..< self.models.count , id: \.self){ index in
                    Button {
                        //                        print("DEBUG : selected model with name:  \(self.models[index].modelName)")
                        self.isPlacementEnabled = true
                        self.selectedModel = self.models[index]
                    } label: {
                        Image(uiImage: self.models[index].image)
                            .resizable()
                            .frame(height: 80 )
                            .aspectRatio(1/1, contentMode: .fit)
                            .background(Color.white)
                            .cornerRadius(12)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
        }
        .padding(20)
        .background(Color.black.opacity(0.5))

    }
}

struct PlacementButtonsView: View {

    @Binding var isPlacementEnabled: Bool
    @Binding var selectedModel: Model?
    @Binding  var modelConfirmedForPlacement: Model?

    var body: some View {

        HStack{

            //Cancel button
            Button {
                //                print("DEBUG: model ploacement cancelled")
                self.resetPlacementParameters()

            } label: {
                Image(systemName: "xmark")
                    .frame(width: 60, height: 60)
                    .font(.title)
                    .background(Color.white.opacity(0.75))
                    .cornerRadius(30)
                    .padding(20)
            }

            //Confirm button
            Button {
                //                print("DEBUG: model ploacement confirmed")
                self.modelConfirmedForPlacement = self.selectedModel
                self.resetPlacementParameters()

            } label: {
                Image(systemName: "checkmark")
                    .frame(width: 60, height: 60)
                    .font(.title)
                    .background(Color.white.opacity(0.75))
                    .cornerRadius(30)
                    .padding(20)
            }

        }
    }

    func resetPlacementParameters(){
        self.isPlacementEnabled = false
        self.selectedModel = nil
    }

}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif


问:
KeyError: WeakRef when using flask-sqlalchemy version 3
I have seen similar answers to this but have not come across any concrete answer. Since upgrading my Flask-SQLAlchemy version from 2.5.1 to 3.0.2, I am encountering the following error anytime I try to query or do any database operations: KeyError: <weakref at 0x10ed004a0; to 'Flask' at 0x10cb5d880>

My application setup is nearly identical to the one outlined here

```<code>application = Flask(
    __name__, instance_path=instance_path, instance_relative_config=True
)

if configurations.PRODUCTION:
    application.config.from_pyfile("production.py")
else:
    application.config.from_pyfile("local.py")

db = SQLAlchemy()
db.init_app(application)

@application.route("/injury")
def get_injury_by_id():
    return db.session.query(Injury).filter_by(id=1).first()

if __name__ == "__main__":
    application.run()
</code>```

Anytime I try and access this db object to try and run queries on its session, the error stated previously arises. I have tried playing around with the ordering of my initialization, such as by just doing

```<code>db = SQLAlchemy(app=application)
</code>```

But everything seems to be throwing this error. I reverted my version back to 2.5.1 and can confirm this was working up until 3.0.2.

Any suggestions?

Edit Full stack trace after doing a query like db.session.query(Injury).filter_by(id=1).first() shown in the API route above

```<code>[2022-12-28 16:19:35,676...application...ERROR]: The following error occurred 'Traceback (most recent call last):
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/Desktop/project/backend/application.py", line 47, in get_injury_by_name
    return session.query(Injury).filter_by(id=1).first()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 2819, in first
    return self.limit(1)._iter().first()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 2903, in _iter
    result = self.session.execute(
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1700, in execute
    bind = self.get_bind(**bind_arguments)
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask_sqlalchemy/session.py", line 61, in get_bind
    engines = self._db.engines
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask_sqlalchemy/extension.py", line 629, in engines
    return self._app_engines[app]
  File "/usr/local/Cellar/python@3.8/3.8.11/Frameworks/Python.framework/Versions/3.8/lib/python3.8/weakref.py", line 383, in __getitem__
    return self.data[ref(key)]
KeyError: <weakref at 0x10f400540; to 'Flask' at 0x10d31c880>
'
</code>```

Another thing to note is if I make a dummy file for testing purposes that looks like such

```<code>with application.app_context():
    db.session.query(Injury).filter_by(**kwargs).first()
</code>```

The query executes properly.

Body:
I have seen similar answers to this but have not come across any concrete answer. Since upgrading my Flask-SQLAlchemy version from 2.5.1 to 3.0.2, I am encountering the following error anytime I try to query or do any database operations: KeyError: <weakref at 0x10ed004a0; to 'Flask' at 0x10cb5d880>

My application setup is nearly identical to the one outlined here

application = Flask(
    __name__, instance_path=instance_path, instance_relative_config=True
)

if configurations.PRODUCTION:
    application.config.from_pyfile("production.py")
else:
    application.config.from_pyfile("local.py")

db = SQLAlchemy()
db.init_app(application)

@application.route("/injury")
def get_injury_by_id():
    return db.session.query(Injury).filter_by(id=1).first()

if __name__ == "__main__":
    application.run()

Anytime I try and access this db object to try and run queries on its session, the error stated previously arises. I have tried playing around with the ordering of my initialization, such as by just doing

db = SQLAlchemy(app=application)

But everything seems to be throwing this error. I reverted my version back to 2.5.1 and can confirm this was working up until 3.0.2.

Any suggestions?

Edit Full stack trace after doing a query like db.session.query(Injury).filter_by(id=1).first() shown in the API route above

[2022-12-28 16:19:35,676...application...ERROR]: The following error occurred 'Traceback (most recent call last):
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/Desktop/project/backend/application.py", line 47, in get_injury_by_name
    return session.query(Injury).filter_by(id=1).first()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 2819, in first
    return self.limit(1)._iter().first()
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 2903, in _iter
    result = self.session.execute(
  File "/Desktop/project/.venv/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1700, in execute
    bind = self.get_bind(**bind_arguments)
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask_sqlalchemy/session.py", line 61, in get_bind
    engines = self._db.engines
  File "/Desktop/project/.venv/lib/python3.8/site-packages/flask_sqlalchemy/extension.py", line 629, in engines
    return self._app_engines[app]
  File "/usr/local/Cellar/python@3.8/3.8.11/Frameworks/Python.framework/Versions/3.8/lib/python3.8/weakref.py", line 383, in __getitem__
    return self.data[ref(key)]
KeyError: <weakref at 0x10f400540; to 'Flask' at 0x10d31c880>
'

Another thing to note is if I make a dummy file for testing purposes that looks like such

with application.app_context():
    db.session.query(Injury).filter_by(**kwargs).first()

The query executes properly.


问:
How to send image path (form data) to mongo DB
I am trying to send the path of images (with multer) to my mongo Db so i can later retrieve the image but can't figure out how it works,
my API route:

```<code>router.post("/", upload.single("file"), async (req, res) => {
    const newPost = new Post({
title: title,
desc: desc,
image: **help me here pls (pathname/filename of image should be here)**
})
    try {
        const savedPost = await newPost.save()
        res.status(200).json(savedPost)
    } catch (error) {
        console.log(error)
    }
})

</code>```

the api only sends the req.body which works just fine (image gets uploaded to local folder but path should be saved in req.body as well ), but how can i get the filename and send it in the same document as the title and description above?

Body:
I am trying to send the path of images (with multer) to my mongo Db so i can later retrieve the image but can't figure out how it works,
my API route:

router.post("/", upload.single("file"), async (req, res) => {
    const newPost = new Post({
title: title,
desc: desc,
image: **help me here pls (pathname/filename of image should be here)**
})
    try {
        const savedPost = await newPost.save()
        res.status(200).json(savedPost)
    } catch (error) {
        console.log(error)
    }
})

the api only sends the req.body which works just fine (image gets uploaded to local folder but path should be saved in req.body as well ), but how can i get the filename and send it in the same document as the title and description above?


问:
Excel concat issue
I have a list of open close time for a point of sale, separated by columns. I have to manually go through the list and convert the open close time separated by columns to a string that looks like this MON - FRI 8:30 - 17:00, SAT 9:00-13:00, SUN closed.

Is there a way to automate this process. So far i was not successful with CONCAT and IF with multiple conditions. Sorry, i do not have this much exp with excel functions.

I understand there is a need for excel to somehow compare data by rows and if the data is the same print the specific content like =IF(AND(A2=C2; A2=E2; A2=G2; A2=I2); "A2"; "NO"). I most definitely wrong, since it didn't work.

Additional problem is that using CONCAT and IF with time turns the time into the number. Overloading the IF with TEXT(A2; "hh:mm:ss") didn't help.

Example of the table is here https://docs.google.com/spreadsheets/d/1b_C7u4UDBESywU8Qe_HRuhTLySZSAcn5a-t87yCcb_s/edit?usp=sharing

Title: Excel concat issue


问:
Apply for loop to filter rows for several columns and store filtered data to list - R
Imagine that I have a dataframe df with 4 columns (colA, colB, colC, and key). key is a column that will be potentially useful as input for merging the processed data (this part is not shown in the example code below). The dataframe has negative values and positive values above 100. However, I would like to filter rows that are only positive and only have values below 100, for the columns colA, colB, and colC. The filtered data should be assigned to a variable describing the column (e.g. new_df$colA). Thereafter, the variable should be stored in the list new. While running the for loop, I am faced with an error:

```<code>Error in paste0("new", column, sep = "_") = df[column < 100 & column >  :
  target of assignment expands to non-language object
</code>```

It wouldn't surprise me if the $ character causes issues - however I am not able to tackle this problem. The relevant code:

```<code>df <- data.frame(colA=c(-10, 30, 50, 60, 102),
                 colB=c(60, 200, 70, -4, 60),
                 colC=c(400, 300, 10, 230, 2))

#create column with unique key to potentially merge processed data on
df$key <- seq(1, nrow(df))

#initialize list with columns that relate to dataframe - every column should be used for filtering data
columns = list(df$colA, df$colB, df$colC)

#create empty list where processed data can be stored to
new = list()

#loop
for(column in columns){
  #create dataframe of relevant column only and key for later data processinh
  df <-  data.frame(column,df$key)
  #select only rows that meet conditions
  paste0("new", column, sep="_") = df[column < 100 & column > 0, ]
  #append new data to list 'new'
  new = c(new, paste0("new", column, sep="_"))
}
</code>```

The expected output is

```<code>colA = 30, 50, 60
colB = 60, 70, 60
colC = 10, 2
</code>```

Body:
Imagine that I have a dataframe df with 4 columns (colA, colB, colC, and key). key is a column that will be potentially useful as input for merging the processed data (this part is not shown in the example code below). The dataframe has negative values and positive values above 100. However, I would like to filter rows that are only positive and only have values below 100, for the columns colA, colB, and colC. The filtered data should be assigned to a variable describing the column (e.g. new_df$colA). Thereafter, the variable should be stored in the list new. While running the for loop, I am faced with an error:

Error in paste0("new", column, sep = "_") = df[column < 100 & column >  :
  target of assignment expands to non-language object

It wouldn't surprise me if the $ character causes issues - however I am not able to tackle this problem. The relevant code:

df <- data.frame(colA=c(-10, 30, 50, 60, 102),
                 colB=c(60, 200, 70, -4, 60),
                 colC=c(400, 300, 10, 230, 2))

#create column with unique key to potentially merge processed data on
df$key <- seq(1, nrow(df))

#initialize list with columns that relate to dataframe - every column should be used for filtering data
columns = list(df$colA, df$colB, df$colC)

#create empty list where processed data can be stored to
new = list()

#loop
for(column in columns){
  #create dataframe of relevant column only and key for later data processinh
  df <-  data.frame(column,df$key)
  #select only rows that meet conditions
  paste0("new", column, sep="_") = df[column < 100 & column > 0, ]
  #append new data to list 'new'
  new = c(new, paste0("new", column, sep="_"))
}

The expected output is

colA = 30, 50, 60
colB = 60, 70, 60
colC = 10, 2


问:
I am using plotly to create a heatmap but it only shows the heatmap for the first frame and disappears after that, how can I fix this?
Here is my current code:

```<code>def animate_play(tracking_df, play_df,players,pffScoutingData, gameId,playId):

    selected_play_df = play_df[(play_df.playId==playId)&(play_df.gameId==gameId)].copy()
    tracking_players_df = pd.merge(tracking_df,players,how="left",on = "nflId")
    tracking_players_df = pd.merge(tracking_players_df,pffScoutingData,how="left",on = ["nflId","playId","gameId"])
    selected_tracking_df = tracking_players_df[(tracking_players_df.playId==playId)&(tracking_players_df.gameId==gameId)].copy()

    sorted_frame_list = selected_tracking_df.frameId.unique()
    sorted_frame_list.sort()

    # get play General information
    line_of_scrimmage = selected_play_df.absoluteYardlineNumber.values[0]
    first_down_marker = line_of_scrimmage + selected_play_df.yardsToGo.values[0]
    down = selected_play_df.down.values[0]
    quarter = selected_play_df.quarter.values[0]
    gameClock = selected_play_df.gameClock.values[0]
    playDescription = selected_play_df.playDescription.values[0]
    # Handle case where we have a really long Play Description and want to split it into two lines
    if len(playDescription.split(" "))>15 and len(playDescription)>115:
        playDescription = " ".join(playDescription.split(" ")[0:16]) + "<br>" + " ".join(playDescription.split(" ")[16:])

    # initialize plotly start and stop buttons for animation
    updatemenus_dict = [
        {
            "buttons": [
                {
                    "args": [None, {"frame": {"duration": 100, "redraw": False},
                                "fromcurrent": True, "transition": {"duration": 0}}],
                    "label": "Play",
                    "method": "animate"
                },
                {
                    "args": [[None], {"frame": {"duration": 0, "redraw": False},
                                      "mode": "immediate",
                                      "transition": {"duration": 0}}],
                    "label": "Pause",
                    "method": "animate"
                }
            ],
            "direction": "left",
            "pad": {"r": 10, "t": 87},
            "showactive": False,
            "type": "buttons",
            "x": 0.1,
            "xanchor": "right",
            "y": 0,
            "yanchor": "top"
        }
    ]
    # initialize plotly slider to show frame position in animation
    sliders_dict = {
        "active": 0,
        "yanchor": "top",
        "xanchor": "left",
        "currentvalue": {
            "font": {"size": 20},
            "prefix": "Frame:",
            "visible": True,
            "xanchor": "right"
        },
        "transition": {"duration": 300, "easing": "cubic-in-out"},
        "pad": {"b": 10, "t": 50},
        "len": 0.9,
        "x": 0.1,
        "y": 0,
        "steps": []
    }

    frames = []
    for i in range(15,len(sorted_frame_list)):
        frameId = sorted_frame_list[i]
        data = []
        # Add Numbers to Field
        data.append(
            go.Scatter(
                x=np.arange(20,110,10),
                y=[5]*len(np.arange(20,110,10)),
                mode='text',
                text=list(map(str,list(np.arange(20, 61, 10)-10)+list(np.arange(40, 9, -10)))),
                textfont_size = 30,
                textfont_family = "Courier New, monospace",
                textfont_color = "#ffffff",
                showlegend=False,
                hoverinfo='none'
            )
        )
        data.append(
            go.Scatter(
                x=np.arange(20,110,10),
                y=[53.5-5]*len(np.arange(20,110,10)),
                mode='text',
                text=list(map(str,list(np.arange(20, 61, 10)-10)+list(np.arange(40, 9, -10)))),
                textfont_size = 30,
                textfont_family = "Courier New, monospace",
                textfont_color = "#ffffff",
                showlegend=False,
                hoverinfo='none'
            )
        )
        # Add line of scrimage
        data.append(
            go.Scatter(
                x=[line_of_scrimmage,line_of_scrimmage],
                y=[0,53.5],
                line_dash='dash',
                line_color='blue',
                showlegend=False,
                hoverinfo='none'
            )
        )
        # Add First down line
        data.append(
            go.Scatter(
                x=[first_down_marker,first_down_marker],
                y=[0,53.5],
                line_dash='dash',
                line_color='yellow',
                showlegend=False,
                hoverinfo='none'
            )
        )

        # Plot Players
        for team in selected_tracking_df.team.unique():
            plot_df = selected_tracking_df[(selected_tracking_df.team==team)&(selected_tracking_df.frameId==frameId)].copy()
            if team != "football":
                hover_text_array=[]
                for nflId in plot_df.nflId:
                    selected_player_df = plot_df[plot_df.nflId==nflId]
                    hover_text_array.append("nflId:{}<br>displayName:{}<br>Position:{}<br>Role:{}".format(selected_player_df["nflId"].values[0],
                                                                                selected_player_df["displayName"].values[0],
                                                                                selected_player_df["pff_positionLinedUp"].values[0],
                                                                                selected_player_df["pff_role"].values[0]))
                data.append(go.Scatter(x=plot_df["x"], y=plot_df["y"],mode = 'markers',marker_color=colors[team],name=team,hovertext=hover_text_array,hoverinfo="text"))
                x_coords = plot_df["x"]
                y_coords = plot_df["y"]
                values = plot_df["pressure"]
                heatmap_trace = go.Heatmap(
                    x=x_coords,
                    y=y_coords,
                    z=values,
                    connectgaps=True,
                    hoverinfo="x+y+z",
                    colorscale=[[0, 'rgba(0,0,255, 0)'], [1, 'rgba(255,0,0, 1)']]
                )
                data.append(heatmap_trace)
            else:
                data.append(go.Scatter(x=plot_df["x"], y=plot_df["y"],mode = 'markers',marker_color=colors[team],name=team,hoverinfo='none'))
                x_coords = plot_df["x"]
                y_coords = plot_df["y"]
                values = plot_df["pressure"]
                heatmap_trace = go.Heatmap(
                    x=x_coords,
                    y=y_coords,
                    z=values,
                    connectgaps=True,
                    hoverinfo="x+y+z",
                    colorscale=[[0, 'rgba(0,0,255, 0)'], [1, 'rgba(255,0,0, 1)']]
                )

                data.append(heatmap_trace)
        # add frame to slider
        slider_step = {"args": [
            [frameId],
            {"frame": {"duration": 100, "redraw": False},
             "mode": "immediate",
             "transition": {"duration": 0}}
        ],
            "label": str(frameId),
            "method": "animate"}
        sliders_dict["steps"].append(slider_step)
        frames.append(go.Frame(data=data, name=str(frameId)))
        #print(data)
    scale=10
    layout = go.Layout(
        autosize=False,
        width=120*scale,
        height=60*scale,
        xaxis=dict(range=[0, 120], autorange=False, tickmode='array',tickvals=np.arange(10, 111, 5).tolist(),showticklabels=False),
        yaxis=dict(range=[0, 53.3], autorange=False,showgrid=False,showticklabels=False),

        plot_bgcolor='#00B140',
        # Create title and add play description at the bottom of the chart for better visual appeal
        title=f"GameId: {gameId}, PlayId: {playId}<br>{gameClock} {quarter}Q"+"<br>"*19+f"{playDescription}",
        updatemenus=updatemenus_dict,
        sliders = [sliders_dict]
    )

    fig = go.Figure(
        data=frames[0]["data"],
        layout= layout,
        frames=frames[1:]
    )

    for y_val in [0,53]:
        fig.add_annotation(
                x=first_down_marker,
                y=y_val,
                text=str(down),
                showarrow=False,
                font=dict(
                    family="Courier New, monospace",
                    size=16,
                    color="black"
                    ),
                align="center",
                bordercolor="black",
                borderwidth=2,
                borderpad=4,
                bgcolor="#ff7f0e",
                opacity=1
                )

    return fig

animate_play(week1,plays,players,pffScoutingData,2021090900
,97).show()
</code>```

I believe the problem is occurring here because the first frame is what always shows the heatmap, but after that the rest of the frames don't include the heatmap:

```<code>fig = go.Figure(
        data=frames[0]["data"],
        layout= layout,
        frames=frames[1:]
    )
</code>```

I tried different things all which failed.

Body:
Here is my current code:

def animate_play(tracking_df, play_df,players,pffScoutingData, gameId,playId):

    selected_play_df = play_df[(play_df.playId==playId)&(play_df.gameId==gameId)].copy()
    tracking_players_df = pd.merge(tracking_df,players,how="left",on = "nflId")
    tracking_players_df = pd.merge(tracking_players_df,pffScoutingData,how="left",on = ["nflId","playId","gameId"])
    selected_tracking_df = tracking_players_df[(tracking_players_df.playId==playId)&(tracking_players_df.gameId==gameId)].copy()

    sorted_frame_list = selected_tracking_df.frameId.unique()
    sorted_frame_list.sort()

    # get play General information
    line_of_scrimmage = selected_play_df.absoluteYardlineNumber.values[0]
    first_down_marker = line_of_scrimmage + selected_play_df.yardsToGo.values[0]
    down = selected_play_df.down.values[0]
    quarter = selected_play_df.quarter.values[0]
    gameClock = selected_play_df.gameClock.values[0]
    playDescription = selected_play_df.playDescription.values[0]
    # Handle case where we have a really long Play Description and want to split it into two lines
    if len(playDescription.split(" "))>15 and len(playDescription)>115:
        playDescription = " ".join(playDescription.split(" ")[0:16]) + "
" + " ".join(playDescription.split(" ")[16:])

    # initialize plotly start and stop buttons for animation
    updatemenus_dict = [
        {
            "buttons": [
                {
                    "args": [None, {"frame": {"duration": 100, "redraw": False},
                                "fromcurrent": True, "transition": {"duration": 0}}],
                    "label": "Play",
                    "method": "animate"
                },
                {
                    "args": [[None], {"frame": {"duration": 0, "redraw": False},
                                      "mode": "immediate",
                                      "transition": {"duration": 0}}],
                    "label": "Pause",
                    "method": "animate"
                }
            ],
            "direction": "left",
            "pad": {"r": 10, "t": 87},
            "showactive": False,
            "type": "buttons",
            "x": 0.1,
            "xanchor": "right",
            "y": 0,
            "yanchor": "top"
        }
    ]
    # initialize plotly slider to show frame position in animation
    sliders_dict = {
        "active": 0,
        "yanchor": "top",
        "xanchor": "left",
        "currentvalue": {
            "font": {"size": 20},
            "prefix": "Frame:",
            "visible": True,
            "xanchor": "right"
        },
        "transition": {"duration": 300, "easing": "cubic-in-out"},
        "pad": {"b": 10, "t": 50},
        "len": 0.9,
        "x": 0.1,
        "y": 0,
        "steps": []
    }

    frames = []
    for i in range(15,len(sorted_frame_list)):
        frameId = sorted_frame_list[i]
        data = []
        # Add Numbers to Field
        data.append(
            go.Scatter(
                x=np.arange(20,110,10),
                y=[5]*len(np.arange(20,110,10)),
                mode='text',
                text=list(map(str,list(np.arange(20, 61, 10)-10)+list(np.arange(40, 9, -10)))),
                textfont_size = 30,
                textfont_family = "Courier New, monospace",
                textfont_color = "#ffffff",
                showlegend=False,
                hoverinfo='none'
            )
        )
        data.append(
            go.Scatter(
                x=np.arange(20,110,10),
                y=[53.5-5]*len(np.arange(20,110,10)),
                mode='text',
                text=list(map(str,list(np.arange(20, 61, 10)-10)+list(np.arange(40, 9, -10)))),
                textfont_size = 30,
                textfont_family = "Courier New, monospace",
                textfont_color = "#ffffff",
                showlegend=False,
                hoverinfo='none'
            )
        )
        # Add line of scrimage
        data.append(
            go.Scatter(
                x=[line_of_scrimmage,line_of_scrimmage],
                y=[0,53.5],
                line_dash='dash',
                line_color='blue',
                showlegend=False,
                hoverinfo='none'
            )
        )
        # Add First down line
        data.append(
            go.Scatter(
                x=[first_down_marker,first_down_marker],
                y=[0,53.5],
                line_dash='dash',
                line_color='yellow',
                showlegend=False,
                hoverinfo='none'
            )
        )

        # Plot Players
        for team in selected_tracking_df.team.unique():
            plot_df = selected_tracking_df[(selected_tracking_df.team==team)&(selected_tracking_df.frameId==frameId)].copy()
            if team != "football":
                hover_text_array=[]
                for nflId in plot_df.nflId:
                    selected_player_df = plot_df[plot_df.nflId==nflId]
                    hover_text_array.append("nflId:{}
displayName:{}
Position:{}
Role:{}".format(selected_player_df["nflId"].values[0],
                                                                                selected_player_df["displayName"].values[0],
                                                                                selected_player_df["pff_positionLinedUp"].values[0],
                                                                                selected_player_df["pff_role"].values[0]))
                data.append(go.Scatter(x=plot_df["x"], y=plot_df["y"],mode = 'markers',marker_color=colors[team],name=team,hovertext=hover_text_array,hoverinfo="text"))
                x_coords = plot_df["x"]
                y_coords = plot_df["y"]
                values = plot_df["pressure"]
                heatmap_trace = go.Heatmap(
                    x=x_coords,
                    y=y_coords,
                    z=values,
                    connectgaps=True,
                    hoverinfo="x+y+z",
                    colorscale=[[0, 'rgba(0,0,255, 0)'], [1, 'rgba(255,0,0, 1)']]
                )
                data.append(heatmap_trace)
            else:
                data.append(go.Scatter(x=plot_df["x"], y=plot_df["y"],mode = 'markers',marker_color=colors[team],name=team,hoverinfo='none'))
                x_coords = plot_df["x"]
                y_coords = plot_df["y"]
                values = plot_df["pressure"]
                heatmap_trace = go.Heatmap(
                    x=x_coords,
                    y=y_coords,
                    z=values,
                    connectgaps=True,
                    hoverinfo="x+y+z",
                    colorscale=[[0, 'rgba(0,0,255, 0)'], [1, 'rgba(255,0,0, 1)']]
                )

                data.append(heatmap_trace)
        # add frame to slider
        slider_step = {"args": [
            [frameId],
            {"frame": {"duration": 100, "redraw": False},
             "mode": "immediate",
             "transition": {"duration": 0}}
        ],
            "label": str(frameId),
            "method": "animate"}
        sliders_dict["steps"].append(slider_step)
        frames.append(go.Frame(data=data, name=str(frameId)))
        #print(data)
    scale=10
    layout = go.Layout(
        autosize=False,
        width=120*scale,
        height=60*scale,
        xaxis=dict(range=[0, 120], autorange=False, tickmode='array',tickvals=np.arange(10, 111, 5).tolist(),showticklabels=False),
        yaxis=dict(range=[0, 53.3], autorange=False,showgrid=False,showticklabels=False),

        plot_bgcolor='#00B140',
        # Create title and add play description at the bottom of the chart for better visual appeal
        title=f"GameId: {gameId}, PlayId: {playId}
{gameClock} {quarter}Q"+"
"*19+f"{playDescription}",
        updatemenus=updatemenus_dict,
        sliders = [sliders_dict]
    )

    fig = go.Figure(
        data=frames[0]["data"],
        layout= layout,
        frames=frames[1:]
    )

    for y_val in [0,53]:
        fig.add_annotation(
                x=first_down_marker,
                y=y_val,
                text=str(down),
                showarrow=False,
                font=dict(
                    family="Courier New, monospace",
                    size=16,
                    color="black"
                    ),
                align="center",
                bordercolor="black",
                borderwidth=2,
                borderpad=4,
                bgcolor="#ff7f0e",
                opacity=1
                )

    return fig

animate_play(week1,plays,players,pffScoutingData,2021090900
,97).show()

I believe the problem is occurring here because the first frame is what always shows the heatmap, but after that the rest of the frames don't include the heatmap:

fig = go.Figure(
        data=frames[0]["data"],
        layout= layout,
        frames=frames[1:]
    )

I tried different things all which failed.


问:
AWS Lightsail wp-config File Bitnami Issues
We are getting mixed content errors for our Bitnami Wordpress Instance with Let's Encrypt. When we go to change the URL in settings > general > URL, they are greyed out - Screenshot:

https://i.stack.imgur.com/ZX30e.png

We cannot find the wp-config file in the SSH Filezilla - Screenshot:

https://i.stack.imgur.com/BgchM.png

We feel that the wp-config file is not setup correctly and need some directions on how to download the config file and upload a new one to fix the mixed content error messages.

Thanks for your input,

Pete


问:
I installed npm on my terminal in vscode but the package.json file it created has a problem it keeps saying unable to load schema files
I installed npm on my terminal in vscode the package.json file it created for me has an error it says

Unable to load schema from 'https://json.schemastore.org/package': getaddrinfo EAI_AGAIN json.schemastore.org.(768)

I did some research and found out that it was from my vscode settings but I don't know which settings in particular

I was expecting no errors after I installed the npm package to be able to build my project with parcel


问:
Ploty shows the plot before calling fig.show() when using iPython
When I am using iPython with plotly, plotly will show a graph for each application of fig.update_layout, fig.update_xaxes, etc. Consider the following:

```<code>import plotly.graph_objects as go
import numpy as np

time = np.linspace(0, 1, 100)
data1 = np.cos(time)
data2 = np.sin(time)

fig = go.Figure(
   [go.Scatter(x=time, y=data1),
    go.Scatter(x=time, y=data2)])

fig.update_layout(title_text='title')  # 1

fig.update_xaxes(title_text='x-axis')  # 2

fig.update_yaxes(title_text='y-axis')  # 3

fig.show()  # 4

</code>```

If I run this code by calling :! python3 file.py, then the code runs fine and only one plot appears.

But if I run the code line by line using iPython then a plot will pop up for 1, 2, 3 and 4 above. So 4 plots in total. How can I suppress plots 1, 2 and 3 and just show the final plot at 4?

Edit:

I dont' think the suggested post answers my question. I am not using a Jupyter notebook. I am using neovim to write the code and then use tmux and slime to send the code to the Ipython terminal. None of the suggestions from the duplicate question worked.

Body:
When I am using iPython with plotly, plotly will show a graph for each application of fig.update_layout, fig.update_xaxes, etc. Consider the following:

import plotly.graph_objects as go
import numpy as np

time = np.linspace(0, 1, 100)
data1 = np.cos(time)
data2 = np.sin(time)

fig = go.Figure(
   [go.Scatter(x=time, y=data1),
    go.Scatter(x=time, y=data2)])

fig.update_layout(title_text='title')  # 1

fig.update_xaxes(title_text='x-axis')  # 2

fig.update_yaxes(title_text='y-axis')  # 3

fig.show()  # 4

If I run this code by calling :! python3 file.py, then the code runs fine and only one plot appears.

But if I run the code line by line using iPython then a plot will pop up for 1, 2, 3 and 4 above. So 4 plots in total. How can I suppress plots 1, 2 and 3 and just show the final plot at 4?

Edit:

I dont' think the suggested post answers my question. I am not using a Jupyter notebook. I am using neovim to write the code and then use tmux and slime to send the code to the Ipython terminal. None of the suggestions from the duplicate question worked.


问:
Service Worker doesn't register
I've implemented a ReactJS web application, and I've added a service worker to cache resources. My service worker works as expected for caching resources when I run it on chromium 72, but when I run it on chromium 49 in WindowsXP it couldn't register and becomes redundant immediately, and shows service Worker evaluation failed. Does anyone know why this happened and how can I fix this? Is it related to the incompatibility of the browser and service worker?

dependencies:{
"webpack": "^5.64.4",
"workbox-core": "^6.5.3",
"react": "^17.0.2",
"babel-loader": "^8.2.3",
...
}

Uncaught TypeError: cannot read property 'set' of undefined in service-worker.js
ServiceWorker startup timed out. The worker was in startup phase:Script evaluated.
Timeout when trying to start the service worker.

script evaluation failed

I've tried to change the webpack.config to target chrome 49 and es5. In addition, change the
browserslist in package.json couldn't helpful.
After logging, I understand after clientsClaim() line in service-worker.js my I get the error, but I don't know the exact problem with it and what happens behind the scenes that couldn't register.

It has an error in redundant state in service worer:
Uncaught TypeError: cannot read property 'set' of undefined in service-worker.js
serviceWorker script evaluation failed.

This is my service-worker.js file:

```<code>import {registerRoute} from "workbox-routing";
import {CacheFirst,StaleWhileRevalidate} from "workbox-strategies";
import { BroadcastUpdatePlugin } from "workbox-broadcast-update";
import { setCacheNameDetails, clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from "workbox-precaching";
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import * as googleAnalytics from "workbox-google-analytics";

setCacheNameDetails({
  googleAnalytics: "googleAnalytics",
  precache: "install-time",
  prefix: "ITM",
  runtime: "run-time",
  suffix: "v1",
});

const maxEntries = 500;
const maxAgeSeconds = 24 * 60 * 60;
const purgeOnQuotaError = true;

clientsClaim();

cleanupOutdatedCaches();

precacheAndRoute(self.__WB_MANIFEST || [], {
  ignoreURLParametersMatching: [/.*/],
  directoryIndex: null,
  cleanUrls: false,
});

googleAnalytics.initialize();

const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
registerRoute(
  ({ request, url }) => {
    if (request.mode !== "navigate") {
      return false;
    }
    if (url.pathname.startsWith("/_")) {
      return false;
    }
    if (url.pathname.match(fileExtensionRegexp)) {
      return false;
    }
    return true;
  },
  createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".png"), // Customize this strategy as needed, e.g., by changing to CacheFirst.
  new CacheFirst({
    cacheName: "ITM-images",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
      }),
    ],
  })
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".ico"),
  new CacheFirst({
    cacheName: "ITM-images",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
      }),
    ],
  })
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".json"),
  new CacheFirst({
    cacheName: "ITM-configs",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
        maxAgeSeconds,
        purgeOnQuotaError,
      }),
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new BroadcastUpdatePlugin(),
    ],
  })
);

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});
</code>```

Title: Service Worker doesn't register

Body:
I've implemented a ReactJS web application, and I've added a service worker to cache resources. My service worker works as expected for caching resources when I run it on chromium 72, but when I run it on chromium 49 in WindowsXP it couldn't register and becomes redundant immediately, and shows service Worker evaluation failed. Does anyone know why this happened and how can I fix this? Is it related to the incompatibility of the browser and service worker?

dependencies:{
"webpack": "^5.64.4",
"workbox-core": "^6.5.3",
"react": "^17.0.2",
"babel-loader": "^8.2.3",
...
}

Uncaught TypeError: cannot read property 'set' of undefined in service-worker.js
ServiceWorker startup timed out. The worker was in startup phase:Script evaluated.
Timeout when trying to start the service worker.

script evaluation failed

I've tried to change the webpack.config to target chrome 49 and es5. In addition, change the
browserslist in package.json couldn't helpful.
After logging, I understand after clientsClaim() line in service-worker.js my I get the error, but I don't know the exact problem with it and what happens behind the scenes that couldn't register.

It has an error in redundant state in service worer:
Uncaught TypeError: cannot read property 'set' of undefined in service-worker.js
serviceWorker script evaluation failed.

This is my service-worker.js file:

import {registerRoute} from "workbox-routing";
import {CacheFirst,StaleWhileRevalidate} from "workbox-strategies";
import { BroadcastUpdatePlugin } from "workbox-broadcast-update";
import { setCacheNameDetails, clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from "workbox-precaching";
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import * as googleAnalytics from "workbox-google-analytics";

setCacheNameDetails({
  googleAnalytics: "googleAnalytics",
  precache: "install-time",
  prefix: "ITM",
  runtime: "run-time",
  suffix: "v1",
});

const maxEntries = 500;
const maxAgeSeconds = 24 * 60 * 60;
const purgeOnQuotaError = true;

clientsClaim();

cleanupOutdatedCaches();

precacheAndRoute(self.__WB_MANIFEST || [], {
  ignoreURLParametersMatching: [/.*/],
  directoryIndex: null,
  cleanUrls: false,
});

googleAnalytics.initialize();

const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
registerRoute(
  ({ request, url }) => {
    if (request.mode !== "navigate") {
      return false;
    }
    if (url.pathname.startsWith("/_")) {
      return false;
    }
    if (url.pathname.match(fileExtensionRegexp)) {
      return false;
    }
    return true;
  },
  createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".png"), // Customize this strategy as needed, e.g., by changing to CacheFirst.
  new CacheFirst({
    cacheName: "ITM-images",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
      }),
    ],
  })
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".ico"),
  new CacheFirst({
    cacheName: "ITM-images",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
      }),
    ],
  })
);

registerRoute(
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".json"),
  new CacheFirst({
    cacheName: "ITM-configs",
    plugins: [
      new ExpirationPlugin({
        maxEntries,
        maxAgeSeconds,
        purgeOnQuotaError,
      }),
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new BroadcastUpdatePlugin(),
    ],
  })
);

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});


问:
PBS Scheduling on Allocating One Node
I am trying to request two nodes in a cluster setting; however, when I print ${PBS_NODEFILE}, only one node is visible. I am running this batch script on the login node. Any suggestions to why I am only seeing one node ?</p>
```<code>#PBS -S /bin/bash
#PBS -V
#PBS -W block=true
#PBS -l nodes=2:ppn=12
#PBS -l walltime=01:00:00
#PBS -N resnet50
#PBS -A MyProject
echo "The nodefile for this job is stored at ${PBS_NODEFILE}"
cat ${PBS_NODEFILE}
</code>```

Title: PBS Scheduling on Allocating One Node

Body:
I am trying to request two nodes in a cluster setting; however, when I print ${PBS_NODEFILE}, only one node is visible. I am running this batch script on the login node. Any suggestions to why I am only seeing one node ?

#PBS -S /bin/bash
#PBS -V
#PBS -W block=true
#PBS -l nodes=2:ppn=12
#PBS -l walltime=01:00:00
#PBS -N resnet50
#PBS -A MyProject
echo "The nodefile for this job is stored at ${PBS_NODEFILE}"
cat ${PBS_NODEFILE}


问:
Electron-forge webpack throws error cannot find module when trying to fork a module
Electron Forge's documentation on the subject is pretty weird. I've been trying to do it for days now.

Basically my use-case is the following. I'm trying to create a desktop app with a built-in http server for home automation. So I initialized my electron forge with webpack-typescript template. I added the necessary dependencies.

In my use-case I'm trying to fork (from child_process) a single file called server.fork.ts which contains really simple implementation of express

```<code>import HttpServer from "./Server"
import { getIpAddresses } from "./utils"

const port = process.env.APP_PORT ?? 3000
const hosts = getIpAddresses()
const host = process.env.APP_HOST ?? hosts.at(0) ?? 'localhost'

const server = new HttpServer(host, Number(port))

server.start()

export default server
</code>```

HttpServer is a class that just calls express.listen() on .start()

My idea of forking the process is basically ... I want to be able turn the HttpServer on and off on a user's whim (a toggle button on the UI) but express by default doesn't have a quit/stop method. Otherwise I would've started it in the main thread anyway.

So anyway I created the server.fork.ts file and I am trying to fork it the following way (using IPC) in src/index.ts which seems to be the main.

```<code>ipcMain.handle('start-express', () => {
    httpFork = fork(`${__dirname}/server.fork.js`)
  })

  ipcMain.handle('stop-express', () => {
    if (httpFork) {
      httpFork.kill('SIGHUP')
    }
  })
</code>```

However, when I run the following code using npm start I get the following error: Error: Cannot find module '<projectrooot>/.webpack/main/server.fork.js' and no matter what I try I can't make WebPack to copy that file over.

I tried messing with tsconfig.json by adding files outside compilerOptions and including this file specifically but unless I hardcode that I want the dist folder to be ./.webpack/main it doesn't really work. And I don't know if this is the proper way since it avoids the electron forge packager and after building for production the app might not run at all.

So lt;dr - How can I make electron-forge to compile extra files, other than ./src/index.ts in the main folder?

Body:
Electron Forge's documentation on the subject is pretty weird. I've been trying to do it for days now.

Basically my use-case is the following. I'm trying to create a desktop app with a built-in http server for home automation. So I initialized my electron forge with webpack-typescript template. I added the necessary dependencies.

In my use-case I'm trying to fork (from child_process) a single file called server.fork.ts which contains really simple implementation of express

import HttpServer from "./Server"
import { getIpAddresses } from "./utils"

const port = process.env.APP_PORT ?? 3000
const hosts = getIpAddresses()
const host = process.env.APP_HOST ?? hosts.at(0) ?? 'localhost'

const server = new HttpServer(host, Number(port))

server.start()

export default server

HttpServer is a class that just calls express.listen() on .start()

My idea of forking the process is basically ... I want to be able turn the HttpServer on and off on a user's whim (a toggle button on the UI) but express by default doesn't have a quit/stop method. Otherwise I would've started it in the main thread anyway.

So anyway I created the server.fork.ts file and I am trying to fork it the following way (using IPC) in src/index.ts which seems to be the main.

ipcMain.handle('start-express', () => {
    httpFork = fork(`${__dirname}/server.fork.js`)
  })

  ipcMain.handle('stop-express', () => {
    if (httpFork) {
      httpFork.kill('SIGHUP')
    }
  })

However, when I run the following code using npm start I get the following error: Error: Cannot find module '<projectrooot>/.webpack/main/server.fork.js' and no matter what I try I can't make WebPack to copy that file over.

I tried messing with tsconfig.json by adding files outside compilerOptions and including this file specifically but unless I hardcode that I want the dist folder to be ./.webpack/main it doesn't really work. And I don't know if this is the proper way since it avoids the electron forge packager and after building for production the app might not run at all.

So lt;dr - How can I make electron-forge to compile extra files, other than ./src/index.ts in the main folder?


问:
I don't have the good version of Ruby in VsCode with Flutter and Pod
So, when I run ruby -v in the terminal in Mac M1, I have the good version of Ruby which is ruby 3.2.0 that I installed with rbenv. The problem is when I run pod outdated in VsCode in my ios folder in flutter I get this

It uses my Ruby version pre-installed on my mac m1 which is the folder usr/lib/ruby and is an old version : 2.6

Also, I can't run my app with "Flutter run" I have lot of problems with everything related with pod (when I add packages like cloud_firestore). Maybe it's because of that, if someone can help me ?


问:
Create routes and render content from WordPress plugin
I wanted to create a WordPress plugin that would add various routes/endpoints/pages to the WordPress site and content for those routes.
I was looking at various SO posts and various blogs but I did not find the exact answer.

Is there a way to add new routes/endpoints from a plugin and use templates or any other way to have logic for content for those routes/endpoints?

For example, activation of that plugin would add routes:

"domain.com/something/parameter"

And I would have a special logic that would show content for that "something" route and that parameter "parameter".


问:
Spring Cloud Stream Rabbit - Enabling error channel reduces throughput
In Spring Cloud Stream Rabbit is there a way to intercept acks in the background. Even though my intent is to only catch NACKS/Errors, since I am enabling publisher returns, it reduces the throughput. I am using a confirmACkChannel to intercept acks. I cannot use the modern way since mine is a stream and message publishing cannot be batched.
I am using a service activator bound to acks channel and another which is bound to the errorchannel.</p>