问:
Make tools very janky (inconsistent across MSYS, Powershell, VSCode)
Attempting to use make, touch... When using make in MSYS, I receive the following error:

```<code>$ make
arm-none-eabi-gcc main.c  -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion -Wformat-truncation -fno-common -Wconversion -g3 -Os -ffunction-sections -fdata-sections -I. -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16  -Tlink.ld -nostartfiles -nostdlib --specs nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=firmware.elf.map -o firmware.elf
make: arm-none-eabi-gcc: No such file or directory
make: *** [Makefile:11: firmware.elf] Error 127
</code>```

I can use make in powershell or VSCode terminal, however. Though, when I try to use touch in VSCode terminal or powershell, I get the following error.

```<code>touch main.c
touch : The term 'touch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
</code>```

I'm fairly new to everything so setting up environment variables has been messy. I'm trying to follow this guide https://github.com/cpq/bare-metal-programming-guide and it's been rocky. Any help would be greatly appreciated!

I've tried editing shortening PATH directory lengths since I saw it mentioned as a point for strange behavior. That and most else of what I've tried has not helped.

Body:
Attempting to use make, touch... When using make in MSYS, I receive the following error:

$ make
arm-none-eabi-gcc main.c  -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion -Wformat-truncation -fno-common -Wconversion -g3 -Os -ffunction-sections -fdata-sections -I. -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16  -Tlink.ld -nostartfiles -nostdlib --specs nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=firmware.elf.map -o firmware.elf
make: arm-none-eabi-gcc: No such file or directory
make: *** [Makefile:11: firmware.elf] Error 127

I can use make in powershell or VSCode terminal, however. Though, when I try to use touch in VSCode terminal or powershell, I get the following error.

touch main.c
touch : The term 'touch' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

I'm fairly new to everything so setting up environment variables has been messy. I'm trying to follow this guide https://github.com/cpq/bare-metal-programming-guide and it's been rocky. Any help would be greatly appreciated!

I've tried editing shortening PATH directory lengths since I saw it mentioned as a point for strange behavior. That and most else of what I've tried has not helped.


来源: stackexchange

问:
How to reconstruct the pixel on a specify cube?
Now I have a vtkImageData (WxHxS) .I want to recontruct the cube to SxHxW

I think there is a mapping for the goal

NEW      ORIGIN

(i,0,0) ⇒ (W-i,0,0)

(0,j,0) ⇒ (W,j,0)

(0,0,k) ⇒ (W,0,k)

so I try to setting the new diminsion and extent for the vtkImageData

```<code>m->SetDimensions(S, H, W);
m->SetSpacing(origin->GetSpacing()[2], origin->GetSpacing()[1], origin->GetSpacing()[0]);
for (int k = 0; k < W; k++)
    for (int j = 0; j < H; j++)
        for (int i = 0; i< S; i++)
        {
        ptr = (unsigned short *)m->GetScalarPointer(i, j, k);
        ori = (unsigned short *)origin->GetScalarPointer(W - 1 - k, j, S -1- i);
        *ptr = *ori;

            }

//But it doesn't get the matter
//However, when I use the pixel method to copy origin data or upsidedow data, it is correct //like below

//copy the same structure
for (int k = 0; k < S; k++)
    for (int j = 0; j < H; j++)
    for (int i = 0; i< W; i++)
    {
        ori = (unsigned short*)origin->GetScalarPointer(i, j, k);
        ptr = (unsigned short*)m->GetScalarPointer(i, j, k);
        *ptr = *ori;
    }
//upsiaedown
    double val; int i = 0;
    for (vtkIdType f = m->GetNumberOfPoints() - 1; f > -1; f--)
    {
        val =m->GetPointData()->GetScalars()->GetTuple1(f);
        origin->GetPointData()->GetScalars()->SetTuple1(i, val);
        i++;
    }
</code>```

correct cubic output

Briefly speaking, I want to get a new vtkImageData which is rotate (alone specify axis)

ContentLicense: CC BY-SA 4.0

Body:
Now I have a vtkImageData (WxHxS) .I want to recontruct the cube to SxHxW

I think there is a mapping for the goal

NEW      ORIGIN

(i,0,0) ⇒ (W-i,0,0)

(0,j,0) ⇒ (W,j,0)

(0,0,k) ⇒ (W,0,k)

so I try to setting the new diminsion and extent for the vtkImageData

m->SetDimensions(S, H, W);
m->SetSpacing(origin->GetSpacing()[2], origin->GetSpacing()[1], origin->GetSpacing()[0]);
for (int k = 0; k < W; k++)
    for (int j = 0; j < H; j++)
        for (int i = 0; i< S; i++)
        {
        ptr = (unsigned short *)m->GetScalarPointer(i, j, k);
        ori = (unsigned short *)origin->GetScalarPointer(W - 1 - k, j, S -1- i);
        *ptr = *ori;

            }

//But it doesn't get the matter
//However, when I use the pixel method to copy origin data or upsidedow data, it is correct //like below

//copy the same structure
for (int k = 0; k < S; k++)
    for (int j = 0; j < H; j++)
    for (int i = 0; i< W; i++)
    {
        ori = (unsigned short*)origin->GetScalarPointer(i, j, k);
        ptr = (unsigned short*)m->GetScalarPointer(i, j, k);
        *ptr = *ori;
    }
//upsiaedown
    double val; int i = 0;
    for (vtkIdType f = m->GetNumberOfPoints() - 1; f > -1; f--)
    {
        val =m->GetPointData()->GetScalars()->GetTuple1(f);
        origin->GetPointData()->GetScalars()->SetTuple1(i, val);
        i++;
    }

correct cubic output

Briefly speaking, I want to get a new vtkImageData which is rotate (alone specify axis)


问:
Is this listener better than a while loop which test foregroundWindow?
I tried to implement a windows hook to grab foreground window event. This code is probably bad because I didnt understand much.
Can you tell me if that is better than a simple while loop that checks the foreground window every 0.1s for a change?

Is this code okay or just horrible?
How can I stop this "listener" when I want to close the app?

```<code>"""
Script using the Windows API to register for window focus changes and print the
titles of newly focused windows.
"""
#https://github.com/Danesprite/windows-fun/blob/master/window%20change%20listener.py
import sys
import time
import ctypes
import ctypes.wintypes
import threading
import six
import win32gui

class ObservableWindowChange(object):
    def __init__(self):
        self.__observers = []

    def register_observer(self, observer):
        self.__observers.append(observer)

    def notify_observers(self, *args, **kwargs):
        win_title = ''.join(args)
        if win_title == '':
            return ''
        for observer in self.__observers:
            observer.notify(win_title)

    def start_event_listener(self):
        # Create a WindowChangeEventListener object with this instance of
        # ObservableWindowChange as a parameter (self)
        listener = WindowChangeEventListener(self)
        listener.listen_forever()

class IWindowChangeObserver(object):
    """
    Base class for observing window changes
    """
    def __init__(self, observable, interface=None):
        observable.register_observer(self)
        self.interface = interface

    def notify(self, win_title):
        raise NotImplementedError

class WindowChangeEventListener(object):
    """
    WindowChangeEventListener
    """
    def __init__(self, observable):
        self.observable = observable

    def listen_forever(self):
        # This is to fix a problem with ascii encoding (windows with Unicode in
        # their titles)
        if six.PY2:
            reload(sys)
            sys.setdefaultencoding('utf8')

        # Look here for DWORD event constants:
        # http://stackoverflow.com/questions/15927262/convert-dword-event-constant-from-wineventproc-to-name-in-c-sharp
        # Don't worry, they work for python too.
        EVENT_SYSTEM_DIALOGSTART = 0x0010
        WINEVENT_OUTOFCONTEXT = 0x0000
        EVENT_SYSTEM_FOREGROUND = 0x0003
        WINEVENT_SKIPOWNPROCESS = 0x0002

        user32 = ctypes.windll.user32
        ole32 = ctypes.windll.ole32
        EnumWindows = ctypes.windll.user32.EnumWindows
        EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool,
                                             ctypes.POINTER(ctypes.c_int),
                                             ctypes.POINTER(ctypes.c_int))
        GetWindowText = ctypes.windll.user32.GetWindowTextW
        GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow
        GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
        IsWindowVisible = ctypes.windll.user32.IsWindowVisible

        ole32.CoInitialize(0)

        WinEventProcType = ctypes.WINFUNCTYPE(
            None,
            ctypes.wintypes.HANDLE,
            ctypes.wintypes.DWORD,
            ctypes.wintypes.HWND,
            ctypes.wintypes.LONG,
            ctypes.wintypes.LONG,
            ctypes.wintypes.DWORD,
            ctypes.wintypes.DWORD
        )

        def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread,
                     dwmsEventTime):
            length = GetWindowTextLength(hwnd)
            buff = ctypes.create_unicode_buffer(length + 1)
            GetWindowText(hwnd, buff, length + 1)
            # hwnd = GetForegroundWindow()
            # Notify observers
            self.observable.notify_observers(buff.value)

        WinEventProc = WinEventProcType(callback)

        user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
        hook = user32.SetWinEventHook(
            EVENT_SYSTEM_FOREGROUND,
            EVENT_SYSTEM_FOREGROUND,
            0,
            WinEventProc,
            0,
            0,
            WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
        )
        if hook == 0:
            print('SetWinEventHook failed')
            exit(1)

        msg = ctypes.wintypes.MSG()
        while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
            user32.TranslateMessageW(msg)
            user32.DispatchMessageW(msg)

        # Stopped receiving events, so clear up the winevent hook and uninitialise.
        print('Stopped receiving new window change events. Exiting...')
        user32.UnhookWinEvent(hook)
        ole32.CoUninitialize()

class WindowObserver(IWindowChangeObserver):
    def notify(self, win_text):
        time.sleep(0.3)
        win_hwnd = win32gui.GetForegroundWindow()
        # print("Window '%s' focused" % win_text)
        if self.interface:
            self.interface.update_perso_and_visibility(win_hwnd)

def run(interface=None):
    # Create an observable and an observer observing it
    subject = ObservableWindowChange()
    observer = WindowObserver(subject, interface=interface)

    # Listen for window changes
    subject.start_event_listener()

class ThreadListener(threading.Thread):
    def __init__(self, interface=None):
        threading.Thread.__init__(self)
        self.interface = interface
        self.start()

    def run(self):
        run(self.interface)

    def kill(self):
        print("kill")

if __name__ == '__main__':

    # Start the 'run' method in a daemonized thread.
    # t = threading.Thread(target=run)
    # t.setDaemon(True)
    # t.start()

    t = ThreadListener(None)

    # Keep the main thread running in a sleep loop until ctrl+c (SIGINT) is caught.
    # Once the main thread terminates, all daemon threads will automatically
    # terminate.
    cpt=0
    while True:
        try:
            time.sleep(0.1)
            cpt+=1
            if cpt>10:
                t.kill()
        except KeyboardInterrupt:
            break
</code>```

