问:
VBA routing not working after switch from Office 16 to Office 365 - Send Email to Mult Recipients from Excel
I thought at first that a permission or something disabled or an add-in in Outlook wasn't active because no emails were populating my drafts folder.  There are no run time errors (the code worked like a charm before the switch to Office 365 desktop).  I ran segments of code to to try to hone in on what the issue might be and I wonder if it might be the function call or Function RangetoHTML(rng As Range), which I scrapped from someone else's code because there are remarks: ' Working in Office 2000-2016.   Perhaps this function cannot work in Office 365 desktop.  I would appreciate if an eagle-eye can possibly tell me if there is a problem with this function in the version of Office running or I may need to rename some objects.

I confirmed that VBA is not disabled somehow in Outlook by running some basic code to send emails (no 1 to many, recipient to rows - which means no function call) and did get an email to deposit in my draft folder.

```<code>Sub AutomateEmails()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim dict As Object 'keep the unique list of emails
    Dim cell As Range
    Dim cell2 As Range
    Dim rng As Range
    Dim i As Long
    Dim WS As Worksheet

    Application.ScreenUpdating = False
    Set OutApp = CreateObject("Outlook.Application")
    Set dict = CreateObject("scripting.dictionary")
    Set WS = ThisWorkbook.Sheets("Sheet1") 'change the name of the sheet accordingly

    On Error GoTo cleanup
    For Each cell In WS.Columns("A").Cells.SpecialCells(xlCellTypeConstants)
        If cell.Value Like "?*@?*.?*" Then

            'check if this email address has been used to generate an outlook email or not
            If dict.exists(cell.Value) = False Then

                dict.Add cell.Value, "" 'add the new email address
                Set OutMail = OutApp.CreateItem(0)
                Set rng = WS.UsedRange.Rows(1)

                'find all of the rows with the same email and add it to the range
                For Each cell2 In WS.UsedRange.Columns(1).Cells
                    If cell2.Value = cell.Value Then
                        Set rng = Application.Union(rng, WS.UsedRange.Rows(cell2.Row))
                    End If
                Next cell2

                On Error Resume Next
                With OutMail
                    .To = cell.Value
                    .BCC = "jeb374@pitt.edu"
                    .Subject = "This is a friendly notice that a PO Requires Your Attention"
                    .HTMLBody = "The following POs have one or more pending invoices that conflict with the PO price and/or quantity. Please disregard if you are already working on resolution." & "<br><br>" & "Please contact jeb374@pitt.edu if additional information is needed. Thanks" & vbNewLine & vbNewLine & vbNewLine & RangetoHTML(rng)
                    .SentOnBehalfOfName = "ppnoids@cfo.pitt.edu"
                    .Save
                End With

                On Error GoTo 0
                Set OutMail = Nothing
            End If
        End If
    Next cell

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub

Function RangetoHTML(rng As Range)
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
</code>```

Body:
I thought at first that a permission or something disabled or an add-in in Outlook wasn't active because no emails were populating my drafts folder.  There are no run time errors (the code worked like a charm before the switch to Office 365 desktop).  I ran segments of code to to try to hone in on what the issue might be and I wonder if it might be the function call or Function RangetoHTML(rng As Range), which I scrapped from someone else's code because there are remarks: ' Working in Office 2000-2016.   Perhaps this function cannot work in Office 365 desktop.  I would appreciate if an eagle-eye can possibly tell me if there is a problem with this function in the version of Office running or I may need to rename some objects.

I confirmed that VBA is not disabled somehow in Outlook by running some basic code to send emails (no 1 to many, recipient to rows - which means no function call) and did get an email to deposit in my draft folder.

Sub AutomateEmails()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim dict As Object 'keep the unique list of emails
    Dim cell As Range
    Dim cell2 As Range
    Dim rng As Range
    Dim i As Long
    Dim WS As Worksheet

    Application.ScreenUpdating = False
    Set OutApp = CreateObject("Outlook.Application")
    Set dict = CreateObject("scripting.dictionary")
    Set WS = ThisWorkbook.Sheets("Sheet1") 'change the name of the sheet accordingly

    On Error GoTo cleanup
    For Each cell In WS.Columns("A").Cells.SpecialCells(xlCellTypeConstants)
        If cell.Value Like "?*@?*.?*" Then

            'check if this email address has been used to generate an outlook email or not
            If dict.exists(cell.Value) = False Then

                dict.Add cell.Value, "" 'add the new email address
                Set OutMail = OutApp.CreateItem(0)
                Set rng = WS.UsedRange.Rows(1)

                'find all of the rows with the same email and add it to the range
                For Each cell2 In WS.UsedRange.Columns(1).Cells
                    If cell2.Value = cell.Value Then
                        Set rng = Application.Union(rng, WS.UsedRange.Rows(cell2.Row))
                    End If
                Next cell2

                On Error Resume Next
                With OutMail
                    .To = cell.Value
                    .BCC = "jeb374@pitt.edu"
                    .Subject = "This is a friendly notice that a PO Requires Your Attention"
                    .HTMLBody = "The following POs have one or more pending invoices that conflict with the PO price and/or quantity. Please disregard if you are already working on resolution." & "

" & "Please contact jeb374@pitt.edu if additional information is needed. Thanks" & vbNewLine & vbNewLine & vbNewLine & RangetoHTML(rng)
                    .SentOnBehalfOfName = "ppnoids@cfo.pitt.edu"
                    .Save
                End With

                On Error GoTo 0
                Set OutMail = Nothing
            End If
        End If
    Next cell

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub

Function RangetoHTML(rng As Range)
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function


来源: stackexchange

问:
Dealing with special characters in file paths - Python script and Athena Query
I have a script that I use to parse out S3 info using Athena and S3 inventory. Currently when it finds a specific file type, the script will use that path to generate a SQL query that is then passed to Athena. Here's an example:

```<code>def getS3TagReportData(session, tag, table):
    whereStatement = ""
    for v in tag.values:
        first = True
        for p in v.paths:
            # print(p) #iterate through paths

            if first:
                whereStatement = f"WHERE dt = (SELECT MAX(dt) FROM \"{awsAthenaDatabase}\".\"{table}\") AND key LIKE '{p}/%'"
                first = False
            else:
                whereStatement += f" OR key LIKE '{p}%'"
</code>```

This works fine until I hit a path where someone has put in an '

For example: bucketname\data\int'l hotel files\data.jpg

Then the query that gets dynamically generated is:

```<code>WHERE dt = (SELECT MAX(dt) FROM \"{awsAthenaDatabase}\".\"{table}\") AND key LIKE 'bucketname\data\int'l hotel files\data.jpg'
</code>```

As you can see, the Where statement is going to fail because there is that extra ' in there. How can I programmatically work around these errors and report them?

I appreciate the help!

ContentLicense: CC BY-SA 4.0

Body:
I have a script that I use to parse out S3 info using Athena and S3 inventory. Currently when it finds a specific file type, the script will use that path to generate a SQL query that is then passed to Athena. Here's an example:

def getS3TagReportData(session, tag, table):
    whereStatement = ""
    for v in tag.values:
        first = True
        for p in v.paths:
            # print(p) #iterate through paths

            if first:
                whereStatement = f"WHERE dt = (SELECT MAX(dt) FROM \"{awsAthenaDatabase}\".\"{table}\") AND key LIKE '{p}/%'"
                first = False
            else:
                whereStatement += f" OR key LIKE '{p}%'"

This works fine until I hit a path where someone has put in an '

For example: bucketname\data\int'l hotel files\data.jpg

Then the query that gets dynamically generated is:

WHERE dt = (SELECT MAX(dt) FROM \"{awsAthenaDatabase}\".\"{table}\") AND key LIKE 'bucketname\data\int'l hotel files\data.jpg'

As you can see, the Where statement is going to fail because there is that extra ' in there. How can I programmatically work around these errors and report them?

I appreciate the help!


问:
tkinter window not opening no matter what
```<code>import tkinter as tk
from tkinter import filedialog, Text
import os

root = tk.Tk()

canvas = tk.Canvas(root, height=700, width=700, bg="#aa0505")
canvas.pack()

root.mainloop()
</code>```

I tried reinstalling python, pip, tkinter, I even switched to a different ide because of this problem.

ps I was originally using vs code but then I thought i might switch to pycharm

Body:
import tkinter as tk
from tkinter import filedialog, Text
import os

root = tk.Tk()

canvas = tk.Canvas(root, height=700, width=700, bg="#aa0505")
canvas.pack()

root.mainloop()

I tried reinstalling python, pip, tkinter, I even switched to a different ide because of this problem.

ps I was originally using vs code but then I thought i might switch to pycharm


问:
''BuiltIn' is not a supported encoding name
I am converting a PDF to Text using 'iText.PdfTextExtractor' and I am receiving this error ONLY on some of the pdf pages I am trying to convert:

'BuiltIn' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. (Parameter 'name')

I've tried adding the following code before opening the file stream, but I am still receiving the error:

```<code>System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);
</code>```

Here is my code:

```<code>public void ExtractFromPdf(string pdfFile, ClaimInfo claimInfo, string memberId)
{
    System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
    Encoding.RegisterProvider(provider);

    PdfReader pdfRead = new PdfReader(pdfFile);
    PdfDocument pdfDoc = new PdfDocument(pdfRead);

    for (int page = 1; page < pdfDoc.GetNumberOfPages(); page++)
    {
        string convertToText = PdfToText(pdfDoc, page);
    }
}

private string PdfToText(PdfDocument pdfDoc, int pageNo)
{
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
    return PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(pageNo), strategy);
}
</code>```

The error occurs at return PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(pageNo), strategy);

I've tried looking everywhere and it seems that 'BuiltIn' is a built in encoding name that I don't know how to find. Any ideas?

Body:
I am converting a PDF to Text using 'iText.PdfTextExtractor' and I am receiving this error ONLY on some of the pdf pages I am trying to convert:

'BuiltIn' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. (Parameter 'name')

I've tried adding the following code before opening the file stream, but I am still receiving the error:

System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);

Here is my code:

public void ExtractFromPdf(string pdfFile, ClaimInfo claimInfo, string memberId)
{
    System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
    Encoding.RegisterProvider(provider);

    PdfReader pdfRead = new PdfReader(pdfFile);
    PdfDocument pdfDoc = new PdfDocument(pdfRead);

    for (int page = 1; page < pdfDoc.GetNumberOfPages(); page++)
    {
        string convertToText = PdfToText(pdfDoc, page);
    }
}

private string PdfToText(PdfDocument pdfDoc, int pageNo)
{
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
    return PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(pageNo), strategy);
}

The error occurs at return PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(pageNo), strategy);

I've tried looking everywhere and it seems that 'BuiltIn' is a built in encoding name that I don't know how to find. Any ideas?


问:
Validate calldata is encoded properly in abi
I have a solidity contract in which I would like to validate the calldata passed into it.

```<code>struct SwapResolverOptions {
    bytes path;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
    address inputTokenAddress;
    address targetAddress;
    address destinationAddress;
}

function validateAdditionalCalldata(bytes calldata resolverOptions) pure override external {
    abi.decode(resolverOptions, (SwapResolverOptions));
}
</code>```

I was under the impression that the abi.decode would throw an error if the calldata was wrong e.g incorrect length or incorrect data in the type.  I wrote a test attempting to verify that:

```<code>    const resolverOptions: SwapResolverOptionsStruct = {
      path: '0x00',
      deadline: BigNumber.from(1000),
      amountIn: BigNumber.from(100000000),
      amountOutMinimum: BigNumber.from(0),
      inputTokenAddress: WMATIC_MUMBAI,
      destinationAddress: owner.address,
      targetAddress: ADDRESS_ZERO,
    };

function encodeResolverOptions(resolverOptions: SwapResolverOptionsStruct): string {
    return defaultAbiCoder.encode(
        ["(bytes path,uint256 deadline,uint256 amountIn,uint256 amountOutMinimum,address inputTokenAddress,address destinationAddress,address targetAddress)"],
        [resolverOptions]
    );
}

    const encodedResolverOptions = encodeResolverOptions(resolverOptions);
    console.log(encodedResolverOptions);
    try {
      const response = await swapResolver.validateAdditionalCalldata(encodedResolverOptions + 'AB');
      console.log(response);
    }
    catch(err) {
      console.log('Error:' + err);
    }
</code>```

I'm arbitrarily appending data to the calldata however no error is thrown?   Note: I've also tried prepending the data (past the 0x)

How do I validate calldata matches the expected calldata in solidity?

Body:
I have a solidity contract in which I would like to validate the calldata passed into it.

struct SwapResolverOptions {
    bytes path;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
    address inputTokenAddress;
    address targetAddress;
    address destinationAddress;
}

function validateAdditionalCalldata(bytes calldata resolverOptions) pure override external {
    abi.decode(resolverOptions, (SwapResolverOptions));
}

I was under the impression that the abi.decode would throw an error if the calldata was wrong e.g incorrect length or incorrect data in the type.  I wrote a test attempting to verify that:

    const resolverOptions: SwapResolverOptionsStruct = {
      path: '0x00',
      deadline: BigNumber.from(1000),
      amountIn: BigNumber.from(100000000),
      amountOutMinimum: BigNumber.from(0),
      inputTokenAddress: WMATIC_MUMBAI,
      destinationAddress: owner.address,
      targetAddress: ADDRESS_ZERO,
    };

function encodeResolverOptions(resolverOptions: SwapResolverOptionsStruct): string {
    return defaultAbiCoder.encode(
        ["(bytes path,uint256 deadline,uint256 amountIn,uint256 amountOutMinimum,address inputTokenAddress,address destinationAddress,address targetAddress)"],
        [resolverOptions]
    );
}

    const encodedResolverOptions = encodeResolverOptions(resolverOptions);
    console.log(encodedResolverOptions);
    try {
      const response = await swapResolver.validateAdditionalCalldata(encodedResolverOptions + 'AB');
      console.log(response);
    }
    catch(err) {
      console.log('Error:' + err);
    }

I'm arbitrarily appending data to the calldata however no error is thrown?   Note: I've also tried prepending the data (past the 0x)

How do I validate calldata matches the expected calldata in solidity?


问:
Using Heroku Pipelines, how can I promote an Vue.JS app from one stage to another while configuring the REST base URL on an ENV var?
I'm using Heroku pipeles to deploy an webapp that has the back-end app writen on Ruby on Rails and the front-end app using VueJS and I'm having trouble promoting the front-end app from one stage to another inside the pipeline because I'm setting up the base URL for my back-end app using and enviroment variable inside my VueJS app.

The problem is that the build process happens when I commit my code to the Heroku repo in one particular stage, and the build process reads the base URL ENV at that moment at sets it up for the VueJS app, but when I promote my app from, let's say, development to staging, the app is not rebuild, so I endup with an app on staging pointing to my developing back-end.

So rather than promoting my front-end app from development to staging, I have to actually add both stage's heroku git repo remote to my local project git repo and push it to both stages so the build process happens separatly in each stage and get's the base URL ENV of that specific stage. It works, but I end up not having to be able to use the promote feature from heroku pipeline.


问:
How to Customize Bootsrap css in module.css (component -level css)
I have added my own classes along bootstrap using backtick butt its not working.
e.g

```<code><nav className=`navbar navbar-expand-lg navbar-light bg-light ${classes.navStyle}`></nav>
</code>```

Here' the extra class(classes.navStyle) is not applied.
Kindly tells possible solution for (component-level-css) when using bootstrap in Reacjs Projects

Possible solution for component-level-css when using bootstrap in project

Body:
I have added my own classes along bootstrap using backtick butt its not working.
e.g

<nav className=`navbar navbar-expand-lg navbar-light bg-light ${classes.navStyle}`>

Here' the extra class(classes.navStyle) is not applied.
Kindly tells possible solution for (component-level-css) when using bootstrap in Reacjs Projects

Possible solution for component-level-css when using bootstrap in project


问:
npm ERR! ERESOLVE unable to resolve dependency tree. Clone repository
```<code>MINGW64 ~/Downloads/Eshop_mobile_app_react_native (master)
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: Eshop@1.0.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^18.2.0" from react-dom@18.2.0
npm ERR! node_modules/react-dom
npm ERR!   react-dom@"^18.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2023-01-04T22_30_23_958Z-debug-0.log
</code>```

I tried running  npm install --legacy-peer-deps and tried running $ npx react-native run-android but the build is failing, and I don't know what to do anymore.

