问:
Disabling UIDocumentPickerViewController's allowsMultipleSelection does not work with rapid selection
I have implemented a UIDocumentPickerViewController using the below code and I want to allow the user to select only a single document. However when the document picker is presented and I rapidly tap on a document twice, the delegate is called twice and two documents are getting added.

```<code>func openDocumentPicker() {
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.jpeg, .png])
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false
    present(documentPicker, animated: true)
}
</code>```

The delegate I used for single file selection is:

```<code>func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    // Handle file selection and display the added file on UI
    dismiss(animated: true)
}
</code>```

This is very strange considering there is a dedicated functionality allowsMultipleSelection which is disabled but does not work. Is there anything I am missing, if not how do I fix this?

Body:
I have implemented a UIDocumentPickerViewController using the below code and I want to allow the user to select only a single document. However when the document picker is presented and I rapidly tap on a document twice, the delegate is called twice and two documents are getting added.

func openDocumentPicker() {
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.jpeg, .png])
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = false
    present(documentPicker, animated: true)
}

The delegate I used for single file selection is:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    // Handle file selection and display the added file on UI
    dismiss(animated: true)
}

This is very strange considering there is a dedicated functionality allowsMultipleSelection which is disabled but does not work. Is there anything I am missing, if not how do I fix this?


来源: stackexchange

问:
Run a loop to insert values
A VBA beginner here. I'm trying to write a code that will add a new column, and using a loop to fill the values in the new column, based on information from other columns. E.g., if a cell in Column 'AL' has "Germany" on it, it will also write "Germany on the new column.
The problem is, that the worksheet includes more than 50k rows and 50 columns, and it takes a few minutes for the loop to be completed. So what I did, is to first filter some values on column 'AL' ("Germany" and "UK"..), run a loop, and then run the loop on another filtered column. But it still takes ages for the two loop to finish.

I wonder if there's a way to improve the process? I think that even though I filtered it, the loop still runs on all values, not just the visible ones.

```<code>Sub Macro6()

      'Filter Germany,UK, EMEA
    Range("AL2").EntireColumn.Insert
    Range("A1").CurrentRegion.AutoFilter 42, Array("Germany", "UK","EMEA")        ''''''
    Range("AQ3").Select
       'Create a loop to insert values
    Do Until ActiveCell.Value = ""
    If ActiveCell.Value = "Germany" Then
    ActiveCell.Offset(0, -5).Value = "Germany"
    ElseIf ActiveCell.Value = "UK" Then
    ActiveCell.Offset(0, -5).Value = "UKI"
    ActiveCell.Offset(0, -5).Value = "EMEA"
    End If
    ActiveCell.Offset(1, 0).Select
    Loop

End Sub

Sub Macro7()

        'Filter APAC, Americas and EMEA
    If ActiveSheet.FilterMode = True Then ActiveSheet.ShowAllData
    Range("A1").CurrentRegion.AutoFilter 38, Array("Americas", "Asia/Pacific", "EMEA")
    Range("AM3").Select
        'Create a loop to insert values
    Do Until ActiveCell.Value = ""
    If ActiveCell.Value = "Americas" Then
    ActiveCell.Offset(0, -1).Value = "Americas"
    ElseIf ActiveCell.Value = "EMEA" Then
    ActiveCell.Offset(0, -1).Value = "EMEA"
    ElseIf ActiveCell.Value = "Asia/Pacific" Then
    ActiveCell.Offset(0, -1).Value = "APAC"
    End If
    ActiveCell.Offset(1, 0).Select
    Loop

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Run a loop to insert values

Body:
A VBA beginner here. I'm trying to write a code that will add a new column, and using a loop to fill the values in the new column, based on information from other columns. E.g., if a cell in Column 'AL' has "Germany" on it, it will also write "Germany on the new column.
The problem is, that the worksheet includes more than 50k rows and 50 columns, and it takes a few minutes for the loop to be completed. So what I did, is to first filter some values on column 'AL' ("Germany" and "UK"..), run a loop, and then run the loop on another filtered column. But it still takes ages for the two loop to finish.

I wonder if there's a way to improve the process? I think that even though I filtered it, the loop still runs on all values, not just the visible ones.

Sub Macro6()

      'Filter Germany,UK, EMEA
    Range("AL2").EntireColumn.Insert
    Range("A1").CurrentRegion.AutoFilter 42, Array("Germany", "UK","EMEA")        ''''''
    Range("AQ3").Select
       'Create a loop to insert values
    Do Until ActiveCell.Value = ""
    If ActiveCell.Value = "Germany" Then
    ActiveCell.Offset(0, -5).Value = "Germany"
    ElseIf ActiveCell.Value = "UK" Then
    ActiveCell.Offset(0, -5).Value = "UKI"
    ActiveCell.Offset(0, -5).Value = "EMEA"
    End If
    ActiveCell.Offset(1, 0).Select
    Loop

End Sub

Sub Macro7()

        'Filter APAC, Americas and EMEA
    If ActiveSheet.FilterMode = True Then ActiveSheet.ShowAllData
    Range("A1").CurrentRegion.AutoFilter 38, Array("Americas", "Asia/Pacific", "EMEA")
    Range("AM3").Select
        'Create a loop to insert values
    Do Until ActiveCell.Value = ""
    If ActiveCell.Value = "Americas" Then
    ActiveCell.Offset(0, -1).Value = "Americas"
    ElseIf ActiveCell.Value = "EMEA" Then
    ActiveCell.Offset(0, -1).Value = "EMEA"
    ElseIf ActiveCell.Value = "Asia/Pacific" Then
    ActiveCell.Offset(0, -1).Value = "APAC"
    End If
    ActiveCell.Offset(1, 0).Select
    Loop

End Sub


问:
Do we need to run load_dotenv() in every module?
I have a .env defined with the following content:

```<code>env=loc
</code>```

I have three python module that make use of this variable.

```<code>├── __init__.py
├── cli.py
|── settings.py
├── commands
│   ├── __init__.py
│   └── output.py
</code>```

settings.py:

```<code>from dotenv import load_dotenv

load_dotenv()

if not os.getenv("env"):
    raise TypeError("'env' variable not found in .env file")
</code>```

output.py:

```<code>import os

def output():
  return getenv("env")
</code>```

cli.py:

```<code>import settings
from commands.output import output
import os

CURR_ENV = getenv("env")
print(CURR_ENV)
print(output())
</code>```

Output:

```<code>loc
None
</code>```

Why is the output from output.py not loc? The environment variables were loaded when load_dotenv() was run for the first time.

Do I have to run load_dotenv() every time I need to access the environment variables?

Body:
I have a .env defined with the following content:

env=loc

I have three python module that make use of this variable.

├── __init__.py
├── cli.py
|── settings.py
├── commands
│   ├── __init__.py
│   └── output.py

settings.py:

from dotenv import load_dotenv

load_dotenv()

if not os.getenv("env"):
    raise TypeError("'env' variable not found in .env file")

output.py:

import os

def output():
  return getenv("env")

cli.py:

import settings
from commands.output import output
import os

CURR_ENV = getenv("env")
print(CURR_ENV)
print(output())

Output:

loc
None

Why is the output from output.py not loc? The environment variables were loaded when load_dotenv() was run for the first time.

Do I have to run load_dotenv() every time I need to access the environment variables?


问:
How to speed up an Electron/Blazor Build on Visual Studio 2022
I have a blazor web assembly project programmed in Visual Studio 2022 Community. I am also using electron with this application. When I build the application this is always happening and it is slowing down my build to like 10 minutes every time I build it. Unacceptable.

```<code>Start Electron Desktop Application...
Arguments:

dotnet publish -r win-x64 -c "Debug" --output "F:\AutoHarp3_Server\AutoHarp_Server\obj\Host\bin" /p:PublishReadyToRun=true /p:PublishSingleFile=true --no-self-contained
MSBuild version 17.3.0+92e077650 for .NET
  Determining projects to restore...
F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj : warning NU1701: Package 'OpenHtmlToPdf 1.12.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0'. This package may not be fully compatible with your project.
  Restored F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj (in 2.46 sec).
          1 file(s) moved.
F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj : warning NU1701: Package 'OpenHtmlToPdf 1.12.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0'. This package may not be fully compatible with your project.
  AutoHarp3_Server -> F:\AutoHarp3_Server\AutoHarp_Server\bin\Debug\net6.0\win-x64\AutoHarp3_Server.dll
