问:
Uploading data with multer - image is an empty object
I want to send product data including an image to the database. I am using multer and get the error:

Cannot read property 'path' of undefined

I have seen that this error is very common and have tried the suggestions that are made on stack overflow without success. What makes me suspicious is, when I log the req.body, the correct data is displayed, but image is an empty object. I also logged the whole thing in my http-request, there image is a file and prototype array.

multer storage:

```<code>import { Request } from "express";
import multer, { FileFilterCallback } from "multer";
import path from 'path'
const maxSize = 100 * 1024 *1024;
type DestinationCallback = (error: Error | null, destination: string) => void
type FileNameCallback = (error: Error | null, filename: string) => void

 const storage = multer.diskStorage({
        destination:(req:Request,file:Express.Multer.File, callback:DestinationCallback)=>{
            callback(null, path.resolve(process.cwd(), 'admin/public/uploads'));
        },

        filename: (req:Request, file:Express.Multer.File, callback:FileNameCallback)=>{
            callback(null, Date.now()+ "--"+ path.extname(file.originalname))
        },
    })

const upload = multer({
    storage:storage,
    fileFilter:(req:Request,file:Express.Multer.File,callback:FileFilterCallback)=>{
        if(
            file.mimetype == "image/png"||
            file.mimetype == "image/jpg" ||
            file.mimetype == "image/jpeg" ||
            file.mimetype == "video/mp4"
        ){
            callback(null, true);
        } else{
            callback(null,false)
            return callback(new Error("Only .png, .jpg, .jpeg, .mp3, .mp4 allowed"))
        }
    },
    limits:{fileSize: maxSize}
});

export default upload
</code>```

;

```<code>My route:

productsRouter.post('/', upload.single('image'), verifyTokenAndAdmin, async (req:Request, res:Response)=>{
    console.log(req.file);
    console.log(req.body);
    try{
        const uploadResult = cloudinary.uploader.upload(req.file!.path,{
            upload_preset: "webshop_ts_mern",
            resource_type: "auto",
        })
        const newProducts = new Products({
            cloudinary_id: uploadResult.public_id,
            title: req.body.title,
            producer: req.body.producer,
            categories: req.body.categories,
            desc: req.body.desc,
            price: req.body.price,
            currency:req.body.currency,
            colors:req.body.colors,
            sizes: req.body.sizes,
            inStock: req.body.inStock,
            image: uploadResult.secure_url,

        })
        const savedproducts = await newProducts.save();
        res.status(200).json(savedproducts);
    } catch(error){
        res.status(403)
        console.log(error);
        throw new Error("Action failed");
    }
});
</code>```

Add my code from frontend.
Input with name="image":

```<code><FormGroup>
            <label htmlFor='image'>Picture</label>
            <input type="file" name='image' id='image' onChange={handleFileChange} style={{marginBottom:"5px"}}/>
      {preview && <img src={preview} alt="Preview" width="300" height="200"/>}
        </FormGroup>
</code>```

handleFileChange:

```<code>const [fileData, setFileData] = useState<FileData>({ image: null });
    const [preview, setPreview] = useState<string | null>(null);
    const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
        const files = e.currentTarget.files;
        if (!files) {
          return;
        }
        const file = files[0]
        setFileData({image:file})
        updatePreview(files[0]);
      };
</code>```

Formdata(image is the last entry, all entries are logged correctly):

```<code>  const onSubmit=(e:React.FormEvent<HTMLFormElement>)=>{
      e.preventDefault();
      const productData = new FormData();
      productData.append("title", formdata.title);
      productData.append("producer", formdata.producer);
      productData.append("categories", JSON.stringify(formdata.categories));
      productData.append("desc", formdata.desc);
      productData.append("price", formdata.price);
      productData.append("colors", JSON.stringify(formdata.colors));
      productData.append("sizes", JSON.stringify(formdata.sizes));
      productData.append("inStock", formdata.inStock);
      productData.append('image', fileData.image!)
      for(let value of productData){
        console.log(value);
      }
      dispatch(createProduct(productData));
    }
</code>```

The log of fileData.image before dispatch:

```<code>> (2) ['image', File] 0 :  "image" 1 :  File {name: 'golf.jpg',
> lastModified: 1643720187661, lastModifiedDate: Tue Feb 01 2022
> 13:56:27 GMT+0100 (Mitteleuropäische Normalzeit), webkitRelativePath:
> '', size: 18769, …} length :  2 [[Prototype]] :  Array(0)
</code>```

The log in my Route:

```<code>undefined
[0] {
[0]   title: 'Golfshoes',
[0]   producer: 'Nike',
[0]   categories: '"Sportshoes"',
[0]   desc: 'Lorem Ipsum',
[0]   price: '89',
[0]   colors: '"white, black"',
[0]   sizes: '"45, 47, 49"',
[0]   inStock: 'true',
[0]   image: {}
[0] }
</code>```

Body:
I want to send product data including an image to the database. I am using multer and get the error:

Cannot read property 'path' of undefined

I have seen that this error is very common and have tried the suggestions that are made on stack overflow without success. What makes me suspicious is, when I log the req.body, the correct data is displayed, but image is an empty object. I also logged the whole thing in my http-request, there image is a file and prototype array.

multer storage:

import { Request } from "express";
import multer, { FileFilterCallback } from "multer";
import path from 'path'
const maxSize = 100 * 1024 *1024;
type DestinationCallback = (error: Error | null, destination: string) => void
type FileNameCallback = (error: Error | null, filename: string) => void

 const storage = multer.diskStorage({
        destination:(req:Request,file:Express.Multer.File, callback:DestinationCallback)=>{
            callback(null, path.resolve(process.cwd(), 'admin/public/uploads'));
        },

        filename: (req:Request, file:Express.Multer.File, callback:FileNameCallback)=>{
            callback(null, Date.now()+ "--"+ path.extname(file.originalname))
        },
    })

const upload = multer({
    storage:storage,
    fileFilter:(req:Request,file:Express.Multer.File,callback:FileFilterCallback)=>{
        if(
            file.mimetype == "image/png"||
            file.mimetype == "image/jpg" ||
            file.mimetype == "image/jpeg" ||
            file.mimetype == "video/mp4"
        ){
            callback(null, true);
        } else{
            callback(null,false)
            return callback(new Error("Only .png, .jpg, .jpeg, .mp3, .mp4 allowed"))
        }
    },
    limits:{fileSize: maxSize}
});

export default upload

;

My route:

productsRouter.post('/', upload.single('image'), verifyTokenAndAdmin, async (req:Request, res:Response)=>{
    console.log(req.file);
    console.log(req.body);
    try{
        const uploadResult = cloudinary.uploader.upload(req.file!.path,{
            upload_preset: "webshop_ts_mern",
            resource_type: "auto",
        })
        const newProducts = new Products({
            cloudinary_id: uploadResult.public_id,
            title: req.body.title,
            producer: req.body.producer,
            categories: req.body.categories,
            desc: req.body.desc,
            price: req.body.price,
            currency:req.body.currency,
            colors:req.body.colors,
            sizes: req.body.sizes,
            inStock: req.body.inStock,
            image: uploadResult.secure_url,

        })
        const savedproducts = await newProducts.save();
        res.status(200).json(savedproducts);
    } catch(error){
        res.status(403)
        console.log(error);
        throw new Error("Action failed");
    }
});

Add my code from frontend.
Input with name="image":

<FormGroup>
            Picture
            <input type="file" name='image' id='image' onChange={handleFileChange} style={{marginBottom:"5px"}}/>
      {preview && }
        </FormGroup>

handleFileChange:

const [fileData, setFileData] = useState<FileData>({ image: null });
    const [preview, setPreview] = useState<string | null>(null);
    const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
        const files = e.currentTarget.files;
        if (!files) {
          return;
        }
        const file = files[0]
        setFileData({image:file})
        updatePreview(files[0]);
      };

Formdata(image is the last entry, all entries are logged correctly):

  const onSubmit=(e:React.FormEvent<HTMLFormElement>)=>{
      e.preventDefault();
      const productData = new FormData();
      productData.append("title", formdata.title);
      productData.append("producer", formdata.producer);
      productData.append("categories", JSON.stringify(formdata.categories));
      productData.append("desc", formdata.desc);
      productData.append("price", formdata.price);
      productData.append("colors", JSON.stringify(formdata.colors));
      productData.append("sizes", JSON.stringify(formdata.sizes));
      productData.append("inStock", formdata.inStock);
      productData.append('image', fileData.image!)
      for(let value of productData){
        console.log(value);
      }
      dispatch(createProduct(productData));
    }

The log of fileData.image before dispatch:

> (2) ['image', File] 0 :  "image" 1 :  File {name: 'golf.jpg',
> lastModified: 1643720187661, lastModifiedDate: Tue Feb 01 2022
> 13:56:27 GMT+0100 (Mitteleuropäische Normalzeit), webkitRelativePath:
> '', size: 18769, …} length :  2 [[Prototype]] :  Array(0)

The log in my Route:

undefined
[0] {
[0]   title: 'Golfshoes',
[0]   producer: 'Nike',
[0]   categories: '"Sportshoes"',
[0]   desc: 'Lorem Ipsum',
[0]   price: '89',
[0]   colors: '"white, black"',
[0]   sizes: '"45, 47, 49"',
[0]   inStock: 'true',
[0]   image: {}
[0] }


来源: stackexchange

问:
Combobox Run-Time Issue
this is the first I've worked with Excel's VBA UserForm and I'm experiencing an issue i don't understand. currently I'm receiving a 1004 error coming from ComboBox1_Change() when ComboBox1's selection is not the same as the activesheet that I'm looking at.
Is there an easy way to fix that? I need to be able to select any sheet without directly looking at it. ComboBox2's selection is based on the column headings of the sheet picked in ComboBox1. Any help would be greatly appreciated! Below is the code as I've developed thus far.