```<code>MINGW64 ~/Downloads/Eshop_mobile_app_react_native (master)
$ npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1735 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...

> Task :react-native-gradle-plugin:compileJava

> Configure project :app
Unable to detect AGP versions for included builds. All projects in the build should use the same AGP version. Class name for the included build object: org.gradle.composite.internal.DefaultIncludedBuild$IncludedBuildImpl_Decorated.

> Configure project :lottie-react-native

> Configure project :react-native-reanimated
AAR for react-native-reanimated has been found
C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\react-native-reanimated\android\react-native-reanimated-68-jsc.aar

Note: C:\Users\PC\Downloads\Eshop_mobile_app_react_native\android\app\src\debug\java\com\eshop\ecommerce\ReactNativeFlipper.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
2 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Get more help at https://help.gradle.org

BUILD FAILED in 48s

    at makeError (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.
</code>```

Body:
MINGW64 ~/Downloads/Eshop_mobile_app_react_native (master)
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: Eshop@1.0.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^18.2.0" from react-dom@18.2.0
npm ERR! node_modules/react-dom
npm ERR!   react-dom@"^18.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2023-01-04T22_30_23_958Z-debug-0.log

I tried running  npm install --legacy-peer-deps and tried running $ npx react-native run-android but the build is failing, and I don't know what to do anymore.

MINGW64 ~/Downloads/Eshop_mobile_app_react_native (master)
$ npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1735 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
info Launching emulator...
info Successfully launched emulator.
info Installing the app...

> Task :react-native-gradle-plugin:compileJava

> Configure project :app
Unable to detect AGP versions for included builds. All projects in the build should use the same AGP version. Class name for the included build object: org.gradle.composite.internal.DefaultIncludedBuild$IncludedBuildImpl_Decorated.

> Configure project :lottie-react-native

> Configure project :react-native-reanimated
AAR for react-native-reanimated has been found
C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\react-native-reanimated\android\react-native-reanimated-68-jsc.aar

Note: C:\Users\PC\Downloads\Eshop_mobile_app_react_native\android\app\src\debug\java\com\eshop\ecommerce\ReactNativeFlipper.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
2 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Get more help at https://help.gradle.org

BUILD FAILED in 48s

    at makeError (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\PC\Downloads\Eshop_mobile_app_react_native\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.


问:
SwiftUI Sort users from the nearest to the most far from current user in LazyVstack ForEach
I'm building an application for a university project, I'm pretty new in coding, and I'm actually facing an issue, I hope one of you will be able to help me.

The idea is simple, you log yourself into the application and you have cards of other users, each card is the profile of a student(user). My issue actually is that I want those cards to be arranged from the nearest user to the most far from the currentUser. Every user's location is already stored in Firebase.

There is my code for this part:

```<code>ScrollView(){
 LazyVStack{
   ForEach(viewModel.users) { user in
     NavigationLink {
       UserProfilView(user: user)
          .navigationBarHidden(true)
                   } label:{
                    ProfilCard(user: user)
                   .frame(width: proxy.size.width/1.05, height: proxy.size.width*1.75)
                  }.padding()
                }
             }
}
</code>```

I looked a lot for an answer on the internet but I didn't find any solution.

I tried multiple things but this one was the one I had the most hope for:

```<code>@State private var currentUser: User?

ScrollView(){
     LazyVStack{
        ForEach(viewModel.users.sorted(by: { location.distance(from: $0.currentUser) < location.distance(from: $1.currentUser)})) { user in
                        NavigationLink {
                                        UserProfilView(user: user)
                                            .navigationBarHidden(true)
                                    }label:{
                                        ProfilCard(user: user)
                                            .frame(width: proxy.size.width/1.05, height: proxy.size.width*1.75)
                    }.padding()
                }
        }
}
</code>```

Body:
I'm building an application for a university project, I'm pretty new in coding, and I'm actually facing an issue, I hope one of you will be able to help me.

The idea is simple, you log yourself into the application and you have cards of other users, each card is the profile of a student(user). My issue actually is that I want those cards to be arranged from the nearest user to the most far from the currentUser. Every user's location is already stored in Firebase.

There is my code for this part:

ScrollView(){
 LazyVStack{
   ForEach(viewModel.users) { user in
     NavigationLink {
       UserProfilView(user: user)
          .navigationBarHidden(true)
                   } label:{
                    ProfilCard(user: user)
                   .frame(width: proxy.size.width/1.05, height: proxy.size.width*1.75)
                  }.padding()
                }
             }
}

I looked a lot for an answer on the internet but I didn't find any solution.

I tried multiple things but this one was the one I had the most hope for:

@State private var currentUser: User?

ScrollView(){
     LazyVStack{
        ForEach(viewModel.users.sorted(by: { location.distance(from: $0.currentUser) < location.distance(from: $1.currentUser)})) { user in
                        NavigationLink {
                                        UserProfilView(user: user)
                                            .navigationBarHidden(true)
                                    }label:{
                                        ProfilCard(user: user)
                                            .frame(width: proxy.size.width/1.05, height: proxy.size.width*1.75)
                    }.padding()
                }
        }
}


问:
How to Specify Range of Values to One Color in ggplot2
I am making a bare ggplot as shown below. How do I specify that all values greater than 16 should be the color black?</p>
```<code>
swell_pal <- colorRampPalette(c("lightskyblue2", "deepskyblue4", "seagreen3", "khaki2", "orangered","darkred"))

swell_limits <- c(0, 16)

swell.list = lapply(sort(unique(clean_data$date)), function(i) {
  ggplot(data = clean_data[clean_data$date==i,], aes(y=y, x=x)) +
  geom_raster(aes(fill = height), interpolate = T) +
  facet_wrap(levels(~date)) +
  scale_fill_gradientn(colours = swell_pal(10), limits = swell_limits, ) +
  theme_classic() +
  theme(axis.line=element_blank(),axis.text.x=element_blank(),
          axis.text.y=element_blank(),axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),legend.position="none",
          panel.background=element_blank(),
        panel.border=element_blank(),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        plot.background=element_blank(),
        plot.margin=unit(c(0,0,0,0), "null"),
        strip.background = element_blank(),
        strip.text.x = element_blank()) +
  coord_sf(xlim = c(-13514631, -13031631), ylim = c(3810758, 4129958), expand = F, datum = 3857)
})

</code>```

Body:
I am making a bare ggplot as shown below. How do I specify that all values greater than 16 should be the color black?

swell_pal <- colorRampPalette(c("lightskyblue2", "deepskyblue4", "seagreen3", "khaki2", "orangered","darkred"))

swell_limits <- c(0, 16)

swell.list = lapply(sort(unique(clean_data$date)), function(i) {
  ggplot(data = clean_data[clean_data$date==i,], aes(y=y, x=x)) +
  geom_raster(aes(fill = height), interpolate = T) +
  facet_wrap(levels(~date)) +
  scale_fill_gradientn(colours = swell_pal(10), limits = swell_limits, ) +
  theme_classic() +
  theme(axis.line=element_blank(),axis.text.x=element_blank(),
          axis.text.y=element_blank(),axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),legend.position="none",
          panel.background=element_blank(),
        panel.border=element_blank(),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        plot.background=element_blank(),
        plot.margin=unit(c(0,0,0,0), "null"),
        strip.background = element_blank(),
        strip.text.x = element_blank()) +
  coord_sf(xlim = c(-13514631, -13031631), ylim = c(3810758, 4129958), expand = F, datum = 3857)
})


问:
Nested data in RTKQuery hook getting join data
I am implementing the "favorites" logic in a project where there are some cards showing some info about songs, and a heart icon shows red if that song is in the user favorites or empty if it is not.

I am using Supabase as a backend (SQL) and I already have a "profiles" table, a "songs" table and a "favorites" table with two foreign keys: profile_id and song_id.

In the project I am using RTKQuery and I have already configured the endpoint to obtain the data for the favorites which is like:

```<code>endpoints: (builder) => ({
        getFavorites: builder.query({
            queryFn: async (id) => {
                const {data, error} = await supabase
                .from('favorites')
                .select(`users_id,songs_id (*)`)
                .eq('users_id',id)

                return { data, error }
            },
            providesTags: ["Favorites"]
        }),
</code>```

Then I get the data with:

```<code>const { data, isSuccess } = useGetFavoritesQuery( id );
</code>```

I am calling this hook from the component mad for each card, which already have the props. So I can check if the prop "song.id" is in some of the ids inside the "favorites" object.

But the problem I am facing is because the data that I really need is the nested object inside data, and each one of the nested objects have the id that I would use to check if it is === to song.id of the component I am calling from.

I have tried several things but I don't know if I am doing fine. This is one solution that I have tried. First I iterate over data to obtain the object "favorites":

```<code>let favorites;
    if (isSuccess){
      data.forEach(element => {
        favorites = element.songs_id;
      })
    }
</code>```

And then the boolean for the heart red or empty:

```<code>const favoriteIconColor = useMemo(() => {
      if (Object.values(favorites).some(item=> item.id === song.id)){
        return true
      }
    } , [favorites, song]);
</code>```

But that is not working. I am thinking about creating just an array with all of the ids in the first iteration, but I am not sure if I am overcomplicating the issue.

I have also considered that maybe there is a way to obtain the data as I need with the query itself, but not sure about it. Any advice?

Body:
I am implementing the "favorites" logic in a project where there are some cards showing some info about songs, and a heart icon shows red if that song is in the user favorites or empty if it is not.

I am using Supabase as a backend (SQL) and I already have a "profiles" table, a "songs" table and a "favorites" table with two foreign keys: profile_id and song_id.

In the project I am using RTKQuery and I have already configured the endpoint to obtain the data for the favorites which is like:

endpoints: (builder) => ({
        getFavorites: builder.query({
            queryFn: async (id) => {
                const {data, error} = await supabase
                .from('favorites')
                .select(`users_id,songs_id (*)`)
                .eq('users_id',id)

                return { data, error }
            },
            providesTags: ["Favorites"]
        }),

Then I get the data with:

const { data, isSuccess } = useGetFavoritesQuery( id );

I am calling this hook from the component mad for each card, which already have the props. So I can check if the prop "song.id" is in some of the ids inside the "favorites" object.

But the problem I am facing is because the data that I really need is the nested object inside data, and each one of the nested objects have the id that I would use to check if it is === to song.id of the component I am calling from.

I have tried several things but I don't know if I am doing fine. This is one solution that I have tried. First I iterate over data to obtain the object "favorites":

let favorites;
    if (isSuccess){
      data.forEach(element => {
        favorites = element.songs_id;
      })
    }

And then the boolean for the heart red or empty:

const favoriteIconColor = useMemo(() => {
      if (Object.values(favorites).some(item=> item.id === song.id)){
        return true
      }
    } , [favorites, song]);

But that is not working. I am thinking about creating just an array with all of the ids in the first iteration, but I am not sure if I am overcomplicating the issue.

I have also considered that maybe there is a way to obtain the data as I need with the query itself, but not sure about it. Any advice?


问:
how to check if video inside a embed iframe has been fully loaded
hey i am trying to check if the video element in iframe embed has been loaded to return a video.duration the issue i can't figure out how i can check if the video exists only i get undefined error the embed is from mega.nz so the video src will be blob:

```<code>let video_error = ""
const iframe = document.createElement('iframe')
iframe.src = "embed link"
document.body.appendChild(iframe);
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
iframe.addEventListener("load", function() {

     var video =iframe.contentWindow.document.getElementsByTagName('video')[0];
        video.addEventListener("load", function() {
            video.onloadedmetadata = () => {
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight

            const audio = new AudioContext()
            const source = audio.createMediaElementSource(video)
            const stream_dest = audio.createMediaStreamDestination()
            source.connect(stream_dest);

            const video_stream = canvas.captureStream(60)
            const audio_stream = stream_dest.stream
            stream_inject = new MediaStream([
                video_stream.getVideoTracks()[0],
                audio_stream.getAudioTracks()[0]
            ])

        }

        video.onplay = () => {
            function step() {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
                requestAnimationFrame(step)
            }
            requestAnimationFrame(step);
        }

        video.onerror = event => {
            video_error = event.target.error.message
        }

    })

});
</code>```

Body:
hey i am trying to check if the video element in iframe embed has been loaded to return a video.duration the issue i can't figure out how i can check if the video exists only i get undefined error the embed is from mega.nz so the video src will be blob:

let video_error = ""
const iframe = document.createElement('iframe')
iframe.src = "embed link"
document.body.appendChild(iframe);
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
iframe.addEventListener("load", function() {

     var video =iframe.contentWindow.document.getElementsByTagName('video')[0];
        video.addEventListener("load", function() {
            video.onloadedmetadata = () => {
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight

            const audio = new AudioContext()
            const source = audio.createMediaElementSource(video)
            const stream_dest = audio.createMediaStreamDestination()
            source.connect(stream_dest);

            const video_stream = canvas.captureStream(60)
            const audio_stream = stream_dest.stream
            stream_inject = new MediaStream([
                video_stream.getVideoTracks()[0],
                audio_stream.getAudioTracks()[0]
            ])

        }

        video.onplay = () => {
            function step() {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
                requestAnimationFrame(step)
            }
            requestAnimationFrame(step);
        }

        video.onerror = event => {
            video_error = event.target.error.message
        }

    })

});


问:
utils.ts:874 Matched leaf route at location "/" does not have an element
utils.ts:874

How do I fix this I haven't a clue.

Matched leaf route at location "/action" does not have an element.
This means it will render an <Outlet /> with a null value by default
resulting in an "empty" page.

Here is my code:

```<code>import React from 'react';
import '../App.css';
import Card from 'react-bootstrap/Card';
import CardGroup from 'react-bootstrap/CardGroup';
import Logo from './logo.png';

class Action extends React.Component {
  render() {
    return (
      <div className="App">
        <font color="white"><h1>Action Based Shows</h1></font>
        {/*Hard coded shows in cards */}
        <CardGroup>
          <Card bg="dark" text="white">
            <a href="https://www.imdb.com/title/tt5675620/"><Card.Img src="http://ayanahaviv.com/wp-content/uploads/2014/11/34-The-Punisher.jpg" /></a>
            <Card.Body>
              <Card.Title>The Punisher</Card.Title>
              2017-2019
              <Card.Text>
                A rocky start can't keep The Punisher from pushing the boundaries of Marvel's TV universe with a fresh take on the comics-derived action thriller.
              </Card.Text>
            </Card.Body>
          </Card>

      </div>
    );
  }
}

export default Action;
</code>```

Body:
utils.ts:874

How do I fix this I haven't a clue.

Matched leaf route at location "/action" does not have an element.
This means it will render an <Outlet /> with a null value by default
resulting in an "empty" page.

Here is my code:

import React from 'react';
import '../App.css';
import Card from 'react-bootstrap/Card';
import CardGroup from 'react-bootstrap/CardGroup';
import Logo from './logo.png';

class Action extends React.Component {
  render() {
    return (

Action Based Shows

        {/*Hard coded shows in cards */}
        <CardGroup>
          <Card bg="dark" text="white">
            <Card.Img src="http://ayanahaviv.com/wp-content/uploads/2014/11/34-The-Punisher.jpg" />
            <Card.Body>
              <Card.Title>The Punisher</Card.Title>
              2017-2019
              <Card.Text>
                A rocky start can't keep The Punisher from pushing the boundaries of Marvel's TV universe with a fresh take on the comics-derived action thriller.
              </Card.Text>
            </Card.Body>
          </Card>

    );
  }
}

export default Action;


问:
mcs command not found in git bash or powershell

mcs command not found

Hello thank you for your time.  I am a little inexperienced.  I'm using visual studio code developer pack with all the c# extensions.  I've tried using git bash and powershell and the mcs command is not found and I don't know where or how to download it.  I'm not even sure what package managers I have. I'm working on a C# Objects project on TeamTreehouse.com and I don't want to keep using workspaces.  I'm trying to compile and run the TreehouseDefense project.

Here is the command I typed into the terminal

```<code>mcs -out:TreehouseDefense.com *.cs && mono TreehouseDefense.com
</code>```

Here is the error message I get

```<code>mcs : The term 'mcs' is not recognized as the name of bja cmdlet, function, script file, or operable program. ioCheck the spelling of the name, or if a path was
included, verify that the path is correct and try
again.
At line:1 char:1
+ mcs --version
+ ~~~
    + CategoryInfo          : ObjectNotFound: (mcs:Str
   ing) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

On my macbook air that command compiles and runs the project.  Unfortunately the mac is out of commission right now.  Also I tried downloading mcs from github but I couldn't find an executable file or anything.  I'm not very good with github yet.  I also searched for bash commands to download mcs but I couldn't find anything except for something to do with RedHat and I think it was the wrong mcs.  I know I'm looking for a c# compiler but that's all I know. Also I installed node.js and tried to use npm to install mcs or mono but those packages apparently did not exist to npm

Body:
mcs command not found

Hello thank you for your time.  I am a little inexperienced.  I'm using visual studio code developer pack with all the c# extensions.  I've tried using git bash and powershell and the mcs command is not found and I don't know where or how to download it.  I'm not even sure what package managers I have. I'm working on a C# Objects project on TeamTreehouse.com and I don't want to keep using workspaces.  I'm trying to compile and run the TreehouseDefense project.

Here is the command I typed into the terminal

mcs -out:TreehouseDefense.com *.cs && mono TreehouseDefense.com

Here is the error message I get

mcs : The term 'mcs' is not recognized as the name of bja cmdlet, function, script file, or operable program. ioCheck the spelling of the name, or if a path was
included, verify that the path is correct and try
again.
At line:1 char:1
+ mcs --version
+ ~~~
    + CategoryInfo          : ObjectNotFound: (mcs:Str
   ing) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

On my macbook air that command compiles and runs the project.  Unfortunately the mac is out of commission right now.  Also I tried downloading mcs from github but I couldn't find an executable file or anything.  I'm not very good with github yet.  I also searched for bash commands to download mcs but I couldn't find anything except for something to do with RedHat and I think it was the wrong mcs.  I know I'm looking for a c# compiler but that's all I know. Also I installed node.js and tried to use npm to install mcs or mono but those packages apparently did not exist to npm


问:
How do i use a custom conda environment on a jupyter notebook running on aws sagemaker?
Completely new to aws. I'm trying to run a .ipynb file on a sagemaker notebook instance in Jupyter Lab. How do I install requirements?

I would like to create and activate a conda environment like this, but it's not working:

```<code>    conda env create -f environment.yaml
    conda activate ldm
</code>```

What's the best and easiest way to have all dependencies installed?

Body:
Completely new to aws. I'm trying to run a .ipynb file on a sagemaker notebook instance in Jupyter Lab. How do I install requirements?

I would like to create and activate a conda environment like this, but it's not working:

    conda env create -f environment.yaml
    conda activate ldm

What's the best and easiest way to have all dependencies installed?


问:
call of get payment status API FawryPay?
I'm trying to set an get payment status API with a payment processor. Below is the code they provided me. There are some information in the $result variable that I want, what I don't understand is what type of variable is '$result' and how can I take certain data from it. printing the $result shows "Transaction ID is : xxxx status is ACCEPTED". What I basically want is to take only the transaction ID and store it in a variable.

```<code>function payFawry($ID)
    {
        $ticket = get_row("select * FROM `tickets` WHERE ID = '$ID' and canceled = 0");
        $user = get_row("select * from users where ID = '$ticket[clientID]'");
        $amount = $ticket[cost].".00";
        $customerMobile = substr($user[phone],-11);
        $description = "Ticket ".$ticket[ID];

        $merchantCode = "CsdsadasdasdasdasdasdaJasdasd";
        $merchantRefNum = $ticket[ID];
        $customerProfileId = $ticket[clientID];
        $paymentMethod = "PAYATFAWRY";
        $cardToken = "";
        $customerEmail = substr($user[email]);
        $secureKey = "sadasdsadafdsfasfasdasdasdasd";
        $signature = $merchantCode.$merchantRefNum.$customerProfileId.$paymentMethod.$amount.$cardToken.$secureKey;
        $signature = hash('sha256', $signature);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://atfawry.com/ECommerceWeb/Fawry/payments/charge',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{ \"merchantCode\":\"$merchantCode\", \"merchantRefNum\":\"$merchantRefNum\", \"customerProfileId\":\"$customerProfileId\", \"customerMobile\":\"$customerMobile\", \"customerEmail\":\"$customerEmail\", \"paymentMethod\":\"$paymentMethod\", \"cardToken\":\"$cardToken\", \"amount\":$amount, \"currencyCode\":\"EGP\", \"description\":\"$description\", \"paymentExpiry\":".strtotime('+3 hour')."077, \"chargeItems\":[ { \"itemId\":\"897fa8e81be26df25db592e81c31c\", \"description\":\"asdasd\", \"price\":$amount, \"quantity\":1 } ], \"signature\":\"$signature\" }",
            CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        $status = 1;
        $response = json_decode ( $response , true ) ;
        $referenceNumber = '<div style="font-size: 18px;line-height: 30px;margin-bottom: 9px;">Please proceed to any Fawry Retail (Kiosk, Supermarket) <br>Ask for Fawry Pay Service and enter you Reference Number: </div><div class="head-span" >'.$response[referenceNumber].'</div>';

        $message = "برجاء استخدام رقم السداد $response[referenceNumber] لكود الخدمة 788 لدى فوري لتأكيد الحجز قم $ticket[ID]";
        $new_password = encode_password($new_password) ;
        send_sms($customerMobile ,$message);

        $r = array("Status"=>$status,"Result"=>$referenceNumber,"referenceNumber"=>$response[referenceNumber],"Errors"=>"","NextStep"=>$NextStep);
        return $r;
    }
</code>```

Returns 1 on success or 0 for non success
https://developer.fawrystaging.com/docs/server-apis/payment-notifications/get-payment-status-v2

Body:
I'm trying to set an get payment status API with a payment processor. Below is the code they provided me. There are some information in the $result variable that I want, what I don't understand is what type of variable is '$result' and how can I take certain data from it. printing the $result shows "Transaction ID is : xxxx status is ACCEPTED". What I basically want is to take only the transaction ID and store it in a variable.

function payFawry($ID)
    {
        $ticket = get_row("select * FROM `tickets` WHERE ID = '$ID' and canceled = 0");
        $user = get_row("select * from users where ID = '$ticket[clientID]'");
        $amount = $ticket[cost].".00";
        $customerMobile = substr($user[phone],-11);
        $description = "Ticket ".$ticket[ID];

        $merchantCode = "CsdsadasdasdasdasdasdaJasdasd";
        $merchantRefNum = $ticket[ID];
        $customerProfileId = $ticket[clientID];
        $paymentMethod = "PAYATFAWRY";
        $cardToken = "";
        $customerEmail = substr($user[email]);
        $secureKey = "sadasdsadafdsfasfasdasdasdasd";
        $signature = $merchantCode.$merchantRefNum.$customerProfileId.$paymentMethod.$amount.$cardToken.$secureKey;
        $signature = hash('sha256', $signature);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://atfawry.com/ECommerceWeb/Fawry/payments/charge',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{ \"merchantCode\":\"$merchantCode\", \"merchantRefNum\":\"$merchantRefNum\", \"customerProfileId\":\"$customerProfileId\", \"customerMobile\":\"$customerMobile\", \"customerEmail\":\"$customerEmail\", \"paymentMethod\":\"$paymentMethod\", \"cardToken\":\"$cardToken\", \"amount\":$amount, \"currencyCode\":\"EGP\", \"description\":\"$description\", \"paymentExpiry\":".strtotime('+3 hour')."077, \"chargeItems\":[ { \"itemId\":\"897fa8e81be26df25db592e81c31c\", \"description\":\"asdasd\", \"price\":$amount, \"quantity\":1 } ], \"signature\":\"$signature\" }",
            CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        $status = 1;
        $response = json_decode ( $response , true ) ;
        $referenceNumber = '
Please proceed to any Fawry Retail (Kiosk, Supermarket)
Ask for Fawry Pay Service and enter you Reference Number:

'.$response[referenceNumber].'
';

        $message = "برجاء استخدام رقم السداد $response[referenceNumber] لكود الخدمة 788 لدى فوري لتأكيد الحجز قم $ticket[ID]";
        $new_password = encode_password($new_password) ;
        send_sms($customerMobile ,$message);

        $r = array("Status"=>$status,"Result"=>$referenceNumber,"referenceNumber"=>$response[referenceNumber],"Errors"=>"","NextStep"=>$NextStep);
        return $r;
    }

Returns 1 on success or 0 for non success
https://developer.fawrystaging.com/docs/server-apis/payment-notifications/get-payment-status-v2


问:
How to use Youtube Analytics API to get the content that can be displayed in Youtube Studio
I would like to get the number of impressions by traffic source, for example, which can be displayed on the youtube studio analytics screen, using the Youtube Analytics API.
Looking at the official reference, it doesn't seem to be possible to get it, but does anyone know how to get it?


问:
j2e maven with imported local jar working on jetty:run but not running on tomcat
j2e maven with imported local jar working on jetty:run but not running on tomcat

I created a multiple application to separate legacy application services(javaee)to newer application(spring boot), I encounter this problem when I run it to tomcat server. This Dao and .xml was from imported local jar for local dataqueue. All of the application made from springboot is running smoothly on tomcat. Please help me, I've limited knowledge on legacy application setup. Thank you so much

Error creating bean with name 'foobarDAO' defined in class path resource [foobar.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframe
work.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [foobar.xml]: Invocation of init method failed; nested
exception is java.lang.AbstractMethodError: Method com/microsoft/jdbc/base/BaseDatabaseMetaData.getJDBCMajorVersion()I is abstract

This is my xml and it is working on REST api, I'm not sure what I need to define here from local imported jar file.

<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>DataQueue Rest</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.foo.bar</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DataQueue Rest</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

</web-app>
```


问:
NSUserActivity state restoration not working in SwiftUI
I'm trying to get state restoration working from SwiftUI. SceneStorage works, but I want to have more control over the process, both so I can disable it for tests and so I can control it from a coordinator separate from my views.

userActivity(_:isActive:_:) gets called when the app opens, but not when the app closes. How can I get it to get called to update the apps state? onContinueUserActivity(_:perform:) on the other hand doesn't get called at all.

What am I missing here?


问:
Vite & Svelte – Build & Dev to ‘dist’ plus an alternative directory
I’m working on a combined project where I want to dump the results of the compile process into the ‘dist’ directory and another directory, possibly called ‘view’.

I’ve tried configuring the vite.config.js file by adding code to the export default defineConfig section of the code, in this case simply to dump everything in the view folder, ex:

export default defineConfig({
  plugins: [svelte({
    build: {
      outDir: "./view"
    }
  })],
})```

I’ve also tried to use vite configuration commands in the build section and failed.

But nothing seems to work. Looking for assistance.

Body:
I’m working on a combined project where I want to dump the results of the compile process into the ‘dist’ directory and another directory, possibly called ‘view’.

I’ve tried configuring the vite.config.js file by adding code to the export default defineConfig section of the code, in this case simply to dump everything in the view folder, ex:

export default defineConfig({
  plugins: [svelte({
    build: {
      outDir: "./view"
    }
  })],
})

I’ve also tried to use vite configuration commands in the build section and failed.

But nothing seems to work. Looking for assistance.


问:
iOS Connect to Wi-Fi via EAP-TTLS and EAP-PEAP
I will briefly explain to you what problem I'm having.

I spent a lot of time to find the solution but without any positive result.

So I hope that you can help me.

Our app is used to connect to a secure network via NEHotspotConfiguration.

NEHotspotConfiguration *configuration = [[NEHotspotConfiguration alloc] initWithSSID:networkName eapSettings:settings];

I configured NEHotspotEAPSettings with: username, password, outerIdentity, identity, supportedEAPTypes (NEHotspotConfigurationEAPTypeEAPTTLS and NEHotspotConfigurationEAPTypeEAPPEAP), trustedServerNames and trustedServerCertificates (client.cer and rootCA.cer).

Those certificates were generated by the guys from the server side and are incorporated in the iOS project via xcode.

I have checked if those certificates are valid. For example, in the debuger logs I can see the expiration date.

In the final step when the alert message appears that the app wants to join the secure network, after pressing the join button we see the message "Unable to join the network".

In the debuger logs I see the following:

NEHotspotEAPSettings failed to find persistent reference for identity. status = -25300

NEHotspotEAPSettings failed to find persistent reference for trusted server certificate. status = -25300

NEHotspotEAPSettings found nil persistent reference for identity

Do you have any ideas on how to fix it or what is wrong?

Thank you in advance!

This is the code for successful authentication

NEHotspotEAPSettings *eapSettings = [[NEHotspotEAPSettings alloc] init]; eapSettings.username = @"username"; eapSettings.password = @"password"; eapSettings.supportedEAPTypes = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NEHotspotConfigurationEAPTypeEAPPEAP], nil]; eapSettings.outerIdentity = @""; eapSettings.trustedServerNames = @[@"xxx.xxx.com"]; NEHotspotConfiguration *hotspotConfig = [[NEHotspotConfiguration alloc]initWithSSID:@"ssidName" eapSettings:eapSettings]; [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) { NSLog(@"success"); }];

This is the code for authentication failure

`NSString *caCertificatePath = [[NSBundle mainBundle] pathForResource:@"caCertificate" ofType:@"cer"];
NSData *caCertificateData = [[NSData alloc] initWithContentsOfFile:caCertificatePath];
SecCertificateRef caCertificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)caCertificateData);