node_modules missing in: F:\AutoHarp3_Server\AutoHarp_Server\obj\Host\node_modules
Start npm install...
npm install
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!
</code>```

Any way to fix this so that it will go faster? I'm not even sure why the last line is even happening. This is where the slow down happens.

Edit to show the whole application message from the beginning.

Body:
I have a blazor web assembly project programmed in Visual Studio 2022 Community. I am also using electron with this application. When I build the application this is always happening and it is slowing down my build to like 10 minutes every time I build it. Unacceptable.

Start Electron Desktop Application...
Arguments:

dotnet publish -r win-x64 -c "Debug" --output "F:\AutoHarp3_Server\AutoHarp_Server\obj\Host\bin" /p:PublishReadyToRun=true /p:PublishSingleFile=true --no-self-contained
MSBuild version 17.3.0+92e077650 for .NET
  Determining projects to restore...
F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj : warning NU1701: Package 'OpenHtmlToPdf 1.12.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0'. This package may not be fully compatible with your project.
  Restored F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj (in 2.46 sec).
          1 file(s) moved.
F:\AutoHarp3_Server\AutoHarp_Server\AutoHarp3_Server.csproj : warning NU1701: Package 'OpenHtmlToPdf 1.12.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net6.0'. This package may not be fully compatible with your project.
  AutoHarp3_Server -> F:\AutoHarp3_Server\AutoHarp_Server\bin\Debug\net6.0\win-x64\AutoHarp3_Server.dll
node_modules missing in: F:\AutoHarp3_Server\AutoHarp_Server\obj\Host\node_modules
Start npm install...
npm install
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!

Any way to fix this so that it will go faster? I'm not even sure why the last line is even happening. This is where the slow down happens.

Edit to show the whole application message from the beginning.


问:
How do perform inner join with where criteria in Power BI?
I have 3 tables that I have pulled into Power BI.

DateTable1 (client-wise month start and end dates):
Client|MonthNumber|MonthStartDate|MonthEndDate

DateTable2 (1 row for each day, for each client):
Client|Date|QuarterNumber

FactSales:
OrderDate|OrderAmt|ProductName

I want to create 1 date table in Power BI such that it has 1 row for each day, for each client and has got the MonthNumber, QuarterNumber.

In SQL I would do an inner join on client name and where criteria to filter on the date range.


问:
Google pay isReadyToPay() returns false in Google Chrome in Android mobile
I am running into an issue where isReadyToPay() from google.payments.api.PaymentsClient always returns false in Android Chrome version.(all other devices it works fine)

If I switch to Desktop version in chrome, it starts working and isReadyToPay() returns true.

enter image description here

Payload passed to isReadyToPay()

```<code>{
 "apiVersion":2,
 "apiVersionMinor":0,
  "allowedPaymentMethods":[
  {
     "type":"CARD",
     "parameters":{
        "allowedAuthMethods":[
           "PAN_ONLY",
           "CRYPTOGRAM_3DS"
        ],
        "allowedCardNetworks":[
           "AMEX",
           "DISCOVER",
           "JCB",
           "MASTERCARD",
           "VISA"
        ]
     }
    }
  ]
}
</code>```

I tried changing allowedAuthMethods and Payment methods to see if it helps but it didn't.

Body:
I am running into an issue where isReadyToPay() from google.payments.api.PaymentsClient always returns false in Android Chrome version.(all other devices it works fine)

If I switch to Desktop version in chrome, it starts working and isReadyToPay() returns true.

enter image description here

Payload passed to isReadyToPay()

{
 "apiVersion":2,
 "apiVersionMinor":0,
  "allowedPaymentMethods":[
  {
     "type":"CARD",
     "parameters":{
        "allowedAuthMethods":[
           "PAN_ONLY",
           "CRYPTOGRAM_3DS"
        ],
        "allowedCardNetworks":[
           "AMEX",
           "DISCOVER",
           "JCB",
           "MASTERCARD",
           "VISA"
        ]
     }
    }
  ]
}

I tried changing allowedAuthMethods and Payment methods to see if it helps but it didn't.


问:
Chromecast M3U8 support
I have a problem with m3u8 support on Chromecast. I have two playlists:
https://kofii12345.usermd.net/radio/playlist.m3u8 - works
https://kofii12345.usermd.net/radio/stack.m3u8, https://kofii12345.usermd.net/radio/master.m3u8 - doesn't work

Why the second ones doesn't work?
How to make audio file as m3u8?

Title: Chromecast M3U8 support


问:
NumPy fill method on a scalar
In the following code

```<code>a = numpy.array([1,2,3])
b = a[0]
b.fill(5)
print(b)
print(a)
</code>```

No error is raised. However, it prints 1 for b. I expected 5. Why this?

Title: NumPy fill method on a scalar

Body:
In the following code

a = numpy.array([1,2,3])
b = a[0]
b.fill(5)
print(b)
print(a)

No error is raised. However, it prints 1 for b. I expected 5. Why this?


问:
ProcessMaker web workflow does not show pre-installation correctly
I set processmaker3.3 on ubuntu 20.04. I followed installation from wiki And Finally it is ran on the browser. But there is a problem in pre-installation interface. This is not working correctly and It is messed up and sloppy. I even cleared browser cache and test it on firefox and chrome. Could it be a problem with public_html (e.g: css) files? In addition, I used two different version of pm. Please see pictures:


问:
Creating and updating Excel Tables through xlwings
I'm trying to create and update excel tables through xlwings. The documentation provides a simple exemple to create a table but it returns the following error : AttributeError: 'Sheet' object has no attribute 'tables'

here are the lines

```<code>import xlwings as xw
sheet = xw.Book().sheets[0]
sheet['A1'].value = [['a', 'b'], [1, 2]]
table = sheet.tables.add(source=sheet['A1'].expand(), name='MyTable')
table
</code>```

Am I missing something?

I've went through a couple of old posts but none seems to be adressing manipulations of excel tables...

Body:
I'm trying to create and update excel tables through xlwings. The documentation provides a simple exemple to create a table but it returns the following error : AttributeError: 'Sheet' object has no attribute 'tables'

here are the lines

import xlwings as xw
sheet = xw.Book().sheets[0]
sheet['A1'].value = [['a', 'b'], [1, 2]]
table = sheet.tables.add(source=sheet['A1'].expand(), name='MyTable')
table

Am I missing something?

I've went through a couple of old posts but none seems to be adressing manipulations of excel tables...


问:
How to count and compare odd and even entries in log message in Cloud Watch
I have a aws cloud watch logs in current format:

```<code>CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": true
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": true
}
CloudwatchEntries: Test {
"identifier": "5232",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "5232",
"IsActiveFlag": true
}

</code>```

Those are the 4 entries for eg. In between it can have both even and odd number IsActiveFlag true too and other key different for eg identifier.

My Question is:

How to extract and display only odd entries.

How to compare all the logs and check if IsActiveFlag are different in any odd number and its subsequent entry i.e even number and summarize the count?

Body:
I have a aws cloud watch logs in current format:

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": true
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "8982",
"IsActiveFlag": true
}
CloudwatchEntries: Test {
"identifier": "5232",
"IsActiveFlag": false
}

CloudwatchEntries: Test {
"identifier": "5232",
"IsActiveFlag": true
}

Those are the 4 entries for eg. In between it can have both even and odd number IsActiveFlag true too and other key different for eg identifier.

My Question is:

How to extract and display only odd entries.

How to compare all the logs and check if IsActiveFlag are different in any odd number and its subsequent entry i.e even number and summarize the count?


问:
clang forces use of 5 argument transform
Why does clang insist on choosing the 5 argument form of transform when there is a matching function signature using 4 arguments?

The compiler seems to think toupper is a binary operator, which is strange.

error message:

```<code>enum_days.cpp:18:5: error: no matching function for call to 'transform'
    transform(daystr.begin(), daystr.end(), daystr.begin(), toupper);
    ^~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/transform.h:26:1: note: candidate template ignored: couldn't infer template argument '_UnaryOperation'
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/transform.h:36:1: note: candidate function template not viable: requires 5 arguments, but 4 were provided
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
^
1 error generated.
</code>```

Code:

```<code>#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

typedef enum Days
{
    SUN, MON, TUE, WED, THU, FRI, SAT
} Days;

// map string value of day to the matching the Days ENUM constant
Days str2Days(string &daystr)
{
    Days dayout;

    transform(daystr.begin(), daystr.end(), daystr.begin(), toupper);

    if (daystr == "SUN") dayout = SUN;
    else if (daystr =="MON") dayout = MON;
    else if (daystr =="TUE") dayout = TUE;
    else if (daystr =="WED") dayout = WED;
    else if (daystr =="THU") dayout = THU;
    else if (daystr =="FRI") dayout = FRI;
    else if (daystr =="SAT") dayout = SAT;
    else {
        cout << "Input string for day is incorrect.\n";
        exit(-1);
    }

    return dayout;
}
</code>```

It's as if the compiler doesn't seem to interpret a string as an array of chars.

Body:
Why does clang insist on choosing the 5 argument form of transform when there is a matching function signature using 4 arguments?

The compiler seems to think toupper is a binary operator, which is strange.

error message:

enum_days.cpp:18:5: error: no matching function for call to 'transform'
    transform(daystr.begin(), daystr.end(), daystr.begin(), toupper);
    ^~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/transform.h:26:1: note: candidate template ignored: couldn't infer template argument '_UnaryOperation'
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/transform.h:36:1: note: candidate function template not viable: requires 5 arguments, but 4 were provided
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
^
1 error generated.

Code:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

typedef enum Days
{
    SUN, MON, TUE, WED, THU, FRI, SAT
} Days;

// map string value of day to the matching the Days ENUM constant
Days str2Days(string &daystr)
{
    Days dayout;

    transform(daystr.begin(), daystr.end(), daystr.begin(), toupper);

    if (daystr == "SUN") dayout = SUN;
    else if (daystr =="MON") dayout = MON;
    else if (daystr =="TUE") dayout = TUE;
    else if (daystr =="WED") dayout = WED;
    else if (daystr =="THU") dayout = THU;
    else if (daystr =="FRI") dayout = FRI;
    else if (daystr =="SAT") dayout = SAT;
    else {
        cout << "Input string for day is incorrect.\n";
        exit(-1);
    }

    return dayout;
}

It's as if the compiler doesn't seem to interpret a string as an array of chars.


问:
I am trying to echo a button that pulls content in a file but it outputs outside of the HTML tag
I am trying to echo a button that pulls content from a file that has variable set on it.

```<code>        $vidplayBtn = require __DIR__ . '\..\vid-play-btn.php';
        if( $displayButton ) {
            $output = '<div class="hero-video-play"><div class="container">';
            $output .= $vidplayBtn;
            $output .= '</div></div>';

            echo $output;
        }
</code>```

But the result outputs the button outside the containing HTML tag and adds a 1 character inside it.

```<code><a href="#jsModalVideo" rel="modal:open" role="button" class="btn_play btn_play_color-" title=""> <div class="flex__container_btn-play"> <p>What makes us different?</p> <svg .... </svg> </div> </a>

<div class="hero-video-play"><div class="container">1</div></div>
</code>```

Below is the content of vid-play-btn.php.

```<code><a href="#jsModalVideo<?= $btn_play_c_video_id ?>" rel="modal:open" role="button" class="btn_play btn_play_color-<?= $btn_play_c_color ?>" title="<?= $btn_play_c_title ?>">
  <div class="flex__container_btn-play">
        <p><?= $btn_play_c_caption ?></p>
        <svg version="1.1" class="play" x="0px" y="0px" height="100px" width="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"> <path class="stroke-solid" fill="none" stroke="white" d="M49.9,2.5C23.6,2.8,2.1,24.4,2.5,50.4C2.9,76.5,24.7,98,50.3,97.5c26.4-0.6,47.4-21.8,47.2-47.7 C97.3,23.7,75.7,2.3,49.9,2.5"/> <path class="stroke-dotted" fill="none" stroke="white" d="M49.9,2.5C23.6,2.8,2.1,24.4,2.5,50.4C2.9,76.5,24.7,98,50.3,97.5c26.4-0.6,47.4-21.8,47.2-47.7 C97.3,23.7,75.7,2.3,49.9,2.5"/> <path class="icon" fill="white" d="M38,69c-1,0.5-1.8,0-1.8-1.1 V32.1c0-1.1,0.8-1.6,1.8-1.1l34,18c1,0.5,1,1.4,0,1.9 L38,69z"/> </svg>
  </div></a>
