问:
ASP.NET Core website select elements option values don't save a "No" value
In my ASP.NET Core 5 application I have several pages of questions where a user will select Yes/No from a select element.
The select elements are using asp tag helpers and are bound to a view model. The select elements are also using asp-items tag to load the options.

The problem occurs when a user selects a value in the select element and then posts back to the controller method. If the user selects "Yes" the value of "Yes" is saved to the database table in the corresponding column.
If the user selects "No" then the value does not save to the database column, and when the view reloads the get method, the "No" value in the select element that should be there is blank.
The strange part, is that if I change the SelectListItem from "No" to "Not" just for the purposes of testing, the "Not" value saves and displays fine.

There are several views in my site that have the same behavior.

Here is my code in a simplified version for space:

View Model

```<code>public class PersonViewModel
{
    public string PersonId { get; set; }
    public string IsEmployed { get; set; }
    public List<SelectListItem> YesNoList { get; set; }
             = new List<SelectListItem>
                {
                    new SelectListItem("", "NA"),
                    new SelectListItem("Yes", "Yes"),
                    new SelectListItem("No", "No")
                };
}
</code>```

Simplified View

```<code>@model WFCDocuments.ViewModels.PersonViewModel
@{
    ViewData["Title"] = "Loan Processing Application";
    Layout = "/Views/Shared/_Layout.cshtml";
}

<div class="row">
    <div class="col-md-12">
        <div class="card border-1 rounded" style="margin: 20px 0px 20px 0px;">
            <div class="card-header">Borrower Information</div>
            <div class="card-body">

                <form id="personForm" asp-action="Borrower" asp-controller="Application" method="post">
                    <input type="hidden" asp-for="PersonId" />

                    <div class="form-group">
                        <label class="form-label">Are You Employed?<span style="color:red; font-weight:bold"> *</span></label>
                        <select asp-for="IsEmployed" asp-items="Model.YesNoList" class="form-select form-control-square">
                        </select>
                    </div>

                    <div class="form-group" style="margin-top:10px;">
                        <input type="submit" class="btn btn-outline-secondary btn-square" value="Save" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</code>```

There is not Javascript that interacts with this form

Controller Get

```<code>[HttpGet]
public async Task<IActionResult> Borrower()
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson borrowerPerson = personService.GetPerson(user.PersonId, _unitOfWork);
    var person = _mapper.Map<PersonViewModel>(borrowerPerson);
    return View(person);
}
</code>```

Controller Post

```<code>[HttpPost]
public async Task<IActionResult> Borrower(PersonViewModel model)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson person = personService.GetPerson(user.PersonId, _unitOfWork);
    person.IsEmployed = model.IsEmployed;
    var b = await _unitOfWork.BorrowerPeople.UpdateAsync(person);
    if (b == false)
    {
        return RedirectToAction("Borrower", "Application").WithWarning("", "Update Borrower Failed");
    }
    return RedirectToAction("Borrower", "Application").WithSuccess("", "Updated Borrower");
}
</code>```

Unit of Work Interface
My IUnitOfWork interface wraps up all the repository interface which in turn handle the EF transactions of the database context.

```<code>namespace WFCDocuments.Domain.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        IAddressRepository Addresses { get; }
        IApplicationAuditRepository ApplicationAudits { get; }
        IApplicationRepository Applications { get; }
        IBankruptcyRepository Bankruptcies { get; }
        ILoanFileRepository LoanFiles { get; }
        IBorrowerPersonRepository BorrowerPeople { get; }
        IDocumentAuditRepository DocumentAudits { get; }
        IDocumentRepository Documents { get; }
        IExpenseTypeRepository ExpenseTypes { get; }
        IFinancialAnalysisExpenseRepository FinancialAnalysisExpenses { get; }
        IFinancialAnalysisRepository FinancialAnalysis { get; }
        IHardshipRepository Hardships { get; }
        IHardshipTypeRepository HardshipTypes { get; }
        IPropertyRepository Properties { get; }
        INonEscrowedLoanRepository NonEscrowedLoans { get; }
        IRequiredIncomeDocumentationRepository RequiredIncomeDocumentations { get; }
        ILenderRepository Lenders { get; }
        IInvitedRepository Invited { get; }
        IStatusRepository Statuses { get; }
        IMenuRepository Menus { get; }
        IMessageRepository Messages { get; }
        IApplicationStatusRepository ApplicationStatuses { get; set; }
        ISignatureRepository Signatures { get; set; }
        IUserRepository Users { get; set; }
        INotificationRepository Notifications { get; set; }
        INotificationEventRepository NotificationEvents { get; set; }
        IIncomeDocumentRepository IncomeDocuments { get; set; }
        IEventLogRepository EventLogs { get; set; }
        ILoanFileNoteRepository LoanFileNotes { get; set; }
        int Complete();
    }
}
</code>```

Edit: 2/9/2022 2:41pm
If I change the select element to a plain input element and manually type in "No", the value is persisted and is displayed through post and get actions.
Something is up with the select elements

Body:
In my ASP.NET Core 5 application I have several pages of questions where a user will select Yes/No from a select element.
The select elements are using asp tag helpers and are bound to a view model. The select elements are also using asp-items tag to load the options.

The problem occurs when a user selects a value in the select element and then posts back to the controller method. If the user selects "Yes" the value of "Yes" is saved to the database table in the corresponding column.
If the user selects "No" then the value does not save to the database column, and when the view reloads the get method, the "No" value in the select element that should be there is blank.
The strange part, is that if I change the SelectListItem from "No" to "Not" just for the purposes of testing, the "Not" value saves and displays fine.

There are several views in my site that have the same behavior.

Here is my code in a simplified version for space:

View Model

public class PersonViewModel
{
    public string PersonId { get; set; }
    public string IsEmployed { get; set; }
    public List<SelectListItem> YesNoList { get; set; }
             = new List<SelectListItem>
                {
                    new SelectListItem("", "NA"),
                    new SelectListItem("Yes", "Yes"),
                    new SelectListItem("No", "No")
                };
}

Simplified View

@model WFCDocuments.ViewModels.PersonViewModel
@{
    ViewData["Title"] = "Loan Processing Application";
    Layout = "/Views/Shared/_Layout.cshtml";
}

Borrower Information

                <form id="personForm" asp-action="Borrower" asp-controller="Application" method="post">
                    <input type="hidden" asp-for="PersonId" />

                        Are You Employed? *
                        <select asp-for="IsEmployed" asp-items="Model.YesNoList" class="form-select form-control-square">
                        </select>

                        <input type="submit" class="btn btn-outline-secondary btn-square" value="Save" />

                </form>

There is not Javascript that interacts with this form

Controller Get

[HttpGet]
public async Task<IActionResult> Borrower()
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson borrowerPerson = personService.GetPerson(user.PersonId, _unitOfWork);
    var person = _mapper.Map<PersonViewModel>(borrowerPerson);
    return View(person);
}

Controller Post

[HttpPost]
public async Task<IActionResult> Borrower(PersonViewModel model)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson person = personService.GetPerson(user.PersonId, _unitOfWork);
    person.IsEmployed = model.IsEmployed;
    var b = await _unitOfWork.BorrowerPeople.UpdateAsync(person);
    if (b == false)
    {
        return RedirectToAction("Borrower", "Application").WithWarning("", "Update Borrower Failed");
    }
    return RedirectToAction("Borrower", "Application").WithSuccess("", "Updated Borrower");
}

Unit of Work Interface
My IUnitOfWork interface wraps up all the repository interface which in turn handle the EF transactions of the database context.

namespace WFCDocuments.Domain.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        IAddressRepository Addresses { get; }
        IApplicationAuditRepository ApplicationAudits { get; }
        IApplicationRepository Applications { get; }
        IBankruptcyRepository Bankruptcies { get; }
        ILoanFileRepository LoanFiles { get; }
        IBorrowerPersonRepository BorrowerPeople { get; }
        IDocumentAuditRepository DocumentAudits { get; }
        IDocumentRepository Documents { get; }
        IExpenseTypeRepository ExpenseTypes { get; }
        IFinancialAnalysisExpenseRepository FinancialAnalysisExpenses { get; }
        IFinancialAnalysisRepository FinancialAnalysis { get; }
        IHardshipRepository Hardships { get; }
        IHardshipTypeRepository HardshipTypes { get; }
        IPropertyRepository Properties { get; }
        INonEscrowedLoanRepository NonEscrowedLoans { get; }
        IRequiredIncomeDocumentationRepository RequiredIncomeDocumentations { get; }
        ILenderRepository Lenders { get; }
        IInvitedRepository Invited { get; }
        IStatusRepository Statuses { get; }
        IMenuRepository Menus { get; }
        IMessageRepository Messages { get; }
        IApplicationStatusRepository ApplicationStatuses { get; set; }
        ISignatureRepository Signatures { get; set; }
        IUserRepository Users { get; set; }
        INotificationRepository Notifications { get; set; }
        INotificationEventRepository NotificationEvents { get; set; }
        IIncomeDocumentRepository IncomeDocuments { get; set; }
        IEventLogRepository EventLogs { get; set; }
        ILoanFileNoteRepository LoanFileNotes { get; set; }
        int Complete();
    }
}

Edit: 2/9/2022 2:41pm
If I change the select element to a plain input element and manually type in "No", the value is persisted and is displayed through post and get actions.
Something is up with the select elements


来源: stackexchange

问:
How to upload a csv file from react js to express using multer
I am new to React and multer, I tried to upload three fields including a csv file to the backend with the help of multer but no success. the application executes until it comes to the

```<code>router.post('/statments', upload.single('file'), function (req, res) {

            console.log(req.body) // form fields
            console.log(req.file) // form files
            res.status(204).end()
        });
</code>```

I use postman to test, it keeps on sending request forever...

At the client :