```<code>Private m_Cancelled As Boolean

Public Property Get Cancelled() As Variant
    Cancelled = m_Cancelled
End Property

Private Sub ComboBox1_Change()
    ComboBox2.List = WorksheetFunction.Transpose(Worksheets(CStr(ComboBox1.Value)).Range(Cells(1, 1), Cells(1, GetColSize)).Value)
End Sub

Private Sub ComboBox2_Change()
    ComboBox3.List = WorksheetFunction.Transpose(Worksheets(CStr(ComboBox1.Value)).Range(Cells(1, 1), Cells(1, GetColSize)).Value)
End Sub

Private Sub CommandButton1_Click()
    Hide
End Sub

Private Sub CommandButton2_Click()
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
End Sub

Private Sub UserForm_Click()

End Sub

Private Sub UserForm_Initialize()

    With UserForm_1
      .Width = Application.Width * 0.24
      .Height = Application.Height * 0.47
    End With

    ComboBox1.Clear

    'Initialize ComboBox1
    Dim WB As Workbook: Set WB = ThisWorkbook
    Dim wCount As Long: wCount = WB.Worksheets.Count
    Dim wsNames() As String: ReDim wsNames(1 To wCount)

    Dim WS As Worksheet, w As Long

    For Each WS In WB.Worksheets
        If WS.Visible = xlSheetVisible Then
            w = w + 1
            wsNames(w) = WS.Name
        End If
    Next WS

    If w < wCount Then ReDim Preserve wsNames(1 To w)

    ComboBox1.List = wsNames

End Sub

Private Sub UserForm_Activate()

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer _
                                        , CloseMode As Integer)

    ' Prevent the form being unloaded
    If CloseMode = vbFormControlMenu Then Cancel = True

    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True

End Sub

Function GetColSize() As Integer
    Dim LastColumn As Integer
    LastColumn = Sheets(ComboBox1.Value).Rows(1).Columns(Sheets(ComboBox1.Value).Columns.Count).End(xlToLeft).Column
'    Debug.Print LastColumn; " Last Column"
    GetColSize = LastColumn
End Function

Function GetRowSize() As Variant
    Dim LastRow As Variant
    LastRow = Sheets(ComboBox1.Value).Cells(Rows.Count, GetBox2Col).End(xlUp).Row
'    Debug.Print LastRow; " Last Row"
    GetRowSize = LastRow
End Function

Function GetComboBox1() As String
    GetComboBox1 = ComboBox1.Value
End Function

Function GetComboBox2() As String
    GetComboBox2 = ComboBox2.Value
    Debug.Print ComboBox2.Value; " is in column "; GetBox2Col
End Function

Function GetBox2Col() As Integer
    Dim i As Integer
    For i = 1 To GetColSize
        If Cells(1, i) = ComboBox2.Value Then
            GetBox2Col = i
            Exit For
        End If
    Next i
End Function

Function GetComboBox3() As String
    GetComboBox3 = ComboBox3.Value
    Debug.Print ComboBox3.Value; " is in column "; GetBox3Col
End Function

Function GetBox3Col() As Integer
    Dim i As Integer
    For i = 1 To GetColSize
        If Cells(1, i) = ComboBox3.Value Then
            GetBox3Col = i
            Exit For
        End If
    Next i
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Title: Combobox Run-Time Issue

Body:
this is the first I've worked with Excel's VBA UserForm and I'm experiencing an issue i don't understand. currently I'm receiving a 1004 error coming from ComboBox1_Change() when ComboBox1's selection is not the same as the activesheet that I'm looking at.
Is there an easy way to fix that? I need to be able to select any sheet without directly looking at it. ComboBox2's selection is based on the column headings of the sheet picked in ComboBox1. Any help would be greatly appreciated! Below is the code as I've developed thus far.

Private m_Cancelled As Boolean

Public Property Get Cancelled() As Variant
    Cancelled = m_Cancelled
End Property

Private Sub ComboBox1_Change()
    ComboBox2.List = WorksheetFunction.Transpose(Worksheets(CStr(ComboBox1.Value)).Range(Cells(1, 1), Cells(1, GetColSize)).Value)
End Sub

Private Sub ComboBox2_Change()
    ComboBox3.List = WorksheetFunction.Transpose(Worksheets(CStr(ComboBox1.Value)).Range(Cells(1, 1), Cells(1, GetColSize)).Value)
End Sub

Private Sub CommandButton1_Click()
    Hide
End Sub

Private Sub CommandButton2_Click()
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
End Sub

Private Sub UserForm_Click()

End Sub

Private Sub UserForm_Initialize()

    With UserForm_1
      .Width = Application.Width * 0.24
      .Height = Application.Height * 0.47
    End With

    ComboBox1.Clear

    'Initialize ComboBox1
    Dim WB As Workbook: Set WB = ThisWorkbook
    Dim wCount As Long: wCount = WB.Worksheets.Count
    Dim wsNames() As String: ReDim wsNames(1 To wCount)

    Dim WS As Worksheet, w As Long

    For Each WS In WB.Worksheets
        If WS.Visible = xlSheetVisible Then
            w = w + 1
            wsNames(w) = WS.Name
        End If
    Next WS

    If w < wCount Then ReDim Preserve wsNames(1 To w)

    ComboBox1.List = wsNames

End Sub

Private Sub UserForm_Activate()

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer _
                                        , CloseMode As Integer)

    ' Prevent the form being unloaded
    If CloseMode = vbFormControlMenu Then Cancel = True

    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True

End Sub

Function GetColSize() As Integer
    Dim LastColumn As Integer
    LastColumn = Sheets(ComboBox1.Value).Rows(1).Columns(Sheets(ComboBox1.Value).Columns.Count).End(xlToLeft).Column
'    Debug.Print LastColumn; " Last Column"
    GetColSize = LastColumn
End Function

Function GetRowSize() As Variant
    Dim LastRow As Variant
    LastRow = Sheets(ComboBox1.Value).Cells(Rows.Count, GetBox2Col).End(xlUp).Row
'    Debug.Print LastRow; " Last Row"
    GetRowSize = LastRow
End Function

Function GetComboBox1() As String
    GetComboBox1 = ComboBox1.Value
End Function

Function GetComboBox2() As String
    GetComboBox2 = ComboBox2.Value
    Debug.Print ComboBox2.Value; " is in column "; GetBox2Col
End Function

Function GetBox2Col() As Integer
    Dim i As Integer
    For i = 1 To GetColSize
        If Cells(1, i) = ComboBox2.Value Then
            GetBox2Col = i
            Exit For
        End If
    Next i
End Function

Function GetComboBox3() As String
    GetComboBox3 = ComboBox3.Value
    Debug.Print ComboBox3.Value; " is in column "; GetBox3Col
End Function

Function GetBox3Col() As Integer
    Dim i As Integer
    For i = 1 To GetColSize
        If Cells(1, i) = ComboBox3.Value Then
            GetBox3Col = i
            Exit For
        End If
    Next i
End Function


Title: i am trying to use prettytable but it is giving me a field row along the top that i do not want

Body:
when i put in my code i am getting a row along the top that i do not know how to get rid of

this is the code:

import prettytable

def front_end():
    # Create a new table
    table = prettytable.PrettyTable()

    # Add the rows of the array to the table
    for row in array:
        table.add_row(row)

    # Set the alignment of the elements to center
    table.align = "c"

    # Set the border characters of the table
    table.border = True
    table.hrules = prettytable.ALL
    table.vrules = prettytable.ALL

    # Print the table
    print(table)

this is its output:

+---------+---------+---------+---------+---------+---------+---------+
| Field 1 | Field 2 | Field 3 | Field 4 | Field 5 | Field 6 | Field 7 |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   1.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   2.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   1.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+

this is what i would like:

+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   0.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   1.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   2.0   |   0.0   |   2.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+
|   0.0   |   1.0   |   0.0   |   1.0   |   0.0   |   0.0   |   0.0   |
+---------+---------+---------+---------+---------+---------+---------+

I have never used prettytable before so maybe there is a easy solution but i don't know it.


问:
how to make table with fixed size of each cell in itextpdf?
I try to make a table in pdf where every cell has the same size.
My code is fairly simple:

```<code>ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
Document doc = new Document(pdfDoc);

Table table = new Table(new float[]{1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f})
            .addCell(new Cell(1,1).add(new Paragraph("Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test2")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test Te")))
            .addCell(new Cell(1,1).add(new Paragraph("Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test2")))
            .addCell(new Cell(1,1).add(new Paragraph("TestTe")))
            .addCell(new Cell(1,1).add(new Paragraph("TestsTestTest")))
            .addCell(new Cell(1,1).add(new Paragraph("TestTes")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test")));
    table.setFontSize(6);
    doc.add(table);
    doc.close();
</code>```

This is the result I'm seeing:

how can I make the table to be expanded for the full page width and with all cells being even (have the same width as others)?

Body:
I try to make a table in pdf where every cell has the same size.
My code is fairly simple:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
Document doc = new Document(pdfDoc);

Table table = new Table(new float[]{1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f})
            .addCell(new Cell(1,1).add(new Paragraph("Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test2")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test Te")))
            .addCell(new Cell(1,1).add(new Paragraph("Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test2")))
            .addCell(new Cell(1,1).add(new Paragraph("TestTe")))
            .addCell(new Cell(1,1).add(new Paragraph("TestsTestTest")))
            .addCell(new Cell(1,1).add(new Paragraph("TestTes")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test Test")))
            .addCell(new Cell(1,1).add(new Paragraph("Test Test")));
    table.setFontSize(6);
    doc.add(table);
    doc.close();

This is the result I'm seeing:

how can I make the table to be expanded for the full page width and with all cells being even (have the same width as others)?


问:
Scikit Learn - KMeans Killing Kernel on 2019 MacBook Pro
I know a similar question has been asked in the past, here - IPython Notebook Kernel getting dead while running Kmeans

But that was 7 years ago so please don't close me.

I'm trying to run scikitlean kmeans clustering on a 2019 MacBook Pro and it keeps killing the kernel. See spec below:

Does anybody know of any known issues out there or work arounds for this? I would have thought this shouldn't be a problem for such an beefy/expensive machine. I don't mind if it takes a while though this is just killing it altogether, even on the simple training dataset following this tutorial - https://github.com/ageron/handson-ml2/blob/master/09_unsupervised_learning.ipynb

This is the code I used and the error it is returning in VS Code.

Code:

```<code>from sklearn.cluster import KMeans

k = 5
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(X)
</code>```

Error:

```<code>Error: Kernel is dead
Error: Kernel is dead
at g._sendKernelShellControl (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1006195)
at g.sendShellMessage (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1005964)
at g.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1008506)
at d.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:37:325680)
at w.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:32:18027)
at w.executeCodeCell (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:301076)
at w.execute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:300703)
at w.start (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:296367)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async t.CellExecutionQueue.executeQueuedCells (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:311160)
at async t.CellExecutionQueue.start (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:310700)
</code>```

Is there anything I can do to at least have the model run? Or another model I could use instead of kmeans? I desperately need to do some clustering analysis of a biomedical dataset for research we are doing into ASD.

Body:
I know a similar question has been asked in the past, here - IPython Notebook Kernel getting dead while running Kmeans

But that was 7 years ago so please don't close me.

I'm trying to run scikitlean kmeans clustering on a 2019 MacBook Pro and it keeps killing the kernel. See spec below:

Does anybody know of any known issues out there or work arounds for this? I would have thought this shouldn't be a problem for such an beefy/expensive machine. I don't mind if it takes a while though this is just killing it altogether, even on the simple training dataset following this tutorial - https://github.com/ageron/handson-ml2/blob/master/09_unsupervised_learning.ipynb

This is the code I used and the error it is returning in VS Code.

Code:

from sklearn.cluster import KMeans

k = 5
kmeans = KMeans(n_clusters=k, random_state=42)
y_pred = kmeans.fit_predict(X)

Error:

Error: Kernel is dead
Error: Kernel is dead
at g._sendKernelShellControl (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1006195)
at g.sendShellMessage (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1005964)
at g.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:1008506)
at d.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:37:325680)
at w.requestExecute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:32:18027)
at w.executeCodeCell (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:301076)
at w.execute (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:300703)
at w.start (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:296367)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async t.CellExecutionQueue.executeQueuedCells (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:311160)
at async t.CellExecutionQueue.start (/Users/canderson/.vscode/extensions/ms-toolsai.jupyter-2021.8.2041215044/out/client/extension.js:52:310700)

Is there anything I can do to at least have the model run? Or another model I could use instead of kmeans? I desperately need to do some clustering analysis of a biomedical dataset for research we are doing into ASD.


问:
Is there a way to build a handlebars partial path with regex?
I am building a small checklist app with express.js and handlebars.js. The app has a checklist that, on completion and submission, will route the user to a page with a small animation. The animation is in a partial file, called by that page.

What I would like to do is generate a random number that I can then use to build a string with, for my partial call. The string will end with a partial file name that ends with that number, and should be able to have any text preceeding that number. That way, I can designate which partials I want to make available at a given time, simply by appending a number to the end of the .hbs filename in the app.

I'm able to use the randomly generated number effectively, but I am having trouble including a regex expression in the string. I thought by using the following I would be able to achieve what I am looking for:

checklist.js

```<code>    router.get('/bedtime-checklist-complete', (req, res, next) => {

    let number = Math.round(Math.random() * 2);
    res.locals.selection = 'animations/' + /.*/ + number;

    //end helper
    res.render('checklists/bedtime-checklist-complete', {
        pageTitle: "Checklist complete!",
        bodyClass: "checklist-complete"
    });
})
</code>```

res.local.selection is the variable that will be passed to bedtime-checklist-complete.hbs, and it will be the path I'm trying to use with handlebars {{}} syntax and lookup function to call in the partial:

bedtime-checklist-complete.hbs

```<code> <main>
        <h1>Great work!</h1>
        <div id="imgContainer">
            {{> (lookup . 'selection') }}
        </div>
    </main>