```<code>SecCertificateRef userCertificate = nil;
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"userCertificate" ofType:@"cer"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
CFStringRef password = CFSTR("password");
const void *keys[] = { kSecImportExportPassphrase }; };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);
CFRelease(options);
CFRelease(password);
if (securityError == errSecSuccess) {
NSLog(@"Success opening p12 certificate. Items: %ld", CFArrayGetCount(items));
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
    userCertificate = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
    NEHotspotEAPSettings *eapSettings = [[NEHotspotEAPSettings alloc] init];
    eapSettings.tlsClientCertificateRequired = YES;
    eapSettings.trustedServerNames = @[@"xxx",@"xxx.xxx.com"];
    eapSettings.supportedEAPTypes = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NEHotspotConfigurationEAPTypeEAPTLS], nil];
    eapSettings.outerIdentity = @"xxxx";
    [eapSettings setTrustedServerCertificates:@[(__bridge id)caCertificateRef]];
    [eapSettings setIdentity: userCertificate];
    NEHotspotConfiguration *hotspotConfig = [[NEHotspotConfiguration alloc]initWithSSID:@"ssidName" eapSettings:eapSettings];
    [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
        NSLog(@"failure");//NEHotspotEAPSettings failed to find persistent reference for identity. status = -25300
    }];
} else {
    NSLog(@"Error opening Certificate.");
}
</code>```

`

The difference between the two is that I want to use certificate authentication not username password authentication

By the way, the test device is iphone12pm, the version is ios16.2, the controller is Cisco.

1、Check the Apple Developer website
2、No valid information in Google Bing and other website searches

Body:
I will briefly explain to you what problem I'm having.

I spent a lot of time to find the solution but without any positive result.

So I hope that you can help me.

Our app is used to connect to a secure network via NEHotspotConfiguration.

NEHotspotConfiguration *configuration = [[NEHotspotConfiguration alloc] initWithSSID:networkName eapSettings:settings];

I configured NEHotspotEAPSettings with: username, password, outerIdentity, identity, supportedEAPTypes (NEHotspotConfigurationEAPTypeEAPTTLS and NEHotspotConfigurationEAPTypeEAPPEAP), trustedServerNames and trustedServerCertificates (client.cer and rootCA.cer).

Those certificates were generated by the guys from the server side and are incorporated in the iOS project via xcode.

I have checked if those certificates are valid. For example, in the debuger logs I can see the expiration date.

In the final step when the alert message appears that the app wants to join the secure network, after pressing the join button we see the message "Unable to join the network".

In the debuger logs I see the following:

NEHotspotEAPSettings failed to find persistent reference for identity. status = -25300

NEHotspotEAPSettings failed to find persistent reference for trusted server certificate. status = -25300

NEHotspotEAPSettings found nil persistent reference for identity

Do you have any ideas on how to fix it or what is wrong?

Thank you in advance!

This is the code for successful authentication

NEHotspotEAPSettings *eapSettings = [[NEHotspotEAPSettings alloc] init]; eapSettings.username = @"username"; eapSettings.password = @"password"; eapSettings.supportedEAPTypes = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NEHotspotConfigurationEAPTypeEAPPEAP], nil]; eapSettings.outerIdentity = @""; eapSettings.trustedServerNames = @[@"xxx.xxx.com"]; NEHotspotConfiguration *hotspotConfig = [[NEHotspotConfiguration alloc]initWithSSID:@"ssidName" eapSettings:eapSettings]; [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) { NSLog(@"success"); }];

This is the code for authentication failure

`NSString *caCertificatePath = [[NSBundle mainBundle] pathForResource:@"caCertificate" ofType:@"cer"];
NSData *caCertificateData = [[NSData alloc] initWithContentsOfFile:caCertificatePath];
SecCertificateRef caCertificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)caCertificateData);