</code>```

What could be causing it? Thanks in advance!

Body:
I am trying to echo a button that pulls content from a file that has variable set on it.

        $vidplayBtn = require __DIR__ . '\..\vid-play-btn.php';
        if( $displayButton ) {
            $output = '

';
            $output .= $vidplayBtn;
            $output .= '

';

            echo $output;
        }

But the result outputs the button outside the containing HTML tag and adds a 1 character inside it.

What makes us different?
 <svg .... </svg>

1

Below is the content of vid-play-btn.php.

<a href="#jsModalVideo<?= $btn_play_c_video_id ?>" rel="modal:open" role="button" class="btn_play btn_play_color-<?= $btn_play_c_color ?>" title="<?= $btn_play_c_title ?>">

<?= $btn_play_c_caption ?>

        <svg version="1.1" class="play" x="0px" y="0px" height="100px" width="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"> <path class="stroke-solid" fill="none" stroke="white" d="M49.9,2.5C23.6,2.8,2.1,24.4,2.5,50.4C2.9,76.5,24.7,98,50.3,97.5c26.4-0.6,47.4-21.8,47.2-47.7 C97.3,23.7,75.7,2.3,49.9,2.5"/> <path class="stroke-dotted" fill="none" stroke="white" d="M49.9,2.5C23.6,2.8,2.1,24.4,2.5,50.4C2.9,76.5,24.7,98,50.3,97.5c26.4-0.6,47.4-21.8,47.2-47.7 C97.3,23.7,75.7,2.3,49.9,2.5"/> <path class="icon" fill="white" d="M38,69c-1,0.5-1.8,0-1.8-1.1 V32.1c0-1.1,0.8-1.6,1.8-1.1l34,18c1,0.5,1,1.4,0,1.9 L38,69z"/> </svg>

What could be causing it? Thanks in advance!


问:
trying to format gt tables, unable to use function ```md```
I'm following this tutorial https://www.youtube.com/watch?v=z0UGmMOxl-c to learn to us gt, and running into the problem that using md( to change fonts is not working as he shows. i'm running the code exactly as he shows in the first few minutes, but nothing happens. is there a package i need to download? a function i need to create?

```<code>library(gt)
library(tidyverse)
library(palmerpenguins)
library(markdown)

penguins%>%
  group_by(species) %>%
summarize_at(
  .vars= c("bill_length_mm",
           "bill_length_mm",
           "flipper_length_mm",
           "body_mass_g"
           ),
  .funs= ~ mean(.,na.rm=TRUE)
  )%>%
  gt(rowname_col = "species")%>%
  tab_header(
    title = md("The *penguins* dataset"),
    subtitle = md("three years of data on penguins on on ***three islands***")
  )
  )%>%
  opt_align_table_header(align="left")
</code>```

furthermore, when i tried to follow his instructions for cols_label i got Error: C stack usage  15923456 is too close to the limit

```<code>penguins%>%
  group_by(species) %>%
summarize_at(
  .vars= c("bill_length_mm",
           "bill_length_mm",
           "flipper_length_mm",
           "body_mass_g"
           ),
  .funs= ~ mean(.,na.rm=TRUE)
  )%>%
  gt(rowname_col = "species")%>%
  tab_header(
    title = md("The *penguins* dataset"),
    subtitle = md("three years of data on penguins on on ***three islands***")
  ) %>%
  cols_label(
    bill_length_mm=md("Bill Length, <br>mm")
  )%>%
  opt_align_table_header(align="left")
</code>```

(second command from bottom)

Body:
I'm following this tutorial https://www.youtube.com/watch?v=z0UGmMOxl-c to learn to us gt, and running into the problem that using md( to change fonts is not working as he shows. i'm running the code exactly as he shows in the first few minutes, but nothing happens. is there a package i need to download? a function i need to create?

library(gt)
library(tidyverse)
library(palmerpenguins)
library(markdown)

penguins%>%
  group_by(species) %>%
summarize_at(
  .vars= c("bill_length_mm",
           "bill_length_mm",
           "flipper_length_mm",
           "body_mass_g"
           ),
  .funs= ~ mean(.,na.rm=TRUE)
  )%>%
  gt(rowname_col = "species")%>%
  tab_header(
    title = md("The *penguins* dataset"),
    subtitle = md("three years of data on penguins on on ***three islands***")
  )
  )%>%
  opt_align_table_header(align="left")

furthermore, when i tried to follow his instructions for cols_label i got Error: C stack usage  15923456 is too close to the limit

penguins%>%
  group_by(species) %>%
summarize_at(
  .vars= c("bill_length_mm",
           "bill_length_mm",
           "flipper_length_mm",
           "body_mass_g"
           ),
  .funs= ~ mean(.,na.rm=TRUE)
  )%>%
  gt(rowname_col = "species")%>%
  tab_header(
    title = md("The *penguins* dataset"),
    subtitle = md("three years of data on penguins on on ***three islands***")
  ) %>%
  cols_label(
    bill_length_mm=md("Bill Length,
mm")
  )%>%
  opt_align_table_header(align="left")

(second command from bottom)


问:
Intermittent OAuth Gmail IMAP authentication failure - no response from server
I have a java client using javamail and google example code to connect to gmail IMAP server using a client secret and OAuth token.  The issue is that about 1/3 of the time, the com.sun.mail.imap.IMAPStore.protocolConnect call fails with an AuthenticationFailedException: Invalid Credentials (Failure) exception.
In the log there are the following lines for each failure:

```<code>DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 1
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@12cdcf4
DEBUG IMAPS: SASL no response
2023-01-04 08:45:55 WARN  ImapStoreFactory.getImapStore.140 - Failed to authenticate to 74.125.142.108 after 5 attempts.
</code>```

(I have a retry loop that backs off after each try up to 5 tries to see if that would help.)

The (partial) stack trace is:

```<code>javax.mail.AuthenticationFailedException: Authentication failed to 74.125.142.108 after 5 attempts.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)
    at com.google.code.samples.oauth2.OAuth2Authenticator.connectToImap(OAuth2Authenticator.java:91)
</code>```

The issue is the SASL no response from the server.

This same code, with the same credentials, works all the other times on the first connection attempt, including to the same IP address, both before and after the failed attempts.

imap.gmail.com resolves to (at least?) 24 different IP addresses that I have seen, and they are all open and accessible from the client machine.

I have tried connecting to a known IP address directly (as opposed to connecting to imap.gmail.com) but then I get a HTTPS certificate failure.

Any ideas as to why this is happening, or how to mitigate or work around would be appreciated.

Thanks!

Linus

Body:
I have a java client using javamail and google example code to connect to gmail IMAP server using a client secret and OAuth token.  The issue is that about 1/3 of the time, the com.sun.mail.imap.IMAPStore.protocolConnect call fails with an AuthenticationFailedException: Invalid Credentials (Failure) exception.
In the log there are the following lines for each failure:

DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 1
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@12cdcf4
DEBUG IMAPS: SASL no response
2023-01-04 08:45:55 WARN  ImapStoreFactory.getImapStore.140 - Failed to authenticate to 74.125.142.108 after 5 attempts.

(I have a retry loop that backs off after each try up to 5 tries to see if that would help.)

The (partial) stack trace is:

javax.mail.AuthenticationFailedException: Authentication failed to 74.125.142.108 after 5 attempts.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)
    at com.google.code.samples.oauth2.OAuth2Authenticator.connectToImap(OAuth2Authenticator.java:91)

The issue is the SASL no response from the server.

This same code, with the same credentials, works all the other times on the first connection attempt, including to the same IP address, both before and after the failed attempts.

imap.gmail.com resolves to (at least?) 24 different IP addresses that I have seen, and they are all open and accessible from the client machine.

I have tried connecting to a known IP address directly (as opposed to connecting to imap.gmail.com) but then I get a HTTPS certificate failure.

Any ideas as to why this is happening, or how to mitigate or work around would be appreciated.

Thanks!

Linus


问:
why did i get an Error saying 'Negative dimension size caused by subtracting 2 from 1' from MaxPooling2D

I was writing a Convolution Neural Network code and this happened, the error continued even after changing the convolutions, I kept getting same errors

inp = Input(shape = (depth, height, width))
conv_1 = Convolution2D(conv_depth_1, kernel_size, kernel_size, padding = 'same', activation = 'relu')(inp)
conv_2 = Convolution2D(conv_depth_1, kernel_size, kernel_size, padding = 'same', activation = 'relu')(conv_1)
pool_1 = MaxPooling2D(pool_size = (pool_size, pool_size))(conv_2)
drop_1 = Dropout(drop_prob_1)(pool_1)

conv_3 = Convolution2D(conv_depth_2,  kernel_size, kernel_size, padding = 'same', activation = 'relu')(drop_1)
conv_4 = Convolution2D(conv_depth_2,  kernel_size, kernel_size, padding = 'same', activation = 'relu')(conv_3)
pool_2 = MaxPooling2D(pool_size = (pool_size, pool_size))(conv_4)
drop_2 = Dropout(drop_prob_1)(pool_2)

flat = Flatten()(drop_2)
hidden = Dense(hidden_size, activation = 'relu')(flat)
drop_3 = Dropout(drop_prob_2)(hidden)
out = Dense(num_classes, activation = 'softmax')(drop_3)
```
<p>I kept getting  this errors</p>
```ValueError: Exception encountered when calling layer "max_pooling2d_15" (type MaxPooling2D).

Negative dimension size caused by subtracting 2 from 1 for '{{node max_pooling2d_15/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NHWC", explicit_paddings=[], ksize=[1, 2, 2, 1], padding="VALID", strides=[1, 2, 2, 1]](Placeholder)' with input shapes: [?,1,1,64].

Call arguments received by layer "max_pooling2d_15" (type MaxPooling2D):
  • inputs=tf.Tensor(shape=(None, 1, 1, 64), dtype=float32)
```

Body:
I was writing a Convolution Neural Network code and this happened, the error continued even after changing the convolutions, I kept getting same errors

inp = Input(shape = (depth, height, width))
conv_1 = Convolution2D(conv_depth_1, kernel_size, kernel_size, padding = 'same', activation = 'relu')(inp)
conv_2 = Convolution2D(conv_depth_1, kernel_size, kernel_size, padding = 'same', activation = 'relu')(conv_1)
pool_1 = MaxPooling2D(pool_size = (pool_size, pool_size))(conv_2)
drop_1 = Dropout(drop_prob_1)(pool_1)

conv_3 = Convolution2D(conv_depth_2,  kernel_size, kernel_size, padding = 'same', activation = 'relu')(drop_1)
conv_4 = Convolution2D(conv_depth_2,  kernel_size, kernel_size, padding = 'same', activation = 'relu')(conv_3)
pool_2 = MaxPooling2D(pool_size = (pool_size, pool_size))(conv_4)
drop_2 = Dropout(drop_prob_1)(pool_2)

flat = Flatten()(drop_2)
hidden = Dense(hidden_size, activation = 'relu')(flat)
drop_3 = Dropout(drop_prob_2)(hidden)
out = Dense(num_classes, activation = 'softmax')(drop_3)

