问:
Unable to Unwrap/Decode a WinRT.IInspectable object from BluetoothLEAdvertisementWatcher::Received event in Powershell
Thanks to the excellent research work done by @windos on BurnToast, I've been able to use WinRT Runtime in Powershell (7.1+ needed) to receive Bluetooth Low Energy advertisement beacons.

What I've been unable to do, is to extract data from the event's returned WinRT.IInspectable object in a reasonable way.

To test the code below, you need to have  Bluetooth adapter and at least one Bluetooth Low Energy device broadcasting its beacon nearby in order to trigger the Received event:

```<code>#requires -version 7.1
Invoke-WebRequest https://github.com/Windos/BurntToast/raw/main/BurntToast/lib/Microsoft.Windows.SDK.NET/WinRT.Runtime.dll -OutFile WinRT.Runtime.dll
Add-Type -Path WinRT.Runtime.dll
Invoke-WebRequest https://github.com/Windos/BurntToast/raw/main/BurntToast/lib/Microsoft.Windows.SDK.NET/Microsoft.Windows.SDK.NET.dll -OutFile Microsoft.Windows.SDK.NET.dll
Add-Type -Path Microsoft.Windows.SDK.NET.dll

$Watcher=[Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher]::new()
Register-ObjectEvent -InputObject $Watcher -EventName Received -Action {
    $Global:Event=$Event
}
$Watcher.Start()
sleep 5 #Should be enough time to have a nearby BLE device to send an advertisement beacon, increase if necessary
$Watcher.Stop()
</code>```

After running the code above, we have a $Global:Event that holds the advertisement:

```<code>$Global:Event.SourceArgs[1].Advertisement

DataSections               : WinRT.IInspectable
Flags                      : GeneralDiscoverableMode, DualModeControllerCapable, DualModeHostCapable
LocalName                  :
ManufacturerData           : WinRT.IInspectable
ServiceUuids               : WinRT.IInspectable
NativeObject               : WinRT.ObjectReference`1[WinRT.Interop.IUnknownVftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {}
</code>```

..and..

```<code>$Global:Event.SourceArgs[1].Advertisement.DataSections

ThisPtr                    : 2230874300144
ObjRef                     : WinRT.ObjectReference`1[WinRT.IInspectable+Vftbl]
NativeObject               : WinRT.ObjectReference`1[WinRT.IInspectable+Vftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {[System.RuntimeTypeHandle,    ABI.System.Collections.IEnumerable+AdaptiveFromAbiHelper]}
</code>```

I understand correctly, I should use the .DataSections Native Object to unwrap the data from the WinRT.IInspectable returned object.
and as such, I would have expected the object to a .target property and a .QueryInterface() method, but that's not the case.

What I have found tho, is that

```<code>$Global:Event.SourceArgs[1].Advertisement.DataSections.AdditionalDataTypes.Values
Data                       : WinRT.IInspectable
DataType                   : 255
NativeObject               : WinRT.ObjectReference`1[WinRT.Interop.IUnknownVftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {}
</code>```

should contain String data (Datatype:255), but instead of a value to convert to string, .Data.objRef contains a ThisPtr and a Vftbl (Virtual function table):

```<code>$Global:Event.SourceArgs[1].Advertisement.DataSections.AdditionalTypeData.Values.data.objref

Vftbl                          ThisPtr
-----                          -------
WinRT.IInspectable+Vftbl 2241526348528
WinRT.IInspectable+Vftbl 2241526344816
WinRT.IInspectable+Vftbl 2241526344176
WinRT.IInspectable+Vftbl 2241526348528
WinRT.IInspectable+Vftbl 2241526344816
WinRT.IInspectable+Vftbl 2241526344176
</code>```

and if I understand correctly I should use

```<code>[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($_.Vftbl)
</code>```

(wrong)
OR, according to
https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.advertisement.bluetoothleadvertisementdatasection.data?view=winrt-22621
I should have an IBuffer ..but at this point, it seems to me I'm going down a rabbit hole..

What is the correct way to extract the data?

Thanks!

Body:
Thanks to the excellent research work done by @windos on BurnToast, I've been able to use WinRT Runtime in Powershell (7.1+ needed) to receive Bluetooth Low Energy advertisement beacons.

What I've been unable to do, is to extract data from the event's returned WinRT.IInspectable object in a reasonable way.

To test the code below, you need to have  Bluetooth adapter and at least one Bluetooth Low Energy device broadcasting its beacon nearby in order to trigger the Received event:

#requires -version 7.1
Invoke-WebRequest https://github.com/Windos/BurntToast/raw/main/BurntToast/lib/Microsoft.Windows.SDK.NET/WinRT.Runtime.dll -OutFile WinRT.Runtime.dll
Add-Type -Path WinRT.Runtime.dll
Invoke-WebRequest https://github.com/Windos/BurntToast/raw/main/BurntToast/lib/Microsoft.Windows.SDK.NET/Microsoft.Windows.SDK.NET.dll -OutFile Microsoft.Windows.SDK.NET.dll
Add-Type -Path Microsoft.Windows.SDK.NET.dll

$Watcher=[Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher]::new()
Register-ObjectEvent -InputObject $Watcher -EventName Received -Action {
    $Global:Event=$Event
}
$Watcher.Start()
sleep 5 #Should be enough time to have a nearby BLE device to send an advertisement beacon, increase if necessary
$Watcher.Stop()

After running the code above, we have a $Global:Event that holds the advertisement:

$Global:Event.SourceArgs[1].Advertisement

DataSections               : WinRT.IInspectable
Flags                      : GeneralDiscoverableMode, DualModeControllerCapable, DualModeHostCapable
LocalName                  :
ManufacturerData           : WinRT.IInspectable
ServiceUuids               : WinRT.IInspectable
NativeObject               : WinRT.ObjectReference`1[WinRT.Interop.IUnknownVftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {}

..and..

$Global:Event.SourceArgs[1].Advertisement.DataSections

ThisPtr                    : 2230874300144
ObjRef                     : WinRT.ObjectReference`1[WinRT.IInspectable+Vftbl]
NativeObject               : WinRT.ObjectReference`1[WinRT.IInspectable+Vftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {[System.RuntimeTypeHandle,    ABI.System.Collections.IEnumerable+AdaptiveFromAbiHelper]}

I understand correctly, I should use the .DataSections Native Object to unwrap the data from the WinRT.IInspectable returned object.
and as such, I would have expected the object to a .target property and a .QueryInterface() method, but that's not the case.

What I have found tho, is that

$Global:Event.SourceArgs[1].Advertisement.DataSections.AdditionalDataTypes.Values
Data                       : WinRT.IInspectable
DataType                   : 255
NativeObject               : WinRT.ObjectReference`1[WinRT.Interop.IUnknownVftbl]
HasUnwrappableNativeObject : True
AdditionalTypeData         : {}

should contain String data (Datatype:255), but instead of a value to convert to string, .Data.objRef contains a ThisPtr and a Vftbl (Virtual function table):

$Global:Event.SourceArgs[1].Advertisement.DataSections.AdditionalTypeData.Values.data.objref

Vftbl                          ThisPtr
-----                          -------
WinRT.IInspectable+Vftbl 2241526348528
WinRT.IInspectable+Vftbl 2241526344816
WinRT.IInspectable+Vftbl 2241526344176
WinRT.IInspectable+Vftbl 2241526348528
WinRT.IInspectable+Vftbl 2241526344816
WinRT.IInspectable+Vftbl 2241526344176

and if I understand correctly I should use

[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($_.Vftbl)

(wrong)
OR, according to
https://learn.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.advertisement.bluetoothleadvertisementdatasection.data?view=winrt-22621
I should have an IBuffer ..but at this point, it seems to me I'm going down a rabbit hole..

What is the correct way to extract the data?

Thanks!


来源: stackexchange

问:
Background service in android to click the mobile screen every 5 minutes
I have setup security camera in my home. It has a mobile app to monitor the camera even when I am out of town. But, the live transmit is getting paused every 5 min. I would like to create a background service for android to click the mobile screen in a specified x,y position for every 5 min to resume that paused live video automatically. So that I don't need to hit the play button every 5 minutes manually to continue watching the security camera.

Can you help me how to achieve this. Any guidance on this would be appreciated!!

I have tried searching in the web. I couldn't find a solution similar to this.

ContentLicense: CC BY-SA 4.0


问:
How do I start a dbt run from the dbt-cloud cli?
I have a dbt project, and the dbt-cloud cli. I have my account ID and my token. I want to do a dbt run.

When I try dbt-cloud job run ... it wants a job-id. But it doesn't seem to like the one I get from dbt-cloud job list

Do I need to create a job template sort of thing on the cloud version? or create a json file to use with dbt-cloud job create ? I haven't figured out how to use --execute-steps with the job create call...

ETA: AH, I seem to have too many accounts and was running from the wrong one? I think it's working now?


问:
Animate dialog overflows with visible scrolls
I have created a dialog that slides out on closing if on mobile view.
Otherwise it just scales backwards.

This component is based on the awesome work from here:
https://web.dev/building-a-dialog-component/#styling-with-open-props

With some tweeks of my own to adapt it to react and my own needs.

This will add scrollbar on html body for a breef second.
This is super annoying and only fix that works is to hide scrollbar on the html-tag.

```<code>  html {
        box-sizing: border-box;
        margin: 0px; padding: 0px
        &::-webkit-scrollbar {
            display: none;
        }
        scrollbar-width: none;
      }
</code>```

I do not like this at all, are there any better solutions for this?

```<code>import { useEffect, useState, useRef } from "react";
import styled, { keyframes } from "styled-components";
import PropTypes from "prop-types";
import { shadow } from "shared/theme";
import { spacingIndex } from "shared/spacing";

const scaleDown = keyframes`
to { transform: scale(.75) }
`;

const slideOutDown = keyframes`
to { transform: translateY(100%) }
`;

const slideInUp = keyframes`
from { transform: translateY(100%) }
`;

const Container = styled.dialog`
    display: ${({ open }) => (open ? "flex" : "none")};
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    border: none;
    max-inline-size: min(90vw, 60ch);
    max-block-size: min(80vh, 100%);
    overflow: hidden;
    margin: auto;
    padding: ${spacingIndex * 2}px;
    inset: 0;
    box-shadow: ${shadow.overlay};
    transition: opacity 0.5s cubic-bezier(0.25, 0, 0.3, 1);
    animation: ${scaleDown} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
    animation-timing-function: cubic-bezier(0.5, -0.5, 0.1, 1.5);

    &:is([open]) {
        animation: ${slideInUp} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
    }

    &:not([open]) {
        pointer-events: none;
        opacity: 0;
    }
    ::backdrop {
        backdrop-filter: blur(4px);
        transition: backdrop-filter 0.5s ease;
    }

    @media (max-width: 768px) {
        animation: ${slideOutDown} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
        margin-block-end: 16px;
    }
`;

const Dialog = ({ isOpened, onClose, children }) => {
    const ref = useRef(null);
    const [open, setOpen] = useState(false);

    const isClickOutsideOfDialog = (dialogEl, event) => {
        if (!dialogEl) return false;
        const rect = dialogEl.getBoundingClientRect();
        return (
            event.clientY < rect.top ||
            event.clientY > rect.bottom ||
            event.clientX < rect.left ||
            event.clientX > rect.right
        );
    };

    const onDialogContainerClick = (event) => {
        if (isClickOutsideOfDialog(ref.current, event)) onClose();
    };

    const handleAnimationEnd = (e) => {
        if (slideInUp.name !== e.animationName) setOpen(false);
    };
    useEffect(() => {
        ref.current?.addEventListener("animationend", handleAnimationEnd);
        return () => ref.current?.removeEventListener("animationend", handleAnimationEnd);
    }, []);

    useEffect(() => {
        if (!isOpened) ref.current?.close();
        if (isOpened) {
            setOpen(true);
            ref.current?.showModal();
        }
    }, [isOpened]);

    return (
        <Container
            {...{
                ref,
                open,
                onClick: onDialogContainerClick,
            }}>
            {children}
        </Container>
    );
};

Dialog.propTypes = {
    isOpened: PropTypes.bool,
    onClose: PropTypes.func,
};

export default Dialog;
</code>```

Edit: Guess I was tired and stupid..Just added position:fixed; because I then move the dialog out of the document flow.

Body:
I have created a dialog that slides out on closing if on mobile view.
Otherwise it just scales backwards.

This component is based on the awesome work from here:
https://web.dev/building-a-dialog-component/#styling-with-open-props

With some tweeks of my own to adapt it to react and my own needs.

This will add scrollbar on html body for a breef second.
This is super annoying and only fix that works is to hide scrollbar on the html-tag.

  html {
        box-sizing: border-box;
        margin: 0px; padding: 0px
        &::-webkit-scrollbar {
            display: none;
        }
        scrollbar-width: none;
      }

I do not like this at all, are there any better solutions for this?

import { useEffect, useState, useRef } from "react";
import styled, { keyframes } from "styled-components";
import PropTypes from "prop-types";
import { shadow } from "shared/theme";
import { spacingIndex } from "shared/spacing";

const scaleDown = keyframes`
to { transform: scale(.75) }
`;

const slideOutDown = keyframes`
to { transform: translateY(100%) }
`;

const slideInUp = keyframes`
from { transform: translateY(100%) }
`;

const Container = styled.dialog`
    display: ${({ open }) => (open ? "flex" : "none")};
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    border: none;
    max-inline-size: min(90vw, 60ch);
    max-block-size: min(80vh, 100%);
    overflow: hidden;
    margin: auto;
    padding: ${spacingIndex * 2}px;
    inset: 0;
    box-shadow: ${shadow.overlay};
    transition: opacity 0.5s cubic-bezier(0.25, 0, 0.3, 1);
    animation: ${scaleDown} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
    animation-timing-function: cubic-bezier(0.5, -0.5, 0.1, 1.5);

    &:is([open]) {
        animation: ${slideInUp} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
    }

    &:not([open]) {
        pointer-events: none;
        opacity: 0;
    }
    ::backdrop {
        backdrop-filter: blur(4px);
        transition: backdrop-filter 0.5s ease;
    }

    @media (max-width: 768px) {
        animation: ${slideOutDown} 0.5s cubic-bezier(0.25, 0, 0.3, 1) forwards;
        margin-block-end: 16px;
    }
`;

const Dialog = ({ isOpened, onClose, children }) => {
    const ref = useRef(null);
    const [open, setOpen] = useState(false);

    const isClickOutsideOfDialog = (dialogEl, event) => {
        if (!dialogEl) return false;
        const rect = dialogEl.getBoundingClientRect();
        return (
            event.clientY < rect.top ||
            event.clientY > rect.bottom ||
            event.clientX < rect.left ||
            event.clientX > rect.right
        );
    };

    const onDialogContainerClick = (event) => {
        if (isClickOutsideOfDialog(ref.current, event)) onClose();
    };

    const handleAnimationEnd = (e) => {
        if (slideInUp.name !== e.animationName) setOpen(false);
    };
    useEffect(() => {
        ref.current?.addEventListener("animationend", handleAnimationEnd);
        return () => ref.current?.removeEventListener("animationend", handleAnimationEnd);
    }, []);

    useEffect(() => {
        if (!isOpened) ref.current?.close();
        if (isOpened) {
            setOpen(true);
            ref.current?.showModal();
        }
    }, [isOpened]);

    return (
        <Container
            {...{
                ref,
                open,
                onClick: onDialogContainerClick,
            }}>
            {children}
        </Container>
    );
};

Dialog.propTypes = {
    isOpened: PropTypes.bool,
    onClose: PropTypes.func,
};

export default Dialog;

Edit: Guess I was tired and stupid..Just added position:fixed; because I then move the dialog out of the document flow.


问:
.innerText does not change any text and button event listener does not work
My english teacher asked me to make some sort of program to help my classmates learn the past tense of irregular verbs. I haven't used javascript in some time, so I copied most of the code from my older projects, but for some reason it doesn't work anymore. Clicking buttons does not alert anything and the text on the page does not change either. I have no idea why it doesn't work.

<!DOCTYPE html>

Verb:

    <form>
      <input type="button" value="Check" id="check" />
      <input type="button" value="Show answer" id="answer" />
      <input type="button" value="Next" id="next" />

      <input type="text" id="verb1" name="verb1" />
      <input type="text" id="verb2" name="verb2" />
      <input type="text" id="verb3" name="verb3" />
    </form>

Learn three forms of verbs!

Score: 0

```


问:
How to integrate require.js for the backend of an html page?
I first and foremost want to say that I am not super well versed with module integration and  backend environments in general, which explains why this question may seem ridiculous.

I am currently trying to put together a basic website displaying scraped data within an HTML table using require.js and puppeteer. That said, I am running into issues when trying to load the webpage and can't seem to figure out how to fix it, even after consulting the require.js common error documentation for debugging.

Here is my current js script:

```<code>const puppeteer = require('puppeteer')
const fs = require('fs/promises')

async function start() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto("https://ciffc.net/en/ciffc/ext/member/sitrep/")

const names = await page.evaluate(() => {
    return Array.from(document.querySelectorAll("#apl_table_wrapper td:nth-of-type(2)")).map(x => x.textContent)
})
await fs.writeFile("names.txt", names.join("\r\n"))

await browser.close()
}

start()
</code>```

And here is the integration of the script within the head element of the HTML:

```<code><head>
    <title>Data Table</title>
    <meta charSet="utf-8"/>
    <link rel="stylesheet" href="style.css">
    <script src="https://requirejs.org/docs/release/2.3.1/minified/require.js"></script>
    <script src="index.js"></script>
</head>
</code>```

Now when I load this html page, I run into this following error:

Uncaught Error: Module name "puppeteer" has not been loaded yet for context: _. Use require([])

I consulted the require.js documentation and found this specific error referenced within the "Common Errors" page, mentioning that this error occurs when there is a require('name') call, but the 'name' module has not been loaded yet. I then amended my code accordingly: which leads to an Uncaught SyntaxError: Identifier 'puppeteer' has already been declared:

```<code>require(['puppeteer', 'fs/promises'], function(puppeteer) {

    const puppeteer = require('puppeteer')
    const fs = require('fs/promises')
    //rest of script
});
</code>```

which leads to:

Uncaught SyntaxError: Identifier 'puppeteer' has already been declared

I have tried many different iterations of the script but have yet to be successful in getting it loaded correctly. How can I fix this issue?

Body:
I first and foremost want to say that I am not super well versed with module integration and  backend environments in general, which explains why this question may seem ridiculous.

I am currently trying to put together a basic website displaying scraped data within an HTML table using require.js and puppeteer. That said, I am running into issues when trying to load the webpage and can't seem to figure out how to fix it, even after consulting the require.js common error documentation for debugging.

Here is my current js script:

const puppeteer = require('puppeteer')
const fs = require('fs/promises')

async function start() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto("https://ciffc.net/en/ciffc/ext/member/sitrep/")

const names = await page.evaluate(() => {
    return Array.from(document.querySelectorAll("#apl_table_wrapper td:nth-of-type(2)")).map(x => x.textContent)
})
await fs.writeFile("names.txt", names.join("\r\n"))

await browser.close()
}

start()

And here is the integration of the script within the head element of the HTML:

    <title>Data Table</title>
    <meta charSet="utf-8"/>
    <link rel="stylesheet" href="style.css">

Now when I load this html page, I run into this following error:

Uncaught Error: Module name "puppeteer" has not been loaded yet for context: _. Use require([])

I consulted the require.js documentation and found this specific error referenced within the "Common Errors" page, mentioning that this error occurs when there is a require('name') call, but the 'name' module has not been loaded yet. I then amended my code accordingly: which leads to an Uncaught SyntaxError: Identifier 'puppeteer' has already been declared:

require(['puppeteer', 'fs/promises'], function(puppeteer) {

    const puppeteer = require('puppeteer')
    const fs = require('fs/promises')
    //rest of script
});

which leads to:

Uncaught SyntaxError: Identifier 'puppeteer' has already been declared

I have tried many different iterations of the script but have yet to be successful in getting it loaded correctly. How can I fix this issue?


问:
how to have multiple "chasers" in a ws2812b strip triggered by pressing the space bar?
I wrote a small python script to have a light travel down a piece of ws2812b led strip that is triggered when I press the spacebar on the keyboard attached to the raspberry pi. The script works well, but I can only press the spacebar once and then have to wait for the light effect to travel down the strip. I'd like a way for every time I press space, it sends another light racing down the strip.</p>
```<code>import keyboard #using keyboard module to get key presses
import time #to wait a certain amount of time
import neopixel
import board

# LED strip configuration:
LED_COUNT      = 48             # Number of LED pixels.
LED_PIN        = board.D18      # GPIO pin connected to the pixels (18 uses PWM!)
ORDER          = neopixel.GRB   #or RGB
CHASER_SIZE    = 10

# Create NeoPixel object with appropriate configuration.
strip = neopixel.NeoPixel(
    LED_PIN, LED_COUNT, brightness=1.0, auto_write=False, pixel_order=ORDER
)

#Clear the strip
strip.fill(0)
strip.show()

def chaser(GREEN=255, RED=255, BLUE=255, SPEED=.01):
    for x in range(LED_COUNT+CHASER_SIZE):
        for y in range(CHASER_SIZE):
            if (x>LED_COUNT-1):

                #print("X: ", y, " Y: ", y) #debug
                strip[x-CHASER_SIZE]=(0)
            else:
                if (x-y>=0):
                    strip[x-y]=(GREEN/(y+1), RED/(y+1), BLUE/(y+1))
                    strip[x-CHASER_SIZE]=(0)

        strip.show()
        time.sleep(SPEED)

    return

if __name__ == '__main__':

    while True: #loop while running
        if keyboard.is_pressed('esc'): #check if "Esc" was pressed
            print("pressed esc")
            #Clear the strip
            strip.fill(0)
            strip.show()
            exit() #Quit program
        if keyboard.is_pressed('space'):
            chaser()
</code>```

Body:
I wrote a small python script to have a light travel down a piece of ws2812b led strip that is triggered when I press the spacebar on the keyboard attached to the raspberry pi. The script works well, but I can only press the spacebar once and then have to wait for the light effect to travel down the strip. I'd like a way for every time I press space, it sends another light racing down the strip.

import keyboard #using keyboard module to get key presses
import time #to wait a certain amount of time
import neopixel
import board

# LED strip configuration:
LED_COUNT      = 48             # Number of LED pixels.
LED_PIN        = board.D18      # GPIO pin connected to the pixels (18 uses PWM!)
ORDER          = neopixel.GRB   #or RGB
CHASER_SIZE    = 10

# Create NeoPixel object with appropriate configuration.
strip = neopixel.NeoPixel(
    LED_PIN, LED_COUNT, brightness=1.0, auto_write=False, pixel_order=ORDER
)

#Clear the strip
strip.fill(0)
strip.show()

def chaser(GREEN=255, RED=255, BLUE=255, SPEED=.01):
    for x in range(LED_COUNT+CHASER_SIZE):
        for y in range(CHASER_SIZE):
            if (x>LED_COUNT-1):

                #print("X: ", y, " Y: ", y) #debug
                strip[x-CHASER_SIZE]=(0)
            else:
                if (x-y>=0):
                    strip[x-y]=(GREEN/(y+1), RED/(y+1), BLUE/(y+1))
                    strip[x-CHASER_SIZE]=(0)

        strip.show()
        time.sleep(SPEED)

    return

if __name__ == '__main__':

    while True: #loop while running
        if keyboard.is_pressed('esc'): #check if "Esc" was pressed
            print("pressed esc")
            #Clear the strip
            strip.fill(0)
            strip.show()
            exit() #Quit program
        if keyboard.is_pressed('space'):
            chaser()


问:
Saving large matrix in a file in Python
I am producing a large matrix in python from a loop function, so i want to save it in a file for further using, to do this i used this following where bxx is my matrix of dimension (3324, 1, 24464):

```<code>#write matrix to file
import numpy
my_matrix = bxx
numpy.savetxt('matrix.txt', my_matrix, delimiter = ',')

#read file into a matrix
import numpy
my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)
</code>```

I got the error massage :

```<code>Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_11628\2774506594.py in <module>
      6 #read file into a matrix
      7 import numpy
----> 8 my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)