</code>```

However, what is happening is that the selections variable I'm building in the express router and then passing to the handlebars partial is being passed litterally, so '//.*/' is in the path. Is there a way I can make the regex work with the partial call?

Body:
I am building a small checklist app with express.js and handlebars.js. The app has a checklist that, on completion and submission, will route the user to a page with a small animation. The animation is in a partial file, called by that page.

What I would like to do is generate a random number that I can then use to build a string with, for my partial call. The string will end with a partial file name that ends with that number, and should be able to have any text preceeding that number. That way, I can designate which partials I want to make available at a given time, simply by appending a number to the end of the .hbs filename in the app.

I'm able to use the randomly generated number effectively, but I am having trouble including a regex expression in the string. I thought by using the following I would be able to achieve what I am looking for:

checklist.js

    router.get('/bedtime-checklist-complete', (req, res, next) => {

    let number = Math.round(Math.random() * 2);
    res.locals.selection = 'animations/' + /.*/ + number;

    //end helper
    res.render('checklists/bedtime-checklist-complete', {
        pageTitle: "Checklist complete!",
        bodyClass: "checklist-complete"
    });
})

res.local.selection is the variable that will be passed to bedtime-checklist-complete.hbs, and it will be the path I'm trying to use with handlebars {{}} syntax and lookup function to call in the partial:

bedtime-checklist-complete.hbs

Great work!

            {{> (lookup . 'selection') }}

However, what is happening is that the selections variable I'm building in the express router and then passing to the handlebars partial is being passed litterally, so '//.*/' is in the path. Is there a way I can make the regex work with the partial call?


问:
Is there any possiable to skip downstream operation at upstream within reactor or spring cloud gateway GatewayFilterChain?
I writen a filter named LogFilter like this:

```<code>public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=======start======");
        return chain.filter(exchange)
                .then(Mono.defer(() -> {
                    //log time used
                    log.info("========end=======");
                    return Mono.<Void>empty();
                })).doOnError(throwable -> {
                    //log the ex
                    log.error("ex");
                    log.info("========end=======");
                });
    }

    @Override
    public int getOrder() {
        return -1000;
    }
}
</code>```

what bother me is that : when I look back the log file , I found that some request(traceId) only have a line =======start====== but do not have a line ========end=======. And my colleague also tell some response routed by Spring Cloud Gateway only have empty content.

I do not familiar with Reactor or Webflux ， so can any other filter behind my LogFilter have the ability to skip execution of then and doOnError logic in LogFilter ?

I guess maybe ==end== logged to other request(traceId) , but i dno't find any traceId related to two ==end== line.

Body:
I writen a filter named LogFilter like this:

public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=======start======");
        return chain.filter(exchange)
                .then(Mono.defer(() -> {
                    //log time used
                    log.info("========end=======");
                    return Mono.<Void>empty();
                })).doOnError(throwable -> {
                    //log the ex
                    log.error("ex");
                    log.info("========end=======");
                });
    }

    @Override
    public int getOrder() {
        return -1000;
    }
}

what bother me is that : when I look back the log file , I found that some request(traceId) only have a line =======start====== but do not have a line ========end=======. And my colleague also tell some response routed by Spring Cloud Gateway only have empty content.

I do not familiar with Reactor or Webflux ， so can any other filter behind my LogFilter have the ability to skip execution of then and doOnError logic in LogFilter ?

I guess maybe ==end== logged to other request(traceId) , but i dno't find any traceId related to two ==end== line.


问:
Use Mockito to ignore lambda when comparing Kotlin data class?
I want to assert that two instances of a data class are the same like this:

        val expectedViewState = MyViewState(
            title = "Title",
            subtitle = "Subittle",
            onTap = any()
        )

        assertEquals(expectedViewState, actualViewState)
```

These assertions always fail because of onTap: (String) -> Unit. Is there a way to basically ignore this field without overriding equals on the data class itself?

Body:
I want to assert that two instances of a data class are the same like this:

        val expectedViewState = MyViewState(
            title = "Title",
            subtitle = "Subittle",
            onTap = any()
        )

        assertEquals(expectedViewState, actualViewState)

These assertions always fail because of onTap: (String) -> Unit. Is there a way to basically ignore this field without overriding equals on the data class itself?


问:
How to identify the string in a list through dynamic function added inside a grepl boolean search?
Would basically like to identify the folder that has the current month. Normally this would work

```<code>grepl("\\December",dir(Main_Directory)
</code>```

However I would like to do this instead

```<code>grepl("\\{format(Sys.Date(),format="%B")}",dir(Main_Directory)
</code>```

but it gives an error Error: unexpected input in "grepl...."

Body:
Would basically like to identify the folder that has the current month. Normally this would work