I kept getting  this errors

ValueError: Exception encountered when calling layer "max_pooling2d_15" (type MaxPooling2D).

Negative dimension size caused by subtracting 2 from 1 for '{{node max_pooling2d_15/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NHWC", explicit_paddings=[], ksize=[1, 2, 2, 1], padding="VALID", strides=[1, 2, 2, 1]](Placeholder)' with input shapes: [?,1,1,64].

Call arguments received by layer "max_pooling2d_15" (type MaxPooling2D):
  • inputs=tf.Tensor(shape=(None, 1, 1, 64), dtype=float32)


问:
Failed download telegram files with API :RuntimeError: Event loop is closed
I try to download last 10 files from my telegram private chat but seems to hard to do it

I get this error and other similar errors

```<code>PS C:\Users\Administrator\Desktop\temp> python scaricadatelegram.py
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000002A
B3BCCB80>
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\proactor_events.py", line 116, in __del__
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\proactor_events.py", line 108, in close
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\base_events.py", line 746, in call_soon
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
</code>```

It appears that an exception is thrown when the __del__ method of the _ProactorBasePipeTransport class is called. The trace of this exception indicates that an error occurred while closing an object of type event loop.

I write this code

```<code>import asyncio
import telegram

# Enter your token and chat ID
TOKEN = "5881++++++:++++++++++++++++++++++++++++++++-k0"
CHAT_ID = "-100++++++++++"

# Create an instance of the bot
bot = telegram.Bot(token=TOKEN)

async def main():
    # Get the last 10 messages in all chats
    updates = await bot.get_updates(offset=-10, limit=10)
    messages = updates[::-1]

    # Filter messages that come from private chat
    private_messages = [
        message for message in messages if message.message and message.message.chat.id == CHAT_ID
    ]

    # For each message, check if it contains a file
    for message in private_messages:
        if message.message.document:
            # Download the file and save it in the current path
            file = await bot.download_file(message.message.document.file_id)
            open(f"{message.message.document.file_name}", "wb").write(file)
            print(f"Scaricato il file {message.message.document.file_name}")

def run():
    # Get the current event loop
    loop = asyncio.get_event_loop()

    # Start the coroutine
    loop.run_until_complete(main())

    # Close the loop of events
    loop.close()

# Run the code
run()
</code>```

I replace this part

```<code># Close the loop of events
        loop.close()

    # Run the code
    run()
</code>```

with

```<code>    # Run the code
    run()
</code>```

Now I don't have errors on Terminal but no files from telegram are downloaded

Body:
I try to download last 10 files from my telegram private chat but seems to hard to do it

I get this error and other similar errors

PS C:\Users\Administrator\Desktop\temp> python scaricadatelegram.py
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000002A
B3BCCB80>
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\proactor_events.py", line 116, in __del__
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\proactor_events.py", line 108, in close
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\base_events.py", line 746, in call_soon
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asynci
o\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed

It appears that an exception is thrown when the __del__ method of the _ProactorBasePipeTransport class is called. The trace of this exception indicates that an error occurred while closing an object of type event loop.

I write this code

import asyncio
import telegram

# Enter your token and chat ID
TOKEN = "5881++++++:++++++++++++++++++++++++++++++++-k0"
CHAT_ID = "-100++++++++++"

# Create an instance of the bot
bot = telegram.Bot(token=TOKEN)

async def main():
    # Get the last 10 messages in all chats
    updates = await bot.get_updates(offset=-10, limit=10)
    messages = updates[::-1]

    # Filter messages that come from private chat
    private_messages = [
        message for message in messages if message.message and message.message.chat.id == CHAT_ID
    ]

    # For each message, check if it contains a file
    for message in private_messages:
        if message.message.document:
            # Download the file and save it in the current path
            file = await bot.download_file(message.message.document.file_id)
            open(f"{message.message.document.file_name}", "wb").write(file)
            print(f"Scaricato il file {message.message.document.file_name}")

def run():
    # Get the current event loop
    loop = asyncio.get_event_loop()

    # Start the coroutine
    loop.run_until_complete(main())

    # Close the loop of events
    loop.close()

# Run the code
run()

I replace this part

# Close the loop of events
        loop.close()

    # Run the code
    run()

with

    # Run the code
    run()

Now I don't have errors on Terminal but no files from telegram are downloaded


问:
Set and use variable in RUN instruction using Windows cmd as shell
This is a MWE of my Dockerfile: (I'm hand-composing, not using docker-compose)

```<code># escape=`
FROM mcr.microsoft.com/windows/servercore:ltsc2019-amd64
SHELL ["cmd", "/S", "/C"]
RUN set zz=foo && echo %zz%
</code>```

When I build the container, I expect this to print foo, but instead I get %zz% which seems to indicate that echo doesn't see the variable zz set.

```<code>Step 20/24 : RUN set zz=foo && echo %zz%
 ---> Running in b1f462e81c5c
%zz%
Removing intermediate container b1f462e81c5c
 ---> 9c0abf6eb928
</code>```

If I run this on the command line, it works as expected:

```<code>C:\> cmd /S /C set zz=foo && echo %zz%
foo
</code>```

How can I make the RUN instruction work like the command prompt?

My actual use case, in case this is an XY problem: I'm reading the contents of a user-provided file into a variable and then using that in a command which sets some global config file.

```<code>RUN `
  set /p pat=<your_pat.txt && `
  git config --global url."https://%pat%@github.com/".insteadOf "https://github.com/"
</code>```

Body:
This is a MWE of my Dockerfile: (I'm hand-composing, not using docker-compose)

# escape=`
FROM mcr.microsoft.com/windows/servercore:ltsc2019-amd64
SHELL ["cmd", "/S", "/C"]
RUN set zz=foo && echo %zz%

When I build the container, I expect this to print foo, but instead I get %zz% which seems to indicate that echo doesn't see the variable zz set.

Step 20/24 : RUN set zz=foo && echo %zz%
 ---> Running in b1f462e81c5c
%zz%
Removing intermediate container b1f462e81c5c
 ---> 9c0abf6eb928

If I run this on the command line, it works as expected:

C:\> cmd /S /C set zz=foo && echo %zz%
foo

How can I make the RUN instruction work like the command prompt?

My actual use case, in case this is an XY problem: I'm reading the contents of a user-provided file into a variable and then using that in a command which sets some global config file.

RUN `
  set /p pat=<your_pat.txt && `
  git config --global url."https://%pat%@github.com/".insteadOf "https://github.com/"


问:
Uncaught Error: Attempt to assign property "filename" on null
The below error message is triggered in PHP 8:

Uncaught Error: Attempt to assign property "filename" on null in

This points to this line of code:

$pluginInfo->filename = $this->pluginFile;

The whole section of code is:

```<code>$pluginInfo = null;
    if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){
        $pluginInfo = PluginInfo_2_2::fromJson($result['body'], $this->debugMode);
        $pluginInfo->filename = $this->pluginFile;
        $pluginInfo->slug = $this->slug;
    } else if ( $this->debugMode ) {
        $message = sprintf("The URL %s does not point to a valid plugin metadata file. ", $url);
        if ( is_wp_error($result) ) {
            $message .= "WP HTTP error: " . $result->get_error_message();
        } else if ( isset($result['response']['code']) ) {
            $message .= "HTTP response code is " . $result['response']['code'] . " (expected: 200)";
        } else {
            $message .= "wp_remote_get() returned an unexpected result.";
        }
        trigger_error($message, E_USER_WARNING);
    }

    $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
    return $pluginInfo;
}
</code>```

Still at early stages of learning PHP, and struggling to rewrite this code for PHP 8 compatibility.

Any help would be appreciated.

Only current fix is to go back to PHP 7.4.

Body:
The below error message is triggered in PHP 8:

Uncaught Error: Attempt to assign property "filename" on null in

This points to this line of code:

$pluginInfo->filename = $this->pluginFile;

The whole section of code is:

$pluginInfo = null;
    if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){
        $pluginInfo = PluginInfo_2_2::fromJson($result['body'], $this->debugMode);
        $pluginInfo->filename = $this->pluginFile;
        $pluginInfo->slug = $this->slug;
    } else if ( $this->debugMode ) {
        $message = sprintf("The URL %s does not point to a valid plugin metadata file. ", $url);
        if ( is_wp_error($result) ) {
            $message .= "WP HTTP error: " . $result->get_error_message();
        } else if ( isset($result['response']['code']) ) {
            $message .= "HTTP response code is " . $result['response']['code'] . " (expected: 200)";
        } else {
            $message .= "wp_remote_get() returned an unexpected result.";
        }
        trigger_error($message, E_USER_WARNING);
    }

    $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
    return $pluginInfo;
}

Still at early stages of learning PHP, and struggling to rewrite this code for PHP 8 compatibility.

Any help would be appreciated.

Only current fix is to go back to PHP 7.4.


问:
Concatenating values in a pandas dataframe by two non-overlapping groupping variable
I have a pandas dataframe with two columns: doc_ID and paragraph_ID. I want to concatenate the values in the sentences column for each group defined by doc_ID and paragraph_ID. If the size of the group is greater than 7, the sentences column should be concatenated for each group defined by paragraph_ID. If the size of the group is 7 or less, the sentences column should be concatenated for each group defined by doc_ID.

I wrote the following function to do this, but it is not working as expected:

```<code>def concatenate_sentences(group):
    if len(group) > 7:
        return ' '.join(group.groupby('paragraph_ID')['sentences'].sum())
    else:
        return ' '.join(group.groupby('doc_ID')['sentences'].sum())

test_df = df.groupby(['paragraph_ID', 'doc_ID']).apply(concatenate_sentences).reset_index()

</code>```

Notes:

The dataframe has the following structure:

doc_ID
paragraph_ID
sentences

1
1
Lorem

1
1
ipsum

1
2
dolor

2
1
sit

2
2
amet

The resulting dataframe should look something like this

doc_ID
paragraph_ID
sentences

1
1
Lorem ipsum

1
2
dolor

2
1
sit amet

Body:
I have a pandas dataframe with two columns: doc_ID and paragraph_ID. I want to concatenate the values in the sentences column for each group defined by doc_ID and paragraph_ID. If the size of the group is greater than 7, the sentences column should be concatenated for each group defined by paragraph_ID. If the size of the group is 7 or less, the sentences column should be concatenated for each group defined by doc_ID.

I wrote the following function to do this, but it is not working as expected:

def concatenate_sentences(group):
    if len(group) > 7:
        return ' '.join(group.groupby('paragraph_ID')['sentences'].sum())
    else:
        return ' '.join(group.groupby('doc_ID')['sentences'].sum())