~\Anaconda3\envs\myenv\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows, like)
   1148         for x in read_data(_loadtxt_chunksize):
   1149             if X is None:
-> 1150                 X = np.array(x, dtype)
   1151             else:
   1152                 nshape = list(X.shape)

MemoryError: Unable to allocate 620. MiB for an array with shape (3324, 1, 24464) and data type float64
</code>```

Title: Saving large matrix in a file in Python

Body:
I am producing a large matrix in python from a loop function, so i want to save it in a file for further using, to do this i used this following where bxx is my matrix of dimension (3324, 1, 24464):

#write matrix to file
import numpy
my_matrix = bxx
numpy.savetxt('matrix.txt', my_matrix, delimiter = ',')

#read file into a matrix
import numpy
my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)

I got the error massage :

Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_11628\2774506594.py in <module>
      6 #read file into a matrix
      7 import numpy
----> 8 my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)

~\Anaconda3\envs\myenv\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows, like)
   1148         for x in read_data(_loadtxt_chunksize):
   1149             if X is None:
-> 1150                 X = np.array(x, dtype)
   1151             else:
   1152                 nshape = list(X.shape)

MemoryError: Unable to allocate 620. MiB for an array with shape (3324, 1, 24464) and data type float64


问:
How to send params of current request to the constructor of the service?
Update: I have fixed it by only supplying the pattern of the path of the collection, and creating a function that can parse the provided IDs and now the functions themselves create the collections when they are called upon and it also works with Typescript:)

Updated in the repository:
https://github.com/Darkbound/nestjs-firebase/tree/main/src/firebase

In the user service:
https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/user.service.ts

In the purchase transactions service: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts

In the purchase transactions controller: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.controller.ts#L14

Now the functionality works out of the box, the service class simply needs to extend the FirebaseCollectionService and give it the pattern of the path to the collection and thats it!

https://github.com/Darkbound/nestjs-firebase I have uploaded it into a repository, you only need to add .env with the keys for firebase admin.

And the specific example: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts

I have created a class that gives me the functionality to perform CRUD operations on firebase, so that I can just directly inherit from it for any of my CRUD resources, as the logic is again usually mostly the same. Just like Nestjs generator gives me all of the routes for it.

```<code>@Injectable()
export class UserService extends NestjsFirebase<User> {
  constructor(@InjectFirebaseAdmin() firebase: FirebaseAdmin) {
    super(firebase, "users");
    // console.log(userId);
  }
}
</code>```

This works great, I can reuse that for any level 1 collection I have in firebase, however if I want to get into a nested collection on firebase, well thats a problem, because the path there needs to be dynamic and super(firebase, "this is no longer just users").

Say if I want to access the transactions of a user, so users/SomeUserIdXYZ/transactions, then the path is entirely dependent on the userId and is changing, therefor, I need to recreate the instance of the service (I simply need a new instance of the class), with a new path:

super(firebase, ["users", userId, "transactions"]

However with my still limited knowledge about Nestjs I know that everything in it basically is a Singleton and there is probably no way to do this? To get a new instance of the service, for every request that I have?

The solution that I can think of is, to handle that within my route functions, so if its a findTransactions:

```<code>  @Get("users/:userId/transactions")
  async findTransactions(@Param("userId") userId: string) {
    return this.userService.findAll(`users/${userId}/transactions`);
  }
</code>```

And I am pretty sure that this will work, if I add a path argument to each of the functions, but this seems like coupling the Controller with what my Path in firebase should look like, instead I need to be able to give it just the params so that it can create its own path.

This is NestjsFirebase:

```<code>@Injectable()
class NestjsFirebase<T> {
  constructor(@InjectFirebaseAdmin() private readonly firebase: FirebaseAdmin, private readonly collectionPath: string) {}

    async findAll(userId: string): Promise<T> {
      const db = new FirebaseCollectionService<T>(this.firebase, this.collectionPath);

      return await db.findAll(userId);
    }
}

export class FirebaseCollectionService<T> {
  protected db: CollectionReference<T>;

  constructor(firebase: FirebaseAdmin, collectionPath: string) {
    super(firebase.db);

    this.db = this.createCollectionPath(collectionPath);
  }

  public async findAll(id: string) {
     ... some logic to find all transactions ...

  }
}
</code>```

Body:
Update: I have fixed it by only supplying the pattern of the path of the collection, and creating a function that can parse the provided IDs and now the functions themselves create the collections when they are called upon and it also works with Typescript:)

Updated in the repository:
https://github.com/Darkbound/nestjs-firebase/tree/main/src/firebase

In the user service:
https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/user.service.ts

In the purchase transactions service: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts

In the purchase transactions controller: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.controller.ts#L14

Now the functionality works out of the box, the service class simply needs to extend the FirebaseCollectionService and give it the pattern of the path to the collection and thats it!

https://github.com/Darkbound/nestjs-firebase I have uploaded it into a repository, you only need to add .env with the keys for firebase admin.

And the specific example: https://github.com/Darkbound/nestjs-firebase/blob/main/src/user/modules/purchase-transaction/purchase-transaction.service.ts

I have created a class that gives me the functionality to perform CRUD operations on firebase, so that I can just directly inherit from it for any of my CRUD resources, as the logic is again usually mostly the same. Just like Nestjs generator gives me all of the routes for it.

@Injectable()
export class UserService extends NestjsFirebase<User> {
  constructor(@InjectFirebaseAdmin() firebase: FirebaseAdmin) {
    super(firebase, "users");
    // console.log(userId);
  }
}

This works great, I can reuse that for any level 1 collection I have in firebase, however if I want to get into a nested collection on firebase, well thats a problem, because the path there needs to be dynamic and super(firebase, "this is no longer just users").

Say if I want to access the transactions of a user, so users/SomeUserIdXYZ/transactions, then the path is entirely dependent on the userId and is changing, therefor, I need to recreate the instance of the service (I simply need a new instance of the class), with a new path:

super(firebase, ["users", userId, "transactions"]

However with my still limited knowledge about Nestjs I know that everything in it basically is a Singleton and there is probably no way to do this? To get a new instance of the service, for every request that I have?

The solution that I can think of is, to handle that within my route functions, so if its a findTransactions:

  @Get("users/:userId/transactions")
  async findTransactions(@Param("userId") userId: string) {
    return this.userService.findAll(`users/${userId}/transactions`);
  }

And I am pretty sure that this will work, if I add a path argument to each of the functions, but this seems like coupling the Controller with what my Path in firebase should look like, instead I need to be able to give it just the params so that it can create its own path.

This is NestjsFirebase:

@Injectable()
class NestjsFirebase<T> {
  constructor(@InjectFirebaseAdmin() private readonly firebase: FirebaseAdmin, private readonly collectionPath: string) {}

    async findAll(userId: string): Promise<T> {
      const db = new FirebaseCollectionService<T>(this.firebase, this.collectionPath);

      return await db.findAll(userId);
    }
}

export class FirebaseCollectionService<T> {
  protected db: CollectionReference<T>;

  constructor(firebase: FirebaseAdmin, collectionPath: string) {
    super(firebase.db);

    this.db = this.createCollectionPath(collectionPath);
  }

  public async findAll(id: string) {
     ... some logic to find all transactions ...

  }
}


问:
How to restrict access to backend App Engine application from a specific EXTERNAL React-JS frontend?
I would like to access all my Flask routes of my Python application running in a Google App Engine only from a React-JS frontend and therefore deny all other requests which are not coming from that frontend.

Sofar I've created a Service Account (SA), enabled IAP for the target App Engine resource, assigned the IAP-secured Web App User role to that SA, so that only this SA can access my application.
Now, the missing part is how to let my frontend (in React-JS) use that SA to access the backend resources.


问:
Python script fails to connect to remote database: Character set unsupported
I am trying to connect to a remote api, grab some json data, parse it, and the save it to a database running on a remote machine, the api calls and data parsing I have, but trying to setup my python script to connect to the database I get the following error:

```<code>mysql.connector.errors.ProgrammingError: Character set 'utf8' unsupported
</code>```

I have tried changing my connection string to what seems to be the character set that my table is using, utf8mb4_generic_ci, but I still get the error, just with that rather than the utf8.

```<code>mysql+mysqlconnector://root:<password>@<ip>:3306/<Database>?charset=utf8mb4_generic_ci
</code>```

Picture showing example table, with charset

I am using MariaDB 10.9.2 for my database, and phpMyAdmin to manage it. My code looks something like:

# Import libraries
from sqlalchemy import create_engine

# Setup sql connection
engine = create_engine('mysql+mysqlconnector://root:<Password>@<IP>:3306/<Database>')
connection = engine.connect()

# Run a sample query
result = connection.execute("SELECT * FROM users")

# Fetch the results
for row in result:
    print(row)

# Close the connection
connection.close()
```