grepl("\\December",dir(Main_Directory)

However I would like to do this instead

grepl("\\{format(Sys.Date(),format="%B")}",dir(Main_Directory)

but it gives an error Error: unexpected input in "grepl...."


问:
"TypeError: Cannot read properties of undefined (reading 'name')" in Dicord.js v14
```<code>const {SlashCommandBuilder} = require("discord.js");
const json = require("../sql.json")

const objId = 9

const filteredObj = json.filter((obj) => obj.id === objId)[0]
const name = filteredObj.name
const age = filteredObj.age
const id = filteredObj.id

module.exports = {
    data: new SlashCommandBuilder()
    .setName("id")
    .setDescription("Make id check"),
  async execute (client, interaction){
    await interaction.reply({content: `name: ${json.name}\nage: ${json.age}\nid: ${json.id}`});
},
};
</code>```

I have a discord.js v14 code searching json file

But i am getting this error:

"TypeError: Cannot read properties of undefined (reading 'name')"

How can ı fix that?

Body:
const {SlashCommandBuilder} = require("discord.js");
const json = require("../sql.json")

const objId = 9

const filteredObj = json.filter((obj) => obj.id === objId)[0]
const name = filteredObj.name
const age = filteredObj.age
const id = filteredObj.id

module.exports = {
    data: new SlashCommandBuilder()
    .setName("id")
    .setDescription("Make id check"),
  async execute (client, interaction){
    await interaction.reply({content: `name: ${json.name}\nage: ${json.age}\nid: ${json.id}`});
},
};

I have a discord.js v14 code searching json file

But i am getting this error:

"TypeError: Cannot read properties of undefined (reading 'name')"

How can ı fix that?


问:
How to let subusers in sendgrid inheit the same webhooks as the main account
We create subusers for sendgrid from the api.

But we're finding ourselves having to each time assign the webhooks and verified webhooks and if later we change the webhook we will need a script to rechange it on all subusers.

Is there a way for subusers to inherit the main account event webhooks by default ?


问:
Identify broken tables in AWS Glue
I have a lot of files (JSON, PARQUET) in Data Lake that is created/updated on a daily basis. I configured Glue Crawlers that create tables on top of such files, but I noticed that some of these tables could not be queried (since schema has been changed, or files are broken, or files are placed in the wrong location, etc.). Is there any solution that I can use to identify such broken tables in AWS Glue to notify data users about such issues?</p>

Title: Identify broken tables in AWS Glue


问:
Find the value of a prolog singleton variable embedded in facts
(This is for Advent of Code, Day 21, Part 2)

I have a prolog program with a bunch of facts expressing a tree of math operations. One of those nodes is a variable. And because I've currently got each node in that tree as a separate fact, that means the node that's a variable is a singleton variable that is kind of a pain to reference. I need to figure out the value of that singleton variable.

Here's my current code, based on the sample from Advent of Code:

```<code>:- use_module(library(clpfd)).
:- debug.

monkey_says(dbpl, [5]).
monkey_says(cczh, [sllz, add, lgvd]).
monkey_says(zczc, [2]).
monkey_says(ptdq, [humn, sub, dvpt]).
monkey_says(dvpt, [3]).
monkey_says(lfqf, [4]).
monkey_says(ljgn, [2]).
monkey_says(sjmn, [drzm, mul, dbpl]).
monkey_says(sllz, [4]).
monkey_says(pppw, [cczh, div, lfqf]).
monkey_says(lgvd, [ljgn, mul, ptdq]).
monkey_says(drzm, [hmdt, sub, zczc]).
monkey_says(hmdt, [32]).
monkey_says(root, [pppw, equ, sjmn]).
monkey_says(humn, [_X]).

meval(M_id, Val) :-
    monkey_says(M_id, V_raw),
    (
        [Val] = V_raw;
        (
            [A, Op, B] = V_raw,
            meval(A, Va),
            meval(B, Vb),
            (
                Op = add, Val #= Va + Vb;
                Op = sub, Val #= Va - Vb;
                Op = mul, Val #= Va * Vb;
                Op = div, Val #= Va // Vb;
                Op = equ, ( Va #= Vb, Val #= Va)
            )
        )
    ).

main :-
    meval(root, M),
    write(M).
</code>```

I'm currently trying to solve this in Swish, so then I have Swish run this query (but I've tried many others):

```<code>meval(root, M), monkey_says(humn, [Y]).
</code>```

Is there a built-in that finds the value of that variable? Is my code fundamentally flawed? What am I supposed to be doing here?

Body:
(This is for Advent of Code, Day 21, Part 2)

I have a prolog program with a bunch of facts expressing a tree of math operations. One of those nodes is a variable. And because I've currently got each node in that tree as a separate fact, that means the node that's a variable is a singleton variable that is kind of a pain to reference. I need to figure out the value of that singleton variable.

Here's my current code, based on the sample from Advent of Code:

:- use_module(library(clpfd)).
:- debug.

monkey_says(dbpl, [5]).
monkey_says(cczh, [sllz, add, lgvd]).
monkey_says(zczc, [2]).
monkey_says(ptdq, [humn, sub, dvpt]).
monkey_says(dvpt, [3]).
monkey_says(lfqf, [4]).
monkey_says(ljgn, [2]).
monkey_says(sjmn, [drzm, mul, dbpl]).
monkey_says(sllz, [4]).
monkey_says(pppw, [cczh, div, lfqf]).
monkey_says(lgvd, [ljgn, mul, ptdq]).
monkey_says(drzm, [hmdt, sub, zczc]).
monkey_says(hmdt, [32]).
monkey_says(root, [pppw, equ, sjmn]).
monkey_says(humn, [_X]).

meval(M_id, Val) :-
    monkey_says(M_id, V_raw),
    (
        [Val] = V_raw;
        (
            [A, Op, B] = V_raw,
            meval(A, Va),
            meval(B, Vb),
            (
                Op = add, Val #= Va + Vb;
                Op = sub, Val #= Va - Vb;
                Op = mul, Val #= Va * Vb;
                Op = div, Val #= Va // Vb;
                Op = equ, ( Va #= Vb, Val #= Va)
            )
        )
    ).

main :-
    meval(root, M),
    write(M).

I'm currently trying to solve this in Swish, so then I have Swish run this query (but I've tried many others):

meval(root, M), monkey_says(humn, [Y]).

Is there a built-in that finds the value of that variable? Is my code fundamentally flawed? What am I supposed to be doing here?


问:
How does the default prerendering work in Nextjs?

By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO.

https://nextjs.org/learn/basics/data-fetching/pre-rendering

How does this kind of pre-rendering work actually?

What if I have some queries on my page, that require authentication to work?


问:
how can I pass the content of an array which is inside a struct to a function?
I have two functions, one saves the content of a file in a 2d array called "maze", this array is inside a struct. On the other hand, the second function is meant to print the content of that 2d array into the console.

My problem is that the second function is not printing the content of that 2d array that is inside the struct. I believe is because I am not passing the content of the array correctly but I am not sure.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* X and Y will be used to define the size of the maze*/
#define X 20
#define Y 40

typedef struct
{
    char maze[X][Y]; /* X and Y have been defined as X = 20 and Y = 40*/
    char robot;
    int x,y;

}Cords;
</code>```

This are my function prototypes:

```<code>void save_maze(Cords);
void print_maze(Cords);
</code>```

Function that saves the file content into the 2d array:

```<code>void save_maze(Cords border)
{
    int i,j,k,x,y;
    char wall;
    FILE *FileMaze;

    FileMaze = fopen("maze.txt","r");
    if (FileMaze == NULL)
    {
    printf("\n The file is missing");
    }
    else
    {
        printf("File was open! \n");
        while(fscanf(FileMaze,"%d %d %c",&x,&y,&wall)!= EOF)
        {
             border.maze[x][y] = wall;
        }
    }

    fclose(FileMaze);
    printf("The Maze has been saved! \n");

}
</code>```

Function That should print the 2d array:

```<code>void print_maze(Cords border)
{
    int i,j,k,x,y;
    int row,col;
    row=X;
    col=Y;
    for (i = 0; i <row ; i++)
    {
        for (j = 0; j < col; j++)
        {
            if(border.maze[i][j] != 'x' && border.maze[i][j] != 'o' && border.maze[i][j] != 'S' && border.maze[i][j] != 'E')
            {
                border.maze[i][j] = ' ';
            }
            else
            {
                printf("%2c",border.maze[i][j]);
            }
        }
        printf("\n\r");
    }
}
</code>```

The "print_maze" function does not print the content of the 2d array which is inside the struct.

Body:
I have two functions, one saves the content of a file in a 2d array called "maze", this array is inside a struct. On the other hand, the second function is meant to print the content of that 2d array into the console.

My problem is that the second function is not printing the content of that 2d array that is inside the struct. I believe is because I am not passing the content of the array correctly but I am not sure.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* X and Y will be used to define the size of the maze*/
#define X 20
#define Y 40

typedef struct
{
    char maze[X][Y]; /* X and Y have been defined as X = 20 and Y = 40*/
    char robot;
    int x,y;

}Cords;

This are my function prototypes:

void save_maze(Cords);
void print_maze(Cords);

Function that saves the file content into the 2d array:

void save_maze(Cords border)
{
    int i,j,k,x,y;
    char wall;
    FILE *FileMaze;

    FileMaze = fopen("maze.txt","r");
    if (FileMaze == NULL)
    {
    printf("\n The file is missing");
    }
    else
    {
        printf("File was open! \n");
        while(fscanf(FileMaze,"%d %d %c",&x,&y,&wall)!= EOF)
        {
             border.maze[x][y] = wall;
        }
    }

    fclose(FileMaze);
    printf("The Maze has been saved! \n");

}

Function That should print the 2d array:

void print_maze(Cords border)
{
    int i,j,k,x,y;
    int row,col;
    row=X;
    col=Y;
    for (i = 0; i <row ; i++)
    {
        for (j = 0; j < col; j++)
        {
            if(border.maze[i][j] != 'x' && border.maze[i][j] != 'o' && border.maze[i][j] != 'S' && border.maze[i][j] != 'E')
            {
                border.maze[i][j] = ' ';
            }
            else
            {
                printf("%2c",border.maze[i][j]);
            }
        }
        printf("\n\r");
    }
}

The "print_maze" function does not print the content of the 2d array which is inside the struct.


问:
Woocommerce change upload file interface
I found a code on the web which allows me to attach custom PDF invoices for every order. But the problem is that I don't want to use classic media uploader interface, I want to keep there only images and files related to website, and have very simple upload file button inside this code to upload invoices in seperated subfolder /woocommerce_upload/invoices which are protected with htaccess. I tried several ways to change that but without any luck :(</p>
```<code><?php

defined( 'ABSPATH' ) || exit;

class AttachFilesToWooCommerceOrderEmail {
private static $instance;

private $privateUploads;  // Whether to upload files to WooCommerce protected area.

// Returns an instance of this class.
public static function get_instance() {
    if ( null == self::$instance ) {
        self::$instance = new self;
    }
    return self::$instance;
}

// Initialize the plugin variables.
private function __construct() {
    $this->privateUploads = false;

    $this->init();
}

// Set up WordPress specfic actions.
private function init() {
    // Verify that CMB2 plugin is active.
    add_action( 'admin_notices', array( $this, 'verify_cmb2_active' ) );

    // Add the metabox to allow for adding files to attach to the "Completed order" email.
    add_action( 'cmb2_admin_init', array( $this, 'order_files_metabox' ) );

    add_filter( 'woocommerce_email_attachments', array( $this, 'conditionally_attach_order_files_to_order_email' ), 10, 4 );

    // For testing.
    //add_action( 'woocommerce_email_order_details', array( $this, 'testing_order_attachments_code' ), 10, 4 );

    if ( $this->privateUploads ) {
        add_filter( 'plupload_default_params', array( $this, 'add_page_type_to_upload_field' ) );
        add_filter( 'upload_dir', array( $this, 'change_upload_dir_for_shop_order_uploads' ), 20 );
    }

}

// Verify that CMB2 plugin is active.
function verify_cmb2_active() {
    if ( ! defined( 'CMB2_LOADED' ) ) {
        $plugin_data = get_plugin_data( __FILE__ );
        $plugin_name = $plugin_data['Name'];
?>
<div class="notice notice-warning is-dismissible"><p>Plugin <strong><?php echo
$plugin_name; ?></strong> requires <a href="https://wordpress.org/plugins/cmb2/">CMB2 plugin</a>.</p></div>
<?php
        //error_log( 'CMB2 is not active.' );
    }
}

// Add the metabox to allow for adding files to attach to the "Completed order" email.
function order_files_metabox() {
    // When private uploads is enabled previews may not be available so mention this in the metabox description text.
    $privateUploadsMessage = '';
    if ( $this->privateUploads ) {
        $privateUploadsMessage = '<br/><br/>Note: Private uploads is enabled so previews of attachments may not be available.';
    }

    $cmb = new_cmb2_box( array(
        'id'            => 'order_attachments',
        'title'         => 'Order Attachments',
        'object_types'  => array( 'shop_order', ), // Limit to Order post type
        'context'       => 'side',
        'priority'      => 'high',
        'show_names'    => true, // Show field names on the left
    ) );
    $cmb->add_field( array(
        'desc' => 'Upload the files that will be attached to the "Completed order" email.<br/><br/>The files must be uploaded <strong>before</strong> marking the order Complete.' . $privateUploadsMessage,
        'id'   => 'order_file_list',
        'type' => 'file_list',
        'preview_size' => array( 100, 100 ), // Default: array( 50, 50 )
        'query_args' => array( 'type' => array( 'image', 'application/pdf' ) ), // Set to only allow image attachments. This can be disabled or edited.
    ) );
}

function conditionally_attach_order_files_to_order_email( $attachments, $email_id,
$object, $email_obj ) {
    // Only attach files to Completed Order email, otherwise return early.
    if ( 'customer_completed_order' != $email_id ) {
        return $attachments;
    }

    $files = get_post_meta( $object->get_id(), 'order_file_list', true );
    foreach ( (array) $files as $attachment_id => $attachment_url ) {
        $attachments[] = get_attached_file( $attachment_id );
    }

    return $attachments;
}

// Add the post type as a field that will be available when the file is uploaded. This
// will be used to change the upload destination directory for uploads from 'shop_order' type.
function add_page_type_to_upload_field( $params ) {
    if ( ! is_admin() ) { return $params; }

    $screen = get_current_screen();
    if ( isset( $screen ) ){
        $params['post_type'] = $screen->post_type;
    }

    return $params;
}

// Put uploads from a 'shop_order' into the same directory as downloadable files. This
// directory is protected with a .htaccess file to prevent direct access.
function change_upload_dir_for_shop_order_uploads( $pathdata ) {
    //error_log( 'upload_dir $_POST: ' . var_export( $_POST, true ) );

    // This code is (almost) identical to that in upload_dir() in woocommerce/includes/admin/class-wc-admin-post-types.php.
    if( (isset( $_POST['post_type'] ) && 'shop_order' === $_POST['post_type'] )) {
        if ( empty( $pathdata['subdir'] ) ) {
            $pathdata['path']   = $pathdata['path'] . '/woocommerce_uploads/invoices';
            $pathdata['url']    = $pathdata['url'] . '/woocommerce_uploads/invoices';
            $pathdata['subdir'] = '/woocommerce_uploads';
            //error_log( 'Empty subdir: ' . var_export( $pathdata, true ) );
        } else {
            $new_subdir = '/woocommerce_uploads/invoices' . $pathdata['subdir'];
            $pathdata['path']   = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['path'] );
            $pathdata['url']    = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['url'] );
            $pathdata['subdir'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['subdir'] );
            //error_log( 'Non-empty subdir: ' . var_export( $pathdata, true ) );
        }
    }

    return $pathdata;
}