This is supposed to be a windows hook that detects the foreground window change. When the change occurs, the interface given as a parameter is updated.
It seems to work but sometimes the detection doesn't happen.

Thanks for your help

Body:
I tried to implement a windows hook to grab foreground window event. This code is probably bad because I didnt understand much.
Can you tell me if that is better than a simple while loop that checks the foreground window every 0.1s for a change?

Is this code okay or just horrible?
How can I stop this "listener" when I want to close the app?

"""
Script using the Windows API to register for window focus changes and print the
titles of newly focused windows.
"""
#https://github.com/Danesprite/windows-fun/blob/master/window%20change%20listener.py
import sys
import time
import ctypes
import ctypes.wintypes
import threading
import six
import win32gui

class ObservableWindowChange(object):
    def __init__(self):
        self.__observers = []

    def register_observer(self, observer):
        self.__observers.append(observer)

    def notify_observers(self, *args, **kwargs):
        win_title = ''.join(args)
        if win_title == '':
            return ''
        for observer in self.__observers:
            observer.notify(win_title)

    def start_event_listener(self):
        # Create a WindowChangeEventListener object with this instance of
        # ObservableWindowChange as a parameter (self)
        listener = WindowChangeEventListener(self)
        listener.listen_forever()

class IWindowChangeObserver(object):
    """
    Base class for observing window changes
    """
    def __init__(self, observable, interface=None):
        observable.register_observer(self)
        self.interface = interface

    def notify(self, win_title):
        raise NotImplementedError

class WindowChangeEventListener(object):
    """
    WindowChangeEventListener
    """
    def __init__(self, observable):
        self.observable = observable

    def listen_forever(self):
        # This is to fix a problem with ascii encoding (windows with Unicode in
        # their titles)
        if six.PY2:
            reload(sys)
            sys.setdefaultencoding('utf8')

        # Look here for DWORD event constants:
        # http://stackoverflow.com/questions/15927262/convert-dword-event-constant-from-wineventproc-to-name-in-c-sharp
        # Don't worry, they work for python too.
        EVENT_SYSTEM_DIALOGSTART = 0x0010
        WINEVENT_OUTOFCONTEXT = 0x0000
        EVENT_SYSTEM_FOREGROUND = 0x0003
        WINEVENT_SKIPOWNPROCESS = 0x0002

        user32 = ctypes.windll.user32
        ole32 = ctypes.windll.ole32
        EnumWindows = ctypes.windll.user32.EnumWindows
        EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool,
                                             ctypes.POINTER(ctypes.c_int),
                                             ctypes.POINTER(ctypes.c_int))
        GetWindowText = ctypes.windll.user32.GetWindowTextW
        GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow
        GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
        IsWindowVisible = ctypes.windll.user32.IsWindowVisible

        ole32.CoInitialize(0)

        WinEventProcType = ctypes.WINFUNCTYPE(
            None,
            ctypes.wintypes.HANDLE,
            ctypes.wintypes.DWORD,
            ctypes.wintypes.HWND,
            ctypes.wintypes.LONG,
            ctypes.wintypes.LONG,
            ctypes.wintypes.DWORD,
            ctypes.wintypes.DWORD
        )

        def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread,
                     dwmsEventTime):
            length = GetWindowTextLength(hwnd)
            buff = ctypes.create_unicode_buffer(length + 1)
            GetWindowText(hwnd, buff, length + 1)
            # hwnd = GetForegroundWindow()
            # Notify observers
            self.observable.notify_observers(buff.value)

        WinEventProc = WinEventProcType(callback)

        user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
        hook = user32.SetWinEventHook(
            EVENT_SYSTEM_FOREGROUND,
            EVENT_SYSTEM_FOREGROUND,
            0,
            WinEventProc,
            0,
            0,
            WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
        )
        if hook == 0:
            print('SetWinEventHook failed')
            exit(1)

        msg = ctypes.wintypes.MSG()
        while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
            user32.TranslateMessageW(msg)
            user32.DispatchMessageW(msg)

        # Stopped receiving events, so clear up the winevent hook and uninitialise.
        print('Stopped receiving new window change events. Exiting...')
        user32.UnhookWinEvent(hook)
        ole32.CoUninitialize()

class WindowObserver(IWindowChangeObserver):
    def notify(self, win_text):
        time.sleep(0.3)
        win_hwnd = win32gui.GetForegroundWindow()
        # print("Window '%s' focused" % win_text)
        if self.interface:
            self.interface.update_perso_and_visibility(win_hwnd)

def run(interface=None):
    # Create an observable and an observer observing it
    subject = ObservableWindowChange()
    observer = WindowObserver(subject, interface=interface)

    # Listen for window changes
    subject.start_event_listener()

class ThreadListener(threading.Thread):
    def __init__(self, interface=None):
        threading.Thread.__init__(self)
        self.interface = interface
        self.start()

    def run(self):
        run(self.interface)

    def kill(self):
        print("kill")

if __name__ == '__main__':

    # Start the 'run' method in a daemonized thread.
    # t = threading.Thread(target=run)
    # t.setDaemon(True)
    # t.start()

    t = ThreadListener(None)

    # Keep the main thread running in a sleep loop until ctrl+c (SIGINT) is caught.
    # Once the main thread terminates, all daemon threads will automatically
    # terminate.
    cpt=0
    while True:
        try:
            time.sleep(0.1)
            cpt+=1
            if cpt>10:
                t.kill()
        except KeyboardInterrupt:
            break

This is supposed to be a windows hook that detects the foreground window change. When the change occurs, the interface given as a parameter is updated.
It seems to work but sometimes the detection doesn't happen.

Thanks for your help


问:
How can I time taken between 2 events
I am trying to record the time taken between 2 sensors being activated

I am using ladder logic for my university project although struggling with code to record time taken between two events so as to store the information

Title: How can I time taken between 2 events


问:
Connect to AWS RDS Aurora for Postgres from Node JS
I have a Node JS application hosted on EC2 instances that I am trying to connect with an RDS Aurora Postgres cluster. The cluster consists of 1 writer and 2 readers. I have whitelisted the security group attached to the EC2 instances as an ingress rule on the security group associated with the database cluster which allows the EC2 instances to communicate with the database in the cluster.

I am having some issues connecting the application on the EC2 instance to the database. I have read this link, but that discusses using a JDBC driver in order to connect the database. I'm not sure if I can use a JDBC driver to allow a Node JS application to connect to this database cluster. I'm not finding any useful examples to connect a Node app to Aurora Postgres.

Any advice on connecting Node JS to Aurora Postgres DB cluster would be helpful.


问:
How to modify VBA SpellNumber function such that the last "and" does not show?
I have gotten a modified SpellNumber code from this forum:
https://www.excelforum.com/excel-general/499112-adding-and-to-spellnumber-code.html
from the post: Bob Phillips 01-09-2006, 05:15 AM #8

I have modified it a little as well and so the output becomes:

Number
Result

100,000
One Hundred Thousand and

2,000,224
Two Million and Two Hundred and Twenty Four

2,000
Two Thousand and

200
Two Hundred and

1,100
One Thousand and  One Hundred and

120.23
One Hundred and Twenty Point Twenty Three

The desired outcome that I need is for "and" not to appear at the end of the string if there is nothing else behind it. Example the result of 200 & 2000. How should I tweak the code?

Here is the code that I tweaked:

```<code>Option Explicit

Function SpellNumber(ByVal MyNumber)
Dim ipos As Long
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = "Thousand "
Place(3) = "Million "
Place(4) = "Billion "
Place(5) = "Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1

Loop
Select Case Dollars
Case ""
Dollars = ""
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars
End Select

Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and Point One"
Case Else
Cents = "Point " & Cents
End Select

Dollars = Replace(Dollars, "Hundred ", "Hundred and ")
Dollars = Replace(Dollars, "Hundred and Thousand", "Hundred Thousand ")
Dollars = Replace(Dollars, "Hundred and Million", "Hundred Million and ")
Dollars = Replace(Dollars, "Thousand", "Thousand and ")
Dollars = Replace(Dollars, "Million", "Million and ")
SpellNumber = Dollars & Cents
End Function

' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & "Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten "
Case 11: Result = "Eleven "
Case 12: Result = "Twelve "
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen "
Case 15: Result = "Fifteen "
Case 16: Result = "Sixteen "
Case 17: Result = "Seventeen "
Case 18: Result = "Eighteen "
Case 19: Result = "Nineteen "
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty "
Case 3: Result = "Thirty "
Case 4: Result = "Forty "
Case 5: Result = "Fifty "
Case 6: Result = "Sixty "
Case 7: Result = "Seventy "
Case 8: Result = "Eighty "
Case 9: Result = "Ninety "
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
GetTens = Result
End Function

' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One "
Case 2: GetDigit = "Two "
Case 3: GetDigit = "Three "
Case 4: GetDigit = "Four "
Case 5: GetDigit = "Five "
Case 6: GetDigit = "Six "
Case 7: GetDigit = "Seven "
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine "
Case Else: GetDigit = ""
End Select
End Function

</code>```

The desired outcome:
For example:

Number
Result

200
Two Hundred

1100
One Thousand and One Hundred

120.23
One Hundred and Twenty Three Point Twenty Three

2,000,23
Two Million and Two Hundred and Twenty Four

The part that I have modified from the original are only these:

```<code>Loop
Select Case Dollars
Case ""
Dollars = ""
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars
End Select

Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and Point One"
Case Else
Cents = "Point " & Cents
End Select

Dollars = Replace(Dollars, "Hundred ", "Hundred and ")
Dollars = Replace(Dollars, "Hundred and Thousand", "Hundred Thousand ")
Dollars = Replace(Dollars, "Hundred and Million", "Hundred Million and ")
Dollars = Replace(Dollars, "Thousand", "Thousand and ")
Dollars = Replace(Dollars, "Million", "Million and ")
SpellNumber = Dollars & Cents
</code>```

Thank you very much for the help!

Body:
I have gotten a modified SpellNumber code from this forum:
https://www.excelforum.com/excel-general/499112-adding-and-to-spellnumber-code.html
from the post: Bob Phillips 01-09-2006, 05:15 AM #8

I have modified it a little as well and so the output becomes:

Number
Result

100,000
One Hundred Thousand and

2,000,224
Two Million and Two Hundred and Twenty Four

2,000
Two Thousand and

200
Two Hundred and

1,100
One Thousand and  One Hundred and

120.23
One Hundred and Twenty Point Twenty Three

The desired outcome that I need is for "and" not to appear at the end of the string if there is nothing else behind it. Example the result of 200 & 2000. How should I tweak the code?

Here is the code that I tweaked:

Option Explicit

Function SpellNumber(ByVal MyNumber)
Dim ipos As Long
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = "Thousand "
Place(3) = "Million "
Place(4) = "Billion "
Place(5) = "Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1

Loop
Select Case Dollars
Case ""
Dollars = ""
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars
End Select

Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and Point One"
Case Else
Cents = "Point " & Cents
End Select

Dollars = Replace(Dollars, "Hundred ", "Hundred and ")
Dollars = Replace(Dollars, "Hundred and Thousand", "Hundred Thousand ")
Dollars = Replace(Dollars, "Hundred and Million", "Hundred Million and ")
Dollars = Replace(Dollars, "Thousand", "Thousand and ")
Dollars = Replace(Dollars, "Million", "Million and ")
SpellNumber = Dollars & Cents
End Function

' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & "Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten "
Case 11: Result = "Eleven "
Case 12: Result = "Twelve "
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen "
Case 15: Result = "Fifteen "
Case 16: Result = "Sixteen "
Case 17: Result = "Seventeen "
Case 18: Result = "Eighteen "
Case 19: Result = "Nineteen "
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty "
Case 3: Result = "Thirty "
Case 4: Result = "Forty "
Case 5: Result = "Fifty "
Case 6: Result = "Sixty "
Case 7: Result = "Seventy "
Case 8: Result = "Eighty "
Case 9: Result = "Ninety "
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
GetTens = Result
End Function

' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One "
Case 2: GetDigit = "Two "
Case 3: GetDigit = "Three "
Case 4: GetDigit = "Four "
Case 5: GetDigit = "Five "
Case 6: GetDigit = "Six "
Case 7: GetDigit = "Seven "
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine "
Case Else: GetDigit = ""
End Select
End Function

The desired outcome:
For example:

Number
Result

200
Two Hundred

1100
One Thousand and One Hundred

120.23
One Hundred and Twenty Three Point Twenty Three

2,000,23
Two Million and Two Hundred and Twenty Four

The part that I have modified from the original are only these:

Loop
Select Case Dollars
Case ""
Dollars = ""
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars
End Select

Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and Point One"
Case Else
Cents = "Point " & Cents
End Select

Dollars = Replace(Dollars, "Hundred ", "Hundred and ")
Dollars = Replace(Dollars, "Hundred and Thousand", "Hundred Thousand ")
Dollars = Replace(Dollars, "Hundred and Million", "Hundred Million and ")
Dollars = Replace(Dollars, "Thousand", "Thousand and ")
Dollars = Replace(Dollars, "Million", "Million and ")
SpellNumber = Dollars & Cents

Thank you very much for the help!


问:
swiftui -- tabview has error when use offset
I found the height was wrong when I'm dragging,how can i fix it?

The height in the tabview will be subtracted from the safe height when dragging.

work with tabview with background

work with tabview without background

work with backgroun without tabview

```<code>struct TabViewTest: View {
    @State var offset: CGFloat = 0
    @State var startY: CGFloat = 0

    var body: some View {
        ZStack(alignment: .top) {
            VStack {

                  // work without tabview
//                GeometryReader { proxy in
//                    ZStack {
//                        Color.green
//                            .frame(height: 100)
//                        Text("row height:\(proxy.size.height)")
//                    }
//                }
                // work with tabview without background
//                TabView {
//                    ForEach(0..<5) { i in
//                        GeometryReader { proxy in
//                            Text("row\(i) height:\(proxy.size.height)")
//                        }
//                    }
//                }

                // work with tabview
                TabView {
                    ForEach(0..<5) { i in
                        GeometryReader { proxy in
                            ZStack {
                                Color.green
                                    .frame(height: 100)
                                Text("row\(i) height:\(proxy.size.height)")
                            }
                        }
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .frame(height: 150)
                .background(.gray)
                .offset(y: offset)

                Spacer()
            }

            Color.brown
                .frame(height: 300)
                .offset(y: 200 + offset)
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            offset = value.translation.height + startY
                        })
                        .onEnded({ value in
                            startY = offset
                        })
                )
        }

    }
}
</code>```

I hope the Tabview has a correct height,please help me.

Body:
I found the height was wrong when I'm dragging,how can i fix it?

The height in the tabview will be subtracted from the safe height when dragging.

work with tabview with background

work with tabview without background

work with backgroun without tabview

struct TabViewTest: View {
    @State var offset: CGFloat = 0
    @State var startY: CGFloat = 0

    var body: some View {
        ZStack(alignment: .top) {
            VStack {

                  // work without tabview
//                GeometryReader { proxy in
//                    ZStack {
//                        Color.green
//                            .frame(height: 100)
//                        Text("row height:\(proxy.size.height)")
//                    }
//                }
                // work with tabview without background
//                TabView {
//                    ForEach(0..<5) { i in
//                        GeometryReader { proxy in
//                            Text("row\(i) height:\(proxy.size.height)")
//                        }
//                    }
//                }

                // work with tabview
                TabView {
                    ForEach(0..<5) { i in
                        GeometryReader { proxy in
                            ZStack {
                                Color.green
                                    .frame(height: 100)
                                Text("row\(i) height:\(proxy.size.height)")
                            }
                        }
                    }
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .frame(height: 150)
                .background(.gray)
                .offset(y: offset)

                Spacer()
            }

            Color.brown
                .frame(height: 300)
                .offset(y: 200 + offset)
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            offset = value.translation.height + startY
                        })
                        .onEnded({ value in
                            startY = offset
                        })
                )
        }

    }
}

I hope the Tabview has a correct height,please help me.


问:
Node.js Sendgrid API v3 sending attachments end up corrupted/broken in the email. Next.js
I have a form that is working to send emails from a contact form on Next.js using API routes and I'm trying to add attachments to the form. The form sends the email with everything including the attachment but the attachment is broken. I've read every question on here relating to it and it's still not working.

My guess is it's the

```<code>const attachments = Buffer.from(body.attachments).toString("base64");

</code>```

causing the issue. Probably not converting correctly. I have limited experience with Buffer.

```<code>//email form for invidual van magazine inquiries

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY_LETTER);

export default async function handler(req, res) {

const body = JSON.parse(req.body);
console.log(body.attachments);
const attachments = Buffer.from(body.attachments).toString("base64");

const msg = \`
Name: ${body.name}\\r\\n
Phone: ${body.phone}\\r\\n
Email: \<a href="mailto:${body.email}"\>${body.email}\</a\>\\r\\n
Letter: ${body.letter}

\`;

const data = {
to: "john@doe.com",
from: `info@randomcompany.com`,
subject: `${body.subject}`,
text: msg,
html: msg.replace(/\\r\\n/g, "\<br /\>"),
attachments: [
{
content: attachments,
filename: "attachment.pdf",
type: "application/pdf",
disposition: "attachment",
},
],
};

await sgMail
.send(data)
.then(() =\> {
console.log("Email sent");
})
.catch((error) =\> {
console.log(error.response.body);
});

res.status(200).json({ status: "ok" });
}

</code>```