test_df = df.groupby(['paragraph_ID', 'doc_ID']).apply(concatenate_sentences).reset_index()

Notes:

The dataframe has the following structure:

doc_ID
paragraph_ID
sentences

1
1
Lorem

1
1
ipsum

1
2
dolor

2
1
sit

2
2
amet

The resulting dataframe should look something like this

doc_ID
paragraph_ID
sentences

1
1
Lorem ipsum

1
2
dolor

2
1
sit amet


问:
Sending email by Nodemailer with GoDaddy hosted email, problem with sending on vercel.com
this is my config for nodemailer which is working on localhost without any problems.

```<code>export const transporter = nodemailer.createTransport({
  pool: true,
  service: 'Godaddy',
  host: 'smtp.secureserver.net',
  port: 587,
  secure: false,
  auth: {
    user: email,
    pass,
  },
});
</code>```

After deploy on vercel.com there is a problem while I'm sending an email. On screenshot you can see this error.

Propably the reason why I get this error is Serverless Function Execution Timeout.

Maybe somebody knwos how to fix it?

enter image description here

I tryed every configurations from here link

Body:
this is my config for nodemailer which is working on localhost without any problems.

export const transporter = nodemailer.createTransport({
  pool: true,
  service: 'Godaddy',
  host: 'smtp.secureserver.net',
  port: 587,
  secure: false,
  auth: {
    user: email,
    pass,
  },
});

After deploy on vercel.com there is a problem while I'm sending an email. On screenshot you can see this error.

Propably the reason why I get this error is Serverless Function Execution Timeout.

Maybe somebody knwos how to fix it?

enter image description here

I tryed every configurations from here link


问:
Unable to set working directory for Jupyter Lab on Mac
I'm working with Jupyter Lab on a Mac.  I've been trying to change the working directory in a .ipynb script via os.chdir(), so I can use the code to iteratively process multiple files in the working directory.

Eventually, I would like to use os.listdir() to iterate through the files in the directory.

My laptop files show up properly in the menu on the left, but for some reason, the following code won't work:

```<code># set working directory
os.chdir('C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python')
path = os.getcwd()
</code>```

It produces the error: FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python'

I've quadruple checked the path names and tried all combinations of '', "", as well as , \, and /.

I read that I should try modifying the jupyter config file.  But when I download the file (via jupyter notebook --generate-config), the only lines in the file are:

```<code>c.NotebookApp.allow_credentials = False
c.NotebookApp.port = 8889
c.NotebookApp.password_required = True
</code>```

There is no line for c.NotebookApp.notebook_dir = ''.

Unsure why I'm having so much trouble with this.  Any insight would be greatly appreciated!  Thanks ahead of time!

Body:
I'm working with Jupyter Lab on a Mac.  I've been trying to change the working directory in a .ipynb script via os.chdir(), so I can use the code to iteratively process multiple files in the working directory.

Eventually, I would like to use os.listdir() to iterate through the files in the directory.

My laptop files show up properly in the menu on the left, but for some reason, the following code won't work:

# set working directory
os.chdir('C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python')
path = os.getcwd()

It produces the error: FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python'

I've quadruple checked the path names and tried all combinations of '', "", as well as , \, and /.

I read that I should try modifying the jupyter config file.  But when I download the file (via jupyter notebook --generate-config), the only lines in the file are:

c.NotebookApp.allow_credentials = False
c.NotebookApp.port = 8889
c.NotebookApp.password_required = True

There is no line for c.NotebookApp.notebook_dir = ''.

Unsure why I'm having so much trouble with this.  Any insight would be greatly appreciated!  Thanks ahead of time!


问:
documenting CSV data, using python

Not sure this is the right place to ask, but it has to be a common problem.

I'm collecting AC voltage(real, apparent, etc.) vs. an input parameter to measure the performance of a solar inverter. I read data from a meter, the invert, and other test equipment and then write the data to a CSV file for later plotting. The details here are not important except to say that part works.

There are various modes available with their own values that I want to record with the data.  I.e., I might set the foo-parameter to 0.5 and then record the complex voltage output versus the DC input.  I need to do this for several values of the foo-parameter, and many parameters should be recorded.

I've modified my plot routine to allow #comment lines.  This will allow me to record the parameters that were selected for any data set.

Is there a standard way of doing this, or otherwise documenting data collected like this?

Title: documenting CSV data, using python


问:
Use plsda as method in caret::train (R)
I'd like to perform classification with plsda and use the caret::train function to take care of the cross validation. I see that plsda is included in caret, but the example doesn't show it used with train. Instead the train and test sets are hardcoded once. When I try to include method = plsrda in caret::train I get

```<code>Error: Model plsda is not in caret's built-in library
</code>```

I know one option is to code a cross-validated plsda myself, but I'd really like to just throw it into caret::train. Is this possible?

Title: Use plsda as method in caret::train (R)

Body:
I'd like to perform classification with plsda and use the caret::train function to take care of the cross validation. I see that plsda is included in caret, but the example doesn't show it used with train. Instead the train and test sets are hardcoded once. When I try to include method = plsrda in caret::train I get

Error: Model plsda is not in caret's built-in library

I know one option is to code a cross-validated plsda myself, but I'd really like to just throw it into caret::train. Is this possible?


问:
mount efs from different vpc in different account using transit gateway using dns
I am trying to mount to a shared efs in one account's vpc with another ec2(s) in another account's vpc.

I have a transit gateway set up with the relevant routing in place.

I am trying to mount with dns , the efs dns is only resolvable in the account where it resides and I am trying to steer away from using IPs because the ec2s can be in different in availabilty zones.

Is there any way to resolve the dns with a single dns entry that will resolve to the mount target in the correct availability zone ?

Authorizing hosted zones between is not an issue , I am just struggling to find a clean way of doing this . I've thought of trying efs-a.example.com and it's respective az mount target ip . But I'd still like something that can be like efs.example.com to resolve the respective azs efs ip.

Is using IPs the only way to mount correctly based on azs besides the solution the above yet similar solution ?


问:
Containerd list all containers through containerd.sock
I am looking for the way of listing containers in containerd through
/run/containerd/containerd.sock
in the same way as it is done for Docker https://docs.docker.com/engine/api/v1.41/#tag/Container/operation/ContainerList.

I have already tried

grpcurl -proto /containerd/api/services/containers/v1/containers.proto
-unix /run/containerd/containerd.sock containerd.services.containers.v1.Containers/List

And got the following error

Failed to dial target host "/run/containerd/containerd.sock": tls:
first record does not look like a TLS handshake

What am I doing wrong?


问:
git pull one small commit, fatal: pack has bad object at offset 2715294897: inflate returned 1 fatal: fetch-pack: invalid index-pack output
I'm trying to git pull after coming back from the holidays and I'm running into this error:

```<code>$git pull
remote: Azure Repos
remote: Found 499 objects to send. (105 ms)
fatal: pack has bad object at offset 2460869627: inflate returned 1
fatal: fetch-pack: invalid index-pack output
</code>```

According to all the other similar posts I've seen, the problem is related to large files over unstable internet. However, I checked the git log and it seems I'm missing only one commit a972c3de and the contents of this commit is only a 5 line documentation change.

I'm confused on a couple different fronts: why does my pull find 499 objects to send if I'm only pulling one commit? Is there something about the nature of git pull that I'm missing? And how do I fix this issue?

```<code>$git log
commit 81002f8ee963b75aa1fc2c3472f6cc7b585d0c97 (HEAD -> master, origin/master, origin/HEAD)
Author: Yuning Deng <yuningdeng@microsoft.com>
Date:   Mon Sep 5 07:40:44 2022 +0000

    Merged PR 337: fix kpe frontend error

    fix kpe frontend error

commit b752478346f7e910ad45523a2503b87434e9a0f6
Author: Prerna Singh <prernasingh@microsoft.com>
Date:   Wed Aug 17 21:13:34 2022 +0000

    Merged PR 324: merge sdv2 model to master

    - merging sdv2 model code to master

commit 8cb84335b4c0983c2734d7db887f26131b4d7d7c (xianx/fix_blingdemo_ng_env)
Author: Xian Xu <xianx@microsoft.com>
Date:   Mon Aug 15 23:18:28 2022 +0000

    Merged PR 329: updating documentation for blingdemo

    updating documentation for blingdemo
</code>```

Body:
I'm trying to git pull after coming back from the holidays and I'm running into this error:

$git pull
remote: Azure Repos
remote: Found 499 objects to send. (105 ms)
fatal: pack has bad object at offset 2460869627: inflate returned 1
fatal: fetch-pack: invalid index-pack output

According to all the other similar posts I've seen, the problem is related to large files over unstable internet. However, I checked the git log and it seems I'm missing only one commit a972c3de and the contents of this commit is only a 5 line documentation change.

I'm confused on a couple different fronts: why does my pull find 499 objects to send if I'm only pulling one commit? Is there something about the nature of git pull that I'm missing? And how do I fix this issue?

$git log
commit 81002f8ee963b75aa1fc2c3472f6cc7b585d0c97 (HEAD -> master, origin/master, origin/HEAD)
Author: Yuning Deng <yuningdeng@microsoft.com>
Date:   Mon Sep 5 07:40:44 2022 +0000

    Merged PR 337: fix kpe frontend error

    fix kpe frontend error

commit b752478346f7e910ad45523a2503b87434e9a0f6
Author: Prerna Singh <prernasingh@microsoft.com>
Date:   Wed Aug 17 21:13:34 2022 +0000

    Merged PR 324: merge sdv2 model to master

    - merging sdv2 model code to master

commit 8cb84335b4c0983c2734d7db887f26131b4d7d7c (xianx/fix_blingdemo_ng_env)
Author: Xian Xu <xianx@microsoft.com>
Date:   Mon Aug 15 23:18:28 2022 +0000

    Merged PR 329: updating documentation for blingdemo

    updating documentation for blingdemo


问:
How to get new issues to show up at the top of Github Project's boards instead of being shown at the bottom?
Recently, the company where I work started using GitHub Projects.

GitHub projects has a native integration with other features from GitHub, such as issues and Pull Requests.

The team would like to change the behavior a bit so that newly created issues are shown at the top of the column on the GitHub Projects board instead of being shown at the bottom.

Is this possible? If yes, how to do it?


问:
FireBase Test Not Sending Notifications
I am working with a Vanilla React Native project that uses Expo Modules (NOT built on Expo) and I am trying to hook up Firebase Push Notifications. I followed the instructions here and it seems like everything should be working. I get the Firebase Token as expected, and there are no firebase errors in the console. The Notifications Permissions pop up appears when I run it on an emulator, letting me know that it's properly configured on Apple's side of things.