```<code>import React from 'react'
import '../../../assets/css/bankStatementAnalysis.css'
import {useState} from 'react'
import axios from 'axios';
import {useNavigate} from "react-router-dom"

const AddCreditCardStmnt = () => {
    const [bankName, setBankname] = useState("");
    const [creditCardNo, setCreditcardno] = useState("");
    //selectedFile contains information on the currently picked file
    const [selectedFile, setSelectedFile] = useState("")
    //isFilePicked determines if a file has been picked or not
   // const [isFilePicked, setIsFilePicked] = useState("")
   // const [isSelected, setIsSelected] = useState("false")
    const [statement, setStatement] = useState("");
    const navigate = useNavigate();

    const changeHandler =(e) => {
        setSelectedFile(true)
        setStatement(e.target.files[0])
      //  setIsSelected(true)
    }

    const saveStmnt = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('bankName', bankName)
        formData.append('creditCardNo', creditCardNo)
        formData.append('file', statement)
      //  formData.append('file', e.target.files[0])

      const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    };

        try {
            await axios.post("http://localhost:3001/statements", formData,
           config, {
        });
        navigate("/");
        } catch (error) {
            console.log(error);
        }
};

return (

    <div className="columns mt-5">
    <div className="column is-half">
    <form onSubmit={saveStmnt} enctype="multipart/form-data">
        <div className="field">
        <label className="label">Bank Name</label>
        <div className="control">
            <div className="select is-fullwidth">
                    <select value={bankName} onChange={(e) =>setBankname(e.target.value)}>
                        <option value="citi">Citi</option>
                        <option value="americanexpress">American Express</option>
                        <option value="wellsfargo">Wells Fargo</option>
                        <option value=""></option>
                    </select>
                </div>
    </div>
    <div className="field">
        <label className="label">Credit Card Number</label>
            <div className="control">
                <input
                type="text"
                className="input"
                value={creditCardNo}
                onChange={(e) => setCreditcardno(e.target.value)}
                placeholder="Email"/>
            </div>
    </div>
    <div className="field">
        <label className="label">Statement</label>

            <div className="control">
            <input
            type="file"
            className="input"
            onChange={changeHandler}
        />
     </div>
            </div>
    </div>
    <div className="field">
        <div className="control">
        <button type="submit" className="button is-success">
            Save
        </button>
        </div>
    </div>
</form>
    </div>
    </div>
    );
};

export default AddCreditCardStmnt;
</code>```

At backend

In my router handler:

```<code>import express from "express"
const  router = express.Router();

import {getStatements, addStatements} from "../controllers/CreditCardAnalysis.js"

router.get('/statements', getStatements)
router.post('/statements',  addStatements)

export default router;
</code>```

in the controller :

```<code>export const addStatements = async (req,res) => {
     console.log("perform saveStmnt")

     var storage = multer.diskStorage({
        destination: function (request, file, callback) {
            callback(null, './uploads/');
        },
        filename: function (request, file, callback) {
            console.log(file);
            callback(null, file.originalname)
        }
    });

    var upload = multer({ storage: storage });
    const  router = express.Router();
    console.log("perform router.post")
    router.post('/statments', upload.single('file'), function (req, res) {

        console.log(req.body) // form fields
        console.log(req.file) // form files
        res.status(204).end()
    });
   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to React and multer, I tried to upload three fields including a csv file to the backend with the help of multer but no success. the application executes until it comes to the

router.post('/statments', upload.single('file'), function (req, res) {

            console.log(req.body) // form fields
            console.log(req.file) // form files
            res.status(204).end()
        });

I use postman to test, it keeps on sending request forever...

At the client :

import React from 'react'
import '../../../assets/css/bankStatementAnalysis.css'
import {useState} from 'react'
import axios from 'axios';
import {useNavigate} from "react-router-dom"

const AddCreditCardStmnt = () => {
    const [bankName, setBankname] = useState("");
    const [creditCardNo, setCreditcardno] = useState("");
    //selectedFile contains information on the currently picked file
    const [selectedFile, setSelectedFile] = useState("")
    //isFilePicked determines if a file has been picked or not
   // const [isFilePicked, setIsFilePicked] = useState("")
   // const [isSelected, setIsSelected] = useState("false")
    const [statement, setStatement] = useState("");
    const navigate = useNavigate();

    const changeHandler =(e) => {
        setSelectedFile(true)
        setStatement(e.target.files[0])
      //  setIsSelected(true)
    }

    const saveStmnt = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('bankName', bankName)
        formData.append('creditCardNo', creditCardNo)
        formData.append('file', statement)
      //  formData.append('file', e.target.files[0])

      const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    };

        try {
            await axios.post("http://localhost:3001/statements", formData,
           config, {
        });
        navigate("/");
        } catch (error) {
            console.log(error);
        }
};

return (

    <form onSubmit={saveStmnt} enctype="multipart/form-data">

        Bank Name

                    <select value={bankName} onChange={(e) =>setBankname(e.target.value)}>
                        <option value="citi">Citi</option>
                        <option value="americanexpress">American Express</option>
                        <option value="wellsfargo">Wells Fargo</option>
                        <option value=""></option>
                    </select>

        Credit Card Number

                <input
                type="text"
                className="input"
                value={creditCardNo}
                onChange={(e) => setCreditcardno(e.target.value)}
                placeholder="Email"/>

        Statement

            <input
            type="file"
            className="input"
            onChange={changeHandler}
        />

        <button type="submit" className="button is-success">
            Save
        </button>

</form>

    );
};

export default AddCreditCardStmnt;

At backend

In my router handler:

import express from "express"
const  router = express.Router();

import {getStatements, addStatements} from "../controllers/CreditCardAnalysis.js"

router.get('/statements', getStatements)
router.post('/statements',  addStatements)

export default router;

in the controller :

export const addStatements = async (req,res) => {
     console.log("perform saveStmnt")

     var storage = multer.diskStorage({
        destination: function (request, file, callback) {
            callback(null, './uploads/');
        },
        filename: function (request, file, callback) {
            console.log(file);
            callback(null, file.originalname)
        }
    });

    var upload = multer({ storage: storage });
    const  router = express.Router();
    console.log("perform router.post")
    router.post('/statments', upload.single('file'), function (req, res) {

        console.log(req.body) // form fields
        console.log(req.file) // form files
        res.status(204).end()
    });
   }


问:
Node.js ERR_OSSL_EVP_UNSUPPORTED
I'm trying to create mintable NFT and while I was using metaplex sugar i see only one thing when using command "yarn start":

```<code>opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
</code>```

This is how "scripts" look like:

```<code>"scripts": {
    "start": "react-scripts --openssl-legacy-provider start",,
    "lint": "prettier -c 'src/**/*.{ts,tsx}' && npm run lint:eslint",
    "lint:eslint": "eslint 'src/**/*.{ts,tsx}'",
    "lint:fix": "prettier --write 'src/**/*.{ts,tsx}' && eslint --fix 'src/**/*.{ts,tsx}'",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },
</code>```

I tried using different versions of Nodes but nothing helped me. I tried to replace "scripts" using thhis:

```<code>"scripts": {
    "start": "export SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts start",
    "build": "export SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts build"
}
</code>```

but it still doesn't work.

Title: Node.js ERR_OSSL_EVP_UNSUPPORTED

Body:
I'm trying to create mintable NFT and while I was using metaplex sugar i see only one thing when using command "yarn start":

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'

This is how "scripts" look like:

"scripts": {
    "start": "react-scripts --openssl-legacy-provider start",,
    "lint": "prettier -c 'src/**/*.{ts,tsx}' && npm run lint:eslint",
    "lint:eslint": "eslint 'src/**/*.{ts,tsx}'",
    "lint:fix": "prettier --write 'src/**/*.{ts,tsx}' && eslint --fix 'src/**/*.{ts,tsx}'",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },

I tried using different versions of Nodes but nothing helped me. I tried to replace "scripts" using thhis:

"scripts": {
    "start": "export SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts start",
    "build": "export SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts build"
}

but it still doesn't work.


问:
Jest throw error when testing Select mode="tags" ant design
Jest throw error when testing Select mode="tags" ant design ^4.23.1.
When I try to get toMatchSnapshot() component in Jest (react-testing-library). I get this error: TypeError: Cannot read properties of null (reading 'scrollWidth')

Does anyone know how to solve this error?
Error:

```<code>FAIL  __tests__/containers/Home/Home.test.js
  <Home />
    ✕ Render component toMatchSnapshot() (192 ms)

  ● <Home /> › Render component toMatchSnapshot()

    TypeError: Cannot read properties of null (reading 'scrollWidth')

      203 |
      204 |     const tree = renderer
    > 205 |       .create(
          |        ^
      206 |         <BrowserRouter>
      207 |           <Home />
      208 |         </BrowserRouter>

</code>```

My test:

```<code>test("Render component toMatchSnapshot()", () => {
    mockedUseSelectors.mockReturnValue({});
    const dispatch = jest.fn();
    mockedDispatch.mockReturnValue(dispatch);

    const tree = renderer
      .create(
        <BrowserRouter>
          <Home />
        </BrowserRouter>
      )
      .toJSON();

    expect(tree).toMatchSnapshot();
  });
</code>```

And my Select component:

```<code>    <Select
      bordered={false}
      mode="tags". // if I delete this the error disappears
      {...(isMaxValues && { open: false })}
      style={{
        width: "100%"
      }}
      allowClear
      placeholder={placeholder}
      onChange={onChange}
      options={options}
    />
</code>```

I can't find suitable solution. maybe I must mock scrollWidth, but how?

I would be grateful for any answer, thanks!

Body:
Jest throw error when testing Select mode="tags" ant design ^4.23.1.
When I try to get toMatchSnapshot() component in Jest (react-testing-library). I get this error: TypeError: Cannot read properties of null (reading 'scrollWidth')

Does anyone know how to solve this error?
Error:

FAIL  __tests__/containers/Home/Home.test.js
  <Home />
    ✕ Render component toMatchSnapshot() (192 ms)

  ● <Home /> › Render component toMatchSnapshot()

    TypeError: Cannot read properties of null (reading 'scrollWidth')

      203 |
      204 |     const tree = renderer
    > 205 |       .create(
          |        ^
      206 |         <BrowserRouter>
      207 |           <Home />
      208 |         </BrowserRouter>

My test:

test("Render component toMatchSnapshot()", () => {
    mockedUseSelectors.mockReturnValue({});
    const dispatch = jest.fn();
    mockedDispatch.mockReturnValue(dispatch);

    const tree = renderer
      .create(
        <BrowserRouter>
          <Home />
        </BrowserRouter>
      )
      .toJSON();

    expect(tree).toMatchSnapshot();
  });

And my Select component:

    <Select
      bordered={false}
      mode="tags". // if I delete this the error disappears
      {...(isMaxValues && { open: false })}
      style={{
        width: "100%"
      }}
      allowClear
      placeholder={placeholder}
      onChange={onChange}
      options={options}
    />

I can't find suitable solution. maybe I must mock scrollWidth, but how?

I would be grateful for any answer, thanks!


问:
Why does QuillJS/React-Quill ignore my dangerouslyPasteHTML? (Video Embedding)
```<code>
  const youTubeVideoHandler = () => {
    const editor = quillRef.current.getEditor();
    let url = prompt("Enter Video URL: ");
    url = getVideoUrl(url);
    // console.log("URL", url);
    const newHTML = `<iframe class="ql-video" frameborder="0" allowfullscreen="true" src=${url}></iframe>`;
    let range = editor.getSelection();
    editor.clipboard.dangerouslyPasteHTML(range, newHTML);
    // if (url != null) {
    //   editor.insertEmbed(range, "video", url);
    // }
  };

</code>```

I am using quill-upload to allow users to upload their own videos and images to the editor (works great) but I also wanted them to be able to embed YouTube links and this is where things get crazy.

I have a button for this, and the code for the handler is above.

The clipboard.dangerouslyPasteHTML and the commented-out insertEmbed methods both fail for me in spectacular ways that I don't understand.

For dangerouslyPasteHTML, if 'newHTML' was something benign like Hello
 then it works as expected. With my example however quill completely ignores that I want an iframe and gives me a video instead with the "quill-upload-video" class which makes it useless as I can't embed the YouTube link at this point as it requires an iframe.

For insertEmbed, the same thing happens. It gives me a  element with the "quill-upload-video" class.

I am certain that something about the quill-upload package is telling Quill to do this but I can't understand what. Is there a hacky-way to force raw HTML in some other way or override what quill-upload is doing to influence this?

Body:
  const youTubeVideoHandler = () => {
    const editor = quillRef.current.getEditor();
    let url = prompt("Enter Video URL: ");
    url = getVideoUrl(url);
    // console.log("URL", url);
    const newHTML = `<iframe class="ql-video" frameborder="0" allowfullscreen="true" src=${url}></iframe>`;
    let range = editor.getSelection();
    editor.clipboard.dangerouslyPasteHTML(range, newHTML);
    // if (url != null) {
    //   editor.insertEmbed(range, "video", url);
    // }
  };

I am using quill-upload to allow users to upload their own videos and images to the editor (works great) but I also wanted them to be able to embed YouTube links and this is where things get crazy.

I have a button for this, and the code for the handler is above.

The clipboard.dangerouslyPasteHTML and the commented-out insertEmbed methods both fail for me in spectacular ways that I don't understand.

For dangerouslyPasteHTML, if 'newHTML' was something benign like Hello
 then it works as expected. With my example however quill completely ignores that I want an iframe and gives me a video instead with the "quill-upload-video" class which makes it useless as I can't embed the YouTube link at this point as it requires an iframe.

For insertEmbed, the same thing happens. It gives me a  element with the "quill-upload-video" class.

I am certain that something about the quill-upload package is telling Quill to do this but I can't understand what. Is there a hacky-way to force raw HTML in some other way or override what quill-upload is doing to influence this?


问:
Which GCP Log Explorer query will show success message of data loading to BigQuery by Dataflow Job so that log sink to pub/sub can be created
I am running a Dataflow streaming job which reads data from pub/sub topic and performs streaming insert into BigQuery.

Once data loaded, I want to capture the success status from Log explorer to send acknowledgement back to another pub/sub topic.

What Log Explorer query can serve the purpose ?

I tried to run query below, but did not help.

```<code>protoPayload.serviceData.jobCompletedEvent.job.jobConfiguration.load.destinationTable.datasetId="[REPLACE_WITH_YOUR_DATASET_ID]"
protoPayload.serviceData.jobCompletedEvent.job.jobConfiguration.load.destinationTable.projectId="REPLACE_WITH_YOUR_PROJECT_ID"
protoPayload.methodName="jobservice.jobcompleted"
protoPayload.state="DONE"
</code>```

Please help.

Thanking you,
Santanu

Body:
I am running a Dataflow streaming job which reads data from pub/sub topic and performs streaming insert into BigQuery.

Once data loaded, I want to capture the success status from Log explorer to send acknowledgement back to another pub/sub topic.

What Log Explorer query can serve the purpose ?

I tried to run query below, but did not help.

protoPayload.serviceData.jobCompletedEvent.job.jobConfiguration.load.destinationTable.datasetId="[REPLACE_WITH_YOUR_DATASET_ID]"
protoPayload.serviceData.jobCompletedEvent.job.jobConfiguration.load.destinationTable.projectId="REPLACE_WITH_YOUR_PROJECT_ID"
protoPayload.methodName="jobservice.jobcompleted"
protoPayload.state="DONE"

Please help.

Thanking you,
Santanu


问:
Make consumers in the consumer group idempotent while using mirror maker
I am trying to perform Kafka cluster migration from one cluster to another cluster using Mirror Maker 2.0. I am using Kafka 2.8.1 which has good support for consumer-group replication and offset sync.
I have encountered a scenario where I want to migration a topic along with its producers and consumers from source cluster to target cluster.

Example:
I have topic A which I want to migrate, it has 3 partitions

```<code>source -> topic = A
destination -> topic = source.A
</code>```

topic A is replicated as source.A in target cluster

I have a consumer-group topic-a-reader-group created at source cluster with 3 consumers. It is replicated at destination cluster with same name, I have created 1 consumers in this group at destination cluster.

Now when I producer messages at source cluster to topic A, it is consumed by 3 consumers are source cluster and this message will also get replicated at target cluster which is consumer by the consumer present in the consumer-group running at target cluster. Basically the message is read both by source consumer and target consumer. Duplicate read for consumer ultimately.

I want only one consumer to get this message, not to duplicate at source and destination.  In my application, I can't just turn off the consumer at source and move it to target cluster(time critical application). So I want to keep both consumers at source and target running for sometime and turn off source consumer after some duration where both are running active.

Is there any idempotence property available for consumer-group which let only one consumer-group to read the message in mirror maker scenario without being duplicated at source and target cluster?

Please suggest if there are any other approach to move consumers from source to target cluster without downtime.

Body:
I am trying to perform Kafka cluster migration from one cluster to another cluster using Mirror Maker 2.0. I am using Kafka 2.8.1 which has good support for consumer-group replication and offset sync.
I have encountered a scenario where I want to migration a topic along with its producers and consumers from source cluster to target cluster.

Example:
I have topic A which I want to migrate, it has 3 partitions

source -> topic = A
destination -> topic = source.A

topic A is replicated as source.A in target cluster

I have a consumer-group topic-a-reader-group created at source cluster with 3 consumers. It is replicated at destination cluster with same name, I have created 1 consumers in this group at destination cluster.

Now when I producer messages at source cluster to topic A, it is consumed by 3 consumers are source cluster and this message will also get replicated at target cluster which is consumer by the consumer present in the consumer-group running at target cluster. Basically the message is read both by source consumer and target consumer. Duplicate read for consumer ultimately.

I want only one consumer to get this message, not to duplicate at source and destination.  In my application, I can't just turn off the consumer at source and move it to target cluster(time critical application). So I want to keep both consumers at source and target running for sometime and turn off source consumer after some duration where both are running active.

Is there any idempotence property available for consumer-group which let only one consumer-group to read the message in mirror maker scenario without being duplicated at source and target cluster?

Please suggest if there are any other approach to move consumers from source to target cluster without downtime.


问:
How can I edit VBA code to center the imported pictures in their cells
I am relatively new to VBA so perhaps there is a simple solution to this? I am using the code below to import multiple pictures into a column. However, I need to center the pictures in their cells too. Is there a way to alter the current code? Which works great! (except the pictures are not centered).

Thank you

```<code>Sub InsertMultipleRGPictures()

    Dim Pictures() As Variant
    Dim PictureFormat As String
    Dim PicRng As Range
    Dim PicShape As Shape
    Dim xPicRg As Range
    Dim xPic As Picture
    Dim xRg As Range
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Application.Calculation = xlCalculationManual
    Sheets("Auto Post").Range("AZ3:AZ9").Select
     Columns("AZ:AZ").ColumnWidth = 57
     Set xRg = Range("AZ3:AZ14")
        For Each xPic In ActiveSheet.Pictures

        Set xPicRg = Range(xPic.TopLeftCell.Address & ":" & xPic.BottomRightCell.Address)
        If Not Intersect(xRg, xPicRg) Is Nothing Then xPic.Delete
        Next
On Error Resume Next
PictureFormat = "Test Files (*.png; *.jpeg), *.png; *.jpeg"
Pictures = Application.GetOpenFilename(PictureFormat, MultiSelect:=True)
    PicColIndex = Application.ActiveCell.Column
If IsArray(Pictures) Then
              PicRowIndex = Application.ActiveCell.Row
    For lLoop = LBound(Pictures) To UBound(Pictures)
        Set PicRng = Cells(PicRowIndex, PicColIndex)
        With ActiveSheet.Shapes.AddPicture(Pictures(lLoop), msoFalse, msoCTrue, msoFalse, msoCTrue, PicRng.Left, PicRng.Top, -1, -1)
         .LockAspectRatio = msoTrue
       .Height = 250 * 3 / 4

       Rng.RowHeight = .Height
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth

               End With
        PicRowIndex = PicRowIndex + 1
    Next
        MsgBox "Import Complete- Pictures"
    End If
    Columns("AZ:AZ").ColumnWidth = 50
   Application.ScreenUpdating = True
   Application.DisplayStatusBar = True
   Application.Calculation = xlCalculationAutomatic
End Sub

</code>```

Body:
I am relatively new to VBA so perhaps there is a simple solution to this? I am using the code below to import multiple pictures into a column. However, I need to center the pictures in their cells too. Is there a way to alter the current code? Which works great! (except the pictures are not centered).

Thank you

Sub InsertMultipleRGPictures()

    Dim Pictures() As Variant
    Dim PictureFormat As String
    Dim PicRng As Range
    Dim PicShape As Shape
    Dim xPicRg As Range
    Dim xPic As Picture
    Dim xRg As Range
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Application.Calculation = xlCalculationManual
    Sheets("Auto Post").Range("AZ3:AZ9").Select
     Columns("AZ:AZ").ColumnWidth = 57
     Set xRg = Range("AZ3:AZ14")
        For Each xPic In ActiveSheet.Pictures

        Set xPicRg = Range(xPic.TopLeftCell.Address & ":" & xPic.BottomRightCell.Address)
        If Not Intersect(xRg, xPicRg) Is Nothing Then xPic.Delete
        Next
On Error Resume Next
PictureFormat = "Test Files (*.png; *.jpeg), *.png; *.jpeg"
Pictures = Application.GetOpenFilename(PictureFormat, MultiSelect:=True)
    PicColIndex = Application.ActiveCell.Column
If IsArray(Pictures) Then
              PicRowIndex = Application.ActiveCell.Row
    For lLoop = LBound(Pictures) To UBound(Pictures)
        Set PicRng = Cells(PicRowIndex, PicColIndex)
        With ActiveSheet.Shapes.AddPicture(Pictures(lLoop), msoFalse, msoCTrue, msoFalse, msoCTrue, PicRng.Left, PicRng.Top, -1, -1)
         .LockAspectRatio = msoTrue
       .Height = 250 * 3 / 4

       Rng.RowHeight = .Height
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth
                Rng.ColumnWidth = .Width / Rng.Width * Rng.ColumnWidth

               End With
        PicRowIndex = PicRowIndex + 1
    Next
        MsgBox "Import Complete- Pictures"
    End If
    Columns("AZ:AZ").ColumnWidth = 50
   Application.ScreenUpdating = True
   Application.DisplayStatusBar = True
   Application.Calculation = xlCalculationAutomatic
End Sub


问:
How do I ungroup an sf dataframe with multiple sfc_POINT geometries to retain only 1 geometry column?
I have an sf dataframe (sfc_POINT geometry) made from 2 other sf dataframes (also sfc_POINT geometry). I want my final sf dataframe to have a single geometry column for a clean dataset for analysis, my current sf dataframe seems to have 6 groups and 6 geometry columns. I think the problem stems from using the dplyr::groupby() function in the 2 sf dataframes I used to derive my current sf dataframe. Realizing this, I went back and made sure to use the dplyr::ungroup() function at multiple steps, but the problem persists.

Below is my the geometry structure of my data, and code block where I attempted to ungroup any variables, remove the sf geometry, and recreate geometry.

"yo" is my current sfc_POINT dataframe. It is a tibble [3,063 × 3], S3: tbl_df/tbl/data.frame. Here is the output from the str(yo$geometry):

$ geometry :sfc_POINT of length 168465; first list element:  'XY' num [1:2] 256552 282745  - attr(*, "groups")= tibble [3,063 × 3] (S3: tbl_df/tbl/data.frame)   ..$ Animal.ID: Factor w/ 112 levels "140040","140050",..: 3 3 3 3 3 3 3 3 3 3 ...   ..$ Date     : Date[1:3063], format: "2014-10-25" "2014-10-26" "2014-10-27" "2014-10-28" ... - attr(*, "sf_column")= chr "geometry" - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...

```<code>yo <- yo %>%
  #make sure data are ungrouped
  dplyr::ungroup() %>%
  #create UTM coordinates from current sf geometry
  mutate(UTME = st_coordinates(yo)[,1],
         UTMN = st_coordinates(yo)[,2]) %>%
  #drop grouped geometry
  st_drop_geometry() %>%
  #convert to standard dataframe to remove sfc_POINT format
  as.data.frame() %>%
  #recreate one geometry column with coordinates I derived above
  st_as_sf(coords = c("UTME", "UTMN"), remove = T, crs = MontanaCRS)
</code>```

I expected this to result in 1 geometry column of coordinates, but it is still putting out 6  POINT columns. I've worked a lot in the sf package and have not had this problem. I would appreciate any help or insight. Thanks a lot!

Body:
I have an sf dataframe (sfc_POINT geometry) made from 2 other sf dataframes (also sfc_POINT geometry). I want my final sf dataframe to have a single geometry column for a clean dataset for analysis, my current sf dataframe seems to have 6 groups and 6 geometry columns. I think the problem stems from using the dplyr::groupby() function in the 2 sf dataframes I used to derive my current sf dataframe. Realizing this, I went back and made sure to use the dplyr::ungroup() function at multiple steps, but the problem persists.

Below is my the geometry structure of my data, and code block where I attempted to ungroup any variables, remove the sf geometry, and recreate geometry.

"yo" is my current sfc_POINT dataframe. It is a tibble [3,063 × 3], S3: tbl_df/tbl/data.frame. Here is the output from the str(yo$geometry):

$ geometry :sfc_POINT of length 168465; first list element:  'XY' num [1:2] 256552 282745  - attr(*, "groups")= tibble [3,063 × 3] (S3: tbl_df/tbl/data.frame)   ..$ Animal.ID: Factor w/ 112 levels "140040","140050",..: 3 3 3 3 3 3 3 3 3 3 ...   ..$ Date     : Date[1:3063], format: "2014-10-25" "2014-10-26" "2014-10-27" "2014-10-28" ... - attr(*, "sf_column")= chr "geometry" - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...

yo <- yo %>%
  #make sure data are ungrouped
  dplyr::ungroup() %>%
  #create UTM coordinates from current sf geometry
  mutate(UTME = st_coordinates(yo)[,1],
         UTMN = st_coordinates(yo)[,2]) %>%
  #drop grouped geometry
  st_drop_geometry() %>%
  #convert to standard dataframe to remove sfc_POINT format
  as.data.frame() %>%
  #recreate one geometry column with coordinates I derived above
  st_as_sf(coords = c("UTME", "UTMN"), remove = T, crs = MontanaCRS)

I expected this to result in 1 geometry column of coordinates, but it is still putting out 6  POINT columns. I've worked a lot in the sf package and have not had this problem. I would appreciate any help or insight. Thanks a lot!


问:
Merge rows from multiple tables SQL (incremental)
I'm consolidating the information of 7 SQL databases into one.
I've made a SSIS package and used Lookup transformation and I managed to get the result as expected.

The problem: 30 million rows. And I want to perform a daily task to add to the destination table the new rows in the source tables.

So it takes like 4 hours to execute the package...

Any suggestion ?
Thanks!

I have only tried full cache mode...


问:
Android Studio: Emulator looks like it was dropped
This is my first time downloading Android Studio on my laptop(MacBook Pro) and the emulator looks like the phone was dropped and the program is pretty slow. How might I fix this?

I tried uninstalling and reinstalling and I made sure that I downloaded the the program for the one with a silicon chip and I reached out to one of my old professors. He wasn't too sure how to fix it either.


问:
How to do JaxB XML Unmarshalling/Marshalling of element with package name?
I got following XML with element name being present with their package name. How can I marshal/unmarshal the given XML using JaxB?

```<code><com.jaraws.api.Vehicle>
  <number>KT12356</number>
  <engine>DIESEL<engine>
</com.jaraws.api.Vehicle>
</code>```

With Java class being written as:

```<code>package com.jaraws.api;

@XmlRootElement
public class Vehicle{
  private String number;
  private String engine;

  // Getters Setter for number and engine attributes
  @XmlElement
  public String getNumber(){
    return number;
  }

  public void setNumber(){
    this.number=number;
  }

  @XmlElement
  public String getEngine(){
    return engine;
  }

  public void setEngine(){
    this.engine=engine;
  }
}
</code>```

Is it achievable or I am not doing something in a right matter. I want to marshal / unmarshal the xml in given format only.

Body:
I got following XML with element name being present with their package name. How can I marshal/unmarshal the given XML using JaxB?

<com.jaraws.api.Vehicle>
  <number>KT12356</number>
  <engine>DIESEL<engine>
</com.jaraws.api.Vehicle>

With Java class being written as:

package com.jaraws.api;

@XmlRootElement
public class Vehicle{
  private String number;
  private String engine;

  // Getters Setter for number and engine attributes
  @XmlElement
  public String getNumber(){
    return number;
  }

  public void setNumber(){
    this.number=number;
  }

  @XmlElement
  public String getEngine(){
    return engine;
  }

  public void setEngine(){
    this.engine=engine;
  }
}

Is it achievable or I am not doing something in a right matter. I want to marshal / unmarshal the xml in given format only.


问:
i have problem in creating custom cfg parser , to check if a given code has syntax error or no using NLP (NLTK)
```<code>
# Define the CFG for a Python for loop
for_loop_grammar = nltk.CFG.fromstring("""
    S -> 'for' VAR 'in' RANGE ':' BODY
    VAR -> 'i' | 'j' | 'k' | 'l' | 'm' | 'n'
    RANGE -> 'range' '(' NUM NUM'*' ')'
    BODY -> STMT
    STMT -> 'print(' VAR ')'
    NUM -> '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
    NUM -> NUM NUM
""")

def check_syntax(code):
    # Parse the code using the CFG
    parser = nltk.ChartParser(for_loop_grammar)
    try:
        parse_tree = next(parser.parse(code.split()))
        return "Valid syntax"
    except StopIteration:
        return "Invalid syntax"

# Test the function with some sample code
print(check_syntax("for i in range(5): print(i)"))
</code>```

i have this code , my goal is to make a python program to check  if a given code has syntax error or no using NLP,
when i run the code i get this error "ValueError: Grammar does not cover some of the input words: "'range(5):print(i)'".

Body:
# Define the CFG for a Python for loop
for_loop_grammar = nltk.CFG.fromstring("""
    S -> 'for' VAR 'in' RANGE ':' BODY
    VAR -> 'i' | 'j' | 'k' | 'l' | 'm' | 'n'
    RANGE -> 'range' '(' NUM NUM'*' ')'
    BODY -> STMT
    STMT -> 'print(' VAR ')'
    NUM -> '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
    NUM -> NUM NUM
""")

def check_syntax(code):
    # Parse the code using the CFG
    parser = nltk.ChartParser(for_loop_grammar)
    try:
        parse_tree = next(parser.parse(code.split()))
        return "Valid syntax"
    except StopIteration:
        return "Invalid syntax"

# Test the function with some sample code
print(check_syntax("for i in range(5): print(i)"))

i have this code , my goal is to make a python program to check  if a given code has syntax error or no using NLP,
when i run the code i get this error "ValueError: Grammar does not cover some of the input words: "'range(5):print(i)'".


问:
When will expo-image-picker return an HEIC file on IOS?
I have an IOS react native app that uses expo-image-picker to get images from the Image Library and  Camera. When testing the app through Expo Go on an iPhone SE, the uri in ImagePicker.ImageInfo always gives a jpg file.

This behavior persists even when I upload an HEIC file to my phone, and use that file with the image picker. I also have High Efficiency setting enabled in the format section of the camera settings.

While this is my desired behavior, I don't want to rely on a misunderstanding of the library. Nowhere in the documentation are HEIC files mentioned, except for one example that indicates it is possible for the library to retrieve HEIC files.

Is it possible to get HEIC files, if so how?


问:
Find the actual scope of a variable declared multiple times in Java
I have a program that is like this :

```<code>class A {
String abc;

public void f1(){
    String abc = 'test';
    System.out.println(abc);
    if (true){
          String abc = 'something else';
          System.out.println(abc);
    }
}

public void f2(){
    String abc = 'something else';
    System.out.println(abc);
}
</code>```

}

Now as we can see here we have three different variable declarations of the string abc. I wish to make a dependency matrix which will have slots for all the three declarations , that point to different memory locations. Is there any way I could get the declarations for each variable name along with the parent class or method it belongs to? Or more precisely , can I get the scope of a variable ,I.E whether it is a class variable or a variable that belongs to a method ?

I have tried using JavaParser but couldn’t find a suitable method that would do the same. Kindly help me out. Thanks a lot!!

Body:
I have a program that is like this :

class A {
String abc;

public void f1(){
    String abc = 'test';
    System.out.println(abc);
    if (true){
          String abc = 'something else';
          System.out.println(abc);
    }
}

public void f2(){
    String abc = 'something else';
    System.out.println(abc);
}

}

Now as we can see here we have three different variable declarations of the string abc. I wish to make a dependency matrix which will have slots for all the three declarations , that point to different memory locations. Is there any way I could get the declarations for each variable name along with the parent class or method it belongs to? Or more precisely , can I get the scope of a variable ,I.E whether it is a class variable or a variable that belongs to a method ?

I have tried using JavaParser but couldn’t find a suitable method that would do the same. Kindly help me out. Thanks a lot!!


问:
How to make my Ionic app backend work on android?
I'm creating an app that uses Ionic and VueJS for the front-end, and for the back-end, Express and Mongoose.
When I run the file containing the express app, it creates a localhost on port 3000 and can handle POST & GET requests. The front-end make a http POST call on localhost:3000, using axios, to send data to the database.

On my PC it works well but when I deploy the app on android it does nothing.


问:
C# - Trying to grab and save a pdf into my database
In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?

The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.

```<code>Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

bool? response = openFileDialog.ShowDialog();

var fileContent = string.Empty;

var filestream = openFileDialog.OpenFile();

using (StreamReader reader = new StreamReader(filestream))
{
    fileContent = reader.ReadToEnd();
}

// make folder path
string FolderPath = "ProjectPDFs\\";

string RootPath = "X:\\Vents-US Inventory";

DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));