The form on the frontend is :

```<code><motion.form
                  initial={{ opacity: 0, y: 100 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 1.0 }}
                  onSubmit={handleSubmit}
                  className="mt-16  flex flex-col lg:flex-row rounded-l-lg justify-center items-center"
                >
                  <div className="flex flex-col space-y-3  justify-center items-center">
                    <input
                      id="name"
                      name="name"
                      type="text"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none focus:outline-none  w-[350px] "
                      placeholder="Name"
                      required
                    />
                    <input
                      id="subject"
                      name="subject"
                      type="text"
                      className="hidden"
                      disabled
                      value={`Letter to the Editor`}
                    />
                    <input
                      id="email"
                      name="email"
                      type="text"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none focus:outline-none  w-[350px]"
                      placeholder="Email Address"
                      required
                    />
                    <input
                      id="phone"
                      type="text"
                      name="phone"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none focus:outline-none  w-[350px]"
                      placeholder="Phone (optional)"
                    />
                    <textarea
                      name="letter"
                      id="letter"
                      className="px-4 h-48 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none flex justify-center items-center focus:outline-none  w-[350px]"
                      placeholder="Letter To The Editor"
                    ></textarea>
                    <div className="flex flex-col text-center items-center justify-center text-sm w-3/4 ">
                      <label
                        className="flex justify-center items-center  w-full mx-4 my-5"
                        htmlFor="attachments"
                      >
                        Attach PDF?
                      </label>
                      <input
                        className="flex justify-center items-center w-full mx-auto my-2"
                        type="file"
                        name="attachments"
                        id="attachments"
                      />
                    </div>
</code>```
```<code>  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = {};
    Array.from(e.currentTarget.elements).forEach((field) => {
      if (!field.name) return;
      formData[field.name] = field.value;
    });
    fetch("/api/letter", {
      method: "POST",
      body: JSON.stringify(formData),
    });
    // }).then(() => {
    //   setSubmitted(true);
    // });
  };
</code>```

If anyone can point me in the correct direction it would be greatly appreciated

I have tried using setting the state with the file but that didn't work

Here is the console log that returns after sending the email

```<code>  console.log("body:", req.body);
  const body = JSON.parse(req.body);
  console.log("body attachments:", body.attachments);
  const attachments = Buffer.from(body.attachments).toString("base64");
  console.log("attachments:", attachments);
</code>```
```<code>body: {"name":"Chris","subject":"Letter to the Editor","email":"asada@ada.com","phone":"test","letter":"test","attachments":"C:\\fakepath\\upwork js questions.pdf"}
body attachments: C:\fakepath\upwork js questions.pdf
attachments: QzpcZmFrZXBhdGhcdXB3b3JrIGpzIHF1ZXN0aW9ucy5wZGY=
Email sent
</code>```

Body:
I have a form that is working to send emails from a contact form on Next.js using API routes and I'm trying to add attachments to the form. The form sends the email with everything including the attachment but the attachment is broken. I've read every question on here relating to it and it's still not working.

My guess is it's the

const attachments = Buffer.from(body.attachments).toString("base64");

causing the issue. Probably not converting correctly. I have limited experience with Buffer.

//email form for invidual van magazine inquiries

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY_LETTER);

export default async function handler(req, res) {

const body = JSON.parse(req.body);
console.log(body.attachments);
const attachments = Buffer.from(body.attachments).toString("base64");

const msg = \`
Name: ${body.name}\\r\\n
Phone: ${body.phone}\\r\\n
Email: \${body.email}\\\r\\n
Letter: ${body.letter}

\`;

const data = {
to: "john@doe.com",
from: `info@randomcompany.com`,
subject: `${body.subject}`,
text: msg,
html: msg.replace(/\\r\\n/g, "\
"),
attachments: [
{
content: attachments,
filename: "attachment.pdf",
type: "application/pdf",
disposition: "attachment",
},
],
};

await sgMail
.send(data)
.then(() =\> {
console.log("Email sent");
})
.catch((error) =\> {
console.log(error.response.body);
});

res.status(200).json({ status: "ok" });
}

The form on the frontend is :

<motion.form
                  initial={{ opacity: 0, y: 100 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 1.0 }}
                  onSubmit={handleSubmit}
                  className="mt-16  flex flex-col lg:flex-row rounded-l-lg justify-center items-center"
                >

                    <input
                      id="name"
                      name="name"
                      type="text"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none focus:outline-none  w-[350px] "
                      placeholder="Name"
                      required
                    />
                    <input
                      id="subject"
                      name="subject"
                      type="text"
                      className="hidden"
                      disabled
                      value={`Letter to the Editor`}
                    />
                    <input
                      id="email"
                      name="email"
                      type="text"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none focus:outline-none  w-[350px]"
                      placeholder="Email Address"
                      required
                    />
                    <input
                      id="phone"
                      type="text"
                      name="phone"
                      className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none focus:outline-none  w-[350px]"
                      placeholder="Phone (optional)"
                    />
                    <textarea
                      name="letter"
                      id="letter"
                      className="px-4 h-48 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2  focus:ring-none flex justify-center items-center focus:outline-none  w-[350px]"
                      placeholder="Letter To The Editor"
                    ></textarea>

                        Attach PDF?

                      <input
                        className="flex justify-center items-center w-full mx-auto my-2"
                        type="file"
                        name="attachments"
                        id="attachments"
                      />

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = {};
    Array.from(e.currentTarget.elements).forEach((field) => {
      if (!field.name) return;
      formData[field.name] = field.value;
    });
    fetch("/api/letter", {
      method: "POST",
      body: JSON.stringify(formData),
    });
    // }).then(() => {
    //   setSubmitted(true);
    // });
  };

If anyone can point me in the correct direction it would be greatly appreciated

I have tried using setting the state with the file but that didn't work

Here is the console log that returns after sending the email

  console.log("body:", req.body);
  const body = JSON.parse(req.body);
  console.log("body attachments:", body.attachments);
  const attachments = Buffer.from(body.attachments).toString("base64");
  console.log("attachments:", attachments);

body: {"name":"Chris","subject":"Letter to the Editor","email":"asada@ada.com","phone":"test","letter":"test","attachments":"C:\\fakepath\\upwork js questions.pdf"}
body attachments: C:\fakepath\upwork js questions.pdf
attachments: QzpcZmFrZXBhdGhcdXB3b3JrIGpzIHF1ZXN0aW9ucy5wZGY=
Email sent


问:
convert webclient.upload file to httpclient code
i'm trying to convert the following code to httpclient code, webclient works fine, but i suppose it's obsolete and microsoft is recommending we moe to httpclient, it is uploading a zip file to an azure blob storage url, then another api kicks off a process to import that zip file to dynamics 365

Again, this webclient code works perfectly

```<code>using var webClient = new WebClient();

webClient.Headers.Add("Content-Type", "application/zip");
webClient.Headers.Add("x-ms-blob-type", "BlockBlob");
webClient.Headers.Add("Overwrite", "T");

webClient.UploadFile(azureWriteUrl, WebRequestMethods.Http.Put, filePath);`
</code>```

i have tried this httpclient code, it uploads the file successfully, get back a 201 created, but something is not "creating" or "uploading" the zip file correctly here, as the api that consumes this uploaded file (to azure blob url) doesn't like it.

```<code>_httpClient = new HttpClient();

_httpClient.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob");
_httpClient.DefaultRequestHeaders.Add("Overwrite", "T");

var formContent = new MultipartFormDataContent();

using var stream = File.OpenRead(filePath);

formContent.Add(new StreamContent(stream), "testImportPackage", "testImportPackage.zip");

using var response = await _httpClient.PutAsync(azureWriteUrl, formContent);
var responseContent = response.Content.ReadAsStringAsync().Result;
</code>```

The import API returns the following error:

Exception occurred while executing action ImportFromPackage on Entity DataManagementDefinitionGroup: Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory.

Body:
i'm trying to convert the following code to httpclient code, webclient works fine, but i suppose it's obsolete and microsoft is recommending we moe to httpclient, it is uploading a zip file to an azure blob storage url, then another api kicks off a process to import that zip file to dynamics 365

Again, this webclient code works perfectly

using var webClient = new WebClient();

webClient.Headers.Add("Content-Type", "application/zip");
webClient.Headers.Add("x-ms-blob-type", "BlockBlob");
webClient.Headers.Add("Overwrite", "T");

webClient.UploadFile(azureWriteUrl, WebRequestMethods.Http.Put, filePath);`

i have tried this httpclient code, it uploads the file successfully, get back a 201 created, but something is not "creating" or "uploading" the zip file correctly here, as the api that consumes this uploaded file (to azure blob url) doesn't like it.

_httpClient = new HttpClient();

_httpClient.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob");
_httpClient.DefaultRequestHeaders.Add("Overwrite", "T");

var formContent = new MultipartFormDataContent();

using var stream = File.OpenRead(filePath);

formContent.Add(new StreamContent(stream), "testImportPackage", "testImportPackage.zip");

using var response = await _httpClient.PutAsync(azureWriteUrl, formContent);
var responseContent = response.Content.ReadAsStringAsync().Result;

The import API returns the following error:

Exception occurred while executing action ImportFromPackage on Entity DataManagementDefinitionGroup: Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory.


问:
How to run a .cmd file from changing location [SD Card]
I am working on a gaming library that can be put onto an sd card and different Windows devices.  All of the files for the emulators and roms are within one folder.  When I move the sd card around, it will change from A Drive to D Drive, etc.

How would I write a cmd file that doesn't require the entire address of the file but rather just checks the shared parent folder and then routes from there.

On a command line you can do the two dots (..) but I'm not sure how to do this on a written file.  Here is my file and it's location explained below.

File Location:
A:\Console\Nintendo\64\cmdfiles\SuperMario64.cmd

Code:

```<code>@echo off
echo Starting Super Mario 64...
call "Nintendo64.cmd" "A:\Console\Nintendo\64\Games\Super Mario 64.n64"
</code>```

Desired Code:

```<code>@echo off
echo Starting Super Mario 64...
call "Nintendo64.cmd" "..\Games\Super Mario 64.n64"
</code>```

Body:
I am working on a gaming library that can be put onto an sd card and different Windows devices.  All of the files for the emulators and roms are within one folder.  When I move the sd card around, it will change from A Drive to D Drive, etc.

How would I write a cmd file that doesn't require the entire address of the file but rather just checks the shared parent folder and then routes from there.

On a command line you can do the two dots (..) but I'm not sure how to do this on a written file.  Here is my file and it's location explained below.

File Location:
A:\Console\Nintendo\64\cmdfiles\SuperMario64.cmd

Code:

@echo off
echo Starting Super Mario 64...
call "Nintendo64.cmd" "A:\Console\Nintendo\64\Games\Super Mario 64.n64"

Desired Code:

@echo off
echo Starting Super Mario 64...
call "Nintendo64.cmd" "..\Games\Super Mario 64.n64"


问:
Confusing inaccuracy in Emgu CV stereo calibration
I have 9 stereo camera rigs that are essentially identical.  I am calibrating them all with the same methodology:

Capture 25 images of an 8x11 chessboard (the same one for all rigs) in varying positions and orientations

Detect the corners for all images using FindChessboardCorners and refine them using CornerSubPix

Calibrate each camera intrinsics individually using CalibrateCamera

Calibrate the extrinsics using StereoCalibrate passing the CameraMatrix and DistortionCoeffs from #3 and using the FixIntrinsics flag

Compute the rectification transformations using StereoRectify

Then, with a projector using structured light, I place a sphere (the same one for all rigs) of known radius (16 mm) in front of the rigs and measure the sphere using:

Use image processing to match a large number of features between the two cameras in the distorted images

Use UndistortPoints to get their undistorted image locations

Use TriangulatePoints to get the points in homogeneous coordinates

Use ConvertFromHomogeneous to get the points in world coordinates

On two of the rigs, the sphere measurement comes out highly accurate (RMSE 0.034 mm).  However, on the other seven rigs, the measurement comes out with an unacceptable RMSE 0.15 mm (5x).  Also, the inaccuracy of each of the measurements seems to be skewed vertically.  Its as if the sphere is measured "spherical" in the horizontal direction, but slightly skewed vertically with a peak pointing slightly downward.

I have picked my methodology apart for a few weeks and tried almost every variation I can think of.  However, after recalibrating the devices multiple times and recapturing sphere measurements multiple times, the same two devices remain spot-on and the other seven devices keep giving the exact same error.  Nothing about the calibration results of the 7 incorrect rigs stands out as "erroneous" in comparison to the results of the 2 good rigs other than the sphere measurement.  Also, I cannot find anything about the rigs that are significantly different hardware-wise.

I am pulling my hair out at this point and am turning to this fine community to see if anyone notices anything I'm missing in my above described calibration procedure.  I've tried every variation I can think of in each step of the above process.  However, the process seems valid since it works for 2 of the 9 devices.

Thank you!


问:
User Authentication not working as expected
I created a web app that authenticates users using Passport.js where they are able to log-in or register either using the web form or google authentication. The web app is working fine and as expected locally, however, when deployed, it is allowing me to register but, when logged in, I try to press any button, it logs me out asks me to sign in again. The log is giving me a bunch of 304 and 302 status code errors. I don't know what is wrong. Please help.

Once I log in, I expect it to keep me logged in until I sign out. Instead, once I log in and try to use the web app, it logs me out. I am using: express, mongoose, session, express-passport, passport-local-mongoose, passport-google-oauth20, mongoose-findorcreate

Here is the link to my deployed web app: https://upset-gilet-lion.cyclic.app/

Here is a screenshot of deployed app logs:
logs screenshot

Here is my app.js code:

```<code>require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require("mongoose-findorcreate")

const app = express();

app.use(express.static(__dirname + "/public/"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));

// Initializing Session
app.use(session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false
}));