Body:
I am trying to connect to a remote api, grab some json data, parse it, and the save it to a database running on a remote machine, the api calls and data parsing I have, but trying to setup my python script to connect to the database I get the following error:

mysql.connector.errors.ProgrammingError: Character set 'utf8' unsupported

I have tried changing my connection string to what seems to be the character set that my table is using, utf8mb4_generic_ci, but I still get the error, just with that rather than the utf8.

mysql+mysqlconnector://root:<password>@<ip>:3306/<Database>?charset=utf8mb4_generic_ci

Picture showing example table, with charset

I am using MariaDB 10.9.2 for my database, and phpMyAdmin to manage it. My code looks something like:

# Import libraries
from sqlalchemy import create_engine

# Setup sql connection
engine = create_engine('mysql+mysqlconnector://root:<Password>@<IP>:3306/<Database>')
connection = engine.connect()

# Run a sample query
result = connection.execute("SELECT * FROM users")

# Fetch the results
for row in result:
    print(row)

# Close the connection
connection.close()


问:
run a bash script from build command of eclipse IDE on windows
I have a C/C++ project which is imported to an eclipse based IDE (STM32CubeIDE) on Win 11.
Inorder to compile the project, I have to enter some commands in git-bash. so for simplicity I wrote them into an .sh which is named build.sh and put it in the project folder, since then I just need to run this bash like this:
source build.sh
in git-bash, and here is its content:

```<code>#!/bin/sh

source Q:/stm32.sh

cd Q:/dev/my_project

make build_all
</code>```

Right now, I want this script to be called, whenever I press the Build button of the IDE.
I found out that for this I have to change the build command from Propertise->C/C++ Build, uncheck the use default build command and then enter the proper command for running the script.
But I could have not do this by now.
I've tried to solve this problem by entering this
${workspace_loc:/${ProjName}/build.sh}
into the build command, which didn't work.

So my question is that what should I enter here to run the build.sh?
Do you know a better solution for my problem?

Body:
I have a C/C++ project which is imported to an eclipse based IDE (STM32CubeIDE) on Win 11.
Inorder to compile the project, I have to enter some commands in git-bash. so for simplicity I wrote them into an .sh which is named build.sh and put it in the project folder, since then I just need to run this bash like this:
source build.sh
in git-bash, and here is its content:

#!/bin/sh

source Q:/stm32.sh

cd Q:/dev/my_project

make build_all

Right now, I want this script to be called, whenever I press the Build button of the IDE.
I found out that for this I have to change the build command from Propertise->C/C++ Build, uncheck the use default build command and then enter the proper command for running the script.
But I could have not do this by now.
I've tried to solve this problem by entering this
${workspace_loc:/${ProjName}/build.sh}
into the build command, which didn't work.

So my question is that what should I enter here to run the build.sh?
Do you know a better solution for my problem?


问:
href of static html called in router does not work as expected
First the index.pug: (located in /views/config)

```<code>html
  head
    some header
  body
    h1 some body
    a("onepage") some text
</code>```

In the app.ts: (only the important parts)

```<code>app.set("views", path.join(__dirname, "views"));
app.use("/config", configRouter);
</code>```

In the configRouter.ts

```<code>const configRouter = express.Router();
configRouter.get("/", (req, res) => {
    res.render("config/index.pug");
});

</code>```

Can someone help me?

When I press on the "some text" link i get navigated to mainpage/onepage instead of mainpage/config/onepage as I would expect.

Body:
First the index.pug: (located in /views/config)

html
  head
    some header
  body
    h1 some body
    a("onepage") some text

In the app.ts: (only the important parts)

app.set("views", path.join(__dirname, "views"));
app.use("/config", configRouter);

In the configRouter.ts

const configRouter = express.Router();
configRouter.get("/", (req, res) => {
    res.render("config/index.pug");
});

Can someone help me?

When I press on the "some text" link i get navigated to mainpage/onepage instead of mainpage/config/onepage as I would expect.


问:
SQL Server & C#: How to save changes to date field after it has been converted to varchar format
I have a C# WinForms app that receives a date field (Start_Date) from an MS SQl Server database that has been converted to a varchar (10) format before displaying it in a textbox in my app. I convert it to a varchar format so that the time portion doesn't show up when it's displayed in the textbox.  Even though Start_Date  is a date and not datetime data type in the database, the WinForms app textbox automatically adds the unwanted time portion which is why I have to convert it.

However, when I save changes to the date in that textbox, it will not write those changes back to the database (presumably because it was converted to a varchar format for display). How can I show the Start_Date field in the textbox with only the date portion and not the time component and still allow changes to be made to that date field and then saved back to the database.

Thank you.

Here's the code when I pull the data from the database:

```<code>SELECT CONVERT (VARCHAR (10), Start_Date, 101) AS StartDate FROM Table1
</code>```

Here's the code binding the Start_Date field to the textbox from a data table called dt:

```<code>txtStart_Date.DataBindings.Add("Text", dt, "StartDate")
</code>```

Body:
I have a C# WinForms app that receives a date field (Start_Date) from an MS SQl Server database that has been converted to a varchar (10) format before displaying it in a textbox in my app. I convert it to a varchar format so that the time portion doesn't show up when it's displayed in the textbox.  Even though Start_Date  is a date and not datetime data type in the database, the WinForms app textbox automatically adds the unwanted time portion which is why I have to convert it.

However, when I save changes to the date in that textbox, it will not write those changes back to the database (presumably because it was converted to a varchar format for display). How can I show the Start_Date field in the textbox with only the date portion and not the time component and still allow changes to be made to that date field and then saved back to the database.

Thank you.

Here's the code when I pull the data from the database:

SELECT CONVERT (VARCHAR (10), Start_Date, 101) AS StartDate FROM Table1

Here's the code binding the Start_Date field to the textbox from a data table called dt:

txtStart_Date.DataBindings.Add("Text", dt, "StartDate")


问:
twitter bootstrap rails fields_for equivalent
I am working with a Rails 6.1 project and am using the twitter-bootstrap-rails gem to create a form using bootstrap_form_for for an object that has an association.

I would like to add the association fields to the form, and am finding that Rails has a fields_for, helper but I am not finding any equivalent in twitter-bootstrap-rails.

I was successfully using the fields_forhelper until I needed to create a form_group in it for radio buttons, where the data for the group is coming from an array of hashes.

Although the fields_forhelper does have the ability to create radio button groups, I am not seeing how to use a hash to populate the radio button fields.

How does one add form fields for an object's association, when using the twitter-bootstrap-rails gem maintaining the the full form_group capabilities?

If this isn't possible, can anyone point me to documentation on creating a radio button group under fields_for using an array of hashes as the data source?

Many thanks in advance for your suggestions.


问:
Cross Compiling IamGui with SDL2 and Vulkan from Ubuntu 22.04 LTS WSL on Rasptberry Pi 4 aarch64 with cmake and aarch64-linux-gnu-gcc/g++
I'm trying to cross compile from Win10 to Raspian OS on the Raspberry Pi 4. For this reason I use the Ubuntu 22.04 LTS WSL. I installed gcc/g++, CMake, Ninja, SDL2, Vulkan SDK, aarch64-linux-gnu-gcc/g++.

In the CMakeLists.txt I call find_package(SDL2 REQUIRED) and find_package(Vulkan REQUIRED).
When I compile with the normal gcc and g++ there is no problem, but when I try the aarch64-linux-gnu-gcc and aarch64-linux-gnu-g++

```<code>set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_CROSSCOMPILING TRUE)

set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
</code>```

Error message:

```<code>CMake Error at CMakeLists.txt:66 (find_package):
  By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2", but
  CMake did not find one.

  Could not find a package configuration file provided by "SDL2" with any of
  the following names:

    SDL2Config.cmake
    sdl2-config.cmake

  Add the installation prefix of "SDL2" to CMAKE_PREFIX_PATH or set
  "SDL2_DIR" to a directory containing one of the above files.  If "SDL2"
  provides a separate development package or SDK, be sure it has been
  installed.
</code>```

The libs can be found in the folder /usr/lib/x86_64-linux-gnu