Directory.CreateDirectory(FolderDir.ToString());

string filePath = "";

string FileName = openFileDialog.SafeFileName;

if (fileContent.Length > 0)
{
    filePath = Path.Combine(FolderDir.ToString(), FileName);
    using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
        byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);

        Stream stream = new MemoryStream(bytestream);

        stream.CopyTo(fileStream);
    }
}

</code>```

Body:
In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?

The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.

Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

bool? response = openFileDialog.ShowDialog();

var fileContent = string.Empty;

var filestream = openFileDialog.OpenFile();

using (StreamReader reader = new StreamReader(filestream))
{
    fileContent = reader.ReadToEnd();
}

// make folder path
string FolderPath = "ProjectPDFs\\";

string RootPath = "X:\\Vents-US Inventory";

DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));

Directory.CreateDirectory(FolderDir.ToString());

string filePath = "";

string FileName = openFileDialog.SafeFileName;

if (fileContent.Length > 0)
{
    filePath = Path.Combine(FolderDir.ToString(), FileName);
    using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
        byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);

        Stream stream = new MemoryStream(bytestream);

        stream.CopyTo(fileStream);
    }
}


问:
Sitemap can be read, but has errors - invalid date
I am getting this error on Google search console after updating my sitemap.xml. I checked the line numbers shown but the dates are the same as the dates on the original sitemap. Any ideas?

"Sitemap can be read, but has errors

An invalid date was found. Please fix the date or formatting before resubmitting.
Examples
Line 440
Parent tag:
url
Tag:
lastmod"


问:
Express.JS equivalent of Java's HTTPS Server
In Express.JS, creating a HTTPS server from a private key and certificate is quite simple:

```<code>var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpsServer = https.createServer(credentials, app);
</code>```

I was wondering if there is a Java equivalent of this code.

I have been trying to look into creating a HTTPS Server in Java but I get confused with the whole keystore files. Could someone guide me thoroughly?

Body:
In Express.JS, creating a HTTPS server from a private key and certificate is quite simple:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpsServer = https.createServer(credentials, app);

I was wondering if there is a Java equivalent of this code.

I have been trying to look into creating a HTTPS Server in Java but I get confused with the whole keystore files. Could someone guide me thoroughly?


问:
querying open street map data includes data beyond specified bbox
I am trying to map parks and green areas in San Francisco, I am querying the data from open street map with a bounding box (location_spec). When I plot the data, it shows data way beyond the specified bounding box (as can be seen from the screenshot https://imgbb.com/kDhXyVB).
For other queries (e.g. institutions) the query works normally.

```<code>location_spec <- opq(bbox = c(-122.572290,37.684714,-122.336771,37.820440))