// Test the code - list the paths to the attachments.
function testing_order_attachments_code( $order, $sent_to_admin, $plain_text, $email ) {
    $files = get_post_meta( $order->get_id(), 'order_file_list', true );

    echo '```', var_export( $files, true ), '```';

    foreach ( (array) $files as $attachment_id => $attachment_url ) {
        echo '<p>', get_attached_file( $attachment_id ), '</p>';
    }
}
}

$AttachFilesToWooCommerceOrderEmail = AttachFilesToWooCommerceOrderEmail::get_instance();
</code>```

Body:
I found a code on the web which allows me to attach custom PDF invoices for every order. But the problem is that I don't want to use classic media uploader interface, I want to keep there only images and files related to website, and have very simple upload file button inside this code to upload invoices in seperated subfolder /woocommerce_upload/invoices which are protected with htaccess. I tried several ways to change that but without any luck :(

<?php

defined( 'ABSPATH' ) || exit;

class AttachFilesToWooCommerceOrderEmail {
private static $instance;

private $privateUploads;  // Whether to upload files to WooCommerce protected area.

// Returns an instance of this class.
public static function get_instance() {
    if ( null == self::$instance ) {
        self::$instance = new self;
    }
    return self::$instance;
}

// Initialize the plugin variables.
private function __construct() {
    $this->privateUploads = false;

    $this->init();
}

// Set up WordPress specfic actions.
private function init() {
    // Verify that CMB2 plugin is active.
    add_action( 'admin_notices', array( $this, 'verify_cmb2_active' ) );

    // Add the metabox to allow for adding files to attach to the "Completed order" email.
    add_action( 'cmb2_admin_init', array( $this, 'order_files_metabox' ) );

    add_filter( 'woocommerce_email_attachments', array( $this, 'conditionally_attach_order_files_to_order_email' ), 10, 4 );

    // For testing.
    //add_action( 'woocommerce_email_order_details', array( $this, 'testing_order_attachments_code' ), 10, 4 );

    if ( $this->privateUploads ) {
        add_filter( 'plupload_default_params', array( $this, 'add_page_type_to_upload_field' ) );
        add_filter( 'upload_dir', array( $this, 'change_upload_dir_for_shop_order_uploads' ), 20 );
    }

}

// Verify that CMB2 plugin is active.
function verify_cmb2_active() {
    if ( ! defined( 'CMB2_LOADED' ) ) {
        $plugin_data = get_plugin_data( __FILE__ );
        $plugin_name = $plugin_data['Name'];
?>

Plugin <?php echo
$plugin_name; ?> requires CMB2 plugin.

<?php
        //error_log( 'CMB2 is not active.' );
    }
}

// Add the metabox to allow for adding files to attach to the "Completed order" email.
function order_files_metabox() {
    // When private uploads is enabled previews may not be available so mention this in the metabox description text.
    $privateUploadsMessage = '';
    if ( $this->privateUploads ) {
        $privateUploadsMessage = '

Note: Private uploads is enabled so previews of attachments may not be available.';
    }

    $cmb = new_cmb2_box( array(
        'id'            => 'order_attachments',
        'title'         => 'Order Attachments',
        'object_types'  => array( 'shop_order', ), // Limit to Order post type
        'context'       => 'side',
        'priority'      => 'high',
        'show_names'    => true, // Show field names on the left
    ) );
    $cmb->add_field( array(
        'desc' => 'Upload the files that will be attached to the "Completed order" email.

The files must be uploaded before marking the order Complete.' . $privateUploadsMessage,
        'id'   => 'order_file_list',
        'type' => 'file_list',
        'preview_size' => array( 100, 100 ), // Default: array( 50, 50 )
        'query_args' => array( 'type' => array( 'image', 'application/pdf' ) ), // Set to only allow image attachments. This can be disabled or edited.
    ) );
}

function conditionally_attach_order_files_to_order_email( $attachments, $email_id,
$object, $email_obj ) {
    // Only attach files to Completed Order email, otherwise return early.
    if ( 'customer_completed_order' != $email_id ) {
        return $attachments;
    }

    $files = get_post_meta( $object->get_id(), 'order_file_list', true );
    foreach ( (array) $files as $attachment_id => $attachment_url ) {
        $attachments[] = get_attached_file( $attachment_id );
    }

    return $attachments;
}

// Add the post type as a field that will be available when the file is uploaded. This
// will be used to change the upload destination directory for uploads from 'shop_order' type.
function add_page_type_to_upload_field( $params ) {
    if ( ! is_admin() ) { return $params; }

    $screen = get_current_screen();
    if ( isset( $screen ) ){
        $params['post_type'] = $screen->post_type;
    }

    return $params;
}

// Put uploads from a 'shop_order' into the same directory as downloadable files. This
// directory is protected with a .htaccess file to prevent direct access.
function change_upload_dir_for_shop_order_uploads( $pathdata ) {
    //error_log( 'upload_dir $_POST: ' . var_export( $_POST, true ) );

    // This code is (almost) identical to that in upload_dir() in woocommerce/includes/admin/class-wc-admin-post-types.php.
    if( (isset( $_POST['post_type'] ) && 'shop_order' === $_POST['post_type'] )) {
        if ( empty( $pathdata['subdir'] ) ) {
            $pathdata['path']   = $pathdata['path'] . '/woocommerce_uploads/invoices';
            $pathdata['url']    = $pathdata['url'] . '/woocommerce_uploads/invoices';
            $pathdata['subdir'] = '/woocommerce_uploads';
            //error_log( 'Empty subdir: ' . var_export( $pathdata, true ) );
        } else {
            $new_subdir = '/woocommerce_uploads/invoices' . $pathdata['subdir'];
            $pathdata['path']   = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['path'] );
            $pathdata['url']    = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['url'] );
            $pathdata['subdir'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['subdir'] );
            //error_log( 'Non-empty subdir: ' . var_export( $pathdata, true ) );
        }
    }

    return $pathdata;
}

// Test the code - list the paths to the attachments.
function testing_order_attachments_code( $order, $sent_to_admin, $plain_text, $email ) {
    $files = get_post_meta( $order->get_id(), 'order_file_list', true );

    echo '
', var_export( $files, true ), '
';

    foreach ( (array) $files as $attachment_id => $attachment_url ) {
        echo '
', get_attached_file( $attachment_id ), '
';
    }
}
}

$AttachFilesToWooCommerceOrderEmail = AttachFilesToWooCommerceOrderEmail::get_instance();


问:
Firebase Realtime Database rules auth !== null not working with Firebase Authentication
I have a project in Firebase that I enable a Realtime Database and Authentication (with Sign-in with password method).

I was able to sign up, and sign in with Web Api Key just fine. But when I use the idToken returned from the Sign-in call, I cannot seems to read or write despite the fact that I used the rule ".read" : "auth !== null" and ".write" : "auth !== null".

Sign up (Guide Link) with the following call:

```<code>https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]
</code>```

Sign in (Guide Link) with the following call:

```<code>https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]
</code>```

which return a data in the following format:

```<code>  "kind": "identitytoolkit#VerifyPasswordResponse",
  "localId": "kdjRwh9BzSSmPK5GKkn8dSwXok33",
  "email": "<sign-up-email>",
  "displayName": "",
  "idToken": "<String-of-token-in-form:::eyJhbGciOiJSUzI1NiIsImtpZCI6InRCME0yQSJ9.eyJpc3MiOiJodHRwczovL2lk>",
  "registered": true
</code>```

Read data from Realtime Database with:

```<code>curl -X GET \
  'https://<DATABASE-NAME>/users.json?auth=<idToken-gotten-above>'