Why are they not in the folder /usr/lib/aarch64-linux-gnu?
How can I use or install them for the aarch64-linux-gnu-gcc/g++?

Thank you in advance!

```<code>set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
</code>```

In this link at the bottom aarch64-linux-gnu files are mentioned, but there are non installed in my /usr/lib/aarch64-linux-gnu folder

https://ubuntu.pkgs.org/20.04/ubuntu-universe-arm64/libsdl2-dev_2.0.10+dfsg1-3_arm64.deb.html

Body:
I'm trying to cross compile from Win10 to Raspian OS on the Raspberry Pi 4. For this reason I use the Ubuntu 22.04 LTS WSL. I installed gcc/g++, CMake, Ninja, SDL2, Vulkan SDK, aarch64-linux-gnu-gcc/g++.

In the CMakeLists.txt I call find_package(SDL2 REQUIRED) and find_package(Vulkan REQUIRED).
When I compile with the normal gcc and g++ there is no problem, but when I try the aarch64-linux-gnu-gcc and aarch64-linux-gnu-g++

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_CROSSCOMPILING TRUE)

set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)

Error message:

CMake Error at CMakeLists.txt:66 (find_package):
  By not providing "FindSDL2.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2", but
  CMake did not find one.

  Could not find a package configuration file provided by "SDL2" with any of
  the following names:

    SDL2Config.cmake
    sdl2-config.cmake

  Add the installation prefix of "SDL2" to CMAKE_PREFIX_PATH or set
  "SDL2_DIR" to a directory containing one of the above files.  If "SDL2"
  provides a separate development package or SDK, be sure it has been
  installed.

The libs can be found in the folder /usr/lib/x86_64-linux-gnu

Why are they not in the folder /usr/lib/aarch64-linux-gnu?
How can I use or install them for the aarch64-linux-gnu-gcc/g++?

Thank you in advance!

set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)

In this link at the bottom aarch64-linux-gnu files are mentioned, but there are non installed in my /usr/lib/aarch64-linux-gnu folder

https://ubuntu.pkgs.org/20.04/ubuntu-universe-arm64/libsdl2-dev_2.0.10+dfsg1-3_arm64.deb.html


问:
Azure Signal R Service with Angular 13
I've been trying to setup an integration between an Angular 13 client-side app and a .NET Framework 4.8 API with an Azure Signal R Service. After much trial and error this week I have finally got my api to build without CORS errors and I can make a successful negotiate call using postman. I am using the @aspnet/signalr client-side package since that is the only signal R package that support Azure Signal R Services.

Below is the angular code I am using to make a connection to my signal R hub named DashboardHub

```<code>import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';

@Injectable()
export class SignalrService {
    public initializeSignalRConnection(): void {
        let connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:58556/signalr/dashboardhub")
        .configureLogging(signalR.LogLevel.Debug)
        .build();

        connection.start()
        .then(() => {
            console.log("connection.start");
            //connection.invoke("send", "Hello")
        })
        .catch((error) => {
            console.log("connection start error", error);
        });

        connection.on("send", data => {
            console.log(data);
        });
    }
}
</code>```

The problem I am having is within the connection.start which returns an error Cannot read properties of undefined (reading 'length'). Screenshot of that browser error below.

API Signal R mapping for context

And here is the DashboardHub for reference

Title: Azure Signal R Service with Angular 13

Body:
I've been trying to setup an integration between an Angular 13 client-side app and a .NET Framework 4.8 API with an Azure Signal R Service. After much trial and error this week I have finally got my api to build without CORS errors and I can make a successful negotiate call using postman. I am using the @aspnet/signalr client-side package since that is the only signal R package that support Azure Signal R Services.

Below is the angular code I am using to make a connection to my signal R hub named DashboardHub

import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';

@Injectable()
export class SignalrService {
    public initializeSignalRConnection(): void {
        let connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:58556/signalr/dashboardhub")
        .configureLogging(signalR.LogLevel.Debug)
        .build();

        connection.start()
        .then(() => {
            console.log("connection.start");
            //connection.invoke("send", "Hello")
        })
        .catch((error) => {
            console.log("connection start error", error);
        });

        connection.on("send", data => {
            console.log(data);
        });
    }
}

The problem I am having is within the connection.start which returns an error Cannot read properties of undefined (reading 'length'). Screenshot of that browser error below.

API Signal R mapping for context

And here is the DashboardHub for reference


问:
How can I attach an IoT Core policy to a Cognito Identity Id on a post authentication Lambda trigger for an Amplify deployed web application?
Situation:

I have a ReactJS web application that is deployed through AWS Amplify and uses Amplify Studio backend to handle authentication through Cognito services and aws-amplify sdk (sign in, sign up).

The web application also implements the use of react native aws-amplify sdk pubsub to subscribe to an MQTT topic in IoT Core and retrieve messages but only to authenticated users.

As per step 2 in the pubsub documentation: Attach your policy to your Amazon Cognito Identity.

If I use the AWS CLI to attach the IoT policy to the user and then I sign in with that user through the web application I am able to successfully subscribe and receive MQTT messages -- it works perectly!

Problem:

The application allows Cognito self-service user sign up (Self-registration) and expects to have many users.

I implemented a post authentication lambda trigger function in the Cognito user pool created by the Amplify service.

The lambda function runs the following sample from AWS documentation with two (2) additional console logs:

```<code>exports.handler = (event, context, callback) => {

    // Send post authentication data to Cloudwatch logs
    console.log ("Authentication successful");
    console.log ("Trigger function =", event.triggerSource);
    console.log ("User pool = ", event.userPoolId);
    console.log ("App client ID = ", event.callerContext.clientId);
    console.log ("User ID = ", event.userName);

*** console.log("Event = ", event);
    console.log("Context = ", context);***

    // Return to Amazon Cognito
    callback(null, event);
};
</code>```

I then authenticate with the user again through the application and go to CloudWatch logs for that Lambda function.

This is the information I get from logging Event and Context after post authentication trigger:

Event log:

```<code>{
  version: '1',
  region: 'us-east-1',
  userPoolId: 'us-east-1_*********',
  userName: '4eea4a48-92b6-45da-b26e-*********',
  callerContext: {
    awsSdkVersion: 'aws-sdk-unknown-unknown',
    clientId: '*********'
  },
  triggerSource: 'PostAuthentication_Authentication',
  request: {
    userAttributes: {
      sub: '4eea4a48-92b6-45da-b26e-*********',
      'cognito:email_alias': '*********.com',
      'cognito:user_status': 'CONFIRMED',
      email_verified: 'true',
      name: 'asdfasdf',
      email: '*********.com'
    },
    newDeviceUsed: false
  },
  response: {}
}
</code>```

Context log:

```<code>{
  callbackWaitsForEmptyEventLoop: [Getter/Setter],
  succeed: [Function (anonymous)],
  fail: [Function (anonymous)],
  done: [Function (anonymous)],
  functionVersion: '$LATEST',
  functionName: 'userAccess_iotCore_attachPolicyToCognitoIdentityID',
  memoryLimitInMB: '128',
  logGroupName: '/aws/lambda/userAccess_iotCore_attachPolicyToCognitoIdentityID',
  logStreamName: '2023/01/13/[$LATEST]4eb4287aa4db4dd8a6b6efd810a7***',
  clientContext: undefined,
  identity: undefined,
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:*********:function:userAccess_iotCore_attachPolicyToCognitoIdentityID',
  awsRequestId: 'bf6afd1c-117c-4a9e-9d3b-*********',
  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis]
}
</code>```

The big issue here is that context.identity is undefined so I am not able to get that authenticated user's Amazon Cognito Identity Id to attach the required IoT policy for PubSub to work through the application.

Questions:

How can I get the Amazon Cognito Identity Id after post authentication trigger to then attach an IoT policy?

From the web application using the aws-amplify sdk I am able to get this Id after sign in. Is there any API I can use from the application to attach this policy?

Thanks.

Body:
Situation:

I have a ReactJS web application that is deployed through AWS Amplify and uses Amplify Studio backend to handle authentication through Cognito services and aws-amplify sdk (sign in, sign up).

The web application also implements the use of react native aws-amplify sdk pubsub to subscribe to an MQTT topic in IoT Core and retrieve messages but only to authenticated users.

As per step 2 in the pubsub documentation: Attach your policy to your Amazon Cognito Identity.

If I use the AWS CLI to attach the IoT policy to the user and then I sign in with that user through the web application I am able to successfully subscribe and receive MQTT messages -- it works perectly!

Problem:

The application allows Cognito self-service user sign up (Self-registration) and expects to have many users.

I implemented a post authentication lambda trigger function in the Cognito user pool created by the Amplify service.

The lambda function runs the following sample from AWS documentation with two (2) additional console logs:

exports.handler = (event, context, callback) => {

    // Send post authentication data to Cloudwatch logs
    console.log ("Authentication successful");
    console.log ("Trigger function =", event.triggerSource);
    console.log ("User pool = ", event.userPoolId);
    console.log ("App client ID = ", event.callerContext.clientId);
    console.log ("User ID = ", event.userName);

*** console.log("Event = ", event);
    console.log("Context = ", context);***

    // Return to Amazon Cognito
    callback(null, event);
};

I then authenticate with the user again through the application and go to CloudWatch logs for that Lambda function.

This is the information I get from logging Event and Context after post authentication trigger:

Event log:

{
  version: '1',
  region: 'us-east-1',
  userPoolId: 'us-east-1_*********',
  userName: '4eea4a48-92b6-45da-b26e-*********',
  callerContext: {
    awsSdkVersion: 'aws-sdk-unknown-unknown',
    clientId: '*********'
  },
  triggerSource: 'PostAuthentication_Authentication',
  request: {
    userAttributes: {
      sub: '4eea4a48-92b6-45da-b26e-*********',
      'cognito:email_alias': '*********.com',
      'cognito:user_status': 'CONFIRMED',
      email_verified: 'true',
      name: 'asdfasdf',
      email: '*********.com'
    },
    newDeviceUsed: false
  },
  response: {}
}

Context log:

{
  callbackWaitsForEmptyEventLoop: [Getter/Setter],
  succeed: [Function (anonymous)],
  fail: [Function (anonymous)],
  done: [Function (anonymous)],
  functionVersion: '$LATEST',
  functionName: 'userAccess_iotCore_attachPolicyToCognitoIdentityID',
  memoryLimitInMB: '128',
  logGroupName: '/aws/lambda/userAccess_iotCore_attachPolicyToCognitoIdentityID',
  logStreamName: '2023/01/13/[$LATEST]4eb4287aa4db4dd8a6b6efd810a7***',
  clientContext: undefined,
  identity: undefined,
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:*********:function:userAccess_iotCore_attachPolicyToCognitoIdentityID',
  awsRequestId: 'bf6afd1c-117c-4a9e-9d3b-*********',
  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis]
}

The big issue here is that context.identity is undefined so I am not able to get that authenticated user's Amazon Cognito Identity Id to attach the required IoT policy for PubSub to work through the application.

Questions:

How can I get the Amazon Cognito Identity Id after post authentication trigger to then attach an IoT policy?

From the web application using the aws-amplify sdk I am able to get this Id after sign in. Is there any API I can use from the application to attach this policy?

Thanks.


问:
Convert the elastic search response to a list
I am using elastic 7.17.3 and NEST 7.17.3
I have a elastic response which I am trying to put in a list. I have below method. The method is generic and is called from different model classes.

```<code>public class Account
    {
        [JsonProperty(AnalyticsFields.AccessRegions)]
        public string[] AccessRegions { get; set; }
        [JsonProperty(AnalyticsFields.AccessUsers)]
        public string[] AccessUsers { get; set; }
        [JsonProperty(AnalyticsFields.AccountId)]
        public string AccountId { get; set; }
        [JsonProperty(AnalyticsFields.AccountIdAndName)]
        public string AccountIdAndName { get; set; }
        [JsonProperty(AnalyticsFields.AdvisorId)]
        public string AdvisorId { get; set; }
        [JsonProperty(AnalyticsFields.AdvisorIdAndName)]
        public string AdvisorIdAndName { get; set; }

    }
</code>```

This is how the method converting the elastic response looks like

```<code>private void AddSearchResponseHits<T>(ISearchResponse<T> searchResponse, List<T> results) where T : class
        {
            results.AddRange(searchResponse.Hits.Select(h => h.Source).ToArray());
        }
</code>```

The problem is the field value becomes null even thought the searchresponse have the complete response from elastic. Please help me out. The field values should load in respective properties in the model class.

Body:
I am using elastic 7.17.3 and NEST 7.17.3
I have a elastic response which I am trying to put in a list. I have below method. The method is generic and is called from different model classes.

public class Account
    {
        [JsonProperty(AnalyticsFields.AccessRegions)]
        public string[] AccessRegions { get; set; }
        [JsonProperty(AnalyticsFields.AccessUsers)]
        public string[] AccessUsers { get; set; }
        [JsonProperty(AnalyticsFields.AccountId)]
        public string AccountId { get; set; }
        [JsonProperty(AnalyticsFields.AccountIdAndName)]
        public string AccountIdAndName { get; set; }
        [JsonProperty(AnalyticsFields.AdvisorId)]
        public string AdvisorId { get; set; }
        [JsonProperty(AnalyticsFields.AdvisorIdAndName)]
        public string AdvisorIdAndName { get; set; }

    }

This is how the method converting the elastic response looks like

private void AddSearchResponseHits<T>(ISearchResponse<T> searchResponse, List<T> results) where T : class
        {
            results.AddRange(searchResponse.Hits.Select(h => h.Source).ToArray());
        }

The problem is the field value becomes null even thought the searchresponse have the complete response from elastic. Please help me out. The field values should load in respective properties in the model class.


问:
Typescript can't infer function generic type with parameters type
i have a very specific problem
consider this signature

```<code>public async createSubscriberChannel<
    T extends Messages.PubsubParams,
    K extends Messages.PubsubMessage<T>
  >(metadata: ChannelMetadata<T, K, TbNextgenQueue>, args: SubscriberArgs<T>)
</code>```

and this call

```<code>const publisherChannel = await rabbitmqController.createPublisherChannel(
    new TaskCreatedMetadata(),
    {
      exchange: TbNextgenExchange.TASK_CREATED,
      exchangeOptions: {
        durable: false,
      },
    }
  );
</code>```

with TaskCreatedMetadata

```<code>export class TaskCreatedMetadata extends ChannelMetadata<
  Messages.TaskCreatedParams,
  Messages.PubsubMessage<Messages.TaskCreatedParams>,
  TbNextgenQueue.TASK_CREATED
> {
  readonly queueName = TbNextgenQueue.TASK_CREATED;
}
</code>```

now when i call the createSubscriberChannel function is not infering that T is of type Messages.TaskCreatedParams , is considering Messages.PubsubParams. I want that inference, is there any way to make it work as i expect ?

I am expecting to infer T generic using argument type

Body:
i have a very specific problem
consider this signature

public async createSubscriberChannel<
    T extends Messages.PubsubParams,
    K extends Messages.PubsubMessage<T>
  >(metadata: ChannelMetadata<T, K, TbNextgenQueue>, args: SubscriberArgs<T>)

and this call

const publisherChannel = await rabbitmqController.createPublisherChannel(
    new TaskCreatedMetadata(),
    {
      exchange: TbNextgenExchange.TASK_CREATED,
      exchangeOptions: {
        durable: false,
      },
    }
  );

with TaskCreatedMetadata

export class TaskCreatedMetadata extends ChannelMetadata<
  Messages.TaskCreatedParams,
  Messages.PubsubMessage<Messages.TaskCreatedParams>,
  TbNextgenQueue.TASK_CREATED
> {
  readonly queueName = TbNextgenQueue.TASK_CREATED;
}

now when i call the createSubscriberChannel function is not infering that T is of type Messages.TaskCreatedParams , is considering Messages.PubsubParams. I want that inference, is there any way to make it work as i expect ?

I am expecting to infer T generic using argument type


问:
cant play audio using Ipython.display.Audio in Pycharm, but works in jupyter notebook
when I try in Pycharm to play an audio sound using the following code, it doesn't work. the code finishes without error, but nothing happens.
the same code works in Jupyter notebook and will create a small interface to play the audio sound. How can I make it work in Pycharm as well?

below is the code that works in Jupyter notebook

```<code>import numpy as np
import IPython.display as ipd
seconds=1
sample_rate=4000
t=np.arange( int(seconds*sample_rate) ) / sample_rate
x=np.sin(2*np.pi*440*t)
sound=ipd.display(ipd.Audio(data=x, rate=sample_rate))
</code>```

Body:
when I try in Pycharm to play an audio sound using the following code, it doesn't work. the code finishes without error, but nothing happens.
the same code works in Jupyter notebook and will create a small interface to play the audio sound. How can I make it work in Pycharm as well?

below is the code that works in Jupyter notebook

import numpy as np
import IPython.display as ipd
seconds=1
sample_rate=4000
t=np.arange( int(seconds*sample_rate) ) / sample_rate
x=np.sin(2*np.pi*440*t)
sound=ipd.display(ipd.Audio(data=x, rate=sample_rate))


问:
spark read stream from parquet source
```<code>job1 -> parquet files [inputPath] -> job2 -> delta table [outputPath]
</code>```

job1 writes stream to parquet files which are up to 3 days old.

I want to start job2 which will start from latest streamed files and will process latest only so will not try to process data that is older than last hour if i start now.

Right now I do:

```<code>val outDF = spark
    .readStream
    .option("latestFirst", "true")
    .option("maxFilesPerTrigger", "10000")
    .schema(Encoders.product[InputData].schema)
    .parquet(inputPath)
    .transform(Processor().process)

StreamDeltaWriter
  .write(outDF, outputPath, partitioningCols, checkpointLocation)
  .awaitTermination()
</code>```

The issue i have is that it starts with latest files then it processes backwards so it does not processes latest arriving file as it tries to process all historical files first.

How to solve it?

EDIT:

according to documentation if latestFirst true if set together with maxFilesPerTrigger then maxFileAge is ignored.

Would maxFileAge work if I do latestFirst only without maxFilesPerTrigger ?

Title: spark read stream from parquet source

Body:
job1 -> parquet files [inputPath] -> job2 -> delta table [outputPath]

job1 writes stream to parquet files which are up to 3 days old.

I want to start job2 which will start from latest streamed files and will process latest only so will not try to process data that is older than last hour if i start now.

Right now I do:

val outDF = spark
    .readStream
    .option("latestFirst", "true")
    .option("maxFilesPerTrigger", "10000")
    .schema(Encoders.product[InputData].schema)
    .parquet(inputPath)
    .transform(Processor().process)

StreamDeltaWriter
  .write(outDF, outputPath, partitioningCols, checkpointLocation)
  .awaitTermination()

The issue i have is that it starts with latest files then it processes backwards so it does not processes latest arriving file as it tries to process all historical files first.

How to solve it?

EDIT:

according to documentation if latestFirst true if set together with maxFilesPerTrigger then maxFileAge is ignored.

Would maxFileAge work if I do latestFirst only without maxFilesPerTrigger ?


问:
How to pass local arguments to "kpt fn render"?
I am trying to parameterize the kpt fn render pipeline.

I know that kpt pkg get automagically creates the package-context.yaml file containing a ConfigMap that in turn contains the name of the local kpt package. That is a good start, but what if I want to add additional local parameters to the pipeline between kpt pkg get and kpt fn render? Are there any best practices for this, or is this considered an anti-pattern for some reason?

Our current approach is to pass the parameters as environment variables, and the first step of the pipeline (a Starlark script) injects a ConfigMap with the parameters into the package. The rest of the pipeline steps refer to the fields of this "parameters" ConfigMap. Is there a better way?


问:
Integrating Type Tests into Unit Tests with Typescript
I have grown very used to creating "type tests" in my Typescript projects which depend on narrow typing and I do this using the @type-challenges/utils type utilities. So for instance here is a test I have in one of my repos:

```<code>describe("example of a type test", () => {

  it("SetRemoval<TSet, TRemoval>", () => {
    type Set1 = ["foo", "bar", "baz"];
    type Set2 = ["bat-shit-crazy", "never mind"];

    type T1 = SetRemoval<Set1, "foo">;
    type T2 = SetRemoval<Set1, ["foo"]>;
    type T3 = SetRemoval<[...Set1, ...Set2], ["foo", "never mind"]>;

    type cases = [
      Expect<Equal<T1, readonly ["bar", "baz"]>>,
      Expect<Equal<T2, readonly ["bar", "baz"]>>,
      Expect<Equal<T3, readonly ["bar", "baz", "bat-shit-crazy"]>>,
    ];
    const cases: cases = [ true, true, true ];
  });

});
</code>```