osm_greens <- location_spec1 %>%
  add_osm_feature(key = "leisure",
                  value = c("park","nature_reserve","recreation_ground","golf_course","pitch","garden")) %>%
  osmdata_sf()

ggplot()+
  geom_sf(data = institutions,col="red")+
  geom_sf(data = osm_greens_poly,col="green")
</code>```

What could be the reason for this? I tried removing all observations where addr.city was not "San Francisco". This kind of "solved" the problem with the polygons outside of SF but it also left me with barely any parks in the city which means I can't use it.

In case you want to check with the institutions I queried:

```<code>specified_institutions <- c("kindergarten", "college","school","university")

osm_institution <- location_spec %>%
  add_osm_feature(key = "building", value = specified_institutions) %>%
  osmdata_sf ()

#transforming polygons into points
institution_polys <- osm_institution$osm_polygons %>%
  filter( building %in% specified_institutions) %>%
  select(where(institution_polys$name != NA))

#creating a centroid
institution_polys$geometry <- st_centroid(institution_polys$geometry)
institution_polys <- st_sf(institution_polys)

</code>```

Body:
I am trying to map parks and green areas in San Francisco, I am querying the data from open street map with a bounding box (location_spec). When I plot the data, it shows data way beyond the specified bounding box (as can be seen from the screenshot https://imgbb.com/kDhXyVB).
For other queries (e.g. institutions) the query works normally.

location_spec <- opq(bbox = c(-122.572290,37.684714,-122.336771,37.820440))

osm_greens <- location_spec1 %>%
  add_osm_feature(key = "leisure",
                  value = c("park","nature_reserve","recreation_ground","golf_course","pitch","garden")) %>%
  osmdata_sf()

ggplot()+
  geom_sf(data = institutions,col="red")+
  geom_sf(data = osm_greens_poly,col="green")

What could be the reason for this? I tried removing all observations where addr.city was not "San Francisco". This kind of "solved" the problem with the polygons outside of SF but it also left me with barely any parks in the city which means I can't use it.

In case you want to check with the institutions I queried:

specified_institutions <- c("kindergarten", "college","school","university")

osm_institution <- location_spec %>%
  add_osm_feature(key = "building", value = specified_institutions) %>%
  osmdata_sf ()

#transforming polygons into points
institution_polys <- osm_institution$osm_polygons %>%
  filter( building %in% specified_institutions) %>%
  select(where(institution_polys$name != NA))

#creating a centroid
institution_polys$geometry <- st_centroid(institution_polys$geometry)
institution_polys <- st_sf(institution_polys)


问:
Making Axios Request to open link in ms-word using Office URI scheme
i am writing a react app that should deliver word files to clients and opening them in word. I am trying to use this:   https://learn.microsoft.com/en-us/office/client-developer/office-uri-schemes?redirectedfrom=MSDN

So i tried it like this:

```<code>function TestComponent(props: any) {
    const handleClick = () => {
        axios.get("ms-word:ofe|u|https://127.0.0.1:8000/api/getDocxDocument/52312");
    };
    return (
            <button onClick={handleClick}>open document</button>
    );
}
</code>```

But i get a "Unsupported protocol msword" error.

Is there a way to do what i want with axios?

Body:
i am writing a react app that should deliver word files to clients and opening them in word. I am trying to use this:   https://learn.microsoft.com/en-us/office/client-developer/office-uri-schemes?redirectedfrom=MSDN

So i tried it like this:

function TestComponent(props: any) {
    const handleClick = () => {
        axios.get("ms-word:ofe|u|https://127.0.0.1:8000/api/getDocxDocument/52312");
    };
    return (
            <button onClick={handleClick}>open document</button>
    );
}

But i get a "Unsupported protocol msword" error.

Is there a way to do what i want with axios?


问:
Atomic SELECT and subsequent INSERT from php
Assume I want to update a MySQL database from PHP based on a value just read from the database, in an atomic matter. If I did not need atomicity, I would write, for instance,

```<code>$Result = mysqli_fetch_all (mysqli_query ($SqlConnection, "SELECT * FROM mytable"), MYSQLI_ASSOC);
if (some_condition($Result))
    mysqli_query ($SqlConnection, "INSERT INTO table (value) VALUES (1);");
else
    mysqli_query ($SqlConnection, "INSERT INTO table (value) VALUES (0);");