</code>```

and rules set to

```<code>{
  "rules": {
    "users": {
      ".read": "auth!==null"
    }
  }
}
</code>```

The API call returned

```<code>{
  "error" : "Permission denied"
}
</code>```

I was expecting the data correctly returned.

What went wrong?

Body:
I have a project in Firebase that I enable a Realtime Database and Authentication (with Sign-in with password method).

I was able to sign up, and sign in with Web Api Key just fine. But when I use the idToken returned from the Sign-in call, I cannot seems to read or write despite the fact that I used the rule ".read" : "auth !== null" and ".write" : "auth !== null".

Sign up (Guide Link) with the following call:

https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]

Sign in (Guide Link) with the following call:

https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]

which return a data in the following format:

  "kind": "identitytoolkit#VerifyPasswordResponse",
  "localId": "kdjRwh9BzSSmPK5GKkn8dSwXok33",
  "email": "<sign-up-email>",
  "displayName": "",
  "idToken": "<String-of-token-in-form:::eyJhbGciOiJSUzI1NiIsImtpZCI6InRCME0yQSJ9.eyJpc3MiOiJodHRwczovL2lk>",
  "registered": true

Read data from Realtime Database with:

curl -X GET \
  'https://<DATABASE-NAME>/users.json?auth=<idToken-gotten-above>'

and rules set to

{
  "rules": {
    "users": {
      ".read": "auth!==null"
    }
  }
}

The API call returned

{
  "error" : "Permission denied"
}

I was expecting the data correctly returned.

What went wrong?


问:
Is it possible to hide typescript types in Visual Studio Code?
Hi Stack Overflow friends,

In MS Visual Studio Code, is it possible to hide the Typescript types? I have to work with Typescript, which is OK-ish, but with all these custom type names I find it hard to read/scan through the code.

I just want to see

```<code>setSidebarItems(state, sidebarItems){
  state.sidebarItems = sidebarItems
}
</code>```

Thanks!

Body:
Hi Stack Overflow friends,

In MS Visual Studio Code, is it possible to hide the Typescript types? I have to work with Typescript, which is OK-ish, but with all these custom type names I find it hard to read/scan through the code.

I just want to see

setSidebarItems(state, sidebarItems){
  state.sidebarItems = sidebarItems
}

Thanks!


问:
Scrapy doesn't download files, but data is clean/complete and there are no errors
I run this and I get all the data cleanly from the yield article when I run it in the command line, but I don't actually download the files in the second function, download.  The files field in the csv is empty and the files aren't showing up in the local_folder directory.  I don't get any error messages, which is making it hard to troubleshoot. Can someone please point me in the right direction.  Thank you.

thespider.py

import re
import scrapy
import unidecode
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.loader import ItemLoader
from dhqscraper.items import FileDownloader

class DhqSpider(CrawlSpider):
    name = 'dhq'
    allowed_domains = ['digitalhumanities.org']
    start_urls = ['http://www.digitalhumanities.org/dhq/vol/16/3/index.html']

    rules = (
            Rule(LinkExtractor(allow = 'index.html')),
            Rule(LinkExtractor(allow = 'vol'), callback='parse_article'),
        )

    def parse_article(self, response):
        article = {
            'title' : response.css('h1.articleTitle').xpath('normalize-space(text())').get(default='').strip(),
            'author' : response.css('div.author a').xpath('normalize-space(text())').getall(),
            'year' : unidecode.unidecode(response.css('div#pubInfo::text')[0].get()),
            'volume' : unidecode.unidecode(response.css('div#pubInfo::text')[1].get()),
            'xmllink' : response.urljoin(response.xpath('(//div[@class="toolbar"]/a[contains(@href, ".xml")]/@href)[1]').get()),
        }
        article ['author'] = [unidecode.unidecode(i) for i in article['author']]
        yield article

        def download(self, response):
            file_url = article['xmllink']
            item = FileDownloader()
            item['file_urls'] = [file_url]
            yield item
```
<p>items.py</p>
<pre class="lang-py prettyprint-override"><code>import scrapy
from scrapy.loader import ItemLoader
from scrapy.linkextractors import LinkExtractor
from itemloaders.processors import TakeFirst, MapCompose
from w3lib.html import remove_tags

class FileDownloader(scrapy.Item):
    file_urls = scrapy.Field()
    files = scrapy.Field
</code>```

settings.py

ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
FILES_STORE = 'local_folder'
```

Body:
I run this and I get all the data cleanly from the yield article when I run it in the command line, but I don't actually download the files in the second function, download.  The files field in the csv is empty and the files aren't showing up in the local_folder directory.  I don't get any error messages, which is making it hard to troubleshoot. Can someone please point me in the right direction.  Thank you.

thespider.py

import re
import scrapy
import unidecode
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.loader import ItemLoader
from dhqscraper.items import FileDownloader

class DhqSpider(CrawlSpider):
    name = 'dhq'
    allowed_domains = ['digitalhumanities.org']
    start_urls = ['http://www.digitalhumanities.org/dhq/vol/16/3/index.html']

    rules = (
            Rule(LinkExtractor(allow = 'index.html')),
            Rule(LinkExtractor(allow = 'vol'), callback='parse_article'),
        )

    def parse_article(self, response):
        article = {
            'title' : response.css('h1.articleTitle').xpath('normalize-space(text())').get(default='').strip(),
            'author' : response.css('div.author a').xpath('normalize-space(text())').getall(),
            'year' : unidecode.unidecode(response.css('div#pubInfo::text')[0].get()),
            'volume' : unidecode.unidecode(response.css('div#pubInfo::text')[1].get()),
            'xmllink' : response.urljoin(response.xpath('(//div[@class="toolbar"]/a[contains(@href, ".xml")]/@href)[1]').get()),
        }
        article ['author'] = [unidecode.unidecode(i) for i in article['author']]
        yield article

        def download(self, response):
            file_url = article['xmllink']
            item = FileDownloader()
            item['file_urls'] = [file_url]
            yield item

items.py

import scrapy
from scrapy.loader import ItemLoader
from scrapy.linkextractors import LinkExtractor
from itemloaders.processors import TakeFirst, MapCompose
from w3lib.html import remove_tags

class FileDownloader(scrapy.Item):
    file_urls = scrapy.Field()
    files = scrapy.Field

settings.py

ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
FILES_STORE = 'local_folder'


问:
DBxtra Scheduler locking up when connecting to AWS Aurora database
We recently had to update our Aurora database running on AWS due to a required updated from AWS.

Since this update, our DBxtra scheduler reports have been locking up when connecting to the database  to grab the data. Not only does DBxtra scheduler not complete, but other PHP applications that connect to the same database are also locking up, until the DBxtra schedule that is running is cancelled.

At which point the database processes clear up and all goes back to normal.

We have identified that if we run 3 queries from a larger listed schedule this works. But when we move to 3 or more queries in the schedule this is when the connection fails and everything locks up.

What we don't understand is that before the database 'upgrade' our scheduled of reports has been working fine for years, with schedules of varying sizes from 3-25 sets of queries / reports running.

Myself and our IT contact have liaised with AWS directly to get not helpful answers and the documentation about the updated DB doesn't bring any light to the issue either.

So why would the latest Aurora database upgrade affect this? Any ideas?

So far we have built a 'copy' of some typical DBxtra schedule to connect to a test DB instance and replicated the issue occurring on our main database.

We have also ensured that the individual queries all work on their own.

But when we have hundreds of queries running for hundreds of different reports. It's just not practical or sensible to split ALL of our larger groups of queries in to batches of 3 (as we know 4 is the magic number that locks the db connection), when the batches of up to 25 were working totally fine before the Aurora upgrade that was forced on us.


问:
Neo4j.Driver code fails in .net 6 console application but works in forms
I am trying to call this GetNotificationsCount()  function from both .Net 6 Forms application and a console application.

```<code>public async Task<long> GetNotificationsCount()
{
    var query = @"Match (p:Notification) RETURN count(p) as notificationCount";
    var count = await _dataAccess.ExecuteReadScalarAsync<long>(query);
    return count;
}
</code>```

this is basically calling a function below:

```<code>public async Task<T> ExecuteReadScalarAsync<T>(string query, IDictionary<string, object>? parameters = null)
{
    try
    {
        parameters = parameters == null ? new Dictionary<string, object>() : parameters;
        using (var session = _driver.AsyncSession(o => o.WithDatabase(_database)))
        {
           var result = await session.ExecuteReadAsync(async tx => // <-- ***Fails Here***
            {
                T scalar = default(T);
                var res = await tx.RunAsync(query, parameters);
                scalar = (await res.SingleAsync())[0].As<T>();
                return scalar;
            });
            return result;
        }
    }
    catch (Exception ex)
    {
        // **** Did not reach here either *****
        _logger.LogError(ex, "There was a problem while executing database query");
        throw;
    }
}
</code>```

Strange Issue I am having is that this exact same code works when I call it behind a button_click() event on a form, however when I call from the console main() function application crashes without any indication or exception.

I am using Neo4j.Driver version 5.3.0 if it makes any difference

does anyone have a clue why this may be happening?

Body:
I am trying to call this GetNotificationsCount()  function from both .Net 6 Forms application and a console application.

public async Task<long> GetNotificationsCount()
{
    var query = @"Match (p:Notification) RETURN count(p) as notificationCount";
    var count = await _dataAccess.ExecuteReadScalarAsync<long>(query);
    return count;
}

this is basically calling a function below:

public async Task<T> ExecuteReadScalarAsync<T>(string query, IDictionary<string, object>? parameters = null)
{
    try
    {
        parameters = parameters == null ? new Dictionary<string, object>() : parameters;
        using (var session = _driver.AsyncSession(o => o.WithDatabase(_database)))
        {
           var result = await session.ExecuteReadAsync(async tx => // <-- ***Fails Here***
            {
                T scalar = default(T);
                var res = await tx.RunAsync(query, parameters);
                scalar = (await res.SingleAsync())[0].As<T>();
                return scalar;
            });
            return result;
        }
    }
    catch (Exception ex)
    {
        // **** Did not reach here either *****
        _logger.LogError(ex, "There was a problem while executing database query");
        throw;
    }
}

Strange Issue I am having is that this exact same code works when I call it behind a button_click() event on a form, however when I call from the console main() function application crashes without any indication or exception.

I am using Neo4j.Driver version 5.3.0 if it makes any difference

does anyone have a clue why this may be happening?


问:
pytorch predict "cannot unpack non-iterable float object"
i want to predict image but it gives following error
cannot unpack non-iterable float object
`

```<code>import PIL
from PIL import Image
import io
import cv2
mean=np.array([0.485,0.456,0.406])
std=np.array([0.229,0.224,0.225])

def transform_image(image_bytes):
    my_transforms = transforms.Compose([transforms.Resize(255),
                                        transforms.CenterCrop(224),
                                        transforms.ToTensor(),
                                        transforms.Normalize(
                                            [0.485, 0.456, 0.406],
                                            [0.229, 0.224, 0.225])])
    image = Image.open(io.BytesIO(image_bytes))
    return my_transforms(image).unsqueeze(0)

PATH="/content/drive/MyDrive/fyp/kha/mpg_resnet18.pt"