// Initializing Passport
app.use(passport.initialize());
app.use(passport.session());

// Connecting to MongoDB using Mongoose
mongoose.set('strictQuery', true);

const mongodb = "mongodb://127.0.0.1:27017/userDB"

const mongodbNet = "mongodb+srv://admin-bhoami:"+ process.env.PASSWORD +"@secretscluster.uztbzho.mongodb.net/userDB";

mongoose.connect(mongodbNet, function(err){
    if (err) {
        console.log('Unable to connect to MongoDB');
        console.log(err);
    } else {
        console.log('Successfully connected to MongoDB');
    }
});

// Creating a new User Database
const userSchema = new mongoose.Schema ({
    email: String,
    password: String,
    googleId: String,
    secret: Array
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

// Set Local Login Strategy
passport.use(User.createStrategy());

// Serialize and Deserialize
passport.serializeUser(function(user, done) {
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

// Google Authentication Strategy that authenticates users using a Google Account and OAuth 2.0 tokens.
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "https://upset-gilet-lion.cyclic.app/auth/google/secrets", //"http://localhost:3000/auth/google/secrets"
    },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({username: profile.emails[0].value, googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

// Home Page
app.route("/")
    .get(function(req, res) {
        res.render("home");
    });

// Google Authentication Route
app.get('/auth/google',
  passport.authenticate('google', { scope: ["openid", "profile", "email"] }));

app.get("/auth/google/secrets",
  passport.authenticate("google", { failureRedirect: "/signin" }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect("/secrets");
});

// Sign-Up Page
app.route("/signup")
    .get(function(req, res) {
        res.render("signup");
    })
    .post(function(req, res) {
        User.register({username: req.body.username}, req.body.password, function(err, user) {
            if (err) {
                console.log(err);
                res.redirect("/signup");
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

// Sign-In Page
app.route("/signin")
    .get(function(req, res) {
        res.render("signin");
    })
    .post(function(req, res) {
        // Check database to see if the username provided exists in it.
        User.findOne({username: req.body.username}, function(err, foundUser) {
            // If username found, create an object "user" to store username and password which was used for login
            if (foundUser) {
                const user = new User ({
                    username: req.body.username,
                    password: req.body.password
                });
                // Use the "user" object to compare against username and password stored in Database.
                // The code below will either return false is no match was found or it will return the 'found user'.
                passport.authenticate("local", function (err, user) {
                    if (err) {
                        console.log(err);
                    } else {
                        // the 'user' below is the user returned from passport.authenticate callback; it will either be false if no match was found or the user
                        if (user) {
                            // If the user is found, then he/she is logged in or they are redirected to sign in page.
                            req.login(user, function(err) {
                                res.redirect("/secrets");
                            })
                        } else {
                            res.redirect("/signin");
                        }
                    }
                }) (req, res);
            // If no username is found, redirect to sign in page; i.e. user does not exists
            } else {
                res.redirect("/signin");
            }
        });
    });

// Secrets Page
app.route("/secrets")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            User.find({secret: {$ne: null}}, function(err, users) {
                if (!err) {
                    if (users) {
                        res.render("secrets", {usersWithSecrets: users});
                    } else {
                        console.log(err);
                    }
                } else {
                    console.log(err);
                }
            });
        } else {
            res.redirect("/signin");
        }
    });

// Sign-Out Route
app.route("/signout")
    .get(function(req, res) {
        req.logout(function(err) {
            if (err) {
                console.log(err);
            } else {
                res.redirect("/")
            }
        });
    });

// Submit Route
app.route("/submit")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            res.render("submit");
        } else {
            res.redirect("/signin");
        }
    })
    .post(function(req, res) {
        const submittedSecret = req.body.secret;
        if(req.isAuthenticated()) {
            req.user.secret.push(submittedSecret);
            req.user.save(function() {
                res.redirect("/secrets");
            })
        } else {
            res.redirect("/signin");
        }
    });

// Delete Route
app.route("/delete")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            res.render("delete", {secrets: req.user.secret});
        } else {
            res.redirect("/signin");
        }
    })
    .post(function(req, res) {
        if(req.isAuthenticated()){
            User.findById(req.user.id, function (err,foundUser){
              foundUser.secret.splice(foundUser.secret.indexOf(req.body.secret),1);
              foundUser.save(function (err) {
                if(!err){
                  res.redirect("/secrets");
                }
              });
            });
          }else {
            res.redirect("/signin");
          }
    });

const PORT = process.env.PORT || 3000;

app.listen(PORT, function() {
    console.log("Server started on Port ${PORT}");
});
</code>```

Body:
I created a web app that authenticates users using Passport.js where they are able to log-in or register either using the web form or google authentication. The web app is working fine and as expected locally, however, when deployed, it is allowing me to register but, when logged in, I try to press any button, it logs me out asks me to sign in again. The log is giving me a bunch of 304 and 302 status code errors. I don't know what is wrong. Please help.

Once I log in, I expect it to keep me logged in until I sign out. Instead, once I log in and try to use the web app, it logs me out. I am using: express, mongoose, session, express-passport, passport-local-mongoose, passport-google-oauth20, mongoose-findorcreate

Here is the link to my deployed web app: https://upset-gilet-lion.cyclic.app/

Here is a screenshot of deployed app logs:
logs screenshot

Here is my app.js code:

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require("mongoose-findorcreate")

const app = express();

app.use(express.static(__dirname + "/public/"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));

// Initializing Session
app.use(session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false
}));

// Initializing Passport
app.use(passport.initialize());
app.use(passport.session());

// Connecting to MongoDB using Mongoose
mongoose.set('strictQuery', true);

const mongodb = "mongodb://127.0.0.1:27017/userDB"

const mongodbNet = "mongodb+srv://admin-bhoami:"+ process.env.PASSWORD +"@secretscluster.uztbzho.mongodb.net/userDB";

mongoose.connect(mongodbNet, function(err){
    if (err) {
        console.log('Unable to connect to MongoDB');
        console.log(err);
    } else {
        console.log('Successfully connected to MongoDB');
    }
});

// Creating a new User Database
const userSchema = new mongoose.Schema ({
    email: String,
    password: String,
    googleId: String,
    secret: Array
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

// Set Local Login Strategy
passport.use(User.createStrategy());

// Serialize and Deserialize
passport.serializeUser(function(user, done) {
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

// Google Authentication Strategy that authenticates users using a Google Account and OAuth 2.0 tokens.
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "https://upset-gilet-lion.cyclic.app/auth/google/secrets", //"http://localhost:3000/auth/google/secrets"
    },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({username: profile.emails[0].value, googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

// Home Page
app.route("/")
    .get(function(req, res) {
        res.render("home");
    });

// Google Authentication Route
app.get('/auth/google',
  passport.authenticate('google', { scope: ["openid", "profile", "email"] }));

app.get("/auth/google/secrets",
  passport.authenticate("google", { failureRedirect: "/signin" }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect("/secrets");
});

// Sign-Up Page
app.route("/signup")
    .get(function(req, res) {
        res.render("signup");
    })
    .post(function(req, res) {
        User.register({username: req.body.username}, req.body.password, function(err, user) {
            if (err) {
                console.log(err);
                res.redirect("/signup");
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

// Sign-In Page
app.route("/signin")
    .get(function(req, res) {
        res.render("signin");
    })
    .post(function(req, res) {
        // Check database to see if the username provided exists in it.
        User.findOne({username: req.body.username}, function(err, foundUser) {
            // If username found, create an object "user" to store username and password which was used for login
            if (foundUser) {
                const user = new User ({
                    username: req.body.username,
                    password: req.body.password
                });
                // Use the "user" object to compare against username and password stored in Database.
                // The code below will either return false is no match was found or it will return the 'found user'.
                passport.authenticate("local", function (err, user) {
                    if (err) {
                        console.log(err);
                    } else {
                        // the 'user' below is the user returned from passport.authenticate callback; it will either be false if no match was found or the user
                        if (user) {
                            // If the user is found, then he/she is logged in or they are redirected to sign in page.
                            req.login(user, function(err) {
                                res.redirect("/secrets");
                            })
                        } else {
                            res.redirect("/signin");
                        }
                    }
                }) (req, res);
            // If no username is found, redirect to sign in page; i.e. user does not exists
            } else {
                res.redirect("/signin");
            }
        });
    });

// Secrets Page
app.route("/secrets")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            User.find({secret: {$ne: null}}, function(err, users) {
                if (!err) {
                    if (users) {
                        res.render("secrets", {usersWithSecrets: users});
                    } else {
                        console.log(err);
                    }
                } else {
                    console.log(err);
                }
            });
        } else {
            res.redirect("/signin");
        }
    });

// Sign-Out Route
app.route("/signout")
    .get(function(req, res) {
        req.logout(function(err) {
            if (err) {
                console.log(err);
            } else {
                res.redirect("/")
            }
        });
    });

// Submit Route
app.route("/submit")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            res.render("submit");
        } else {
            res.redirect("/signin");
        }
    })
    .post(function(req, res) {
        const submittedSecret = req.body.secret;
        if(req.isAuthenticated()) {
            req.user.secret.push(submittedSecret);
            req.user.save(function() {
                res.redirect("/secrets");
            })
        } else {
            res.redirect("/signin");
        }
    });

// Delete Route
app.route("/delete")
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            res.render("delete", {secrets: req.user.secret});
        } else {
            res.redirect("/signin");
        }
    })
    .post(function(req, res) {
        if(req.isAuthenticated()){
            User.findById(req.user.id, function (err,foundUser){
              foundUser.secret.splice(foundUser.secret.indexOf(req.body.secret),1);
              foundUser.save(function (err) {
                if(!err){
                  res.redirect("/secrets");
                }
              });
            });
          }else {
            res.redirect("/signin");
          }
    });

const PORT = process.env.PORT || 3000;

app.listen(PORT, function() {
    console.log("Server started on Port ${PORT}");
});


问:
how to set configuration macros for esp32 arduino freertos
Are FreeRTOS of espidf framework and freeRTOS of arduino framework different versions on esp32 platform?
and how can I set CONFIG_XXX in ardunino framework? Is this only possible with the espidf version?

I defined CONFIG_XXX in the platformio configuration file(platformio.ini),
however it didn't work.


问:
macoOS openclc crashes with Illegal instruction: 4 when trying to --migrate source code
I have a working Hello World program, borrowed from these two sites.

I'm trying to migrate it to metal code using this command:

openclc --migrate hello.c
```
<p>When I run that command, it crashes with Illegal Instruction 4:</p>
```0  libLLVMContainer.dylib   0x00007ffa3257fc95 PrintStackTrace(void*) + 37
1  libLLVMContainer.dylib   0x00007ffa325800bd SignalHandler(int) + 493
2  libsystem_platform.dylib 0x00007ff81c9d9c1d _sigtramp + 29
3  libsystem_platform.dylib 000000000000000000 _sigtramp + 18446603370100843520
4  openclc                  0x00000001029b246c cc1_main(char const**, char const**, char const*, void*) + 1564
5  openclc                  0x00000001029b4006 main + 1395
6  dyld                     0x00000002034a9310 start + 2432
Stack dump:
0.  Program arguments: /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/openclc -cc1 -triple x86_64-apple-macosx10.18.0 -migrate -disable-free -disable-llvm-verifier -main-file-name ocl.c -pic-level 2 -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 133.3 -resource-dir /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/../lib/clang/3.2 -fmodule-cache-path /var/folders/qy/3y6k069d0h58zd4wkb53ksnh0000gn/T/clang-module-cache -fdebug-compilation-dir /Users/risner/Documents/stackoverflow/winterbash -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10.18.0 -fobjc-dispatch-method=mixed -fobjc-default-synthesize-properties -fdiagnostics-show-option -fcolor-diagnostics -o ocl.remap -x c ocl.c
openclc: error: unable to execute command: Illegal instruction: 4
openclc: error: clang frontend command failed due to signal (use -v to see invocation)
LLVM version 3.2
Target: x86_64-apple-darwin22.1.0
Thread model: posix
openclc: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
openclc: note: diagnostic msg: Error generating preprocessed source(s).
```
<p>I was expecting to see the OpenCL code migrated to Metal code using the <code>openclc</code> tool apple provides to convert OpenCL to native Metal graphics commands.</p>
<p>I should point out this tool is provided with the Operating System, I did not install <code>openclc</code>. It is in a private framework of the OS:</p>
```/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/A/Libraries/openclc
```

Xcode calls this tool automatically when compiling OpenCL code to compile to binary.

Body:
I have a working Hello World program, borrowed from these two sites.

I'm trying to migrate it to metal code using this command:

openclc --migrate hello.c

When I run that command, it crashes with Illegal Instruction 4:

0  libLLVMContainer.dylib   0x00007ffa3257fc95 PrintStackTrace(void*) + 37
1  libLLVMContainer.dylib   0x00007ffa325800bd SignalHandler(int) + 493
2  libsystem_platform.dylib 0x00007ff81c9d9c1d _sigtramp + 29
3  libsystem_platform.dylib 000000000000000000 _sigtramp + 18446603370100843520
4  openclc                  0x00000001029b246c cc1_main(char const**, char const**, char const*, void*) + 1564
5  openclc                  0x00000001029b4006 main + 1395
6  dyld                     0x00000002034a9310 start + 2432
Stack dump:
0.  Program arguments: /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/openclc -cc1 -triple x86_64-apple-macosx10.18.0 -migrate -disable-free -disable-llvm-verifier -main-file-name ocl.c -pic-level 2 -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 133.3 -resource-dir /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/../lib/clang/3.2 -fmodule-cache-path /var/folders/qy/3y6k069d0h58zd4wkb53ksnh0000gn/T/clang-module-cache -fdebug-compilation-dir /Users/risner/Documents/stackoverflow/winterbash -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10.18.0 -fobjc-dispatch-method=mixed -fobjc-default-synthesize-properties -fdiagnostics-show-option -fcolor-diagnostics -o ocl.remap -x c ocl.c
openclc: error: unable to execute command: Illegal instruction: 4
openclc: error: clang frontend command failed due to signal (use -v to see invocation)
LLVM version 3.2
Target: x86_64-apple-darwin22.1.0
Thread model: posix
openclc: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
openclc: note: diagnostic msg: Error generating preprocessed source(s).

I was expecting to see the OpenCL code migrated to Metal code using the openclc tool apple provides to convert OpenCL to native Metal graphics commands.

I should point out this tool is provided with the Operating System, I did not install openclc. It is in a private framework of the OS:

/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/A/Libraries/openclc

Xcode calls this tool automatically when compiling OpenCL code to compile to binary.


问:
Hide some elements when text starts to overflow
I'm making a button that has text content and an icon, I'd like to make it so that when it starts to put content onto multiple lines it hides the icon.

Here's a code example with three cases: one where the content fits just fine and the icon looks good, one where the content can't fit and the icon is pretty lame, and a last one that's more like how I would like it to work with the icon being hidden.

First box fits content

  <button class="reactive-button">

    awesome
  </button>

Second box has lots of content and puts everything on multiple lines

  <button class="reactive-button">

    uh oh
  </button>

If the second example hid the icon (like this) that would be super sweet

  <button class="reactive-button">
    this works
  </button>

```


问:
NextJS 13 - Loading / App Structure Design Issue
Summary : The structure is waiting for query to fully load before loading the page, it works almost like a PHP app where server render has to complete before the page is shown.

I'm trying to get it to at least load the website first , then query and load the server data. Let me provide more information below.

Hosted on Vercel. NextJS 13 App is currently on Beta.

I feel that i structured it wrongly causing the app to run like a server side rendering site. Could you please advise on structures for NextJS 13 App folder.

Route Structure

```<code>    Route (app)                                Size     First Load JS
    ┌ ○ /                                      0 B                0 B
    ├ λ /questions/[questionId]                144 B          66.8 kB
    └ ○ /search
λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
</code>```

From my understanding, NextJS 13 App , by default all are treated as ServerSide pages instead of Client unless you declare the client.

When the Link is clicked routed towards /questions , it will take 2.35 seconds before the UI will update , the 2.35 seconds was a fetch query "fetchQuestions" under the Question File (Code below)

Root File Summary

```<code>import Link from 'next/link';
import { Suspense } from 'react';
import { qLists } from '../typings';
import { SideBarRight } from './SideBarRight';
import { SideBarLeft } from './SideBarLeft';

const fetchqList = async () => {
  const res = await fetch('https://example.com', {
    next: { revalidate: 5 },
  });
  const data = await res.json();
  const qLists: qLists[] = data;
  return qLists;
};

async function Home() {
  const qLists = await fetchqList();
  {qLists.map((qList) => (
     <Link href={`/questions/${qList.id}`}>
       XXX
     </Link>
  ))}
  <SideBars />
  return (xxx);
}
export default Home;
</code>```

Question File Summary

```<code>import Link from 'next/link';
import { Suspense } from 'react';

import { SideBarLeft } from '../../SideBarLeft';
import SideBarRight from '../../SideBarRight';

type PageProps = {
  params: {
    questionId: string;
  };
};

const fetchQuestions = async (questionId: string) => {
  const res = await fetch(`https://exmaple.com/${questionId}`);
  const questions = await res.json();
  return questions;
};

async function questionPage({ params: { questionId } }: PageProps) {
  const question = await fetchQuestions(questionId);

  return (
      <SideBarLeft />
      <Suspense fallback={<p>Loading feed...</p>}>
         {question.items[0].value}
      </Suspense>
  );
}
export default questionPage;
</code>```

Body:
Summary : The structure is waiting for query to fully load before loading the page, it works almost like a PHP app where server render has to complete before the page is shown.

I'm trying to get it to at least load the website first , then query and load the server data. Let me provide more information below.

Hosted on Vercel. NextJS 13 App is currently on Beta.

I feel that i structured it wrongly causing the app to run like a server side rendering site. Could you please advise on structures for NextJS 13 App folder.

Route Structure

    Route (app)                                Size     First Load JS
    ┌ ○ /                                      0 B                0 B
    ├ λ /questions/[questionId]                144 B          66.8 kB
    └ ○ /search
λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)

From my understanding, NextJS 13 App , by default all are treated as ServerSide pages instead of Client unless you declare the client.

When the Link is clicked routed towards /questions , it will take 2.35 seconds before the UI will update , the 2.35 seconds was a fetch query "fetchQuestions" under the Question File (Code below)

Root File Summary

import Link from 'next/link';
import { Suspense } from 'react';
import { qLists } from '../typings';
import { SideBarRight } from './SideBarRight';
import { SideBarLeft } from './SideBarLeft';

const fetchqList = async () => {
  const res = await fetch('https://example.com', {
    next: { revalidate: 5 },
  });
  const data = await res.json();
  const qLists: qLists[] = data;
  return qLists;
};

async function Home() {
  const qLists = await fetchqList();
  {qLists.map((qList) => (
     <Link href={`/questions/${qList.id}`}>
       XXX
     </Link>
  ))}
  <SideBars />
  return (xxx);
}
export default Home;

Question File Summary

import Link from 'next/link';
import { Suspense } from 'react';

import { SideBarLeft } from '../../SideBarLeft';
import SideBarRight from '../../SideBarRight';

type PageProps = {
  params: {
    questionId: string;
  };
};

const fetchQuestions = async (questionId: string) => {
  const res = await fetch(`https://exmaple.com/${questionId}`);
  const questions = await res.json();
  return questions;
};