</code>```

This is not atomic since the table might have been updated after the SELECT statement such that the subsequent INSERT statement would do the wrong thing, i.e. based on the old instead of the new state of the table.

I know about START TRANSACTION ... COMMIT, but this does not seem to be applicable if I want to do the condition check in PHP. And as I understand, the SELECT statement must be completed already in order for PHP to know the result.

However, this does not seem to be a problem specific to PHP since this question would arise in any use case where SQL statements are to be executed from outside of the SQL environment.

Body:
Assume I want to update a MySQL database from PHP based on a value just read from the database, in an atomic matter. If I did not need atomicity, I would write, for instance,

$Result = mysqli_fetch_all (mysqli_query ($SqlConnection, "SELECT * FROM mytable"), MYSQLI_ASSOC);
if (some_condition($Result))
    mysqli_query ($SqlConnection, "INSERT INTO table (value) VALUES (1);");
else
    mysqli_query ($SqlConnection, "INSERT INTO table (value) VALUES (0);");

This is not atomic since the table might have been updated after the SELECT statement such that the subsequent INSERT statement would do the wrong thing, i.e. based on the old instead of the new state of the table.

I know about START TRANSACTION ... COMMIT, but this does not seem to be applicable if I want to do the condition check in PHP. And as I understand, the SELECT statement must be completed already in order for PHP to know the result.

However, this does not seem to be a problem specific to PHP since this question would arise in any use case where SQL statements are to be executed from outside of the SQL environment.


问:
Modify Syntax Highlighting Color for Type Aliases
I'd like my type aliases to match the color of types, rather than variables.

```<code>  IntAlias = int
# ^^^^^^^^
# Type alias is highlighted as a variable (#9cdcfe), rather than a type (#4ec9b0)
</code>```

I've tried modifying the Settings.json file to change variable colors, but it doesn't appear to allow for specifying per-type.

Body:
I'd like my type aliases to match the color of types, rather than variables.

  IntAlias = int
# ^^^^^^^^
# Type alias is highlighted as a variable (#9cdcfe), rather than a type (#4ec9b0)

I've tried modifying the Settings.json file to change variable colors, but it doesn't appear to allow for specifying per-type.


问:
Change the thread pool pattern to wait for the response on each retry and start the next retry
We currently create multiple threads in parallel as part of the retry strategy but i want to make the Change in the thread pool pattern to wait for the response on each retry and start the next retry. can anyone suggest the optimal way to do that?

```<code>List<RetryingListenableFuture<List<ResourceInstanceTable>>> futures =
        new ArrayList<>(maxAttempts.get());