The kicker is that I had everything working, but I needed to create a new Firebase project because I changed the App's Bundler ID. Since you cannot edit the Firebase Projects' Bundler ID's, I had to start a new project on
Firebase, but all of the code in my Podfile, AppDelegate, and other files in the code base was already there and did not need to be changed in any way. The only thing code-wise to be changed was the GoogleService-Info.plist file that Firebase provides.

However, when I extract the FCM Token and use it in the Firebase Cloud Messaging Test page, (shown below) nothing happens when I send the test message.

What can I do to try to fix this? I've gone over the steps again and again, making sure I have the proper Apple Key, Provisioning Profile, and Certificate, and that they've been properly uploaded to Firebase. I've also checked inside of Xcode to make sure that Push Notifications and Background Services were enabled, and they both were.

Title: FireBase Test Not Sending Notifications


问:
Trying to use angular brackets
When writing code how do I get angular brackets on windows 11? I tried YouTubing it and also looking it up on Google. I have been stuck trying to figure this out and haven’t been able to.</p>

Title: Trying to use angular brackets


问:
How can I ensure that both the header and the cells of table have the same alignment in React
say you have the following component tree

```<code><Table>
  <Header>
    <HeadCell text-align="left">Head Cell left-aligned</HeadCell>
    <HeadCell text-align="right">Head Cell right-aligned</HeadCell>
  </Header>
  <Body>
    <Row>
     <Cell>should be left-aligned like head</Cell>
     <Cell>should be right-aligned like head</Cell>
    </ Row>
  </Body>
</Table>
</code>```

How could I ensure that the Cells in the Body have the same alignment as their respective HeadCells.

While this could easily be accomplished imperatively with, say good-old jQuery, I'm looking for a more declarative, componenty way of doing it.

Body:
say you have the following component tree

    <HeadCell text-align="left">Head Cell left-aligned</HeadCell>
    <HeadCell text-align="right">Head Cell right-aligned</HeadCell>

    <Row>
     <Cell>should be left-aligned like head</Cell>
     <Cell>should be right-aligned like head</Cell>
    </ Row>

How could I ensure that the Cells in the Body have the same alignment as their respective HeadCells.

While this could easily be accomplished imperatively with, say good-old jQuery, I'm looking for a more declarative, componenty way of doing it.


问:
Most effective way to Rearrange Custom Controls in a FlowLayoutPanel?
I am creating a video parser in C# WinForms. You select files, they get parsed then a custom control (ViewWideNarrow ) is created showing the video's name, duration and so forth, which is then added to FlowLayoutPanel1.

The user then selects in what order to display said custom controls, alphabetically or by Bitrate. My code below works just fine, but it takes a couple of seconds to reorganize around two hundred controls, and I fear on weaker machines it might take even longer, and I wish to optimize the code, or how I handle the custom controls to begin with in respect with modest memory usage. Right now I do not have leaks or high usage.

I decided to use an ID'ing system like so to save memory:

```<code>//ID of the control, and ViewWideNarrow is the custom control itself shown in the FlowLayoutPanel
public Dictionary<int, ViewWideNarrow> Lookup_VideoView = new Dictionary<int, ViewWideNarrow>();

//ID of the control and its respective video's bitrate.
public Dictionary<int, int> Lookup_Bitrate = new Dictionary<int, int>();

//ID of the control and its respective video's title.
public Dictionary<int, string> Lookup_Alphabetical = new Dictionary<int, string>();
</code>```

Which I then organize accordingly to use FI-FO kind of system using:

```<code>Lookup_Alphabetical = Lookup_Alphabetical.OrderBy(item => item.Value, new ComparerAlphabet()).ToDictionary(item => item.Key, item => item.Value);

Lookup_Bitrate = Lookup_Bitrate.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
</code>```

And below is the actual control organization, which is what actually takes a while to complete and is what I suspect needs working on.

```<code>private void OrganizeControls()
        {
            if (SortingOption == Sorting.Alphabetical)
            {
                int h = 0;
                foreach (var item in Lookup_Alphabetical)
                {
                    int key = item.Key;
                    string value = item.Value;
                    ViewWideNarrow View = Lookup_VideoView[key];

                    if (FlowLayoutPanel1.Controls.Contains(View))
                    {
            FlowLayoutPanel1.Controls.SetChildIndex(View, h);
                        h++;
                    }
                }
            }
    }
</code>```

Body:
I am creating a video parser in C# WinForms. You select files, they get parsed then a custom control (ViewWideNarrow ) is created showing the video's name, duration and so forth, which is then added to FlowLayoutPanel1.

The user then selects in what order to display said custom controls, alphabetically or by Bitrate. My code below works just fine, but it takes a couple of seconds to reorganize around two hundred controls, and I fear on weaker machines it might take even longer, and I wish to optimize the code, or how I handle the custom controls to begin with in respect with modest memory usage. Right now I do not have leaks or high usage.

I decided to use an ID'ing system like so to save memory:

//ID of the control, and ViewWideNarrow is the custom control itself shown in the FlowLayoutPanel
public Dictionary<int, ViewWideNarrow> Lookup_VideoView = new Dictionary<int, ViewWideNarrow>();

//ID of the control and its respective video's bitrate.
public Dictionary<int, int> Lookup_Bitrate = new Dictionary<int, int>();

//ID of the control and its respective video's title.
public Dictionary<int, string> Lookup_Alphabetical = new Dictionary<int, string>();

Which I then organize accordingly to use FI-FO kind of system using:

Lookup_Alphabetical = Lookup_Alphabetical.OrderBy(item => item.Value, new ComparerAlphabet()).ToDictionary(item => item.Key, item => item.Value);

Lookup_Bitrate = Lookup_Bitrate.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

And below is the actual control organization, which is what actually takes a while to complete and is what I suspect needs working on.

private void OrganizeControls()
        {
            if (SortingOption == Sorting.Alphabetical)
            {
                int h = 0;
                foreach (var item in Lookup_Alphabetical)
                {
                    int key = item.Key;
                    string value = item.Value;
                    ViewWideNarrow View = Lookup_VideoView[key];

                    if (FlowLayoutPanel1.Controls.Contains(View))
                    {
            FlowLayoutPanel1.Controls.SetChildIndex(View, h);
                        h++;
                    }
                }
            }
    }


问:
React Webpack.config.js issue
Being fairly new to the world of react, I'm trying to create a successfully webpack.config.js for my react solution. My webpack.config.js contains the following code:

```<code>
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/index.js',
    plugins: [
        new HtmlWebpackPlugin({
          title: 'Caching',
          template: './index.html'
        })
      ],
    output: {
        filename: 'main.[hash].js',
        chunkFilename: '[name].[hash].[chunkhash].chunk.js',
        path: path.resolve(__dirname, 'build'),
        clean: true,
        publicPath: ""
    },
    optimization: {
        moduleIds: 'deterministic',
         runtimeChunk: 'single',
         splitChunks: {
           cacheGroups: {
             vendor: {
               test: /[\\/]node_modules[\\/]/,
               name: 'vendors',
               chunks: 'all',
             },
           },
         },
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: {
                                localIdentName: "[name]__[local]___[hash:base64:5]",
                            },
                            sourceMap: true
                        }
                     }
                  ]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                loader: 'url-loader?limit=10000&name=img/[name].[ext]'
            }
        ]
    }
};
</code>```

However, when I execute npm run build the following files are created.
enter image description here

And the webpack.plugin interjects this line into my entry point
enter image description here

Which is obvious the wrong name, producing a 404 error message. I have read a number of articles about creating Webpack.config.js  but I'm unable to resolve my issue for removing the 404 error and getting the correct filename interjected into my entry point

Title: React Webpack.config.js issue

Body:
Being fairly new to the world of react, I'm trying to create a successfully webpack.config.js for my react solution. My webpack.config.js contains the following code:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/index.js',
    plugins: [
        new HtmlWebpackPlugin({
          title: 'Caching',
          template: './index.html'
        })
      ],
    output: {
        filename: 'main.[hash].js',
        chunkFilename: '[name].[hash].[chunkhash].chunk.js',
        path: path.resolve(__dirname, 'build'),
        clean: true,
        publicPath: ""
    },
    optimization: {
        moduleIds: 'deterministic',
         runtimeChunk: 'single',
         splitChunks: {
           cacheGroups: {
             vendor: {
               test: /[\\/]node_modules[\\/]/,
               name: 'vendors',
               chunks: 'all',
             },
           },
         },
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: {
                                localIdentName: "[name]__[local]___[hash:base64:5]",
                            },
                            sourceMap: true
                        }
                     }
                  ]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                loader: 'url-loader?limit=10000&name=img/[name].[ext]'
            }
        ]
    }
};

However, when I execute npm run build the following files are created.
enter image description here

And the webpack.plugin interjects this line into my entry point
enter image description here

Which is obvious the wrong name, producing a 404 error message. I have read a number of articles about creating Webpack.config.js  but I'm unable to resolve my issue for removing the 404 error and getting the correct filename interjected into my entry point


问:
Is it ok to use `runBlocking{}` on ExoPlayer's playback thread?
Using ExoPlayer, I need to make a network call just before playback (similar in part to this issue). The network result is also used to to build AdsConfiguration and DrmConfiguration, which are provided to the MediaItem.Builder.

The following code works fine, but I cannot find documentation that confirms it's ok!

```<code>override fun createMediaSource(mediaItem: MediaItem): MediaSource {
    val builder = mediaItem.buildUpon()

// Is it ok to use `runBlocking` here?
    val remoteData = runBlocking {
         fetchPlayableMedia()
    }

    remoteData?.let {
        builder.setUri(it.mediaUri)
            .setAdsConfiguration(it.toAdsConfiguration())
            .setDrmConfiguration(it.toDrmConfiguration())
    }

    return mediaSourceDelegate.createMediaSource(builder.build())
}
</code>```

MediaSource doc says

All methods are called on the player's internal playback thread

which is different from the background thread.

I tried using a ResolvingDataSource, where documentation for resolveDataSpec() clearly mentions

This method is allowed to block until the DataSpec has been resolved.

But resolveDataSpec() is called only after createMediaSource(mediaItem), so it seems too late to set Ads/DRM configuration.

The DataSourceFactory does call createDataSource(), but I'm not sure if httpDataSource.setRequestProperty() can be used to configure Ads/DRM.

To put it differently: how can one do a network call on ExoPlayer's background thread, just before playback, and use the data to set Ads/DRM configuration?

Body:
Using ExoPlayer, I need to make a network call just before playback (similar in part to this issue). The network result is also used to to build AdsConfiguration and DrmConfiguration, which are provided to the MediaItem.Builder.

The following code works fine, but I cannot find documentation that confirms it's ok!