async function questionPage({ params: { questionId } }: PageProps) {
  const question = await fetchQuestions(questionId);

  return (
      <SideBarLeft />
      <Suspense fallback={
Loading feed...
}>
         {question.items[0].value}
      </Suspense>
  );
}
export default questionPage;


问:
How do I add pagination to my swiftui chat app
I am trying to add pagination to my chat app using swiftui and firebase. I want to listen to the newest 20 messages and as soon as the user scrolls to the top, fetch the oldest messages and display them at the top (previous messages).

this is my current code but it doesn't work like it's supposed to.
Also the scrollview will just occasionally not scroll.

```<code>func loadMoreMessages(chatID: String){
    guard !isLoading, hasMoreMessages else { return }
    isLoading = true

    COLLECTION_PERSONAL_CHAT.document(chatID).collection("Messages").order(by: "timeStamp", descending: false).start(afterDocument: firstSnapshot!).limit(to: 20).getDocuments { (snapshot, error) in
        if let error = error {
            print("Error fetching messages: \(error)")
            self.isLoading = false
            return
        }

        var messagesToAppend : [Message] = []
        let dp = DispatchGroup()
        var documents = snapshot!.documents

        for document in documents {
            dp.enter()
            var data = document.data()
            let id = data["id"] as? String ?? ""
            let type = data["type"] as? String ?? ""
            let value = data["value"] as? String ?? ""
            let repliedMessageID = data["repliedMessageID"] as? String ?? ""
            if type == "repliedMessage"{
                dp.enter()
                self.fetchReplyMessages(chatID: chatID, messageID: repliedMessageID) { fetchedReplyMessage in
                    data["repliedMessage"] = fetchedReplyMessage
                    dp.leave()
                }
            }
            if type == "postMessage"{
                dp.enter()
                self.fetchPost(postID: value){ fetchedPost in
                    data["post"] = fetchedPost
                    dp.leave()
                }
            }
            if type == "pollMessage"{
                dp.enter()

                self.fetchPoll(pollID: value){ fetchedPoll in
                    data["poll"] = fetchedPoll
                    dp.leave()
                }
            }
            if type == "eventMessage"{
                dp.enter()

                self.fetchEvent(eventID: value){ fetchedEvent in
                    data["event"] = fetchedEvent
                    dp.leave()
                }
            }
            dp.leave()
            dp.notify(queue: .main, execute:{
                self.isLoading = false
                self.messages.insert(Message(dictionary: data), at: 0)
                print("loaded 1 more message!")
            })
        }
    }
}

func fetchAllMessages(chatID: String, userID: String){
    //how to paginate
    //1. listen to newest 20 messages [20,19,18,17,...,0]
    //2. fetch 20 starting after the 20th
    self.messages.removeAll()
    self.chatListener = COLLECTION_PERSONAL_CHAT.document(chatID).collection("Messages").order(by: "timeStamp", descending: true).limit(to: 20).addSnapshotListener { snapshot, err in
        if err != nil {
            print(err!.localizedDescription)
            return
        }
        var messagesToReturn : [Message] = []
        let dp = DispatchGroup()

        snapshot?.documentChanges.forEach({ doc in
            dp.enter()
            var data = doc.document.data()
            let id = data["id"] as? String ?? ""
            let type = data["type"] as? String ?? ""
            let value = data["value"] as? String ?? ""
            let repliedMessageID = data["repliedMessageID"] as? String ?? ""
            if type == "repliedMessage"{
                dp.enter()
                self.fetchReplyMessages(chatID: chatID, messageID: repliedMessageID) { fetchedReplyMessage in
                    data["repliedMessage"] = fetchedReplyMessage
                    dp.leave()
                }
            }
            if type == "postMessage"{
                dp.enter()
                self.fetchPost(postID: value){ fetchedPost in
                    data["post"] = fetchedPost
                    dp.leave()
                }
            }
            if type == "pollMessage"{
                dp.enter()

                self.fetchPoll(pollID: value){ fetchedPoll in
                    data["poll"] = fetchedPoll
                    dp.leave()
                }
            }
            if type == "eventMessage"{
                dp.enter()

                self.fetchEvent(eventID: value){ fetchedEvent in
                    data["event"] = fetchedEvent
                    dp.leave()
                }
            }
            dp.leave()
            dp.notify(queue: .main, execute:{

                if doc.type == .added {
                    if !self.messages.contains(where: {$0.id == id}){
                        self.messages.append(Message(dictionary: data))
                    }
                }else if doc.type == .removed{
                    self.messages.removeAll(where: {$0.id == id})
                }else if let index = self.messages.firstIndex(where: {$0.id == id}) {
                    self.messages[index] = Message(dictionary: data)
                }
            })
          //end of foreach document changes
        })

        self.firstSnapshot = snapshot!.documents.first
    }
}
</code>```
```<code>ScrollView{
    ScrollViewReader { scrollViewProxy in
        LazyVStack(spacing: 0){
            ForEach(personalChatVM.messages.reversed().indices, id: \.self){ index in

                MessageCell(message: personalChatVM.messages[index], selectedMessage: $selectedMessage,
                            showOverlay: $showOverlay, personalChatVM: personalChatVM).onAppear{
                    if index == 0{
                        print("seen top")
                    }
                }
            }

            VStack{
                ForEach(personalChatVM.chat.usersTyping){ user in
                    HStack{
                        if user.id == userVM.user?.id ?? " "{
                            Text("You are typing").foregroundColor(Color("AccentColor")).bold()
                        }else{
                            Text("\(user.nickName ?? "") is typing...").foregroundColor(Color("AccentColor")).bold()
                        }
                        Spacer()
                    }.padding(5)
                }
            }
            HStack{Spacer()}.padding(0).id("Empty")
        }.padding(.bottom, self.keyboardHeight)
    }
}
</code>```