//The change should be to wait for the response on each retry and start the next one.
for (; attempt < maxAttempts.get() && result == null; attempt++) {
    // Check if any of the previous futures succeeded
    for (int i = futures.size() - 1; i >= 0 && result == null; i--) {
        try {
            result = futures.get(i).get(1, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ignored) {
            // Do nothing
        } catch (ExecutionException e) {
            exception = e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
            if (!isDynamoThrottlingException(e.getCause())) throw exception;
            futures.remove(i);
        }
    }

    if (result == null) {
        RetryingListenableFuture<List<ResourceInstanceTable>> future =
                helper.getTenantInfo().getExecutorService().submit(callable);
        try {
            result = future.get(timeoutPerAttempt.get(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // Add future to the list - who knows, may be it will be done by the next attempt timeout
            futures.add(future);
            exception = e;
        } catch (ExecutionException e) {
            // If it is not a throttling exception - throw it away, we're failed. Otherwise continue
            // with retries, saving exception
            exception = e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
            if (!isDynamoThrottlingException(e.getCause())) throw exception;
        }
    }
}
</code>```

I tried to make changes in the futures.get to start the next retry but it is not optimal. Since we are making multiple threads in parallel in the current approach the change is to wait for the response and start the next retry

Body:
We currently create multiple threads in parallel as part of the retry strategy but i want to make the Change in the thread pool pattern to wait for the response on each retry and start the next retry. can anyone suggest the optimal way to do that?

List<RetryingListenableFuture<List<ResourceInstanceTable>>> futures =
        new ArrayList<>(maxAttempts.get());
//The change should be to wait for the response on each retry and start the next one.
for (; attempt < maxAttempts.get() && result == null; attempt++) {
    // Check if any of the previous futures succeeded
    for (int i = futures.size() - 1; i >= 0 && result == null; i--) {
        try {
            result = futures.get(i).get(1, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ignored) {
            // Do nothing
        } catch (ExecutionException e) {
            exception = e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
            if (!isDynamoThrottlingException(e.getCause())) throw exception;
            futures.remove(i);
        }
    }

    if (result == null) {
        RetryingListenableFuture<List<ResourceInstanceTable>> future =
                helper.getTenantInfo().getExecutorService().submit(callable);
        try {
            result = future.get(timeoutPerAttempt.get(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // Add future to the list - who knows, may be it will be done by the next attempt timeout
            futures.add(future);
            exception = e;
        } catch (ExecutionException e) {
            // If it is not a throttling exception - throw it away, we're failed. Otherwise continue
            // with retries, saving exception
            exception = e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
            if (!isDynamoThrottlingException(e.getCause())) throw exception;
        }
    }
}

I tried to make changes in the futures.get to start the next retry but it is not optimal. Since we are making multiple threads in parallel in the current approach the change is to wait for the response and start the next retry


问:
TeamsFX with the Blazor CascadingAuthenticationState
I've been able to confirm that the SSO for my Blazor app is working with the TeamsFX service, however I've failed to authorize the SSO credential with the CascasdingAuthorizationState component around the app Router.

Does the TeamsFX service extend into the AuthorizeView of a Blazor server app, or is there another service to register to work with the TeamsFX SSO?


问:
Updating upload fingerprint in keystore
We needed to request new keys from Google for signing our Android app due to an administrative issue in the company. We still have the original keystore used to upload the original version of the app to Google Play.

Google issued a new upload key for our app and their email includes an MD5 and a SHA1 fingerprint. When I run keytool -list -keystore myapp.keystore command against the original keystore, I see the following:

How do I proceed from here? I'm a bit confused because the original keystore only contains one entry which is the SHA-256.

Do I need to generate a new keystore or do I need to import the new MD5 and SHA1 and remove the old SHA-256? I'd appreciate help with this.

Title: Updating upload fingerprint in keystore


问:
nmap: error while loading shared libraries: liblua5.3-lpeg.so.2: cannot open shared object file: No such file or directory
I know that this has been questioned before. The thing is that the answer was not sufficient for me. I run raspian and i sudo apt get installed nmap and it was working fine. After some time and some more installations of other packages i was unable to nmap because of this error. I tried everything so far with no success. Can anyone help?

Thank you


问:
Sum columns based on condition on another columns
I have a dataframe as follows and if ts1_diff,ts2_diff,ts3_diff is >= 0 then only sum corresponding ts1 to ts3 columns.So for id=1,ts3_diff>=0 so the value for SUM = 5, for id = 2,all ts1_diff,ts2_diff,ts3_diff is >=0 so we sum(ts1,ts2,ts3)= 10, I am expecting the Column 'SUM'
enter image description here

Any help would be appreciated.Thank you


问:
How does Google send a message back to a user's browser for Chrome extensions that use GCM/FCM for push notifications?
At a high level, I understand the data flow process for Chrome extensions that want to register for push notifications. For example, for an extension to register for push notifications when a user's calendar changes:

Initialization:

Extension calls chrome.gcm.register to register for push notifications for changes to a calendar, and specifics to https://www.example.com as the destination for the notification

Extension also sets up an chrome.gcm.onMessage listener

Push notification:

Change to my calendar

Google sends push notification to https://www.example.com

https://www.example.com makes a call to https://fcm.googleapis.com/fcm/send with appropriate information

Google sends a message to the browser/extension and is picked up by the chrome.gcm.onMessage event listener

Assuming my understanding is right, I am wondering how #4 happens? My browser might be behind a firewall that blocks inbound -- but the extension still works. Is Google sending the message in a new session or an already established session? Is it doing something else?


问:
pptr-testing-library getDocument returns empty object
For integration tests in a Firebase project i use the emulator to provide the backend simulation. Test framework is Jest (29), Testing-Library (13) and pptr-testing-library (0.7) as an adapter to Puppeteer (18).

When running a test regardless if it is started in headless or not, getDocument always returns an empty object when using the following test file.

```<code>import puppeteer, {Browser, Page} from "puppeteer";
import '@testing-library/jest-dom'
import {cleanup, getByTestId, waitFor} from '@testing-library/react'

import { authAdmin } from './FirebaseTestSetupFn'
import {getDocument} from "pptr-testing-library";

let browser: Browser | undefined
let page: Page | undefined

beforeEach( async () => {
  const pages = await browser!.pages() ;
  if (pages && pages.length > 0) {
    page = pages[0]
  } else {
    page = await browser!.newPage()
  }
})

afterEach(async () => {
  await page!.close()
  cleanup()
})

beforeAll(async () => {
  const allUsers = await authAdmin.listUsers()
  allUsers.users.forEach((user) => {
    authAdmin.deleteUser(user.uid)
  })

  browser = await puppeteer.launch({
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-features=DialMediaRouteProvider']
  });
})

describe('Authentication', () => {

  test('Show login page on load without valid token',async () => {
    await page!.goto('http://localhost:8080')
    const $document = (await getDocument(page)) as unknown as HTMLElement

    await waitFor(() => {
      expect(getByTestId($document, 'form-label')).toBeTruthy()
      expect(getByTestId($document, 'form-label').textContent).toContain("Login")
    })
  })

})

</code>```

If a breakpoint is set at the line starting with await waitFor(() => { with headless mode false the page does show the expected content.

When the script is executed it fails at the first expectation with the following error.

```<code>Expected container to be an Element, a Document or a DocumentFragment but got ElementHandle.

Ignored nodes: comments, script, style
<html>
  <head />
  <body />
</html>
TypeError: Expected container to be an Element, a Document or a DocumentFragment but got ElementHandle.

Ignored nodes: comments, script, style
<html>
  <head />
  <body />
</html>
</code>```

Adding console.log(Document :${JSON.stringify($document)}) before the expectation shows that $document is empty.

Any idea how to get the current page content ?

Body:
For integration tests in a Firebase project i use the emulator to provide the backend simulation. Test framework is Jest (29), Testing-Library (13) and pptr-testing-library (0.7) as an adapter to Puppeteer (18).

When running a test regardless if it is started in headless or not, getDocument always returns an empty object when using the following test file.

import puppeteer, {Browser, Page} from "puppeteer";
import '@testing-library/jest-dom'
import {cleanup, getByTestId, waitFor} from '@testing-library/react'

import { authAdmin } from './FirebaseTestSetupFn'
import {getDocument} from "pptr-testing-library";

let browser: Browser | undefined
let page: Page | undefined

beforeEach( async () => {
  const pages = await browser!.pages() ;
  if (pages && pages.length > 0) {
    page = pages[0]
  } else {
    page = await browser!.newPage()
  }
})

afterEach(async () => {
  await page!.close()
  cleanup()
})

beforeAll(async () => {
  const allUsers = await authAdmin.listUsers()
  allUsers.users.forEach((user) => {
    authAdmin.deleteUser(user.uid)
  })

  browser = await puppeteer.launch({
    headless: false,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-features=DialMediaRouteProvider']
  });
})

describe('Authentication', () => {

  test('Show login page on load without valid token',async () => {
    await page!.goto('http://localhost:8080')
    const $document = (await getDocument(page)) as unknown as HTMLElement

    await waitFor(() => {
      expect(getByTestId($document, 'form-label')).toBeTruthy()
      expect(getByTestId($document, 'form-label').textContent).toContain("Login")
    })
  })

})

If a breakpoint is set at the line starting with await waitFor(() => { with headless mode false the page does show the expected content.

When the script is executed it fails at the first expectation with the following error.

Expected container to be an Element, a Document or a DocumentFragment but got ElementHandle.

Ignored nodes: comments, script, style

TypeError: Expected container to be an Element, a Document or a DocumentFragment but got ElementHandle.

Ignored nodes: comments, script, style

Adding console.log(Document :${JSON.stringify($document)}) before the expectation shows that $document is empty.

Any idea how to get the current page content ?


问:
loop offset's api in apps scripts
There is a code, it’s working, everything is cool, but it only returns part of the data, the rest should be displayed if you change the «offset» parameter to a large size, but the problem is that I don’t know how to do this and display all the results in the Google spreadsheet (Apps Scripts)

```<code>function getReturn() {
  const url = 'https://api.com/v3/posting/fbs/list'
  const headerParameters = {
    'Client-Id': '',
    'Api-Key': ''
  }
  const requestBody = {
    "dir": "ASC",
    "filter": {
        "since": "2022-09-06T00:00:00.000Z",
        "to": "2022-12-02T23:59:59.000Z"
    },
    "limit": 1000,
    "offset": 0, // After 1000 requests, it should increase by 1000
    "translit": true,
    "with": {
        "analytics_data": false,
        "financial_data": false
    }
  }
  const options = {
    headers: headerParameters,
    method: "POST",
    payload: JSON.stringify(requestBody)
  }
  const dataAsText = UrlFetchApp.fetch(url, options).getContentText();
  const data = JSON.parse(dataAsText)
  const results = data.result.postings.map(post => {
    return [post['posting_number'], post['status'], post['in_process_at'], post.delivery_method['id']]
  })
  return(results)
}
</code>```

Instead of the first 1000 requests, I expect to receive as many requests as possible

Title: loop offset's api in apps scripts

Body:
There is a code, it’s working, everything is cool, but it only returns part of the data, the rest should be displayed if you change the «offset» parameter to a large size, but the problem is that I don’t know how to do this and display all the results in the Google spreadsheet (Apps Scripts)

function getReturn() {
  const url = 'https://api.com/v3/posting/fbs/list'
  const headerParameters = {
    'Client-Id': '',
    'Api-Key': ''
  }
  const requestBody = {
    "dir": "ASC",
    "filter": {
        "since": "2022-09-06T00:00:00.000Z",
        "to": "2022-12-02T23:59:59.000Z"
    },
    "limit": 1000,
    "offset": 0, // After 1000 requests, it should increase by 1000
    "translit": true,
    "with": {
        "analytics_data": false,
        "financial_data": false
    }
  }
  const options = {
    headers: headerParameters,
    method: "POST",
    payload: JSON.stringify(requestBody)
  }
  const dataAsText = UrlFetchApp.fetch(url, options).getContentText();
  const data = JSON.parse(dataAsText)
  const results = data.result.postings.map(post => {
    return [post['posting_number'], post['status'], post['in_process_at'], post.delivery_method['id']]
  })
  return(results)
}

Instead of the first 1000 requests, I expect to receive as many requests as possible


问:
How to send multiple (list) json objects inside text file to run 'ab' load test POST request?
I would like to send multiple POST requests with multiple json objects inside text file to the python server using apache bench load test tool.

```<code>ab -p sample.txt -T application/json -c 2 -n 4 http://localhost:8080/xxxx
</code>```

If sample.txt contains single instance of json, it works fine

```<code>{"first_name":"Clara","last_name":"Gislason"}

</code>```

however when sample.txt contains list of json objects as below, it doesn't work.

```<code>[{"first_name":"Clara","last_name":"Gislason"},{"first_name":"Meaghan","last_name":"Jenkins"}]

</code>```

Can someone help?

Body:
I would like to send multiple POST requests with multiple json objects inside text file to the python server using apache bench load test tool.

ab -p sample.txt -T application/json -c 2 -n 4 http://localhost:8080/xxxx

If sample.txt contains single instance of json, it works fine

{"first_name":"Clara","last_name":"Gislason"}

however when sample.txt contains list of json objects as below, it doesn't work.

[{"first_name":"Clara","last_name":"Gislason"},{"first_name":"Meaghan","last_name":"Jenkins"}]

Can someone help?


问:
asyncio.wait_for(asyncio.shield, timeout=60000) doesn't wait for the task to finish
I have the following code in Python to interact with S3 objects:

```<code>import boto3
import botocore.exceptions as bexc
import asyncio
import aioboto3
from aiobotocore.session import get_session
import gzip
import utils.processor as processor

async def download_s3_async(self, file):
    session = aioboto3.Session(profile_name=self.current_profile)

    async with session.client("s3") as client:
        start_log = processor.cf_get_start_time_from_filename(file.split("/")[3])
        end_log = processor.cf_get_end_time_from_filename(file.split("/")[3])

        s3_obj = await client.get_object(Bucket=self.cf_bucket, Key=file)
        task = s3_obj["Body"].read()

        try:
            cat = await asyncio.wait_for(asyncio.shield(task), timeout=60000000)
        except asyncio.TimeoutError:
            print('Gave up waiting, task canceled')

        res = gzip.decompress(cat).decode("utf-8")

        print("File with {}-{} timestamp was downloaded and decompressed".format(start_log, end_log))
        return res

async def iterate(self, files):
    result = await asyncio.gather(*map(self.download_s3_async, files))
    return result

def call_async_wrapper(self, s_time, e_time):
    files = self.get_s3_objects_list(s_time, e_time)
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(self.iterate(files))
    return results

def get_waf_actors_info(self, s_date, s_time, e_time):
    self.current_dist = "somepath/path/{}/".format(str(s_date).replace("-", ""))
    self.call_async_wrapper(s_date, s_time, e_time)

</code>```

Files are downloaded for some time, but then suddenly asyncio.TimeoutError is caught and the task gets cancelled. And it's less than a minute (tried 1000000 timeouts as well).

What am I doing wrong?

```<code>...
File with 00:01:29-00:01:59 timestamp was downlaoded and decompressed
File with 00:00:24-00:00:54 timestamp was downlaoded and decompressed
File with 00:03:33-00:04:03 timestamp was downlaoded and decompressed
File with 00:07:01-00:07:31 timestamp was downlaoded and decompressed
File with 00:01:01-00:01:31 timestamp was downlaoded and decompressed
File with 00:06:14-00:06:44 timestamp was downlaoded and decompressed
File with 00:03:59-00:04:29 timestamp was downlaoded and decompressed
File with 00:03:02-00:03:32 timestamp was downlaoded and decompressed
File with 00:09:06-00:09:36 timestamp was downlaoded and decompressed
File with 00:04:12-00:04:42 timestamp was downlaoded and decompressed
File with 00:02:32-00:03:02 timestamp was downlaoded and decompressed
File with 00:02:23-00:02:53 timestamp was downlaoded and decompressed
File with 00:00:08-00:00:38 timestamp was downlaoded and decompressed
File with 00:09:31-00:10:01 timestamp was downlaoded and decompressed
File with 00:00:23-00:00:53 timestamp was downlaoded and decompressed
Gave up waiting, task canceled
</code>```

Should not asyncio.shield prevent the task from timing out?

Body:
I have the following code in Python to interact with S3 objects:

import boto3
import botocore.exceptions as bexc
import asyncio
import aioboto3
from aiobotocore.session import get_session
import gzip
import utils.processor as processor

async def download_s3_async(self, file):
    session = aioboto3.Session(profile_name=self.current_profile)

    async with session.client("s3") as client:
        start_log = processor.cf_get_start_time_from_filename(file.split("/")[3])
        end_log = processor.cf_get_end_time_from_filename(file.split("/")[3])

        s3_obj = await client.get_object(Bucket=self.cf_bucket, Key=file)
        task = s3_obj["Body"].read()

        try:
            cat = await asyncio.wait_for(asyncio.shield(task), timeout=60000000)
        except asyncio.TimeoutError:
            print('Gave up waiting, task canceled')

        res = gzip.decompress(cat).decode("utf-8")

        print("File with {}-{} timestamp was downloaded and decompressed".format(start_log, end_log))
        return res

async def iterate(self, files):
    result = await asyncio.gather(*map(self.download_s3_async, files))
    return result

def call_async_wrapper(self, s_time, e_time):
    files = self.get_s3_objects_list(s_time, e_time)
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(self.iterate(files))
    return results

def get_waf_actors_info(self, s_date, s_time, e_time):
    self.current_dist = "somepath/path/{}/".format(str(s_date).replace("-", ""))
    self.call_async_wrapper(s_date, s_time, e_time)

Files are downloaded for some time, but then suddenly asyncio.TimeoutError is caught and the task gets cancelled. And it's less than a minute (tried 1000000 timeouts as well).

What am I doing wrong?

...
File with 00:01:29-00:01:59 timestamp was downlaoded and decompressed
File with 00:00:24-00:00:54 timestamp was downlaoded and decompressed
File with 00:03:33-00:04:03 timestamp was downlaoded and decompressed
File with 00:07:01-00:07:31 timestamp was downlaoded and decompressed
File with 00:01:01-00:01:31 timestamp was downlaoded and decompressed
File with 00:06:14-00:06:44 timestamp was downlaoded and decompressed
File with 00:03:59-00:04:29 timestamp was downlaoded and decompressed
File with 00:03:02-00:03:32 timestamp was downlaoded and decompressed
File with 00:09:06-00:09:36 timestamp was downlaoded and decompressed
File with 00:04:12-00:04:42 timestamp was downlaoded and decompressed
File with 00:02:32-00:03:02 timestamp was downlaoded and decompressed
File with 00:02:23-00:02:53 timestamp was downlaoded and decompressed
File with 00:00:08-00:00:38 timestamp was downlaoded and decompressed
File with 00:09:31-00:10:01 timestamp was downlaoded and decompressed
File with 00:00:23-00:00:53 timestamp was downlaoded and decompressed
Gave up waiting, task canceled

Should not asyncio.shield prevent the task from timing out?


问:
In vb.net, how to change the color of each individual point of a point or line chart
After adding a new point, I try to set its color, but it doesn't work:

```<code>dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, Yvalue )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.Green
</code>```

I want different color depending on Yvalue.

Body:
After adding a new point, I try to set its color, but it doesn't work:

dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, Yvalue )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.Green

I want different color depending on Yvalue.


问:
Cannot understand why eval is passed in as an argument, i.e., df.<COL_NAME>.apply(eval).apply(np.array) before further processing of the col
I am new to python and I was going through this piece of code available on OpenAI. It is trying to read a CSV and create a dataframe. I checked that in the dataframe, there is already a column named "babbage_search", which contains vectors. What I don't understand is why do we need to pass eval as an argument in this line of code:

```<code>df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)
</code>```

If I remove .apply(eval), I get an error:

```<code>ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U45750'), dtype('<U23')) -> None
</code>```

This is the code snippet:

```<code>import pandas as pd
import numpy as np
from openai.embeddings_utils import get_embedding, cosine_similarity

datafile_path = "../ReviewsWithEmbeddings.csv"
df = pd.read_csv(datafile_path)
df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)