SecCertificateRef userCertificate = nil;
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"userCertificate" ofType:@"cer"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
CFStringRef password = CFSTR("password");
const void *keys[] = { kSecImportExportPassphrase }; };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);
CFRelease(options);
CFRelease(password);
if (securityError == errSecSuccess) {
NSLog(@"Success opening p12 certificate. Items: %ld", CFArrayGetCount(items));
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
    userCertificate = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
    NEHotspotEAPSettings *eapSettings = [[NEHotspotEAPSettings alloc] init];
    eapSettings.tlsClientCertificateRequired = YES;
    eapSettings.trustedServerNames = @[@"xxx",@"xxx.xxx.com"];
    eapSettings.supportedEAPTypes = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NEHotspotConfigurationEAPTypeEAPTLS], nil];
    eapSettings.outerIdentity = @"xxxx";
    [eapSettings setTrustedServerCertificates:@[(__bridge id)caCertificateRef]];
    [eapSettings setIdentity: userCertificate];
    NEHotspotConfiguration *hotspotConfig = [[NEHotspotConfiguration alloc]initWithSSID:@"ssidName" eapSettings:eapSettings];
    [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
        NSLog(@"failure");//NEHotspotEAPSettings failed to find persistent reference for identity. status = -25300
    }];
} else {
    NSLog(@"Error opening Certificate.");
}

`

The difference between the two is that I want to use certificate authentication not username password authentication

By the way, the test device is iphone12pm, the version is ios16.2, the controller is Cisco.

1、Check the Apple Developer website
2、No valid information in Google Bing and other website searches


问:
Setting data protection on cell range only to be edited by specified account
I'm creating a fun little game in Google Sheets -- the part of code I'm working on now is basically locking the row after a specific cell in that row has been edited (essentially, not letting the user to go back and edit anything before that cell).

My full code is below, but I'm looking for a fix with lines specific to the protections. I want my sheet to add a data range that only allows the email amadle@strengthinsheets.com edit access.  However, I'm testing with different accounts, and it seems the protection script is allowing the user to edit (not locking to the specific account).

Is something wrong with this code block? I basically just want to add a protection on the range that doesn't let anyone other than a specific user edit.

```<code>function onEdit(e) {
    var oldText = "-";
var newText = "=";
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var ss = spreadsheet.getActiveSheet();
// var cell = ss.getRange('AB1').getValue();
var answer = ss.getRange("AA2").getValue();
var syntax = ss.getRange("AC2").getValue();
var description = ss.getRange("AC1").getValue();
var type = ss.getRange("AC3").getValue();

if (ss.getRange("AB1").getValue() == "MATCH") {

 SpreadsheetApp.getUi().alert(" Congratulations: "+ answer, "Type: "+type+"\n\nSyntax: "+syntax+"\n\n Description: "+description, SpreadsheetApp.getUi().ButtonSet.OK);

}

 if (e.range.getA1Notation() === 'F5') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B6:N6").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);
    **var ss = SpreadsheetApp.getActive();

  var range = ss.getRange('B5:N5'); // Example of protecting Row 1
  var protection = range.protect().setDescription('GUESS 1');

  var me = "amadle@strengthinsheets.com";
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }

  }**

  if (e.range.getA1Notation() === 'F7') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B8:N8").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

  }

  if (e.range.getA1Notation() === 'F9') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B10:N10").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

var hint = sheet.getRange('AC1').getValue();
  SpreadsheetApp.getUi().alert("Function Hint", hint, SpreadsheetApp.getUi().ButtonSet.OK);
  }

  if (e.range.getA1Notation() === 'F11') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B12:N12").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

  }

    if (e.range.getA1Notation() === 'F13') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B14:N14").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);
  SpreadsheetApp.getUi().alert("Next Time! Correct Answer: "+ answer, "Type: "+type+"\n\nSyntax: "+syntax+"\n\n Description: "+description, SpreadsheetApp.getUi().ButtonSet.OK);
  }
}
</code>```

Body:
I'm creating a fun little game in Google Sheets -- the part of code I'm working on now is basically locking the row after a specific cell in that row has been edited (essentially, not letting the user to go back and edit anything before that cell).

My full code is below, but I'm looking for a fix with lines specific to the protections. I want my sheet to add a data range that only allows the email amadle@strengthinsheets.com edit access.  However, I'm testing with different accounts, and it seems the protection script is allowing the user to edit (not locking to the specific account).

Is something wrong with this code block? I basically just want to add a protection on the range that doesn't let anyone other than a specific user edit.

function onEdit(e) {
    var oldText = "-";
var newText = "=";
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var ss = spreadsheet.getActiveSheet();
// var cell = ss.getRange('AB1').getValue();
var answer = ss.getRange("AA2").getValue();
var syntax = ss.getRange("AC2").getValue();
var description = ss.getRange("AC1").getValue();
var type = ss.getRange("AC3").getValue();

if (ss.getRange("AB1").getValue() == "MATCH") {

 SpreadsheetApp.getUi().alert(" Congratulations: "+ answer, "Type: "+type+"\n\nSyntax: "+syntax+"\n\n Description: "+description, SpreadsheetApp.getUi().ButtonSet.OK);

}

 if (e.range.getA1Notation() === 'F5') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B6:N6").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);
    **var ss = SpreadsheetApp.getActive();

  var range = ss.getRange('B5:N5'); // Example of protecting Row 1
  var protection = range.protect().setDescription('GUESS 1');

  var me = "amadle@strengthinsheets.com";
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }

  }**

  if (e.range.getA1Notation() === 'F7') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B8:N8").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

  }

  if (e.range.getA1Notation() === 'F9') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B10:N10").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

var hint = sheet.getRange('AC1').getValue();
  SpreadsheetApp.getUi().alert("Function Hint", hint, SpreadsheetApp.getUi().ButtonSet.OK);
  }

  if (e.range.getA1Notation() === 'F11') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B12:N12").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);

  }

    if (e.range.getA1Notation() === 'F13') {

var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("B14:N14").createTextFinder(oldText).matchFormulaText(true).replaceAllWith(newText);
  SpreadsheetApp.getUi().alert("Next Time! Correct Answer: "+ answer, "Type: "+type+"\n\nSyntax: "+syntax+"\n\n Description: "+description, SpreadsheetApp.getUi().ButtonSet.OK);
  }
}


问:
Spyder can't show chinese character
I am using Raspbian on Raspberry Pi 4B hardware. When I use
pip3 install spyder, Spyder4 is installed. But I want to use Spyder5.
So I installed miniforge3 as a virtual environment and install Spyder5 by conda install spyder.

Sure, Spyder5 is installed. But a weird thing happened and all the Chinese characters disappeared! I revisited Spyder4 installed by pip3, Chinese characters are working well.

Anyone can help to solve this problem?

I compared the fonts difference between Spyder4 and Spyder5 but found no clear difference.

Title: Spyder can't show chinese character


问:
whether i right join or left join i get the same output why and how to fix it?
```<code>CREATE TABLE teacher(
    id INT PRIMARY KEY AUTO_INCREMENT, -- PRIMARY KEY AUTO_INCREMENt
    name_ VARCHAR(45),
    age INT,
    class INT
    );

CREATE TABLE student(
    id INT PRIMARY KEY AUTO_INCREMENT ,
    name_ VARCHAR(45),
    class INT
    );

INSERT INTO teacher(id, name_ , age, class) VALUES
(DEFAULT ,"Ali", 40, null),
(DEFAULT, "Reza", 30, 2),
(DEFAULT, "Yosef", 50, 3),
(DEFAULT, "Ibrahim", 60, 2);