Body:
I am trying to add pagination to my chat app using swiftui and firebase. I want to listen to the newest 20 messages and as soon as the user scrolls to the top, fetch the oldest messages and display them at the top (previous messages).

this is my current code but it doesn't work like it's supposed to.
Also the scrollview will just occasionally not scroll.

func loadMoreMessages(chatID: String){
    guard !isLoading, hasMoreMessages else { return }
    isLoading = true

    COLLECTION_PERSONAL_CHAT.document(chatID).collection("Messages").order(by: "timeStamp", descending: false).start(afterDocument: firstSnapshot!).limit(to: 20).getDocuments { (snapshot, error) in
        if let error = error {
            print("Error fetching messages: \(error)")
            self.isLoading = false
            return
        }

        var messagesToAppend : [Message] = []
        let dp = DispatchGroup()
        var documents = snapshot!.documents

        for document in documents {
            dp.enter()
            var data = document.data()
            let id = data["id"] as? String ?? ""
            let type = data["type"] as? String ?? ""
            let value = data["value"] as? String ?? ""
            let repliedMessageID = data["repliedMessageID"] as? String ?? ""
            if type == "repliedMessage"{
                dp.enter()
                self.fetchReplyMessages(chatID: chatID, messageID: repliedMessageID) { fetchedReplyMessage in
                    data["repliedMessage"] = fetchedReplyMessage
                    dp.leave()
                }
            }
            if type == "postMessage"{
                dp.enter()
                self.fetchPost(postID: value){ fetchedPost in
                    data["post"] = fetchedPost
                    dp.leave()
                }
            }
            if type == "pollMessage"{
                dp.enter()

                self.fetchPoll(pollID: value){ fetchedPoll in
                    data["poll"] = fetchedPoll
                    dp.leave()
                }
            }
            if type == "eventMessage"{
                dp.enter()

                self.fetchEvent(eventID: value){ fetchedEvent in
                    data["event"] = fetchedEvent
                    dp.leave()
                }
            }
            dp.leave()
            dp.notify(queue: .main, execute:{
                self.isLoading = false
                self.messages.insert(Message(dictionary: data), at: 0)
                print("loaded 1 more message!")
            })
        }
    }
}