model = torch.load(PATH)
model.eval()

def get_prediction(image_bytes,model = torch.load(PATH)):
    tensor = transform_image(image_bytes=image_bytes)
    tensor=tensor
    output = model.forward(tensor)

    probs = torch.nn.functional.softmax(output, dim=1)
    conf, classes = torch.max(probs, 1)
    return conf.item()
image_path="/content/drive/MyDrive/fyp/Original Image/FreshApple/FreshApple (10).jpg"

image = plt.imread(image_path)
print(image.shape)
plt.imshow(image)

with open(image_path, 'rb') as f:
    image_bytes = f.read()

    conf,y_pre=get_prediction(image_bytes=image_bytes)
    print(y_pre, ' at confidence score:{0:.2f}'.format(conf))
</code>```

 your text`
i want to predict a image using resnet 18 but it gives a error

Body:
i want to predict image but it gives following error
cannot unpack non-iterable float object
`

import PIL
from PIL import Image
import io
import cv2
mean=np.array([0.485,0.456,0.406])
std=np.array([0.229,0.224,0.225])

def transform_image(image_bytes):
    my_transforms = transforms.Compose([transforms.Resize(255),
                                        transforms.CenterCrop(224),
                                        transforms.ToTensor(),
                                        transforms.Normalize(
                                            [0.485, 0.456, 0.406],
                                            [0.229, 0.224, 0.225])])
    image = Image.open(io.BytesIO(image_bytes))
    return my_transforms(image).unsqueeze(0)

PATH="/content/drive/MyDrive/fyp/kha/mpg_resnet18.pt"

model = torch.load(PATH)
model.eval()

def get_prediction(image_bytes,model = torch.load(PATH)):
    tensor = transform_image(image_bytes=image_bytes)
    tensor=tensor
    output = model.forward(tensor)

    probs = torch.nn.functional.softmax(output, dim=1)
    conf, classes = torch.max(probs, 1)
    return conf.item()
image_path="/content/drive/MyDrive/fyp/Original Image/FreshApple/FreshApple (10).jpg"

image = plt.imread(image_path)
print(image.shape)
plt.imshow(image)

with open(image_path, 'rb') as f:
    image_bytes = f.read()

    conf,y_pre=get_prediction(image_bytes=image_bytes)
    print(y_pre, ' at confidence score:{0:.2f}'.format(conf))

 your text`
i want to predict a image using resnet 18 but it gives a error