override fun createMediaSource(mediaItem: MediaItem): MediaSource {
    val builder = mediaItem.buildUpon()

// Is it ok to use `runBlocking` here?
    val remoteData = runBlocking {
         fetchPlayableMedia()
    }

    remoteData?.let {
        builder.setUri(it.mediaUri)
            .setAdsConfiguration(it.toAdsConfiguration())
            .setDrmConfiguration(it.toDrmConfiguration())
    }

    return mediaSourceDelegate.createMediaSource(builder.build())
}

MediaSource doc says

All methods are called on the player's internal playback thread

which is different from the background thread.

I tried using a ResolvingDataSource, where documentation for resolveDataSpec() clearly mentions

This method is allowed to block until the DataSpec has been resolved.

But resolveDataSpec() is called only after createMediaSource(mediaItem), so it seems too late to set Ads/DRM configuration.

The DataSourceFactory does call createDataSource(), but I'm not sure if httpDataSource.setRequestProperty() can be used to configure Ads/DRM.

To put it differently: how can one do a network call on ExoPlayer's background thread, just before playback, and use the data to set Ads/DRM configuration?


问:
ios - Change tabs and open modal window dynamically
I have an app that sends local notiffications at specific times. When the user taps on the notification, the app should open on a particular tab (a library tab) and then open automatically one of the lessons (without the user having to tap on it).

I can get the app to switch to the Library tab, but the modal with the lesson never appears.

This is the code I'm using:

```<code>    if let tabBarController = window.rootViewController as? UITabBarController {

        // this works
        tabBarController.selectedViewController!.dismiss(animated: true, completion: nil)
        tabBarController.selectedViewController = tabBarController.viewControllers?[1]

        // Segue to particular lesson
        let vc = tabBarController.selectedViewController as? LibraryViewController
        let lessonVC = LessonViewController()

        let les60 = Lesson(lessonNumber: "60")

        lessonVC.delegate = vc
        lessonVC.lesson = les60
        vc?.present(UINavigationController(rootViewController: lessonVC), animated: true)

    }
</code>```

This is the code I use for every item in the Library:

```<code>    let lessonVC = LessonViewController()
    lessonVC.delegate = self
    lessonVC.lesson = lessonsArray[indexPath.row]
    present(UINavigationController(rootViewController: lessonVC), animated: true)
</code>```

so I tried to replicate it above but it does not work.

Body:
I have an app that sends local notiffications at specific times. When the user taps on the notification, the app should open on a particular tab (a library tab) and then open automatically one of the lessons (without the user having to tap on it).

I can get the app to switch to the Library tab, but the modal with the lesson never appears.

This is the code I'm using:

    if let tabBarController = window.rootViewController as? UITabBarController {

        // this works
        tabBarController.selectedViewController!.dismiss(animated: true, completion: nil)
        tabBarController.selectedViewController = tabBarController.viewControllers?[1]

        // Segue to particular lesson
        let vc = tabBarController.selectedViewController as? LibraryViewController
        let lessonVC = LessonViewController()

        let les60 = Lesson(lessonNumber: "60")

        lessonVC.delegate = vc
        lessonVC.lesson = les60
        vc?.present(UINavigationController(rootViewController: lessonVC), animated: true)

    }

This is the code I use for every item in the Library:

    let lessonVC = LessonViewController()
    lessonVC.delegate = self
    lessonVC.lesson = lessonsArray[indexPath.row]
    present(UINavigationController(rootViewController: lessonVC), animated: true)

so I tried to replicate it above but it does not work.


问:
How to combine all my tables into one (except one of them)
I found this code that allows me to combine all the tables in my Access DB into one big one:

```<code>Dim db As DAO.Database
Dim tdf As DAO.TableDef

Set db = currentdb
For Each tdf In db.TableDefs
    If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
                StrSQL = "INSERT INTO " & "test" & " " & _
                "SELECT * " & _
                "FROM " & tdf.Name & " ;"
            DoCmd.RunSQL StrSQL
    End If
</code>```

It works perfectly but I now need this to combine all the tables but one (called Table1). I wanted to ask this question as a comment on that post but I don't have the rep to comment on it.

Bellow is the changes I've tried but haven't worked.

```<code>"FROM " & tdf.Name & " WHERE <> Table1;"
</code>```

Body:
I found this code that allows me to combine all the tables in my Access DB into one big one:

Dim db As DAO.Database
Dim tdf As DAO.TableDef

Set db = currentdb
For Each tdf In db.TableDefs
    If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
                StrSQL = "INSERT INTO " & "test" & " " & _
                "SELECT * " & _
                "FROM " & tdf.Name & " ;"
            DoCmd.RunSQL StrSQL
    End If

It works perfectly but I now need this to combine all the tables but one (called Table1). I wanted to ask this question as a comment on that post but I don't have the rep to comment on it.

Bellow is the changes I've tried but haven't worked.

"FROM " & tdf.Name & " WHERE <> Table1;"


问:
Why am I getting this error when running a Python script with the MySQL Connector?
So I am currently working on a project which involves creating a Python application to interact with a MySQL database.

With this Python app, i was able to successfully insert rows into a table known as student, but when inserting a row into the enrollment table, it will not work. I will attach all information which may be useful below. Thanks for any help that you can provide!

Python Code:

```<code>import mysql.connector
from mysql.connector import errorcode

def printEmptySpace():
    print("\n\n\n\n\n\n\n")

try:
  #connection opened at start of program execution
  mysql_connection = mysql.connector.connect(host="localhost", user="root", passwd="Caden9036", database="caden_inf2070_project")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Incorrect Username and/or Password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Specified schema does not exist")
  else:
    print(err)
else:
  print("DB and Schema connections were successful")

menu = "Choose An Option\n\n1 - Add\n2 - Remove\n3 - Update\n\nOption: "
option = input(menu)

while option != "1" and option != "2" and option != "3":
    option = input(menu)

printEmptySpace()

if option == "1":
    errors = 0

    studentname = input("Student name (First & Last): ").title()
    period = int(input("Period Id: (1 - P1, 2 - HS2, 3 - HS4, 4 - HS6) "))
    courseid = int(input("Course Id: "))
    moduleid = int(input("Module Id: "))

    printEmptySpace()

    if len(studentname.split(" ")) != 2:
      print("Error: Student name must consist of a first and a last name.")
      errors += 1

    if period <= 0 or period >= 5:
      print("Error: Period can only be a number between one and four.")
      errors += 1

    if courseid <= 0 or courseid >= 6:
      print("Error: Course ID can only be a number between one and five.")
      errors += 1

    validmodules = [
      [1,2,3,4,5],
      [6,7,8,9,10],
      [11,12,13,14,15],
      [16,17,18,19,20],
      [21,22,23,24,25]
    ]

    isvalid = False
    if courseid >= 1 or courseid <= 5:
      for i,v in enumerate(validmodules[courseid-1]):
        if v == moduleid:
          isvalid = True

      if isvalid == False:
        print("Error: The selected module is not a member of the selected course.")
        errors += 1

    if errors >= 1:
      print("Please review the provided errors, and re-run the program.")
    else:
      print("No errors found.")
      print("Enrolling student...")

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "SELECT COALESCE(MAX(student_id), 0) + 1 FROM student"
      mysql_cursor.execute(mysql_query)
      next_student_id = mysql_cursor.fetchone()[0]

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "INSERT INTO student (student_id, student_name, fk_period_id) VALUES (%s, %s, %s)"
      mysql_cursor.execute(mysql_query, (next_student_id, studentname, period))
      mysql_connection.commit()
      mysql_cursor.close()

      print("One record added to the student table.")

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "SELECT COALESCE(MAX(primary_id), 0) + 1 FROM enrollment"
      mysql_cursor.execute(mysql_query)
      next_primary_id = mysql_cursor.fetchone()[0]
      mysql_connection.commit()

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "INSERT INTO enrollment (primary_id, fk_student_id, fk_course_id) VALUES (%s, %s, %s)"
      mysql_cursor.execute(mysql_query, (next_primary_id, next_student_id, courseid))
      mysql_connection.commit()
      mysql_cursor.close()

      print("One record added to enrollment.")

      print("Student has been successfully enrolled.")
</code>```

Error:

```<code>Traceback (most recent call last):
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 565, in cmd_query
_mysql_connector.MySQLInterfaceError: Cannot add or update a child row: a foreign key constraint fails (`caden_inf2070_project`.`enrollment`, CONSTRAINT `fk_course_id` FOREIGN KEY (`fk_student_id`) REFERENCES `course` (`course_id`) ON DELETE CASCADE ON UPDATE CASCADE)

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

Traceback (most recent call last):
  File "/Users/cadenjohnson/Desktop/Coding/caden_inf2070_project.py", line 95, in <module>
    mysql_cursor.execute(mysql_query, (next_primary_id, next_student_id, courseid))
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/cursor_cext.py", line 279, in execute
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 573, in cmd_query
mysql.connector.errors.IntegrityError: 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`caden_inf2070_project`.`enrollment`, CONSTRAINT `fk_course_id` FOREIGN KEY (`fk_student_id`) REFERENCES `course` (`course_id`) ON DELETE CASCADE ON UPDATE CASCADE)
</code>```

Let me know if there is another piece of information that would be helpful in solving this.

I have tried to drop and re-add these foriegn keys, but I am not sure if they are correct or not. In that error it appears that some of them are referencing the wrong tables, but I am not sure.

Body:
So I am currently working on a project which involves creating a Python application to interact with a MySQL database.

With this Python app, i was able to successfully insert rows into a table known as student, but when inserting a row into the enrollment table, it will not work. I will attach all information which may be useful below. Thanks for any help that you can provide!

Python Code:

import mysql.connector
from mysql.connector import errorcode

def printEmptySpace():
    print("\n\n\n\n\n\n\n")

try:
  #connection opened at start of program execution
  mysql_connection = mysql.connector.connect(host="localhost", user="root", passwd="Caden9036", database="caden_inf2070_project")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Incorrect Username and/or Password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Specified schema does not exist")
  else:
    print(err)
else:
  print("DB and Schema connections were successful")

menu = "Choose An Option\n\n1 - Add\n2 - Remove\n3 - Update\n\nOption: "
option = input(menu)

while option != "1" and option != "2" and option != "3":
    option = input(menu)

printEmptySpace()