func fetchAllMessages(chatID: String, userID: String){
    //how to paginate
    //1. listen to newest 20 messages [20,19,18,17,...,0]
    //2. fetch 20 starting after the 20th
    self.messages.removeAll()
    self.chatListener = COLLECTION_PERSONAL_CHAT.document(chatID).collection("Messages").order(by: "timeStamp", descending: true).limit(to: 20).addSnapshotListener { snapshot, err in
        if err != nil {
            print(err!.localizedDescription)
            return
        }
        var messagesToReturn : [Message] = []
        let dp = DispatchGroup()

        snapshot?.documentChanges.forEach({ doc in
            dp.enter()
            var data = doc.document.data()
            let id = data["id"] as? String ?? ""
            let type = data["type"] as? String ?? ""
            let value = data["value"] as? String ?? ""
            let repliedMessageID = data["repliedMessageID"] as? String ?? ""
            if type == "repliedMessage"{
                dp.enter()
                self.fetchReplyMessages(chatID: chatID, messageID: repliedMessageID) { fetchedReplyMessage in
                    data["repliedMessage"] = fetchedReplyMessage
                    dp.leave()
                }
            }
            if type == "postMessage"{
                dp.enter()
                self.fetchPost(postID: value){ fetchedPost in
                    data["post"] = fetchedPost
                    dp.leave()
                }
            }
            if type == "pollMessage"{
                dp.enter()

                self.fetchPoll(pollID: value){ fetchedPoll in
                    data["poll"] = fetchedPoll
                    dp.leave()
                }
            }
            if type == "eventMessage"{
                dp.enter()

                self.fetchEvent(eventID: value){ fetchedEvent in
                    data["event"] = fetchedEvent
                    dp.leave()
                }
            }
            dp.leave()
            dp.notify(queue: .main, execute:{

                if doc.type == .added {
                    if !self.messages.contains(where: {$0.id == id}){
                        self.messages.append(Message(dictionary: data))
                    }
                }else if doc.type == .removed{
                    self.messages.removeAll(where: {$0.id == id})
                }else if let index = self.messages.firstIndex(where: {$0.id == id}) {
                    self.messages[index] = Message(dictionary: data)
                }
            })
          //end of foreach document changes
        })

        self.firstSnapshot = snapshot!.documents.first
    }
}

ScrollView{
    ScrollViewReader { scrollViewProxy in
        LazyVStack(spacing: 0){
            ForEach(personalChatVM.messages.reversed().indices, id: \.self){ index in

                MessageCell(message: personalChatVM.messages[index], selectedMessage: $selectedMessage,
                            showOverlay: $showOverlay, personalChatVM: personalChatVM).onAppear{
                    if index == 0{
                        print("seen top")
                    }
                }
            }

            VStack{
                ForEach(personalChatVM.chat.usersTyping){ user in
                    HStack{
                        if user.id == userVM.user?.id ?? " "{
                            Text("You are typing").foregroundColor(Color("AccentColor")).bold()
                        }else{
                            Text("\(user.nickName ?? "") is typing...").foregroundColor(Color("AccentColor")).bold()
                        }
                        Spacer()
                    }.padding(5)
                }
            }
            HStack{Spacer()}.padding(0).id("Empty")
        }.padding(.bottom, self.keyboardHeight)
    }
}


问:
How can I specify a group of `*.d.ts` files?
How can I specify a group of *.d.ts files? In package.json I can set only 1 specific file or an array of them in types, but let's say I have a project consisting of many .ts files and it is unlikely I will need to write them all in package.json. My declaration files are generated by tsc and output to the types folder.

I tried writing types/**/* or types/* - it doesn't work, in the second project where I plug in this tsc it says there are no types and offers to download from @types. Perhaps there is another option solution to the problem, because I have code written in TypeScript, too, and maybe if you plug in ts code types would not be needed, but in package.json in main can specify 1 file and it clearly should be in my case js, because it should be possible to connect the prefect not only to the project with ts.

I also tried creating index.d.ts with

```<code>export { tee } from '/src/ride';
export { test } from '/src/test';
</code>```

and it works, but it still requires specifying every function to be exported. There must be some simple way to export all types at once, or if the project uses ts, then connect not from dist but from src.

Body:
How can I specify a group of *.d.ts files? In package.json I can set only 1 specific file or an array of them in types, but let's say I have a project consisting of many .ts files and it is unlikely I will need to write them all in package.json. My declaration files are generated by tsc and output to the types folder.

I tried writing types/**/* or types/* - it doesn't work, in the second project where I plug in this tsc it says there are no types and offers to download from @types. Perhaps there is another option solution to the problem, because I have code written in TypeScript, too, and maybe if you plug in ts code types would not be needed, but in package.json in main can specify 1 file and it clearly should be in my case js, because it should be possible to connect the prefect not only to the project with ts.

I also tried creating index.d.ts with

export { tee } from '/src/ride';
export { test } from '/src/test';

and it works, but it still requires specifying every function to be exported. There must be some simple way to export all types at once, or if the project uses ts, then connect not from dist but from src.