INSERT INTO student(id, name_, class)VALUES
(DEFAULT, "Hasan", 2),
(DEFAULT, "Hosein", null),
(DEFAULT, "Hamed", 4),
(DEFAULT, "Idris", 1);

SELECT * FROM teacher
LEFT JOIN student
ON teacher.id = student.id ;
</code>```

i dropped the tables and tried again and again,

Body:
CREATE TABLE teacher(
    id INT PRIMARY KEY AUTO_INCREMENT, -- PRIMARY KEY AUTO_INCREMENt
    name_ VARCHAR(45),
    age INT,
    class INT
    );

CREATE TABLE student(
    id INT PRIMARY KEY AUTO_INCREMENT ,
    name_ VARCHAR(45),
    class INT
    );

INSERT INTO teacher(id, name_ , age, class) VALUES
(DEFAULT ,"Ali", 40, null),
(DEFAULT, "Reza", 30, 2),
(DEFAULT, "Yosef", 50, 3),
(DEFAULT, "Ibrahim", 60, 2);

INSERT INTO student(id, name_, class)VALUES
(DEFAULT, "Hasan", 2),
(DEFAULT, "Hosein", null),
(DEFAULT, "Hamed", 4),
(DEFAULT, "Idris", 1);

SELECT * FROM teacher
LEFT JOIN student
ON teacher.id = student.id ;

i dropped the tables and tried again and again,


问:
Snowflake Moving Averages
Im having issues creating a 4 week moving average calculation on Snowflake, the goal is to have a table with all the distinct weeks and descriptions for each product and the volume and amounts paid for them.

Here is the code that I'm using

```<code>Select
      (date_trunc(WEEK, TO_DATE(YR || '-' || MTH || '-' || DT, 'YYYY-MM-DD'))) as Week ,
      (DESCRIPTION) as "DESC",
      AVG(C.VOL) OVER(PARTITION BY DESC ORDER BY Week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as TXN,
      AVG(C.PRNLC) OVER(PARTITION BY C11.DMADES ORDER BY Week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as PRN
FROM C
GROUP BY Week, "DESC"
</code>```

I keep getting an error

[CAST(C.VOL_17 AS NUMBER(38,3))] is not a valid group by expression

The Code works fine by removing the averages and window functions but then I'd have to go out on other tools and create the 4 week moving average I'd expect to see there, i have tried to remove the grouping and use it as distinct but it would still return 1 line for each record, this goes beyond my expertise I'm afraid, I'm not really sure how Cast comes into play here. Is there another way to accomplish what I want? do you guys see what I'm doing wrong here?

Thank you!

Title: Snowflake Moving Averages

Body:
Im having issues creating a 4 week moving average calculation on Snowflake, the goal is to have a table with all the distinct weeks and descriptions for each product and the volume and amounts paid for them.

Here is the code that I'm using

Select
      (date_trunc(WEEK, TO_DATE(YR || '-' || MTH || '-' || DT, 'YYYY-MM-DD'))) as Week ,
      (DESCRIPTION) as "DESC",
      AVG(C.VOL) OVER(PARTITION BY DESC ORDER BY Week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as TXN,
      AVG(C.PRNLC) OVER(PARTITION BY C11.DMADES ORDER BY Week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as PRN
FROM C
GROUP BY Week, "DESC"

I keep getting an error

[CAST(C.VOL_17 AS NUMBER(38,3))] is not a valid group by expression

The Code works fine by removing the averages and window functions but then I'd have to go out on other tools and create the 4 week moving average I'd expect to see there, i have tried to remove the grouping and use it as distinct but it would still return 1 line for each record, this goes beyond my expertise I'm afraid, I'm not really sure how Cast comes into play here. Is there another way to accomplish what I want? do you guys see what I'm doing wrong here?

Thank you!


问:
How to use async or promise with JQuery $.get?
I'm attempting to implement $.get to retrieve a status from a method inside my myreport/index.cshtm.cs page. The get along with the method call work find although the method is not async because there is nothing in it to implement await. The problem is how long it takes to get a response. It's executing the 'return errorMsg' before setting errorMsg inside $.get. How can I implement an await or promise to wait for the response message to complete before continuing on?

I added a async/await but no luck.

let isCgcFiltersUrl = "/myreport/index/iscgcfilters";

function ValidateClient() {
  let errorMsg = String.empty;
  $.get(isCgcFiltersUrl, async function (response) {
    errorMsg = (await response)
      ? String.empty
      : "An error occurred for this client";
  });

  return errorMsg;
}
```


问:
Slack Block Kit static_select behaves differently on Mac app and iPhone
I am developing a Slack app with Slack's Block Kit.
In Block Kit, I can create a list by using static_select, and I can confirm that action_id is requested when an option is selected.
However, when we checked the behavior on a smart phone, we noticed that there is no action_id response when an option is selected.

I have confirmed that this is not a problem with the Slack app on Mac and Chrome browser, but I have confirmed that the problem occurs with the Slack app on iPhone.
This problem does not occur if I place a static_select under type: actions.

As a solution, I feel that we should have a Submit button separate from the list, but I feel that it would be delicate to add more buttons due to differences in behavior in different environments.
Please let me know if you have any ideas.

```<code># iPhone does not respond to action_id
# (I checked the access log in real time on the server that receives the action_id, but it seems that no request was generated in the first place.)
{
    "blocks": [
        {
            "type": "input",
            "element": {
                "type": "static_select",
                "placeholder": {
                    "type": "plain_text",
                    "text": "Select an item",
                    "emoji": true
                },
                "options": [
                    {
                        "text": {
                            "type": "plain_text",
                            "text": "*this is plain_text text*",
                            "emoji": true
                        },
                        "value": "value-0"
                    }
                ],
                "action_id": "static_select-action"
            },
            "label": {
                "type": "plain_text",
                "text": "Label",
                "emoji": true
            }
        }
    ]
}
</code>```
```<code># iPhone reacts to action_id
{
    "blocks": [
        {
            "type": "actions",
            "elements": [
                {
                    "type": "static_select",
                    "placeholder": {
                        "type": "plain_text",
                        "text": "Select an item",
                        "emoji": true
                    },
                    "options": [
                        {
                            "text": {
                                "type": "plain_text",
                                "text": "*this is plain_text text*",
                                "emoji": true
                            },
                            "value": "value-0"
                        }
                    ],
                    "action_id": "actionId-3"
                }
            ]
        }
    ]
}
</code>```

I would like to have the same behavior between the Slack app on Mac and the Slack app on iPhone.

Body:
I am developing a Slack app with Slack's Block Kit.
In Block Kit, I can create a list by using static_select, and I can confirm that action_id is requested when an option is selected.
However, when we checked the behavior on a smart phone, we noticed that there is no action_id response when an option is selected.

I have confirmed that this is not a problem with the Slack app on Mac and Chrome browser, but I have confirmed that the problem occurs with the Slack app on iPhone.
This problem does not occur if I place a static_select under type: actions.

As a solution, I feel that we should have a Submit button separate from the list, but I feel that it would be delicate to add more buttons due to differences in behavior in different environments.
Please let me know if you have any ideas.

# iPhone does not respond to action_id
# (I checked the access log in real time on the server that receives the action_id, but it seems that no request was generated in the first place.)
{
    "blocks": [
        {
            "type": "input",
            "element": {
                "type": "static_select",
                "placeholder": {
                    "type": "plain_text",
                    "text": "Select an item",
                    "emoji": true
                },
                "options": [
                    {
                        "text": {
                            "type": "plain_text",
                            "text": "*this is plain_text text*",
                            "emoji": true
                        },
                        "value": "value-0"
                    }
                ],
                "action_id": "static_select-action"
            },
            "label": {
                "type": "plain_text",
                "text": "Label",
                "emoji": true
            }
        }
    ]
}

# iPhone reacts to action_id
{
    "blocks": [
        {
            "type": "actions",
            "elements": [
                {
                    "type": "static_select",
                    "placeholder": {
                        "type": "plain_text",
                        "text": "Select an item",
                        "emoji": true
                    },
                    "options": [
                        {
                            "text": {
                                "type": "plain_text",
                                "text": "*this is plain_text text*",
                                "emoji": true
                            },
                            "value": "value-0"
                        }
                    ],
                    "action_id": "actionId-3"
                }
            ]
        }
    ]
}

I would like to have the same behavior between the Slack app on Mac and the Slack app on iPhone.