if option == "1":
    errors = 0

    studentname = input("Student name (First & Last): ").title()
    period = int(input("Period Id: (1 - P1, 2 - HS2, 3 - HS4, 4 - HS6) "))
    courseid = int(input("Course Id: "))
    moduleid = int(input("Module Id: "))

    printEmptySpace()

    if len(studentname.split(" ")) != 2:
      print("Error: Student name must consist of a first and a last name.")
      errors += 1

    if period <= 0 or period >= 5:
      print("Error: Period can only be a number between one and four.")
      errors += 1

    if courseid <= 0 or courseid >= 6:
      print("Error: Course ID can only be a number between one and five.")
      errors += 1

    validmodules = [
      [1,2,3,4,5],
      [6,7,8,9,10],
      [11,12,13,14,15],
      [16,17,18,19,20],
      [21,22,23,24,25]
    ]

    isvalid = False
    if courseid >= 1 or courseid <= 5:
      for i,v in enumerate(validmodules[courseid-1]):
        if v == moduleid:
          isvalid = True

      if isvalid == False:
        print("Error: The selected module is not a member of the selected course.")
        errors += 1

    if errors >= 1:
      print("Please review the provided errors, and re-run the program.")
    else:
      print("No errors found.")
      print("Enrolling student...")

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "SELECT COALESCE(MAX(student_id), 0) + 1 FROM student"
      mysql_cursor.execute(mysql_query)
      next_student_id = mysql_cursor.fetchone()[0]

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "INSERT INTO student (student_id, student_name, fk_period_id) VALUES (%s, %s, %s)"
      mysql_cursor.execute(mysql_query, (next_student_id, studentname, period))
      mysql_connection.commit()
      mysql_cursor.close()

      print("One record added to the student table.")

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "SELECT COALESCE(MAX(primary_id), 0) + 1 FROM enrollment"
      mysql_cursor.execute(mysql_query)
      next_primary_id = mysql_cursor.fetchone()[0]
      mysql_connection.commit()

      mysql_cursor = mysql_connection.cursor()
      mysql_query = "INSERT INTO enrollment (primary_id, fk_student_id, fk_course_id) VALUES (%s, %s, %s)"
      mysql_cursor.execute(mysql_query, (next_primary_id, next_student_id, courseid))
      mysql_connection.commit()
      mysql_cursor.close()

      print("One record added to enrollment.")

      print("Student has been successfully enrolled.")

Error:

Traceback (most recent call last):
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 565, in cmd_query
_mysql_connector.MySQLInterfaceError: Cannot add or update a child row: a foreign key constraint fails (`caden_inf2070_project`.`enrollment`, CONSTRAINT `fk_course_id` FOREIGN KEY (`fk_student_id`) REFERENCES `course` (`course_id`) ON DELETE CASCADE ON UPDATE CASCADE)

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

Traceback (most recent call last):
  File "/Users/cadenjohnson/Desktop/Coding/caden_inf2070_project.py", line 95, in <module>
    mysql_cursor.execute(mysql_query, (next_primary_id, next_student_id, courseid))
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/cursor_cext.py", line 279, in execute
  File "/Volumes/hd2/pb2/build/sb_0-8365893-1662656297.95/build/root/Library/Python/3.9/install.tmp/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 573, in cmd_query
mysql.connector.errors.IntegrityError: 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`caden_inf2070_project`.`enrollment`, CONSTRAINT `fk_course_id` FOREIGN KEY (`fk_student_id`) REFERENCES `course` (`course_id`) ON DELETE CASCADE ON UPDATE CASCADE)

Let me know if there is another piece of information that would be helpful in solving this.

I have tried to drop and re-add these foriegn keys, but I am not sure if they are correct or not. In that error it appears that some of them are referencing the wrong tables, but I am not sure.


问:
VueJS: Unhandled error during execution, Uncaught TypeError
I have a two problems in Vue during using computed properties. I want use it with filter function to show products with correct price category after click but it is not successfully.
In console I see 1 error and 1 warn after click a button.
warn: Unhandled error during execution of native event handler,
error: Uncaught TypeError: _ctx.filter is not a function,
Filters property set to null and array are defined in data().
Below is my code.

```<code><basic-button
      @click="filter('premium')"
      :class="{ selected: filters === 'premium' }"
      >Premium</basic-button
    >
    <basic-button
      @click="filter('middle')"
      :class="{ selected: filters === 'middle' }"
      >Middle</basic-button
    >
    <basic-button
      @click="filter('economy')"
      :class="{ selected: filters === 'economy' }"
      >Economy</basic-button
setup() {
    const expectedProducts = computed(function () {
      if (!filters.value) {
        return expectedProducts.value.filter((prd) => {
          if (filters.value === "premium" && prd.price > 1000) {
            return products.value.price > 1000;
          } else if (
            (filters.value === "middle" && prd.price > 250) ||
            products.value.price < 1000
          ) {
            return products.price > 250 || products.price < 1000;
          } else if (filters.value === "economy" && prd.price < 250) {
            return products.value.price < 1000;
          } else {
            return products;
          }
        });
      }
      function filter(mode) {
        filters.value = mode;
      }

 return {
        filter,
        filters,
        expectedProducts,
        price,
      };

</code>```

I was find some solution/similar problem but I didn't find.

Body:
I have a two problems in Vue during using computed properties. I want use it with filter function to show products with correct price category after click but it is not successfully.
In console I see 1 error and 1 warn after click a button.
warn: Unhandled error during execution of native event handler,
error: Uncaught TypeError: _ctx.filter is not a function,
Filters property set to null and array are defined in data().
Below is my code.

<basic-button
      @click="filter('premium')"
      :class="{ selected: filters === 'premium' }"
      >Premium</basic-button
    >
    <basic-button
      @click="filter('middle')"
      :class="{ selected: filters === 'middle' }"
      >Middle</basic-button
    >
    <basic-button
      @click="filter('economy')"
      :class="{ selected: filters === 'economy' }"
      >Economy</basic-button
setup() {
    const expectedProducts = computed(function () {
      if (!filters.value) {
        return expectedProducts.value.filter((prd) => {
          if (filters.value === "premium" && prd.price > 1000) {
            return products.value.price > 1000;
          } else if (
            (filters.value === "middle" && prd.price > 250) ||
            products.value.price < 1000
          ) {
            return products.price > 250 || products.price < 1000;
          } else if (filters.value === "economy" && prd.price < 250) {
            return products.value.price < 1000;
          } else {
            return products;
          }
        });
      }
      function filter(mode) {
        filters.value = mode;
      }

 return {
        filter,
        filters,
        expectedProducts,
        price,
      };

I was find some solution/similar problem but I didn't find.


问:
How to get all required inputs with React Testing Library
I have a form with mostly but not all required inputs.  Using React Testing Library, I want to grab all the required inputs, verify they do not have the error class, click the submit button, and then verify they do have the error class.

Here is my current test:

test('Submitting the empty form should cause errors on required inputs', async () => {
        const {container} = render(
            <Component />
        );
        // console.log({container});
        screen.debug();
        // this next line is not working
        const requiredInputs = container.querySelectorAll('[required]');
        expect(requiredInputs.length).not.toBe(0);
        console.log({requiredInputs});
        console.log({len: requiredInputs.length});
        requiredInputs.forEach(input => {
            console.log({input});
            expect(input).not.toHaveClass('error-input');
        });
        const submitButton = await screen.getByText(/submit/i);
        await userEvent.click(submitButton);
        requiredInputs.forEach(input => {
            expect(input).toHaveClass('error-input');
        });
    });
```

Now for some reason my reuiredInputs nodelist is empty when I know there are required inputs in there.  I even tried replacing [required] with input and still got an empty list.  Any ideas where I am going wrong?

Body:
I have a form with mostly but not all required inputs.  Using React Testing Library, I want to grab all the required inputs, verify they do not have the error class, click the submit button, and then verify they do have the error class.

Here is my current test:

test('Submitting the empty form should cause errors on required inputs', async () => {
        const {container} = render(
            <Component />
        );
        // console.log({container});
        screen.debug();
        // this next line is not working
        const requiredInputs = container.querySelectorAll('[required]');
        expect(requiredInputs.length).not.toBe(0);
        console.log({requiredInputs});
        console.log({len: requiredInputs.length});
        requiredInputs.forEach(input => {
            console.log({input});
            expect(input).not.toHaveClass('error-input');
        });
        const submitButton = await screen.getByText(/submit/i);
        await userEvent.click(submitButton);
        requiredInputs.forEach(input => {
            expect(input).toHaveClass('error-input');
        });
    });

Now for some reason my reuiredInputs nodelist is empty when I know there are required inputs in there.  I even tried replacing [required] with input and still got an empty list.  Any ideas where I am going wrong?


问:
How to read a S3 file from a REST Endpoint using Apache Camel 2.X
I need to read a file from S3 bucket based on the file name passed from a REST endpoint. The file name will be passed as a uri parameter. The camel route I am using is given below.

```<code>rest().get("/file")
     .to("direct:readFile");

from("direct:readFile")
     .setProperty("FileName",simple("${header.fileName}"))
     .log(LoggingLevel.INFO, "Reading file from S3")
     .setHeader(S3Constants.KEY, simple("${header.fileName}"))
     .to("aws-s3://"+awsBucket+"?amazonS3Client=#s3Client&fileName=${header.fileName}")
     ...

</code>```

Instead of reading the file, this is currently overwriting the existing file in S3 with an empty file. How do I specify that this is a read operation and not a write operation?

I know that the latest version has an operation=getObject parameter for this. But the version I am using is 2.18.1 as the rest of the application is also on this version, and this version does not support this operation.

Is there any other way to achieve this?

Body:
I need to read a file from S3 bucket based on the file name passed from a REST endpoint. The file name will be passed as a uri parameter. The camel route I am using is given below.

rest().get("/file")
     .to("direct:readFile");

from("direct:readFile")
     .setProperty("FileName",simple("${header.fileName}"))
     .log(LoggingLevel.INFO, "Reading file from S3")
     .setHeader(S3Constants.KEY, simple("${header.fileName}"))
     .to("aws-s3://"+awsBucket+"?amazonS3Client=#s3Client&fileName=${header.fileName}")
     ...

Instead of reading the file, this is currently overwriting the existing file in S3 with an empty file. How do I specify that this is a read operation and not a write operation?

I know that the latest version has an operation=getObject parameter for this. But the version I am using is 2.18.1 as the rest of the application is also on this version, and this version does not support this operation.

Is there any other way to achieve this?


问:
Stop VsCode Auto Import/Complete when typing. Only allow when dropdown clicked, or TAB pressed
When i'm trying to type out words, that also have import/method suggestions, VS Code will auto import this as I type as if I wanted it. How do I only allow the suggestion to be accepted on TAB?

Here is an example, I'll type res. (in an effort to do res.rows, and it will assume I wanted one of the suggestions, and in this case, resize.

I still want the import suggestions, so turning off Javascript autoImport isn't my solution. I only want the auto complete/import when TAB is pressed.