What this type utility is not important only that you can see the "shape" of how a test of the type system can be incorporated into a traditional unit testing framework.

The great thing about this type of testing is that:

type errors become immediately visible in any editor which highlights type errors

using tsc over the test files can be used to ensure no type errors exist across tests

Today I use Vitest primarily for unit testing but before that I used Jest, Mocha, and UVU. Most of these test runners will fully ignore type errors and UVU refused to run if there was a type error anywhere in the file. Neither condition is ideal as your "type tests" are either summarized as passing or you lose a lot of test coverage (aka, all tests in a file) whenever there is a type error.

What I would like is the ability to simply test the type validity of a "block" of code rather than a file's. I'm sure this can be created and I've been known to re-create the wheel from time to time but secretly hoping that someone knows of some tooling to do this that already exists in the wild.

Body:
I have grown very used to creating "type tests" in my Typescript projects which depend on narrow typing and I do this using the @type-challenges/utils type utilities. So for instance here is a test I have in one of my repos:

describe("example of a type test", () => {

  it("SetRemoval<TSet, TRemoval>", () => {
    type Set1 = ["foo", "bar", "baz"];
    type Set2 = ["bat-shit-crazy", "never mind"];

    type T1 = SetRemoval<Set1, "foo">;
    type T2 = SetRemoval<Set1, ["foo"]>;
    type T3 = SetRemoval<[...Set1, ...Set2], ["foo", "never mind"]>;

    type cases = [
      Expect<Equal<T1, readonly ["bar", "baz"]>>,
      Expect<Equal<T2, readonly ["bar", "baz"]>>,
      Expect<Equal<T3, readonly ["bar", "baz", "bat-shit-crazy"]>>,
    ];
    const cases: cases = [ true, true, true ];
  });

});

What this type utility is not important only that you can see the "shape" of how a test of the type system can be incorporated into a traditional unit testing framework.

The great thing about this type of testing is that:

type errors become immediately visible in any editor which highlights type errors

using tsc over the test files can be used to ensure no type errors exist across tests

Today I use Vitest primarily for unit testing but before that I used Jest, Mocha, and UVU. Most of these test runners will fully ignore type errors and UVU refused to run if there was a type error anywhere in the file. Neither condition is ideal as your "type tests" are either summarized as passing or you lose a lot of test coverage (aka, all tests in a file) whenever there is a type error.

What I would like is the ability to simply test the type validity of a "block" of code rather than a file's. I'm sure this can be created and I've been known to re-create the wheel from time to time but secretly hoping that someone knows of some tooling to do this that already exists in the wild.


问:
document.getElementsByClassName(class) does not get a live copy of the current HTML (angular)
I'm trying to apply the following function after changing the content but let elements keeps getting the same content when converElemntsToSpanElemnts()(on click) was fired the first time (old value) if there a way to get a live copy of the current HTML

the function now keeps replacing the new content with the old content that it got at the first time I ran the function

```<code>converElemntsToSpanElemnts(className) {
    let elements = document.getElementsByClassName(className);
    Array.from(elements as HTMLCollectionOf<HTMLElement>).forEach((element, index) => {
        element.innerHTML = element.innerHTML.replace(/(<div)/igm, '<span').replace(/<\/div>/igm, '</span>');
        element.innerHTML = element.innerHTML.replace(/(<app-ckeditor-view-content)/igm, '<span').replace(/<\/app-ckeditor-view-content>/igm, '</span>');
        element.innerHTML = element.innerHTML.replace(/(<p)/igm, '<span').replace(/<\/p>/igm, '</span>');
    })
}
</code>```

Body:
I'm trying to apply the following function after changing the content but let elements keeps getting the same content when converElemntsToSpanElemnts()(on click) was fired the first time (old value) if there a way to get a live copy of the current HTML

the function now keeps replacing the new content with the old content that it got at the first time I ran the function

converElemntsToSpanElemnts(className) {
    let elements = document.getElementsByClassName(className);
    Array.from(elements as HTMLCollectionOf<HTMLElement>).forEach((element, index) => {
        element.innerHTML = element.innerHTML.replace(/(<div)/igm, '<span').replace(/<\/div>/igm, '');
        element.innerHTML = element.innerHTML.replace(/(<app-ckeditor-view-content)/igm, '<span').replace(/<\/app-ckeditor-view-content>/igm, '');
        element.innerHTML = element.innerHTML.replace(/(<p)/igm, '<span').replace(/<\/p>/igm, '');
    })
}


问:
Type support for dynamically added instance variable
Because of working a lot with a 3rd party code (Django-ORM), I need to add some variables to the class that are not declared initially.

The simplest Python example would be:

def enrich(obj):
    obj.c = 5
    return obj
```
<p>It works in Python, but strict type checking fails, and I want to benefit from static type analysis</p>
<p>Full example:</p>
<pre class="lang-py prettyprint-override"><code>import typing

class A:
    a = 1
    b = 2

class IExt(typing.Protocol):
    c: int

T = typing.TypeVar('T')

def enrich(obj: T) -> IExt | T:
    typing.cast(IExt, obj).c = 5
    return obj

a = A()

print(a.a)  # OK - Works because class is used explicitly
print(enrich(a).c)  # Not OK - Auto-complete works, but type checking shows error
print(enrich(a).b)  # Not OK - Auto-complete works, but type checking shows error
print(enrich(a).x)  # OK - Fails and is expected to fail
</code>```

The error says

```<code>main.py:21: error: Item "A" of "Union[IExt, A]" has no attribute "c"  [union-attr]
main.py:22: error: Item "IExt" of "Union[IExt, A]" has no attribute "b"  [union-attr]
</code>```

I understand that Union is a bit wrong choice here, because it says that variable is either of two types.

What I want to do is to explain type checker that return type extends Type[T]

So I'd like to do something like

```<code>class IExt(typing.Protocol[T], typing.Type[T]):
    c: int = 0
</code>```

But looks like this is not possible. Any ideas for the workaround?

I definitely want to keep it Generic, as A here is just example.

Body:
Because of working a lot with a 3rd party code (Django-ORM), I need to add some variables to the class that are not declared initially.

The simplest Python example would be:

def enrich(obj):
    obj.c = 5
    return obj

It works in Python, but strict type checking fails, and I want to benefit from static type analysis

Full example:

import typing

class A:
    a = 1
    b = 2

class IExt(typing.Protocol):
    c: int

T = typing.TypeVar('T')

def enrich(obj: T) -> IExt | T:
    typing.cast(IExt, obj).c = 5
    return obj

a = A()

print(a.a)  # OK - Works because class is used explicitly
print(enrich(a).c)  # Not OK - Auto-complete works, but type checking shows error
print(enrich(a).b)  # Not OK - Auto-complete works, but type checking shows error
print(enrich(a).x)  # OK - Fails and is expected to fail

The error says

main.py:21: error: Item "A" of "Union[IExt, A]" has no attribute "c"  [union-attr]
main.py:22: error: Item "IExt" of "Union[IExt, A]" has no attribute "b"  [union-attr]

I understand that Union is a bit wrong choice here, because it says that variable is either of two types.

What I want to do is to explain type checker that return type extends Type[T]

So I'd like to do something like

class IExt(typing.Protocol[T], typing.Type[T]):
    c: int = 0

But looks like this is not possible. Any ideas for the workaround?

I definitely want to keep it Generic, as A here is just example.


问:
Electron builder works on development but not on install
I'm trying to follow other people who had a similar issue like this one
Electron-Builder include external folder I wish i could be more specific on what my problem is, the reason is that i dont know whats wrong.

I am making a react app which has a server with an sqlite db and im trying to use electron.js to make it into an installable/executable

here is my dummy repo https://github.com/Juan321654/electron_react_with_build_installer_sqlite_db the master branch was just how to make electron work with react, the server branch is the one that i need help with
you can clone and just do npm i, npm run start to launch executable. npm run build to build

the code works fine in development mode and even after i make the build project with electron i can launch the executable and it works fine and it reads the data from the database, but as soon as i take the dist folder out of the project to send to someone or install the software, it stops working and it loads the app, but it does not read the data from the server/db, I am not sure if its missing node modules or the server folder, or maybe if im missing some kind of command in my scripts in the package.json?


问:
DiagnosticAnalyzer for type usage
I would like to write DiagnosticAnalyzer, which analyzes if a class (ie. BotAggregate) declared in a MyProject.Domain assembly has it's own DbSet<BotAggregate> declared in MyProjectDbContext class which is placed in MyProject.EFCore assembly.

When I do place the analyzer in MyProject.EFCore project, it does not even see the BotAggregate class declaration (because it scans the assembly where analyzer is referenced). And if I place the analyzer in MyProject.Domain it could not access the MyProjectDbContext to check if there is a required property.

Is it even possible to "cross check" the declaration and usage by Roslyn analyzer?

Title: DiagnosticAnalyzer for type usage


问:
How can I make smooth ASCII animation within the VS terminal?
I'm trying to make it to where I get smooth animations within the visual studio terminal with ASCII.

I've tried looking and everywhere and I cant find a good solution. I have a grid of numbers such as

```<code>000000000
000000000
000000000
000000000
000000000
</code>```

and I want to clear the console and update the grid. The problem is when I clear the terminal with "\033[H\033[2J" it works, and I can rewrite the updated grid. But it gets a blocky glitchy flickery look to it. So, I tried pausing the thread in the correct place but that made it even worse. So, I came to the conclusion that maybe I could only change what number or little sector such as (0,0) and that would eliminate the blocky-ness on all the other numbers or sectors but the ones that were changed would still appear blocky. I am trying to make Snake so this could replace the smooth motion of the snake if I made it in a retro style. However, I can't figure out what String is used to position the cursor or delete and replace a specific character. Any help would be appreciated.

My code for testing:

```<code>import java.util.*;
public class TerminalSnake{
    public static void main(String[] args){
        while(true){
            System.out.print("\033[H\033[2J");
            // System.out.flush();
            for(int i = 0; i<10; i++){
                System.out.println("0000000000000000");
            }
            try{
                Thread.sleep(50);
            } catch(InterruptedException e) {
            }
        }
    }
}
</code>```

Body:
I'm trying to make it to where I get smooth animations within the visual studio terminal with ASCII.