问:
I was watching a tutorial from "GnomeCode" when i ran into this error
Whenever I would run the script I would normally get this error "ServerScriptService.Server.Room:12: attempt to index nil with 'Direction'" (https://i.stack.imgur.com/Upa4k.png) I don't know how to fix this as ive been playing around with it for hours and to still no avail. Here is the original video: https://www.youtube.com/watch?v=QLoF9Er8Oo8&t and here are my scripts:

Room

```<code>local room = {}
room.info = require(script.RoomInfo)
room.LastTurnDirection = nil
room.random = Random.new()

function room.GetRandom(prevRoom)
    local possibleRooms = workspace.Rooms:GetChildren()
    local randomRoom = possibleRooms[room.random:NextInteger(1, #possibleRooms)]

    local direction = room.info[randomRoom.Name]["Direction"]
    local hasstairs = room.info[randomRoom.Name]["Stairs"]
    local prevhadStairs = room.info[prevRoom.Name]["Stairs"]

    if (prevRoom.Name == randomRoom.Name)
        or (direction and direction == room.LastTurnDirection)
        or (hasstairs and prevhadStairs)
    then
        return room.GetRandom(prevRoom)
    else
        if direction then
            room.LastTurnDirection = direction
        end

        return randomRoom
    end

end

function room.Generate(prevRoom)
    local randomRoom = room.GetRandom(prevRoom)
    local newRoom = randomRoom:Clone()

    newRoom.PrimaryPart = newRoom.Entrance
    newRoom:PivotTo(prevRoom.Exit.CFrame)
    newRoom.Entrance.Transparency = 1
    newRoom.Exit.Transparency = 1

    newRoom.Parent = workspace.GeneratedRooms

    return newRoom
end

return room

</code>```

and

RoomInfo

```<code>local roomInfo = {
    ["StartRoom"] = {
        ["Stairs"] = false
    },
    ["Downstairs"] = {
        ["Stairs"] = true
    },
    ["Upstairs"] = {
        ["Stairs"] = true
    },
    ["LeftTurn"] = {
        ["Direction"] = "Left"
    },
    ["RightTurn"] = {
        ["Direction"] = "Right"
    },
    ["LongRoom"] = {

    },
    ["ShortRoom"] = {

    },
}

return roomInfo

</code>```

I tried changing the parts of the script like removing or adding parts to see if it would fix them, but nothing would work.

Body:
Whenever I would run the script I would normally get this error "ServerScriptService.Server.Room:12: attempt to index nil with 'Direction'" (https://i.stack.imgur.com/Upa4k.png) I don't know how to fix this as ive been playing around with it for hours and to still no avail. Here is the original video: https://www.youtube.com/watch?v=QLoF9Er8Oo8&t and here are my scripts:

Room

local room = {}
room.info = require(script.RoomInfo)
room.LastTurnDirection = nil
room.random = Random.new()

function room.GetRandom(prevRoom)
    local possibleRooms = workspace.Rooms:GetChildren()
    local randomRoom = possibleRooms[room.random:NextInteger(1, #possibleRooms)]

    local direction = room.info[randomRoom.Name]["Direction"]
    local hasstairs = room.info[randomRoom.Name]["Stairs"]
    local prevhadStairs = room.info[prevRoom.Name]["Stairs"]

    if (prevRoom.Name == randomRoom.Name)
        or (direction and direction == room.LastTurnDirection)
        or (hasstairs and prevhadStairs)
    then
        return room.GetRandom(prevRoom)
    else
        if direction then
            room.LastTurnDirection = direction
        end

        return randomRoom
    end

end

function room.Generate(prevRoom)
    local randomRoom = room.GetRandom(prevRoom)
    local newRoom = randomRoom:Clone()

    newRoom.PrimaryPart = newRoom.Entrance
    newRoom:PivotTo(prevRoom.Exit.CFrame)
    newRoom.Entrance.Transparency = 1
    newRoom.Exit.Transparency = 1

    newRoom.Parent = workspace.GeneratedRooms

    return newRoom
end

return room

and

RoomInfo

local roomInfo = {
    ["StartRoom"] = {
        ["Stairs"] = false
    },
    ["Downstairs"] = {
        ["Stairs"] = true
    },
    ["Upstairs"] = {
        ["Stairs"] = true
    },
    ["LeftTurn"] = {
        ["Direction"] = "Left"
    },
    ["RightTurn"] = {
        ["Direction"] = "Right"
    },
    ["LongRoom"] = {

    },
    ["ShortRoom"] = {

    },
}

return roomInfo

I tried changing the parts of the script like removing or adding parts to see if it would fix them, but nothing would work.


问:
How to resolve a Connection timed out issue in psycopg2?
I am bootstrapping an AWS Glue job via Jupyter Notebooks, I am very inexperienced, and I am wondering what the cause of the following error is:

```<code>OperationalError:
(psycopg2.OperationalError) connection to server at "fg-a-fs-fr-rds-cluster.cluster-cun8zwbrope0.us-east-1.rds.amazonaws.com" (10.10.129.65),
port 5432 failed: Connection timed out
</code>```

The script I used is as follows:

```<code>engine = db.create_engine('postgresql+psycopg2://$$DatabaseName$$')
connection = engine.connect()
</code>```

I understand that there is trouble connecting to the database, I just have no idea how to deal with this.

Body:
I am bootstrapping an AWS Glue job via Jupyter Notebooks, I am very inexperienced, and I am wondering what the cause of the following error is:

OperationalError:
(psycopg2.OperationalError) connection to server at "fg-a-fs-fr-rds-cluster.cluster-cun8zwbrope0.us-east-1.rds.amazonaws.com" (10.10.129.65),
port 5432 failed: Connection timed out

The script I used is as follows:

engine = db.create_engine('postgresql+psycopg2://$$DatabaseName$$')
connection = engine.connect()

I understand that there is trouble connecting to the database, I just have no idea how to deal with this.


问:
Why is VSCode HTML Does Not Load Page Into Chrome
I'm trying to use HTML in VSCode. This is my settings.json code:

```<code>{
    "code-runner.executorMap": {
        "html": " cd $dir && start chrome $fileName"
        "javascript": "node",
        "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
        "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "php": "php",
        "python": "python -u",
        "perl": "perl",
        "perl6": "perl6",
        "ruby": "ruby",
        "go": "go run",
        "lua": "lua",
        "groovy": "groovy",
        "powershell": "powershell -ExecutionPolicy ByPass -File",
        "bat": "cmd /c",
        "shellscript": "bash",
        "scheme": "csi -script",
        "ahk": "autohotkey",
        "autoit": "autoit3",
        "dart": "dart",
        "pascal": "cd $dir && fpc $fileName && $dir$fileNameWithoutExt",
        "d": "cd $dir && dmd $fileName && $dir$fileNameWithoutExt",
        "haskell": "runhaskell",
        "nim": "nim compile --verbosity:0 --hints:off --run",
        "lisp": "sbcl --script",
        "kit": "kitc --run",
        "v": "v run",
        "sass": "sass --style expanded",
        "scss": "scss --style expanded",
        "less": "cd $dir && lessc $fileName $fileNameWithoutExt.css",
        "FortranFreeForm": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran-modern": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran_fixed-form": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "sml": "cd $dir && sml $fileName"
    }
}
</code>```

This is my HTML code

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Yo</h1>
</body>
</html>
</code>```

I have the file saved as "woof.html".

This is what chrome shows.

Could someone please explain why this is not working? I followed this video: https://www.youtube.com/watch?v=ssF-OdOnf58

Body:
I'm trying to use HTML in VSCode. This is my settings.json code:

{
    "code-runner.executorMap": {
        "html": " cd $dir && start chrome $fileName"
        "javascript": "node",
        "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
        "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "php": "php",
        "python": "python -u",
        "perl": "perl",
        "perl6": "perl6",
        "ruby": "ruby",
        "go": "go run",
        "lua": "lua",
        "groovy": "groovy",
        "powershell": "powershell -ExecutionPolicy ByPass -File",
        "bat": "cmd /c",
        "shellscript": "bash",
        "scheme": "csi -script",
        "ahk": "autohotkey",
        "autoit": "autoit3",
        "dart": "dart",
        "pascal": "cd $dir && fpc $fileName && $dir$fileNameWithoutExt",
        "d": "cd $dir && dmd $fileName && $dir$fileNameWithoutExt",
        "haskell": "runhaskell",
        "nim": "nim compile --verbosity:0 --hints:off --run",
        "lisp": "sbcl --script",
        "kit": "kitc --run",
        "v": "v run",
        "sass": "sass --style expanded",
        "scss": "scss --style expanded",
        "less": "cd $dir && lessc $fileName $fileNameWithoutExt.css",
        "FortranFreeForm": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran-modern": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran_fixed-form": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "fortran": "cd $dir && gfortran $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "sml": "cd $dir && sml $fileName"
    }
}

This is my HTML code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Yo

I have the file saved as "woof.html".

This is what chrome shows.

Could someone please explain why this is not working? I followed this video: https://www.youtube.com/watch?v=ssF-OdOnf58


问:
How do I write a JUnit 5 test to cover the line that bootstraps a Spring Boot Application?
I have the following for my class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AdminConsoleApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminConsoleApplication.class, args);
    }
}
```
<p>But when I try to create a JUnit like:</p>
<pre class="lang-java prettyprint-override"><code>import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.verify;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.mock.mockito.MockBean;

public class AdminConsoleApplicationTests {
    @MockBean
    private SpringApplication springApplication;

    @Test
    public void main_startsSpringApplication() {
        String[] args = {"arg1", "arg2"};
        AdminConsoleApplication.main(args);
        // Verify that the SpringApplication.run method was called with the correct arguments
        verify(springApplication.run());
    }
}
</code>```

I get

java.lang.NullPointerException: Cannot invoke
"org.springframework.boot.SpringApplication.run(String[])" because
"this.springApplication" is null

What is the proper way to handle this?

I also tried

```<code>verify(springApplication).run(AdminConsoleApplication.class, args);
</code>```

But I got

java.lang.NullPointerException: Cannot invoke
"org.springframework.boot.SpringApplication.run(String[])" because
"this.springApplication" is null

Body:
I have the following for my class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AdminConsoleApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminConsoleApplication.class, args);
    }
}

But when I try to create a JUnit like:

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.verify;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.mock.mockito.MockBean;

public class AdminConsoleApplicationTests {
    @MockBean
    private SpringApplication springApplication;

    @Test
    public void main_startsSpringApplication() {
        String[] args = {"arg1", "arg2"};
        AdminConsoleApplication.main(args);
        // Verify that the SpringApplication.run method was called with the correct arguments
        verify(springApplication.run());
    }
}

I get

java.lang.NullPointerException: Cannot invoke
"org.springframework.boot.SpringApplication.run(String[])" because
"this.springApplication" is null

What is the proper way to handle this?

I also tried

verify(springApplication).run(AdminConsoleApplication.class, args);

But I got

java.lang.NullPointerException: Cannot invoke
"org.springframework.boot.SpringApplication.run(String[])" because
"this.springApplication" is null


问:
Proxy server .. confusing domain name and certificat
I've got an apache server ( A) running. It will be considered as a proxy for another local website (B )
in other words: Any request from the internet will arrive at A ( Like www.foo.com )
but this request should be sent "locally" to another web server which is on the LAN
like  "test.intranet.net" ( = server B)

I suppose that the certificate "foo.com" should be installed on A ( And also on B ??)

this "test.intranet.net"  is the server which will receive a WordPress website ( ServerB)

Today on " A ", I have  :

```<code>ServerName www.foo.com

<VirtualHost *:443>
SSLProxyEngine On
SSLProxyCheckPeerCN Off
SSLProxyCheckPeerName Off
SSLProxyVerify none
ProxyRequests off
ProxyPreserveHost On
RequestHeader set X-Forwarded-Port "443"
RequestHeader set X-Forwarded-Proto "https"
**ProxyPass / https://test.intranet.office.net/
ProxyPassReverse / https//test.intranet.office.net/**

SSLCertificateFile /path/for/foo.com_certificate
SSLCertificateKeyFile /path/for/foo.com_certificate
SSLCACertificateFile /path/for/foo.com_certificate
SSLEngine on
</VirtualHost>

but doing this, I am requesting to send the frame foo.com, to https://test.intranet.office.net
( where** test.intranet.office.net** is on ServerB )

1) I have no valid certificate for the website
2) How could it be transparent for the WAN ? using www.foo.com? to go to Server B?
3) using Virtualhost, Server A got all the certificates. Did the server get no certificates at all? - is that correct?

Thanks for your help

</code>```

At the moment... doesn't work out

Body:
I've got an apache server ( A) running. It will be considered as a proxy for another local website (B )
in other words: Any request from the internet will arrive at A ( Like www.foo.com )
but this request should be sent "locally" to another web server which is on the LAN
like  "test.intranet.net" ( = server B)

I suppose that the certificate "foo.com" should be installed on A ( And also on B ??)

this "test.intranet.net"  is the server which will receive a WordPress website ( ServerB)

Today on " A ", I have  :

ServerName www.foo.com

<VirtualHost *:443>
SSLProxyEngine On
SSLProxyCheckPeerCN Off
SSLProxyCheckPeerName Off
SSLProxyVerify none
ProxyRequests off
ProxyPreserveHost On
RequestHeader set X-Forwarded-Port "443"
RequestHeader set X-Forwarded-Proto "https"
**ProxyPass / https://test.intranet.office.net/
ProxyPassReverse / https//test.intranet.office.net/**

SSLCertificateFile /path/for/foo.com_certificate
SSLCertificateKeyFile /path/for/foo.com_certificate
SSLCACertificateFile /path/for/foo.com_certificate
SSLEngine on
</VirtualHost>

but doing this, I am requesting to send the frame foo.com, to https://test.intranet.office.net
( where** test.intranet.office.net** is on ServerB )

1) I have no valid certificate for the website
2) How could it be transparent for the WAN ? using www.foo.com? to go to Server B?
3) using Virtualhost, Server A got all the certificates. Did the server get no certificates at all? - is that correct?

Thanks for your help

At the moment... doesn't work out


问:
useMemo hook resets initial data
I am trying to use the react hook useMemo()

My filter function works good, but I'd like to reset my table "userData" if my search field is empty.

```<code>    if(data !== undefined && "collab" in data){
      let filteredData = userData.filter(e => data.collab === e.name + " " + e.firstname)
      userData = filteredData
      filteredData = null

    } else if (data !== undefined && "job" in data){
      let filteredData = userData.filter(e => data.job === e.job)
      userData = filteredData
      filteredData = null
    } else if (data !== undefined && 'technos' in data){
      console.log(data)
      return userData.filter(e => e.technos.some(t => t.name === data.technos))
    }
</code>```

When I reset data, my userData table is displayed without anything whereas I would like to come back to the initial information of userData

Title: useMemo hook resets initial data

Body:
I am trying to use the react hook useMemo()

My filter function works good, but I'd like to reset my table "userData" if my search field is empty.

    if(data !== undefined && "collab" in data){
      let filteredData = userData.filter(e => data.collab === e.name + " " + e.firstname)
      userData = filteredData
      filteredData = null

    } else if (data !== undefined && "job" in data){
      let filteredData = userData.filter(e => data.job === e.job)
      userData = filteredData
      filteredData = null
    } else if (data !== undefined && 'technos' in data){
      console.log(data)
      return userData.filter(e => e.technos.some(t => t.name === data.technos))
    }

When I reset data, my userData table is displayed without anything whereas I would like to come back to the initial information of userData


问:
Using built in Multiprocessing module python in a cluster
I need to compute a massive data in one of the endpoint in my fastapi backend application. I tried using multiprocess locally and it was fast. I have a k8s cluster in AWS Server, Do you think its advisable to use pythons inbuilt multiprocessing module in a cluster. Will it be an issue when we want to scale up.

I found about fiber multiprocessing by Uber. But looks like they stopped updating it and not sure if it still works.

I implemented multiprocess in the AWS k8s cluster and it didnt have any issues. Just wanted to know how it will react when it scales up in the longer run.


问:
Link two Material UI Autocomplete
I have to entry options one is English and the other one is Arabic, I implemented the english autocomplete I fetched the data from API and showed the option, what I'm trying to do is link the two Autocomplete, when I choose the option in the english one (shops.shopName) I need it automatically to show the Arabic one (shops.shopNameArabic) in the other Autocomplete, I don't know if that is even possible, but I needed to ask.

This is how the data looks:

My Configuration:

```<code>export default function SelectOptions({onBlur}) {

    const [shops, setShops] = useState([]);

    useEffect(() => {
        const getShops = async () => {
          const res = await axios.get("/shops");
        setShops(res.data);
          console.log(res.data);
        };
        getShops()
      }, []);

    return (
        <div>
            <Autocomplete
                disablePortal
                id="shops"
                getOptionLabel={(shops) => `${shops.shopName}`}
                options={shops}
                sx={{ width: 300 }}
                isOptionEqualToValue={(option, value) => option.shopName === value.shopName}
                noOptionsText={"No Available Options"}
                renderOption={(props, shops) => (
                    <li {...props} key={shops.id}>
                        {shops.shopName}
                    </li>
                )}
                renderInput={(params) => <TextField {...params} label="Shop" />}
                onBlur={onBlur}
            />
        </div>
    );
}
</code>```

Title: Link two Material UI Autocomplete

Body:
I have to entry options one is English and the other one is Arabic, I implemented the english autocomplete I fetched the data from API and showed the option, what I'm trying to do is link the two Autocomplete, when I choose the option in the english one (shops.shopName) I need it automatically to show the Arabic one (shops.shopNameArabic) in the other Autocomplete, I don't know if that is even possible, but I needed to ask.

This is how the data looks:

My Configuration:

export default function SelectOptions({onBlur}) {

    const [shops, setShops] = useState([]);

    useEffect(() => {
        const getShops = async () => {
          const res = await axios.get("/shops");
        setShops(res.data);
          console.log(res.data);
        };
        getShops()
      }, []);

    return (

            <Autocomplete
                disablePortal
                id="shops"
                getOptionLabel={(shops) => `${shops.shopName}`}
                options={shops}
                sx={{ width: 300 }}
                isOptionEqualToValue={(option, value) => option.shopName === value.shopName}
                noOptionsText={"No Available Options"}
                renderOption={(props, shops) => (

                        {shops.shopName}

                )}
                renderInput={(params) => <TextField {...params} label="Shop" />}
                onBlur={onBlur}
            />

    );
}