# search through the reviews for a specific product
def search_reviews(df, product_description, n=3, pprint=True):
    embedding = get_embedding(
        product_description,
        engine="text-search-babbage-query-001"
    )
    df["similarities"] = df.babbage_search.apply(lambda x: cosine_similarity(x, embedding))
    print('SIMILARITIES:', df.similarities)
    res = (
        df.sort_values("similarities", ascending=False)
        .head(n)
        .combined.str.replace("Title: ", "")
        .str.replace("; Content:", ": ")
    )
    if pprint:
        for r in res:
            print(r[:200])
    return res

res = search_reviews(df, "Christmas gift", n=3)
</code>```

Body:
I am new to python and I was going through this piece of code available on OpenAI. It is trying to read a CSV and create a dataframe. I checked that in the dataframe, there is already a column named "babbage_search", which contains vectors. What I don't understand is why do we need to pass eval as an argument in this line of code:

df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)

If I remove .apply(eval), I get an error:

ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U45750'), dtype('<U23')) -> None

This is the code snippet:

import pandas as pd
import numpy as np
from openai.embeddings_utils import get_embedding, cosine_similarity

datafile_path = "../ReviewsWithEmbeddings.csv"
df = pd.read_csv(datafile_path)
df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)

# search through the reviews for a specific product
def search_reviews(df, product_description, n=3, pprint=True):
    embedding = get_embedding(
        product_description,
        engine="text-search-babbage-query-001"
    )
    df["similarities"] = df.babbage_search.apply(lambda x: cosine_similarity(x, embedding))
    print('SIMILARITIES:', df.similarities)
    res = (
        df.sort_values("similarities", ascending=False)
        .head(n)
        .combined.str.replace("Title: ", "")
        .str.replace("; Content:", ": ")
    )
    if pprint:
        for r in res:
            print(r[:200])
    return res

res = search_reviews(df, "Christmas gift", n=3)


问:
Issue when login a site using Selenium Webdriver
I want to automate a site login for test and  I am using C# and Selenium ChromeWebDriver.

My code is down below here:

```<code>ChromeOptions options = new();
options.AddArgument("--incognito");
options.AddArgument("--start-maximized");
options.AddArgument("--disable-site-isolation-trials");
options.AddArgument("--disable-features=NetworkService,NetworkServiceInProcess");
//options.AddArgument("--allow-cross-origin-auth-prompt");
//options.AddArgument("--allow-reading-third-party-cookies");
//options.AddArgument("--allow-third-party-cookies");

ChromeDriver driver = new("./", options, TimeSpan.FromMinutes(10));
EventFiringWebDriver eventDriver = new(driver);

driver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(10);

driver.Navigate().GoToUrl("https://xxxx.xx.xx");

//WebDriverWait wait = new(driver, TimeSpan.FromSeconds(1));
</code>```

If I run this code, I am navigated to the Url and if I input login credentials and click sign in button, no result is shown up just like the sign in button has no functionality.

I opened my dev panel and I can see the request is posting every time I press the sign in button, but no result:

The header of request is:

```<code>Request URL: https://xxxx.xx.xx/authprovider/webtoken
Referrer Policy: strict-origin-when-cross-origin
</code>```

I tried it on my normal chrome browser, incognito mode, guest mode and everything was working fine.

If all things go well, the request header must be like this:

```<code>Request URL: https://xxxx.xx.xx/authprovider/webtoken
Request Method: POST
Status Code: 200 OK (from service worker)
Referrer Policy: strict-origin-when-cross-origin
</code>```

And there is also response header incoming too.

I searched for answer for over 10 hours, but still can't this problem.

I am new to Selenium and I can't even make my first step.

Please if anyone has experienced with this problem or anyone expert, give me correct guide about this problem.

EDIT:

If thing go well, the bearer token should be received as response, but no response is coming.

And the response should be coming in like this:

```<code>access_token : "5a1e5347-49f8-4a3f-becf-da1f43079279"
expires_in : 4404
message : "SUCESS"
refresh_token : "95f72d9f-694a-4953-8f18-c010500f1a64"
token_type : "bearer"
</code>```

Body:
I want to automate a site login for test and  I am using C# and Selenium ChromeWebDriver.

My code is down below here:

ChromeOptions options = new();
options.AddArgument("--incognito");
options.AddArgument("--start-maximized");
options.AddArgument("--disable-site-isolation-trials");
options.AddArgument("--disable-features=NetworkService,NetworkServiceInProcess");
//options.AddArgument("--allow-cross-origin-auth-prompt");
//options.AddArgument("--allow-reading-third-party-cookies");
//options.AddArgument("--allow-third-party-cookies");

ChromeDriver driver = new("./", options, TimeSpan.FromMinutes(10));
EventFiringWebDriver eventDriver = new(driver);

driver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(10);

driver.Navigate().GoToUrl("https://xxxx.xx.xx");

//WebDriverWait wait = new(driver, TimeSpan.FromSeconds(1));

If I run this code, I am navigated to the Url and if I input login credentials and click sign in button, no result is shown up just like the sign in button has no functionality.

I opened my dev panel and I can see the request is posting every time I press the sign in button, but no result:

The header of request is:

Request URL: https://xxxx.xx.xx/authprovider/webtoken
Referrer Policy: strict-origin-when-cross-origin

I tried it on my normal chrome browser, incognito mode, guest mode and everything was working fine.

If all things go well, the request header must be like this:

Request URL: https://xxxx.xx.xx/authprovider/webtoken
Request Method: POST
Status Code: 200 OK (from service worker)
Referrer Policy: strict-origin-when-cross-origin

And there is also response header incoming too.

I searched for answer for over 10 hours, but still can't this problem.

I am new to Selenium and I can't even make my first step.

Please if anyone has experienced with this problem or anyone expert, give me correct guide about this problem.

EDIT:

If thing go well, the bearer token should be received as response, but no response is coming.

And the response should be coming in like this:

access_token : "5a1e5347-49f8-4a3f-becf-da1f43079279"
expires_in : 4404
message : "SUCESS"
refresh_token : "95f72d9f-694a-4953-8f18-c010500f1a64"
token_type : "bearer"


问:
23505: could not create unique index "IX_TechneDestinationSectionTitles_NormalizedName" DETAIL: Key ("NormalizedName")=() is duplicated
Fields of my Entity are Id, Title, NormalizedName & An enum.class file After edit in configuration,configurartion file I added Migration. After that I tried to update db. Then I got this Error enter image description here</p>


问:
How to replace a character with string in Span<char>?
I'm currently trying to replace few specific characters with other characters in Span<char>. In my case, I'm trying to replace a space with _ and ' with &27. Should I just

```<code>Span<char>.ToString().Replace("'", "&27")
</code>```

at end of the method?

```<code>Span<char> span = stackalloc char[byte.MaxValue];
for (int i = 0, c = name.Length; i < c; i++) {
    char old = name[i];
    span[i] = old switch {
        ' ' => '_',
        '\'' => char.MinValue,
        _ => name[i]
    };

    if (span[i] is char.MinValue) {
        ReadOnlySpan<char> a = span[(i + 1)..^2];
        span[i] = '&';
        span[i + 1] = '2';
        span[i + 2] = '7';
        span[(i + 3)..^2] = a;
    }
}

return span.ToString();
</code>```

I tried that, but Visual Studio gives an error at span[(i + 3)..^2].

Body:
I'm currently trying to replace few specific characters with other characters in Span<char>. In my case, I'm trying to replace a space with _ and ' with &27. Should I just

Span<char>.ToString().Replace("'", "&27")

at end of the method?

Span<char> span = stackalloc char[byte.MaxValue];
for (int i = 0, c = name.Length; i < c; i++) {
    char old = name[i];
    span[i] = old switch {
        ' ' => '_',
        '\'' => char.MinValue,
        _ => name[i]
    };

    if (span[i] is char.MinValue) {
        ReadOnlySpan<char> a = span[(i + 1)..^2];
        span[i] = '&';
        span[i + 1] = '2';
        span[i + 2] = '7';
        span[(i + 3)..^2] = a;
    }
}

return span.ToString();

I tried that, but Visual Studio gives an error at span[(i + 3)..^2].