I've tried looking and everywhere and I cant find a good solution. I have a grid of numbers such as

000000000
000000000
000000000
000000000
000000000

and I want to clear the console and update the grid. The problem is when I clear the terminal with "\033[H\033[2J" it works, and I can rewrite the updated grid. But it gets a blocky glitchy flickery look to it. So, I tried pausing the thread in the correct place but that made it even worse. So, I came to the conclusion that maybe I could only change what number or little sector such as (0,0) and that would eliminate the blocky-ness on all the other numbers or sectors but the ones that were changed would still appear blocky. I am trying to make Snake so this could replace the smooth motion of the snake if I made it in a retro style. However, I can't figure out what String is used to position the cursor or delete and replace a specific character. Any help would be appreciated.

My code for testing:

import java.util.*;
public class TerminalSnake{
    public static void main(String[] args){
        while(true){
            System.out.print("\033[H\033[2J");
            // System.out.flush();
            for(int i = 0; i<10; i++){
                System.out.println("0000000000000000");
            }
            try{
                Thread.sleep(50);
            } catch(InterruptedException e) {
            }
        }
    }
}


问:
Apollo cache error on deleted "child" table
NOTE:  the __typename Client below refers to a person (like a customer) - not client/server.

Getting the following error:
Cache data may be lost when replacing the clientServices field of a Client object.

To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Client.clientServices field, so InMemoryCache can safely merge these objects:

```<code>  existing: [{"__ref":"ClientService:46"}]
  incoming: []
</code>```

What's happening is that I've deleted a "child" record - so there's no data.

```<code>First time I get this returned.  Note: there's info associated with field clientServices
    {
    "client": {
        "id": "41",
        "companyId": "3",
        "firstName": "Lew",
        "lastName": "Terry",
        "email": "lewterry@diamond.com",
        "clientServices": [
            {
                "id": "46",
                "serviceId": "13",
                "description": "Individual psychotherapy - 45 minutes",
                "sessionFee": 90,
                "cptCode": "90834",
                "__typename": "ClientService"
            }
        ],
        "__typename": "Client"
    }
}

And here's the results on a refetch after the client record is saved and the clientServices "child" data has been deleted so it's an empty array.

{
    "client": {
        "id": "41",
        "companyId": "3",
        "firstName": "Lew",
        "lastName": "Terry",
        "email": "lewterry@diamond.com",
    clientServices: []
        "__typename": "Client"
    }
}

</code>```

Do I really need a custom merge?  Or is there another solution?

Body:
NOTE:  the __typename Client below refers to a person (like a customer) - not client/server.

Getting the following error:
Cache data may be lost when replacing the clientServices field of a Client object.

To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Client.clientServices field, so InMemoryCache can safely merge these objects:

  existing: [{"__ref":"ClientService:46"}]
  incoming: []

What's happening is that I've deleted a "child" record - so there's no data.

First time I get this returned.  Note: there's info associated with field clientServices
    {
    "client": {
        "id": "41",
        "companyId": "3",
        "firstName": "Lew",
        "lastName": "Terry",
        "email": "lewterry@diamond.com",
        "clientServices": [
            {
                "id": "46",
                "serviceId": "13",
                "description": "Individual psychotherapy - 45 minutes",
                "sessionFee": 90,
                "cptCode": "90834",
                "__typename": "ClientService"
            }
        ],
        "__typename": "Client"
    }
}

And here's the results on a refetch after the client record is saved and the clientServices "child" data has been deleted so it's an empty array.

{
    "client": {
        "id": "41",
        "companyId": "3",
        "firstName": "Lew",
        "lastName": "Terry",
        "email": "lewterry@diamond.com",
    clientServices: []
        "__typename": "Client"
    }
}

Do I really need a custom merge?  Or is there another solution?


问:
Grid Search for hyperParameters
I build that net for classify in an image if the person is wearing sunglasses or not, load the data, and train it:

```<code># Define the model
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

# Initialize the model, loss function, and optimizer
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

data = []
labels = []
for inputs, target in train_loader:
    data.append(inputs)
    labels.append(target)

# Train the model
num_epochs = 10
for epoch in range(num_epochs):
    for i, (inputs, labels) in enumerate(train_loader):
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

    # Evaluation on validation set
    correct = 0
    total = 0
    with torch.no_grad():
        for inputs, labels in val_loader:
            outputs = model(inputs)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    val_acc = correct / total
    print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}, Validation Acc: {val_acc:.4f}')
</code>```

I want to do a grid search.

How can I do a grid search for the hyper-parameters?

Which parameters can I do that?

Title: Grid Search for hyperParameters

Body:
I build that net for classify in an image if the person is wearing sunglasses or not, load the data, and train it:

# Define the model
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

# Initialize the model, loss function, and optimizer
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

data = []
labels = []
for inputs, target in train_loader:
    data.append(inputs)
    labels.append(target)

# Train the model
num_epochs = 10
for epoch in range(num_epochs):
    for i, (inputs, labels) in enumerate(train_loader):
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

    # Evaluation on validation set
    correct = 0
    total = 0
    with torch.no_grad():
        for inputs, labels in val_loader:
            outputs = model(inputs)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    val_acc = correct / total
    print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}, Validation Acc: {val_acc:.4f}')

I want to do a grid search.

How can I do a grid search for the hyper-parameters?

Which parameters can I do that?


问:
Azure Test Plans - If a test step fails in Test Plans, can I change the button to create other kind of work item instead of a Bug?
We are current using a work item called "fix" to bugs that are discovered before production, and using test plans. The work item "bug" is used only for bugs that are found already inproduction. Is it possible to manage the Azure test plans to change the "bug" creation to a "fix" creation (already as a child of the originary US would be great).

The point is related in the help article: https://learn.microsoft.com/en-us/azure/devops/test/run-manual-tests?view=azure-devops#create-or-add-to-a-bug

I was not able to find more information.

Thank you very much in advance!

I was expecting to be able to change the item, but I couldn't.


问:
How to get rid of this warning consider registering a custom JavaTypeDescriptor or at least implementing equals/hashCode?
I am getting the following warning,

Encountered Java type [class java.lang.Object] for which we could not
locate a JavaTypeDescriptor and which does not appear to implement
equals and/or hashCode.  This can lead to significant performance
problems when performing equality/dirty checking involving this Java
type. Consider registering a custom JavaTypeDescriptor or at least
implementing equals/hashCode.

I am implementing an application using Spring Boot with Spring Data JPA. I have a class as follows,

```<code>public abstract class SomeClass implements Serializable {

   @Convert(converter = SomeConverter.class)
   private Object someEntity;
}
</code>```

I had to use the Object someEntity because there are multiple classes eligible for that someEntity so I had to use the type as Object. And all the eligible someEntity classes are also extended a superclass but it is an abstract class, so cannot put it here.

Since that warning is there I created a JavaTypeDescriptor as follows,

```<code>public class ObjectJavaTypeDescriptor implements JavaTypeDescriptor<Object> {

    @Override
    public boolean areEqual(Object one, Object another) {
        return one == another || (one != null && one.equals(another));
    }

    @Override
    public Class<Object> getJavaTypeClass() {
        return Object.class;
    }

    @Override
    public int extractHashCode(Object value) {
        return value.hashCode();
    }

    @Override
    public String toString(Object value) {
        return value.toString();
    }

    @Override
    public Object fromString(String string) {
        throw new UnsupportedOperationException("Not supported");
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public <X> X unwrap(Object value, Class<X> type, WrapperOptions options) {
        if (value == null) {
            return null;
        }
        if (Object.class.isAssignableFrom(type)) {
            return (X) value;
        }
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public <X> Object wrap(X value, WrapperOptions options) {
        return value;
    }
}
</code>```

And I tried the following 2 methods to register this TypeDescriptor,

```<code>@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer() {
    return hibernateProperties -> hibernateProperties.put("hibernate.type_descriptors.object",
            "com.example.ObjectJavaTypeDescriptor");
}
</code>```

and this property,

```<code>spring.jpa.properties.hibernate.type_descriptors.object=com.example.ObjectJavaTypeDescriptor
</code>```

But still, the warning is showing, and I see the application is little bit stuck at the starting and also taking some more time to start. How to resolve this issue? Anybody can help me? Thank you.

Body:
I am getting the following warning,

Encountered Java type [class java.lang.Object] for which we could not
locate a JavaTypeDescriptor and which does not appear to implement
equals and/or hashCode.  This can lead to significant performance
problems when performing equality/dirty checking involving this Java
type. Consider registering a custom JavaTypeDescriptor or at least
implementing equals/hashCode.

I am implementing an application using Spring Boot with Spring Data JPA. I have a class as follows,

public abstract class SomeClass implements Serializable {

   @Convert(converter = SomeConverter.class)
   private Object someEntity;
}

I had to use the Object someEntity because there are multiple classes eligible for that someEntity so I had to use the type as Object. And all the eligible someEntity classes are also extended a superclass but it is an abstract class, so cannot put it here.

Since that warning is there I created a JavaTypeDescriptor as follows,

public class ObjectJavaTypeDescriptor implements JavaTypeDescriptor<Object> {

    @Override
    public boolean areEqual(Object one, Object another) {
        return one == another || (one != null && one.equals(another));
    }

    @Override
    public Class<Object> getJavaTypeClass() {
        return Object.class;
    }

    @Override
    public int extractHashCode(Object value) {
        return value.hashCode();
    }

    @Override
    public String toString(Object value) {
        return value.toString();
    }

    @Override
    public Object fromString(String string) {
        throw new UnsupportedOperationException("Not supported");
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public <X> X unwrap(Object value, Class<X> type, WrapperOptions options) {
        if (value == null) {
            return null;
        }
        if (Object.class.isAssignableFrom(type)) {
            return (X) value;
        }
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public <X> Object wrap(X value, WrapperOptions options) {
        return value;
    }
}

And I tried the following 2 methods to register this TypeDescriptor,

@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer() {
    return hibernateProperties -> hibernateProperties.put("hibernate.type_descriptors.object",
            "com.example.ObjectJavaTypeDescriptor");
}

and this property,

spring.jpa.properties.hibernate.type_descriptors.object=com.example.ObjectJavaTypeDescriptor

But still, the warning is showing, and I see the application is little bit stuck at the starting and also taking some more time to start. How to resolve this issue? Anybody can help me? Thank you.