问:
d3js pan with touchpad or mousewheel pressed
I've created zoom behaviour with d3js

```<code>const zoom = d3
      .zoom<SVGSVGElement, unknown>()
      .filter(function (event) {
        return event.which === 2 || event.type === 'wheel';
      })
      .scaleExtent([-10, 10])
      .on('zoom', handleZoom);
</code>```

if i press the mousewheel and move the mouse then pan works, but on touchpad if i put two fingers on the touchpad and move them in the same direction i expect pan effect but zoom works instead. Is there some way to filter the event for pan using touchpad?

const { useEffect } = React;

const App = () => {

  const handleZoom = (event) => {
      d3.select('#group').attr('transform', event.transform);
  }

  useEffect(()=>{
    const zoom = d3
      .zoom()
      .filter(function (event) {
        return event.which === 2 || event.type === 'wheel';
      })
      .scaleExtent([-10, 10])
      .on('zoom', handleZoom);
      d3.select('#workflow').call(zoom)
  }, [handleZoom])

  return (
    <svg id="workflow">
      <g id="group">
        <foreignObject x="100" y="50">

Node 1

        </foreignObject>
        <foreignObject x="200" y="150">

Node 2

        </foreignObject>
      </g>
    </svg>
  )
}

const root = ReactDOM.createRoot(
  document.getElementById('app')
);

root.render(<App/>)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

html, body, #app {
  width: 100%;
  height: 100%;
}

#workflow {
  width: 100%;
  height: 100%;
}

foreignObject {
  width: 1px;
  height: 1px;
  overflow: visible;
}

foreignObject > div {
 padding: 10px;
 background-color: #c0c0c0;
 border-radius: 10px;
 width: 100px
}</code>```

```

I want to set up d3 to work by scrolling the mouse wheel or zoom in/out on the touchpad, and pan to work by holding down the mouse wheel or moving two fingers on the touchpad in the same direction

Body:
I've created zoom behaviour with d3js

const zoom = d3
      .zoom<SVGSVGElement, unknown>()
      .filter(function (event) {
        return event.which === 2 || event.type === 'wheel';
      })
      .scaleExtent([-10, 10])
      .on('zoom', handleZoom);

if i press the mousewheel and move the mouse then pan works, but on touchpad if i put two fingers on the touchpad and move them in the same direction i expect pan effect but zoom works instead. Is there some way to filter the event for pan using touchpad?

const { useEffect } = React;

const App = () => {

  const handleZoom = (event) => {
      d3.select('#group').attr('transform', event.transform);
  }

  useEffect(()=>{
    const zoom = d3
      .zoom()
      .filter(function (event) {
        return event.which === 2 || event.type === 'wheel';
      })
      .scaleExtent([-10, 10])
      .on('zoom', handleZoom);
      d3.select('#workflow').call(zoom)
  }, [handleZoom])

  return (
    <svg id="workflow">
      <g id="group">
        <foreignObject x="100" y="50">

Node 1

        </foreignObject>
        <foreignObject x="200" y="150">

Node 2

        </foreignObject>
      </g>
    </svg>
  )
}

const root = ReactDOM.createRoot(
  document.getElementById('app')
);

root.render(<App/>)

* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

html, body, #app {
  width: 100%;
  height: 100%;
}

#workflow {
  width: 100%;
  height: 100%;
}

foreignObject {
  width: 1px;
  height: 1px;
  overflow: visible;
}

foreignObject > div {
 padding: 10px;
 background-color: #c0c0c0;
 border-radius: 10px;
 width: 100px
}

I want to set up d3 to work by scrolling the mouse wheel or zoom in/out on the touchpad, and pan to work by holding down the mouse wheel or moving two fingers on the touchpad in the same direction


来源: stackexchange

问:
I try to customize the class that calculates LSTM loss values. There is no problem with the data, but the loss value cannot be calculated
```<code>class RmseLoss(torch.nn.Module):
    def __init__(self):
        super(RmseLoss, self).__init__()

    def forward(self, output, target):
        ny = target.shape[0]
        loss = 0
        for k in range(ny):
            p0 = output[:k, :]
            t0 = target[:k, :]
            mask = p0 == p0
            p = p0[mask]
            t = t0[mask]
            temp = torch.sqrt(((p - t) ** 2).mean())
            loss = loss + temp
        return loss
</code>```

mask are all 'True',and temp can be calculated,but the result of loss is tensor (nan)

ContentLicense: CC BY-SA 4.0

Body:
class RmseLoss(torch.nn.Module):
    def __init__(self):
        super(RmseLoss, self).__init__()

    def forward(self, output, target):
        ny = target.shape[0]
        loss = 0
        for k in range(ny):
            p0 = output[:k, :]
            t0 = target[:k, :]
            mask = p0 == p0
            p = p0[mask]
            t = t0[mask]
            temp = torch.sqrt(((p - t) ** 2).mean())
            loss = loss + temp
        return loss

mask are all 'True',and temp can be calculated,but the result of loss is tensor (nan)


问:
How to keep index on a grouped dataframe before converting to tensor
I'm having a issue where I'm tring to take this dataframe df:

```<code>         t1                 t2
0         1           some string
1         4           some string1
2         5           some string2
3         1           some string3
4         4           some string4
</code>```

into:

```<code>         t1                 t2
0         1          [some string, some string3]
1         4          [some string1, some string4]
2         5          [some string2]
</code>```

Have like 10000 rows, and the t2 column value can end up getting large.
This data will also be transformed to a tensor after.

```<code>dataset = tf.data.Dataset.from_tensor_slices(dict(df))
</code>```

Anyone encountered the same issue or have a solution?

This method here:

```<code>df['t2'] = df.groupby(['t1'])['t2'].apply(list)
</code>```

Gives me:

```<code>t1
1         [some string, some string3]
4         [some string1, some string4]
5         [some string2]
</code>```

Body:
I'm having a issue where I'm tring to take this dataframe df:

         t1                 t2
0         1           some string
1         4           some string1
2         5           some string2
3         1           some string3
4         4           some string4

into:

         t1                 t2
0         1          [some string, some string3]
1         4          [some string1, some string4]
2         5          [some string2]

Have like 10000 rows, and the t2 column value can end up getting large.
This data will also be transformed to a tensor after.

dataset = tf.data.Dataset.from_tensor_slices(dict(df))

Anyone encountered the same issue or have a solution?

This method here:

df['t2'] = df.groupby(['t1'])['t2'].apply(list)

Gives me:

t1
1         [some string, some string3]
4         [some string1, some string4]
5         [some string2]


问:
Selenium - Unable to pick particular rows from TestData excel file
I am trying to build the TestDataReader.java file. My code should pick only the rows which are tagged by the particular testcaseid (For eg: for Test Case 1, it should pick only rows with TC_001, for Test Case 2 it should pick only rows with TC_002) and return the data to the Dataprovider method. With the below attached code, When i pass Test Case ID as TC_002, it is putting null in the testData[rowNum][0] column for rows with TC_001.
My expectation is that i should get rows only for TC_002. it should not process for TC_001.
Please suggest what is incorrect in this code.

Below is my TestDatareader class:

```<code>package com.automation.website.kaspick.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestDataReader {

    XSSFWorkbook xlWorkbook = null;
    XSSFSheet sheet = null;
    XSSFRow row = null;
    XSSFCell cell = null;

    String currentDir = Paths.get("").toAbsolutePath().toString();
    String testDataFileName = "\\TestData\\TestData.xlsx";
    String sheetName = null;

    String xlFilePath = currentDir + testDataFileName;

    public Object[][] readTestData(String sheetName, String testCaseID) throws IOException {
        String rowHeader = null;
        String columnValue = null;
        FileInputStream fileInputStream = new FileInputStream(xlFilePath);
        xlWorkbook = new XSSFWorkbook(fileInputStream);
        sheet = xlWorkbook.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for
                                                        // DataProvider

        if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
            for (int rowNum = 0; rowNum < rowCount; rowNum++) {
                HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
                row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
                int columnCount = row.getLastCellNum();
                for (int colNum = 0; colNum < columnCount; colNum++) {
                    rowHeader = sheet.getRow(0).getCell(colNum).toString();
                    if(colNum==0 && !row.getCell(colNum).toString().equalsIgnoreCase(testCaseID)) {
                        break;
                    }
                    if (row.getCell(colNum) != null) {
                        columnValue = row.getCell(colNum).toString();
                    } else {
                        columnValue = "";
                    }
                    testDataInEachRow.put(rowHeader, columnValue);
                }

            }
            testData[rowNum][0] = testDataInEachRow;
        }
        return testData;
    }
}
</code>```

Below is my Test Data. I have masked the data
[TestData.xlsx][1]
[1]: https://i.stack.imgur.com/h6cMf.png

Body:
I am trying to build the TestDataReader.java file. My code should pick only the rows which are tagged by the particular testcaseid (For eg: for Test Case 1, it should pick only rows with TC_001, for Test Case 2 it should pick only rows with TC_002) and return the data to the Dataprovider method. With the below attached code, When i pass Test Case ID as TC_002, it is putting null in the testData[rowNum][0] column for rows with TC_001.
My expectation is that i should get rows only for TC_002. it should not process for TC_001.
Please suggest what is incorrect in this code.

Below is my TestDatareader class:

package com.automation.website.kaspick.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestDataReader {

    XSSFWorkbook xlWorkbook = null;
    XSSFSheet sheet = null;
    XSSFRow row = null;
    XSSFCell cell = null;

    String currentDir = Paths.get("").toAbsolutePath().toString();
    String testDataFileName = "\\TestData\\TestData.xlsx";
    String sheetName = null;

    String xlFilePath = currentDir + testDataFileName;

    public Object[][] readTestData(String sheetName, String testCaseID) throws IOException {
        String rowHeader = null;
        String columnValue = null;
        FileInputStream fileInputStream = new FileInputStream(xlFilePath);
        xlWorkbook = new XSSFWorkbook(fileInputStream);
        sheet = xlWorkbook.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for
                                                        // DataProvider

        if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
            for (int rowNum = 0; rowNum < rowCount; rowNum++) {
                HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
                row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
                int columnCount = row.getLastCellNum();
                for (int colNum = 0; colNum < columnCount; colNum++) {
                    rowHeader = sheet.getRow(0).getCell(colNum).toString();
                    if(colNum==0 && !row.getCell(colNum).toString().equalsIgnoreCase(testCaseID)) {
                        break;
                    }
                    if (row.getCell(colNum) != null) {
                        columnValue = row.getCell(colNum).toString();
                    } else {
                        columnValue = "";
                    }
                    testDataInEachRow.put(rowHeader, columnValue);
                }

            }
            testData[rowNum][0] = testDataInEachRow;
        }
        return testData;
    }
}

Below is my Test Data. I have masked the data
[TestData.xlsx][1]
[1]: https://i.stack.imgur.com/h6cMf.png


问:
Upgrade Yii 2 - no composer
I have no prior experience with Yii, and their documentation did not provide answers to my questions, so here we are:

I have a Yii2 project (2.0.42), which has been installed without composer. Can I upgrade it to the latest version using composer? If yes, how can I do that?

If that is not possible, how can I upgrade it to the latest version using the archive file that I have downloaded?

Title: Upgrade Yii 2 - no composer


问:
Laravel Json array data display blade file
I have three column with different data. every column store data in json format, but now i want to display them, but its not working: Bellow my code:

Response:

```<code>"[{"type":"pllet-a","price_km":50,"size":28000,},{"type":"pellet-b","price_km":40,"size":20000,}]"
</code>```

I want to display only value Example (50 km) in foreach loop. What is the way to fix it into laravel blade file. I have tired json_decode but not working.

Body:
I have three column with different data. every column store data in json format, but now i want to display them, but its not working: Bellow my code:

Response:

"[{"type":"pllet-a","price_km":50,"size":28000,},{"type":"pellet-b","price_km":40,"size":20000,}]"

I want to display only value Example (50 km) in foreach loop. What is the way to fix it into laravel blade file. I have tired json_decode but not working.


问:
Does CLR load entire assembly when only one class is referenced?
In java bytecode for each class is stored in separate file and once the class is referenced, JVM goes ahead and finds and loads this class. CLR bytecode is stored in a single dll with each of the classes of the assembly.

Will runtime load the entire assembly even if I reference only one type from it?


问:
Username Restriction in firebase using xamarin form
My problem is how to avoid duplication of username in xamarin using firebase.

My expected output is upon tapping the username field, if in the database, "usernametest123" is already in there and a new customer upon his/her creating account to my app, and enter a username "usernametest123", a toast will appear like "Username is already exist".
I tried this way;
my code behind.
`

```<code> async public void CreateAccount_Clicked(System.Object sender, System.EventArgs e)
{
try{
//thats how I declare some variable up to my 11 input fields
 string FName = textfield_Firstname.Text;
 if (string.IsNullOrEmpty(FName )){await this.DisplayToastAsync("Please Enter your first name", 1500);}
//up to 11 input fields also

                CUSTOMER customer = new CUSTOMER();
                customer.CustomerFName = FName;
                var Savedata = await customerRepo.Save(customer);
}
catch(Exception ex){
if(ex.Message.Contains("USERNAME_EXISTS"))
                {
                    await this.DisplayToastAsync("Username already Exist", 1500);
                }
                else
                {
                    await this.DisplayToastAsync(ex.Message,1500);
                }
}

}
</code>```

`
any link that will posted about my concern will be appreciated thank you so much

Body:
My problem is how to avoid duplication of username in xamarin using firebase.

My expected output is upon tapping the username field, if in the database, "usernametest123" is already in there and a new customer upon his/her creating account to my app, and enter a username "usernametest123", a toast will appear like "Username is already exist".
I tried this way;
my code behind.
`

 async public void CreateAccount_Clicked(System.Object sender, System.EventArgs e)
{
try{
//thats how I declare some variable up to my 11 input fields
 string FName = textfield_Firstname.Text;
 if (string.IsNullOrEmpty(FName )){await this.DisplayToastAsync("Please Enter your first name", 1500);}
//up to 11 input fields also

                CUSTOMER customer = new CUSTOMER();
                customer.CustomerFName = FName;
                var Savedata = await customerRepo.Save(customer);
}
catch(Exception ex){
if(ex.Message.Contains("USERNAME_EXISTS"))
                {
                    await this.DisplayToastAsync("Username already Exist", 1500);
                }
                else
                {
                    await this.DisplayToastAsync(ex.Message,1500);
                }
}

}

`
any link that will posted about my concern will be appreciated thank you so much


问:
Converting a docx Node.js buffer into pdf file
I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.

`

```<code>exports.Resolution = functions.https.onCall(async (data, context) => {

  const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
  const templateRef = await admin.storage().bucket()
      .file(file_name);
  const template_content = (await templateRef.download())[0];
  const zip = new PizZip(template_content);

  let doc;
  try {
    doc = new Docxtemplater(zip, { linebreaks: true });
  } catch (error) {
    // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
    errorHandler(error);
  }

  doc.setData({
    date: data.date,
    investorName: data.investorName,
    companyName: data.companyName,
    regNo: data.regNo,
    agreements: data.agreements,
    governmentEntity: data.governmentEntity,
    directors: data.directors,
    equityStake: data.equityStake,
    governmentEntityName: data.governmentEntityName,
    fccp: data.fccp,
    investorDirector:data.investorDirector,
    equity: data.equity

  });

  try {
    doc.render();
  } catch (error) {
    errorHandler(error);
  }

  const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });

  const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
  const printer = new PdfPrinter(fontss);
  const chunks = [];

  const pdfDoc = printer.createPdfKitDocument(contentBuffer);
  pdfDoc.on('data', (chunk) => {
    chunks.push(chunk);
  });

  pdfDoc.on('end', async () => {

    const result = Buffer.concat(chunks);

    function mail (){
      const dest = context.auth.token.email;
         const mailOptions = {
             from: 'MPC <mypocketcounsel@gmail.com>',
             to: dest,
             cc:data.extraEmail,
             subject: 'Resolution Approving Transaction',
             text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
             attachments: [
              {
                filename: nameofFile+'.docx',
                content: contentBuffer
             },
               {
                filename: nameofFile +'.pdf',
                contentType: 'application/pdf',
                content: result

            }
           ]
         };

         // returning result
         return transporter.sendMail(mailOptions);

     }
   return mail();
  });

  pdfDoc.on('error', (err) => {
    return functions.logger.log('An error occured!');
  });

  pdfDoc.end();

});
</code>```

`

This is the function that generates both the docx file and the pdf for me.

Body:
I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.

`

exports.Resolution = functions.https.onCall(async (data, context) => {

  const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
  const templateRef = await admin.storage().bucket()
      .file(file_name);
  const template_content = (await templateRef.download())[0];
  const zip = new PizZip(template_content);

  let doc;
  try {
    doc = new Docxtemplater(zip, { linebreaks: true });
  } catch (error) {
    // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
    errorHandler(error);
  }

  doc.setData({
    date: data.date,
    investorName: data.investorName,
    companyName: data.companyName,
    regNo: data.regNo,
    agreements: data.agreements,
    governmentEntity: data.governmentEntity,
    directors: data.directors,
    equityStake: data.equityStake,
    governmentEntityName: data.governmentEntityName,
    fccp: data.fccp,
    investorDirector:data.investorDirector,
    equity: data.equity

  });

  try {
    doc.render();
  } catch (error) {
    errorHandler(error);
  }

  const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });

  const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
  const printer = new PdfPrinter(fontss);
  const chunks = [];

  const pdfDoc = printer.createPdfKitDocument(contentBuffer);
  pdfDoc.on('data', (chunk) => {
    chunks.push(chunk);
  });

  pdfDoc.on('end', async () => {

    const result = Buffer.concat(chunks);

    function mail (){
      const dest = context.auth.token.email;
         const mailOptions = {
             from: 'MPC <mypocketcounsel@gmail.com>',
             to: dest,
             cc:data.extraEmail,
             subject: 'Resolution Approving Transaction',
             text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
             attachments: [
              {
                filename: nameofFile+'.docx',
                content: contentBuffer
             },
               {
                filename: nameofFile +'.pdf',
                contentType: 'application/pdf',
                content: result

            }
           ]
         };

         // returning result
         return transporter.sendMail(mailOptions);

     }
   return mail();
  });

  pdfDoc.on('error', (err) => {
    return functions.logger.log('An error occured!');
  });

  pdfDoc.end();

});

`

This is the function that generates both the docx file and the pdf for me.


问:
C# Entity Framework multiple ThenInclude?
I have the following code, which works wonderfully:

```<code>Department department = _db.Departments.Where(d => d.Id == id)
            .Include(d => d.Orders.Where(o => o.DeliveryDate >= start && o.DeliveryDate <= end))
            .ThenInclude(p => p.OrderProducts)
            .ThenInclude(x => x.Product)
            .First();
</code>```

It extracts all departments, with the list of orders, and also gets the products contained in those orders. So far so good.

However, each "Order" also has a "User" who made that order. I then tried to simple do this:

```<code>Department department = _db.Departments.Where(d => d.Id == id)
            .Include(d => d.Orders.Where(o => o.DeliveryDate >= start && o.DeliveryDate <= end))
            .ThenInclude(u => u.User)
            .ThenInclude(p => p.OrderProducts)
            .ThenInclude(x => x.Product)
            .First();
</code>```

But this does not work, and gives me the following error:
"ApplicationUser does not contain a definition for OrderProducts"

Now, i am pretty new and not 100% sure how it works, but i'm guessing it is because when i do those "nested" ThenInclude calls, that it looks for a definition on the previous included call. So here, it first gets orders, then includes the users, and then looks for products on the users (which does not exist).

Instead, i need to "go back" and use the Order as a baseline, to then get the products for the order.

How can i achieve this?

I hope my question makes sense - if not, please feel free to verbally shame me into the ground.

Thank you in advance, oh wise internet of brains.

Body:
I have the following code, which works wonderfully:

Department department = _db.Departments.Where(d => d.Id == id)
            .Include(d => d.Orders.Where(o => o.DeliveryDate >= start && o.DeliveryDate <= end))
            .ThenInclude(p => p.OrderProducts)
            .ThenInclude(x => x.Product)
            .First();

It extracts all departments, with the list of orders, and also gets the products contained in those orders. So far so good.

However, each "Order" also has a "User" who made that order. I then tried to simple do this:

Department department = _db.Departments.Where(d => d.Id == id)
            .Include(d => d.Orders.Where(o => o.DeliveryDate >= start && o.DeliveryDate <= end))
            .ThenInclude(u => u.User)
            .ThenInclude(p => p.OrderProducts)
            .ThenInclude(x => x.Product)
            .First();

But this does not work, and gives me the following error:
"ApplicationUser does not contain a definition for OrderProducts"

Now, i am pretty new and not 100% sure how it works, but i'm guessing it is because when i do those "nested" ThenInclude calls, that it looks for a definition on the previous included call. So here, it first gets orders, then includes the users, and then looks for products on the users (which does not exist).

Instead, i need to "go back" and use the Order as a baseline, to then get the products for the order.

How can i achieve this?

I hope my question makes sense - if not, please feel free to verbally shame me into the ground.

Thank you in advance, oh wise internet of brains.


问:
csharp powershell script Set-CsOnlinePstnUsage does not work and throws exception
I have the following powershell script which I am trying to execute via a c# program.

```<code>  Start-Transcript -Path /tmp/powershellpstnusage.log
  Connect-MicrosoftTeams -AccessTokens ($graphtoken, $teamstoken)
  Set-CsOnlinePstnUsage -Identity Global -Usage @{add='TEST'}
  #Get-CsOnlinePstnUsage  | ConvertTo-Json
  Disconnect-MicrosoftTeams
  Stop-Transcript
</code>```

What I want to achieve is setting pstn usage. The above script executes good if comment the line Set-CsOnlinePstnUsage and uncomment Get-CsOnlinePstnUsage. I get the current usage configured.

However if i try to run Set-CsOnlinePstnUsage I get error as below.

```<code>Unhandled exception. System.Management.Automation.CmdletInvocationException: The term 'Out-String' is not recognized as a name of a cmdlet, function, script file, or e
xecutable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
 ---> System.Management.Automation.CommandNotFoundException: The term 'Out-String' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
   at System.Management.Automation.Runspaces.Pipeline.Invoke()
</code>```

The full program is as below.

```<code>Console.WriteLine("============== setPstnOnlineUsage =================");
using (Runspace space = RunspaceFactory.CreateRunspace())
{
          space.Open();

          Console.WriteLine(this.mEToken.graphToken);
          Console.WriteLine(this.mEToken.teamsToken);

          space.SessionStateProxy.SetVariable("graphtoken", this.mEToken.graphToken);
          space.SessionStateProxy.SetVariable("teamstoken", this.mEToken.teamsToken);

          string script = @"
          Start-Transcript -Path /tmp/powershellpstnusage.log
          Connect-MicrosoftTeams -AccessTokens ($graphtoken, $teamstoken)

          Set-CsOnlinePstnUsage -Identity Global -Usage @{add='TEST'} | Out-String

          #Get-CsOnlinePstnUsage  | ConvertTo-Json

          Disconnect-MicrosoftTeams
          Stop-Transcript
      ";

      using (PowerShell ps1 = PowerShell.Create())
      {
              ps1.Runspace = space;
              ps1.AddScript(script);
              ps1.AddCommand("Out-String");

              Collection<PSObject> results = ps1.Invoke();

              var errors = ps1.Streams.Error;
              Console.WriteLine("error count {0}", errors.Count());
              if (errors.Count > 0)
              {
                  var e = errors[0].Exception;
                  Console.WriteLine(e);
                  ps1.Streams.ClearStreams();
                  throw e;
              }

              Console.WriteLine("results size {0}", results.Count());
     }
}
</code>```

I have also tried AddCommand and AddParameters to do the same but still no luck.

Body:
I have the following powershell script which I am trying to execute via a c# program.

  Start-Transcript -Path /tmp/powershellpstnusage.log
  Connect-MicrosoftTeams -AccessTokens ($graphtoken, $teamstoken)
  Set-CsOnlinePstnUsage -Identity Global -Usage @{add='TEST'}
  #Get-CsOnlinePstnUsage  | ConvertTo-Json
  Disconnect-MicrosoftTeams
  Stop-Transcript

What I want to achieve is setting pstn usage. The above script executes good if comment the line Set-CsOnlinePstnUsage and uncomment Get-CsOnlinePstnUsage. I get the current usage configured.

However if i try to run Set-CsOnlinePstnUsage I get error as below.

Unhandled exception. System.Management.Automation.CmdletInvocationException: The term 'Out-String' is not recognized as a name of a cmdlet, function, script file, or e
xecutable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
 ---> System.Management.Automation.CommandNotFoundException: The term 'Out-String' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
   at System.Management.Automation.Runspaces.Pipeline.Invoke()

The full program is as below.

Console.WriteLine("============== setPstnOnlineUsage =================");
using (Runspace space = RunspaceFactory.CreateRunspace())
{
          space.Open();

          Console.WriteLine(this.mEToken.graphToken);
          Console.WriteLine(this.mEToken.teamsToken);

          space.SessionStateProxy.SetVariable("graphtoken", this.mEToken.graphToken);
          space.SessionStateProxy.SetVariable("teamstoken", this.mEToken.teamsToken);

          string script = @"
          Start-Transcript -Path /tmp/powershellpstnusage.log
          Connect-MicrosoftTeams -AccessTokens ($graphtoken, $teamstoken)

          Set-CsOnlinePstnUsage -Identity Global -Usage @{add='TEST'} | Out-String

          #Get-CsOnlinePstnUsage  | ConvertTo-Json

          Disconnect-MicrosoftTeams
          Stop-Transcript
      ";

      using (PowerShell ps1 = PowerShell.Create())
      {
              ps1.Runspace = space;
              ps1.AddScript(script);
              ps1.AddCommand("Out-String");

              Collection<PSObject> results = ps1.Invoke();

              var errors = ps1.Streams.Error;
              Console.WriteLine("error count {0}", errors.Count());
              if (errors.Count > 0)
              {
                  var e = errors[0].Exception;
                  Console.WriteLine(e);
                  ps1.Streams.ClearStreams();
                  throw e;
              }

              Console.WriteLine("results size {0}", results.Count());
     }
}

I have also tried AddCommand and AddParameters to do the same but still no luck.


问:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file , tsx file problem
I am adding my project to monorepo , my project is nextJS 12.1.4 and when i import the UI from Package folder after all steps from the docs of Monorepo i have this problem.

I already have .babelrc file and tsconfig and it is working fine , but when adding the webpack.config.js with ts-loader it fire this error


问:
Keycloak client resources synchronization with swagger file
I'd like to ask if it possible to update Keycloak client resources automatically using swagger file?
Or just to compare swagger.json with Keycloak client resources to find discrepancies and fix it?

We have API Gateway + Keycloak + several back-end REST APIs.
For now we have to manage client resources manually via Keycloak Admin UI every time this APIs have changed.

Thanks in advance.


问:
How to solve IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
When I used the below code and an IndexError occurred. Where the details are shown below.

```<code>for _ in range(niter):

        for i in range(out.ndim):
            slicer = [slice(None, -1) if j == i else slice(None) for j in range(out.ndim)]
            deltas[i][slicer] = numpy.diff(out, axis=i)

        # update matrices
        matrices = [condgradient(delta, spacing) * delta for delta, spacing in zip(deltas, voxelspacing)]

        for i in range(out.ndim):
            slicer = [slice(1, None) if j == i else slice(None) for j in range(out.ndim)]
            matrices[i][slicer] = numpy.diff(matrices[i], axis=i)

        out += gamma * (numpy.sum(matrices, axis=0))

    return out
</code>```

How can I resolve the above error to get the below information.

sigma : integer

dim : integer
img : array_like

Input image (will be cast to numpy.float).

niter : integer

kappa : integer

gamma : float

voxelspacing : tuple of floats or array_like

```<code>File "/home/ct1/anaconda3/anisotropic_filtering.py", line 133, in anisotropic_diffusion     deltas[i][slicer] = numpy.diff(out, axis=i) IndexError: only integers, slices (\`:\`), ellipsis (\`...\`), numpy.newaxis (\`None\`) and integer or boolean arrays are valid indices
</code>```

Body:
When I used the below code and an IndexError occurred. Where the details are shown below.

for _ in range(niter):

        for i in range(out.ndim):
            slicer = [slice(None, -1) if j == i else slice(None) for j in range(out.ndim)]
            deltas[i][slicer] = numpy.diff(out, axis=i)

        # update matrices
        matrices = [condgradient(delta, spacing) * delta for delta, spacing in zip(deltas, voxelspacing)]

        for i in range(out.ndim):
            slicer = [slice(1, None) if j == i else slice(None) for j in range(out.ndim)]
            matrices[i][slicer] = numpy.diff(matrices[i], axis=i)

        out += gamma * (numpy.sum(matrices, axis=0))

    return out

How can I resolve the above error to get the below information.

sigma : integer

dim : integer
img : array_like

Input image (will be cast to numpy.float).

niter : integer

kappa : integer

gamma : float

voxelspacing : tuple of floats or array_like

File "/home/ct1/anaconda3/anisotropic_filtering.py", line 133, in anisotropic_diffusion     deltas[i][slicer] = numpy.diff(out, axis=i) IndexError: only integers, slices (\`:\`), ellipsis (\`...\`), numpy.newaxis (\`None\`) and integer or boolean arrays are valid indices


问:
Add rows for missing timestamp data in df
I have a df like this:

Line
Sensor
Day
Time
Measurement

1
A
1
10:00:00
56

2
A
1
11:00:00
42

3
A
1
12:00:00
87

4
A
1
12:20:00
12

5
A
1
12:50:00
44

I would like to create some rows. Considering that measurements should be taken every 10 minutes I would like to add a non-constant number of rows (i.e there should be 6 between line 1 and 2; two rows between line 3 and 4; 3 rows between line 4 and five)
in order to get something similar to this:

Line
Sensor
Day
Time
Measurement

1
A
1
10:00:00
56

2
A
1
10:10:00
54

3
A
1
10:20:00
35

4
A
1
10:30:00
11

5
A
1
10:40:00
45

6
A
1
10:50:00
56

7
A
1
11:00:00
90

...
...
...
...
...
...
...

13
A
1
12:00:00
87

14
A
1
12:10:00
97

15
A
1
12:20:00
42

16
A
1
12:30:00
67

4
A
1
12:40:00
76

5
A
1
12:50:00
11

Any suggestion?


问:
Strange empty grey box appears when touching View near top of my screen
A button near the top of my View is no longer clickable when I have Views with lots of padding or spacers on my page. When I reduce the padding, I am able to click the button, but only the bottom half of its image (80p tall). The top half still gives me the weird box that shows up.

It seems that the more padding / spacing I have, the further up my button goes on the screen (which is desirable), however, the button cannot be clicked above a certain y coordinate of my screen.

Has anyone seen this before? What does this empty box mean? My only guess is that its the NavigationView interfering with getting the touch, as a similar grey box occurs if I hold the back button down without releasing it.


问:
How to restart a script if a string is equal to Y or y?
```<code>public class Program
{
    public static void Main()
    {
        {
            string value;
            do
            {
                Console.WriteLine("First value to add? : ");
                int a1 = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Second value to add? : ");
                int a2 = Convert.ToInt32(Console.ReadLine());
                Console.Write(a1+a2);
                Console.WriteLine("Type Y or y to restart the program.");
                value = Console.ReadLine();
            }
            while (value == "Y" || "y");
        }
    }
}
</code>```

I get this error:

source.cs(1,1): error CS1022: Type or namespace definition, or end-of-file expected. I think that the script cant access the string but idk.

I expected that the script would restart

Body:
public class Program
{
    public static void Main()
    {
        {
            string value;
            do
            {
                Console.WriteLine("First value to add? : ");
                int a1 = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Second value to add? : ");
                int a2 = Convert.ToInt32(Console.ReadLine());
                Console.Write(a1+a2);
                Console.WriteLine("Type Y or y to restart the program.");
                value = Console.ReadLine();
            }
            while (value == "Y" || "y");
        }
    }
}

I get this error:

source.cs(1,1): error CS1022: Type or namespace definition, or end-of-file expected. I think that the script cant access the string but idk.

I expected that the script would restart


问:
Is it possible to wrap c++ code in a Kotlin/Native .klib?
The problem is that I am trying to use a C++ library with C headers in iOS, but I'm not sure how to proceed.

If yes. How?

Does anyone have a template for this?

Thanks

EDIT: this answer on Reddit is pretty good for consuming (C++?/C) to a .klib https://www.reddit.com/r/Kotlin/comments/ze1mv9/comment/iz6jav1/?utm_source=reddit&utm_medium=web2x&context=3

I still need to figure out how to consume the .klib in iOS


问:
react native nesting navigation header bottom style
friends. Let me talk about my problem

React navigation v6 version is in use.

My stack is currently nested. The problem is that only the first stack has a lower line of the header and the child stack has no lower line of the header.

And the funny thing is, in the ios simulator, the sub-stack also has a line under the header, but it's not visible on the actual device device.

This is a picture of a simulator. As you can see, there's a line under the header.

The picture below is a picture of a real device. There is no line under the header.

Did I write the wrong code overall? If you need my code, please leave a comment. I'll share the code.


问:
Export of safety *.bin-file through the TwinCAT automation interface
Is it possible to do an export (as bin-file, see red marking in the picture) of a safety project through the TwinCAT automation interface (or any other means)? I've looked through the documentation but can't find any API to do it. I've done stuff through the automation interface that is not officially supported previously, but this one I've not managed to solve.


问:
VS code with Jupyter notebook is extremely slow when re-running cells
I’ve got trouble with Jupyter in vscode. On vs code start-up, my 10 cells “run all” in about 3-4 minutes in a perfectly sensible way (loading the data and heavy calculations take time, but plotting is fast, etc). But re-running cells sometimes takes forever.

As an example, the last cell, which is just plotting the data, took 1.6s on 'run all'. When I instantly re-run that last cell (even without changing the code at all), it takes much longer to run (up to 14 minutes!). Why is that?

It isn’t a CPU or memory problem because those climb to only 30% and 75% during the runs, respectively.

I’ve seen the same error on a Jupyter notebook server. The solution was to disable “Variable Inspector nbextension”. Is there an equivalent solution when running jupyter notebooks on vs code?

UPDATE: It's only the case when the "Jupyter: Variables" pane is open. A lot of variables are shown as loading endlessly. The problem might be that the variables are too big to show?

Versions: vs code 1.73.1 / Jupyter  v2022.9.1303220346 / Python 3.10.8 / Windows 11

Note: I have pandas variables, just like in the problem in the above link.


问:
Docker Ports and Airflow Tasks Test
I'd like to ask what's the meaning of this PORT setup?

enter image description here

Sometimes I get the "5555/tcp, 8793/tcp" part and sometimes do not. So what is the function of "5555/tcp, 8793/tcp" and how does it appear when I build my Docker container?

Second question, which Docker container should I execute if I want to use command "airflow tasks test"?

Thanks

I expect to understand Docker container better especially how to use "airflow tasks test" command

Title: Docker Ports and Airflow Tasks Test


问:
How to make a table with expandable (expand and collapse) columns in React (and MUI)?
I am using Material UI table components (which is not more than a styled and convenient API for HTML table elements)  and I want to make my columns expand collapse on click.
This means that I need that when I click on a column, its sub-columns will be visible and all the rows will also show values for the sub-columns, and when I click on the main column again, the sub-columns will collapse and be invisible again, along with all the values in the rows for those sub columns.

I would also like it to be animated with a nice transition of the columns expanding from the main column into view and collapsing into the main column to invisible.

It doesn't necessarily need to be in react or using MUI, it could regular HTML and CSS, but the animations are crucial!

Thank you in advance for the help :)

I tried to use MUI tables components with the Collapse component (which is an animation component to put things into view with a nice transition) but it was neither smooth nor pretty and not even working properly as the columns were sometimes not aligned..

I've looked everywhere on google and couldn't find any example/library for such a feature anywhere.
I was only able to find examples for expand/collapse rows..


问:
I caught this error while trying to interact with a bible api
```<code>undefined:2
<!DOCTYPE html>
^

SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (F:\Udemy\WebDev\WeatherProject\app.js:11:32)
    at IncomingMessage.emit (node:events:513:28)
    at Readable.read (node:internal/streams/readable:539:10)
    at flow (node:internal/streams/readable:1023:34)
    at resume_ (node:internal/streams/readable:1004:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...
</code>```
<p>//I was trying to parse an api to my server. i am new to coding kindly take me through</p>

Body:
undefined:2
<!DOCTYPE html>
^

SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (F:\Udemy\WebDev\WeatherProject\app.js:11:32)
    at IncomingMessage.emit (node:events:513:28)
    at Readable.read (node:internal/streams/readable:539:10)
    at flow (node:internal/streams/readable:1023:34)
    at resume_ (node:internal/streams/readable:1004:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...

//I was trying to parse an api to my server. i am new to coding kindly take me through


问:
io.socket.engineio.client.EngineIOException: server error
I was trying to integrate socket io using https://socketio.github.io/socket.io-client-java/installation.html. I have followed all the steps they mentioned in the article . unfortunately, I am receiving an error while connecting the socket.  io.socket.engineio.client.EngineIOException: server error.  but I have downgrade SDK version 1.0.1 I can easily connect the socket. to use the socket on any incoming function I have to upgrade this version to 2.1.0 forcefully. but the socket is not connecting. kindly help me pls. your help will be appreciated

Socket Url: https://api.b2broker.com/socket.io/?transport=polling


问:
Alert rule in Azure not triggering?
I have created an alert rule according to the following:

https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/alerts-create-new-alert-rule?tabs=metric

My alert rule condition is Http5xx > 1.
I can make endpoint calls with Postman and Powershell and I get a Internal Server error 500 so I know there is an issue. I dont want to fix at the moment because I want to test that the alert is working.
The issue is thatthe alert is never triggered. When is the alert triggered and how does the alert rule check for the error conditions ?
Does it run certain queries periodically ?

Title: Alert rule in Azure not triggering?


问:
How to download a file from a node server, using a react client, but hiding the filename and the path
I have a client/server architecture:

the client is running a reactjs & javascript application;
the server is running a nodejs application with a redis database.

The application start with the client asking the user for his/her email

then pass the email to the server which activates a two factor authentication sending a code to the user's phone.

the server send the user's phone a random code

the user insert the received code into the client and send back to the server

the server check the code and, if correct, send to the client a list of the user's owned files.

The client display a list of files (any kind, any extension), each with a connected button.

when the user push the button, I would like to send to the server just the user's email and the selected file name.

The server must then build the real path and is then able to retrieve the file and return it to the server which should store it as in any normal download (maybe asking the user in which location it want to store the file)

I'm using Axios on the client and express on the server.

I'm not able to realize this architecture:

If I use an 'a' tag, as suggested in several sites, it seems that the entire download is managed by the client, so I have to put the entire path of the file to download, and I don't want to show it.

Have someone an idea on how to approach and solve the problem?

Thank you

Paolo


问:
Pop up progress window in ASP.Net MVC
I have a legacy ASP.NET MVC app using 4.6.1 .NET Framework.
At the moment all I have is only a spinning wheel without any indication of progress.
This is very simple: the front end sends requests -> back end processes -> sends feedback to the front end.

I would like to inform my user to say '1 of 5 processes finished'.
I am not sure what add-on or methods I should implement.
Any idea on how I start will be much appreciated, thank you.

Title: Pop up progress window in ASP.Net MVC


问:
Serving static html pages on amplify
I have a static website using BlitzJS (Similar to NextJS)
My build directory is "dist" and I have another folder "public" that contains static html page called start.html.

The issue is, when I try to open the static page inside the public page it gets redirected to non-html file name with slash, and its not opening.

I tried to use the redirect in amplify console as below, but non worked for me

```<code></^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>   /index.html 200 (Rewrite)`
</code>```

And

```<code>/public/<*> /public/start.html  404 (Rewrite)
</code>```

Thanks

Title: Serving static html pages on amplify

Body:
I have a static website using BlitzJS (Similar to NextJS)
My build directory is "dist" and I have another folder "public" that contains static html page called start.html.

The issue is, when I try to open the static page inside the public page it gets redirected to non-html file name with slash, and its not opening.

I tried to use the redirect in amplify console as below, but non worked for me

</^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>   /index.html 200 (Rewrite)`

And

/public/<*> /public/start.html  404 (Rewrite)

Thanks


问:
How to fix "Jest encountered an unexpected token"
I wrote following unit test case

```<code>import { shallowMount } from '@vue/test-utils'
import OverviewKB from '@/components/knowledgebase/OverviewKB.vue'

describe('Mounted OverviewKB', () => {
  const wrapper = shallowMount(OverviewKB);

  test('does a wrapper exist', () => {
    expect(wrapper.exists()).toBe(true)
  })
})
</code>```

Following error occurred.

Body:
I wrote following unit test case

import { shallowMount } from '@vue/test-utils'
import OverviewKB from '@/components/knowledgebase/OverviewKB.vue'

describe('Mounted OverviewKB', () => {
  const wrapper = shallowMount(OverviewKB);

  test('does a wrapper exist', () => {
    expect(wrapper.exists()).toBe(true)
  })
})

Following error occurred.


问:
Using While Loop in Postgresql

This is my points table

I want to perform FIFO(First in First out) action

The column points has real time entries and considering the first two entries that is 600 and 400 respectively

I withdraw 900 totally i need to update the first column of redeemed_points as 600 and the second one as 300

Title: Using While Loop in Postgresql


问:
nginx how to use ascii hex code in configuration file?
I would like to split a log with \x1e ascii code.

But i don't know how to escape ascii hex code in nginx configuration file.

```<code>log_format main '$request_uri\x1e$time_iso8601\x1e$remote_addr'
</code>```

\x1e is just inserted "\x1e" 4 characters.

how can i insert just x1e one ascii code?

Body:
I would like to split a log with \x1e ascii code.

But i don't know how to escape ascii hex code in nginx configuration file.

log_format main '$request_uri\x1e$time_iso8601\x1e$remote_addr'

\x1e is just inserted "\x1e" 4 characters.

how can i insert just x1e one ascii code?


问:
Converting PyTorch into Tensorflow
How can I convert the next code into TensorFlow?

```<code>import torchvision.transforms as transforms
from xy_dataset import XYDataset

TASK = 'road_following'

CATEGORIES = ['apex']

DATASETS = ['A', 'B']

TRANSFORMS = transforms.Compose([
    transforms.ColorJitter(0.2, 0.2, 0.2, 0.2),
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

datasets = {}
for name in DATASETS:
    datasets[name] = XYDataset(TASK + '_' + name, CATEGORIES, TRANSFORMS, random_hflip=True)
</code>```

I tried to change the transformers into some layers and nodes of Keras TensorFlow but it didn't work out as i expected in the first place

Title: Converting PyTorch into Tensorflow

Body:
How can I convert the next code into TensorFlow?

import torchvision.transforms as transforms
from xy_dataset import XYDataset

TASK = 'road_following'

CATEGORIES = ['apex']

DATASETS = ['A', 'B']

TRANSFORMS = transforms.Compose([
    transforms.ColorJitter(0.2, 0.2, 0.2, 0.2),
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

datasets = {}
for name in DATASETS:
    datasets[name] = XYDataset(TASK + '_' + name, CATEGORIES, TRANSFORMS, random_hflip=True)

I tried to change the transformers into some layers and nodes of Keras TensorFlow but it didn't work out as i expected in the first place


问:
Use UTF-8 with BOM in Xcode
In a cross-platform workflow, I need to keep sources files in UTF-8 with BOM encoding.

When I'm editing these files in Xcode, it opens these files in UTF-8 without BOM, stripping it from file when I save it.

UTF-8 with BOM is not available in encoding drop-down list in Xcode preferences.

Is there a way to force the use of UTF-8 with BOM in Xcode?

Title: Use UTF-8 with BOM in Xcode


问:
Swift coreml: Failed to get the home directory when checking model path
I am using this code for extracting text from image, First time the code runs perfectly after that its start giving this error message [coreml] Failed to get the home directory when checking model path. Here is the code that I am using to extract text form image. This is the same code that I have copied from that I have copied from apple documentation

```<code>func requestORC(image: UIImage) {

        //        guard let cgImage = UIImage(named: "test")?.cgImage else { return }
        guard let cgImage = image.cgImage else { return }

        //        / Create a new image-request handler.
        let requestHandler = VNImageRequestHandler(cgImage: cgImage)

        // Create a new request to recognize text.
        let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)

        do {
            // Perform the text-recognition request.
            try requestHandler.perform([request])
        } catch {
            print("Unable to perform the requests: \(error).")
        }

    }

    func recognizeTextHandler(request: VNRequest, error: Error?) {
        guard let observations =
                request.results as? [VNRecognizedTextObservation] else {
            return
        }
        let recognizedStrings = observations.compactMap { observation in
            // Return the string of the top VNRecognizedText instance.
            return observation.topCandidates(1).first?.string
        }
        // Process the recognized strings.
//        print(recognizedStrings)

        self.recognizedStrings = recognizedStrings

    }
</code>```

Body:
I am using this code for extracting text from image, First time the code runs perfectly after that its start giving this error message [coreml] Failed to get the home directory when checking model path. Here is the code that I am using to extract text form image. This is the same code that I have copied from that I have copied from apple documentation

func requestORC(image: UIImage) {

        //        guard let cgImage = UIImage(named: "test")?.cgImage else { return }
        guard let cgImage = image.cgImage else { return }

        //        / Create a new image-request handler.
        let requestHandler = VNImageRequestHandler(cgImage: cgImage)

        // Create a new request to recognize text.
        let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)

        do {
            // Perform the text-recognition request.
            try requestHandler.perform([request])
        } catch {
            print("Unable to perform the requests: \(error).")
        }

    }

    func recognizeTextHandler(request: VNRequest, error: Error?) {
        guard let observations =
                request.results as? [VNRecognizedTextObservation] else {
            return
        }
        let recognizedStrings = observations.compactMap { observation in
            // Return the string of the top VNRecognizedText instance.
            return observation.topCandidates(1).first?.string
        }
        // Process the recognized strings.
//        print(recognizedStrings)

        self.recognizedStrings = recognizedStrings

    }


问:
How to airdrop NFTs to specific wallet addresses on polygon chain eth?
I have problem how I can send airdrop from contract smart to list of addresses on polygon chain
and that after send will show like this:

pls any tutorial ?????


问:
(change) method won't be able to reflect Changes
As I'm learning Angular JS, I've created two FieldComponents: arm and orr.

As soon as arm releases any changes, Orr will need to update the changes. here is how I have implemented it, but it isn't working as it should. What am I doing wrong?

below is the function I have written and called on html, I apologize for my English I am using Translator.

```<code>inputMap.set('QueryParam.arm', this.arm.getFieldValue());
    this.services.http.fetchApi('/getArm', 'GET', inputMap, '/xxxx/publisher').subscribe(
    async (httpResponse: HttpResponse<any>) => {
        var res = httpResponse.body;
        if(res['Message']=="Success"){
          this.Orr.setValue(res['OrrCode'])
        }

        else if (this.arm.getFieldValue()=='')
        {
          this.Orr.setValue('');
        }
        this.hideSpinner();

    },
</code>```

here is the html

```<code><app-combo-box #arm category="2" fieldID="arm" [formCode]="formCode" domainObjectUrl="/arm/{xxxxxid}" domainObjectCode="arm" (blur)="genericOnBlur(arm, $event)"(change)="armfun()"></app-combo-box>
</code>```

Body:
As I'm learning Angular JS, I've created two FieldComponents: arm and orr.

As soon as arm releases any changes, Orr will need to update the changes. here is how I have implemented it, but it isn't working as it should. What am I doing wrong?

below is the function I have written and called on html, I apologize for my English I am using Translator.

inputMap.set('QueryParam.arm', this.arm.getFieldValue());
    this.services.http.fetchApi('/getArm', 'GET', inputMap, '/xxxx/publisher').subscribe(
    async (httpResponse: HttpResponse<any>) => {
        var res = httpResponse.body;
        if(res['Message']=="Success"){
          this.Orr.setValue(res['OrrCode'])
        }

        else if (this.arm.getFieldValue()=='')
        {
          this.Orr.setValue('');
        }
        this.hideSpinner();

    },

here is the html

<app-combo-box #arm category="2" fieldID="arm" [formCode]="formCode" domainObjectUrl="/arm/{xxxxxid}" domainObjectCode="arm" (blur)="genericOnBlur(arm, $event)"(change)="armfun()"></app-combo-box>


问:
Kibana Visualization of bucket aggregation data
I created an index that collects metrics for different applications and I visualize these metrics in Kibana. However, there is a field that contains bucket aggregation datas (something like that: Variable width histogram aggregation). For better undestanding I show an example of a hit:

```<code>{
  "_index": "metrics-monitoring",
  "_id": "1",
  "_version": 1,
  "_score": null,
  "_source": {
    "kind": "HISTOGRAM",
    "buckets": [
      {
        "min": -3.4028234663852886e+38,
        "max": 0,
        "count": 20
      },
      {
        "min": 0,
        "max": 5,
        "count": 9
      },
      {
        "min": 5,
        "max": 10,
        "count": 1
      },
      {
        "min": 10,
        "max": 25,
        "count": 0
      },
      {
        "min": 25,
        "max": 50,
        "count": 0
      },
      {
        "min": 50,
        "max": 75,
        "count": 0
      },
      {
        "min": 75,
        "max": 100,
        "count": 0
      },
      {
        "min": 100,
        "max": 250,
        "count": 0
      },
      {
        "min": 250,
        "max": 500,
        "count": 0
      },
      {
        "min": 500,
        "max": 750,
        "count": 0
      },
      {
        "min": 750,
        "max": 1000,
        "count": 0
      },
      {
        "min": 1000,
        "max": 2500,
        "count": 0
      },
      {
        "min": 2500,
        "max": 5000,
        "count": 0
      },
      {
        "min": 5000,
        "max": 7500,
        "count": 0
      },
      {
        "min": 7500,
        "max": 10000,
        "count": 0
      },
      {
        "min": 10000,
        "max": 3.4028234663852886e+38,
        "count": 0
      }
    ],
    "count": 349
}
</code>```

I would like to create a histogram/bar chart type visualization from the buckets field values.

Something like this just in Kibana.

How can I do this in Kibana? Is there any way to do that?

Body:
I created an index that collects metrics for different applications and I visualize these metrics in Kibana. However, there is a field that contains bucket aggregation datas (something like that: Variable width histogram aggregation). For better undestanding I show an example of a hit:

{
  "_index": "metrics-monitoring",
  "_id": "1",
  "_version": 1,
  "_score": null,
  "_source": {
    "kind": "HISTOGRAM",
    "buckets": [
      {
        "min": -3.4028234663852886e+38,
        "max": 0,
        "count": 20
      },
      {
        "min": 0,
        "max": 5,
        "count": 9
      },
      {
        "min": 5,
        "max": 10,
        "count": 1
      },
      {
        "min": 10,
        "max": 25,
        "count": 0
      },
      {
        "min": 25,
        "max": 50,
        "count": 0
      },
      {
        "min": 50,
        "max": 75,
        "count": 0
      },
      {
        "min": 75,
        "max": 100,
        "count": 0
      },
      {
        "min": 100,
        "max": 250,
        "count": 0
      },
      {
        "min": 250,
        "max": 500,
        "count": 0
      },
      {
        "min": 500,
        "max": 750,
        "count": 0
      },
      {
        "min": 750,
        "max": 1000,
        "count": 0
      },
      {
        "min": 1000,
        "max": 2500,
        "count": 0
      },
      {
        "min": 2500,
        "max": 5000,
        "count": 0
      },
      {
        "min": 5000,
        "max": 7500,
        "count": 0
      },
      {
        "min": 7500,
        "max": 10000,
        "count": 0
      },
      {
        "min": 10000,
        "max": 3.4028234663852886e+38,
        "count": 0
      }
    ],
    "count": 349
}

I would like to create a histogram/bar chart type visualization from the buckets field values.

Something like this just in Kibana.

How can I do this in Kibana? Is there any way to do that?


问:
roles variable in role guard is not being read properly
I implemented roles for my angular/nestjs/postgresql application ('Admin' and 'User') and i activated the the role guard for my getuserlist() to be only showable to admin upon login in yet it keeps guarding the list for both admin and user in addition of server getting shut down with the following error:
TypeError: Cannot read properties of undefined (reading 'roles')

at C:\Users\naceu\Desktop\MyDeveloperHub\projet internat\projet-internat\projet-internat1\backend\src\users\models\roles.guard.ts:23:45

//I made the guard with the following files :
//role.enum.ts
//role.decorator.ts
/role.guard.ts
//and in the controller file containing the getuserlist()
//this is the role.guard.ts:

```<code>import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { User } from './entities/user.entity';
import Role from './role.enum';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean {
    const requireRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requireRoles) {
      return true;
    }
    // const { user } = context.switchToHttp().getRequest();
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // return matchRoles(roles, user.roles);
    return requireRoles.some((role) => user.roles.includes(role));
  }
}
</code>```

Body:
I implemented roles for my angular/nestjs/postgresql application ('Admin' and 'User') and i activated the the role guard for my getuserlist() to be only showable to admin upon login in yet it keeps guarding the list for both admin and user in addition of server getting shut down with the following error:
TypeError: Cannot read properties of undefined (reading 'roles')

at C:\Users\naceu\Desktop\MyDeveloperHub\projet internat\projet-internat\projet-internat1\backend\src\users\models\roles.guard.ts:23:45

//I made the guard with the following files :
//role.enum.ts
//role.decorator.ts
/role.guard.ts
//and in the controller file containing the getuserlist()
//this is the role.guard.ts:

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { User } from './entities/user.entity';
import Role from './role.enum';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean {
    const requireRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requireRoles) {
      return true;
    }
    // const { user } = context.switchToHttp().getRequest();
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // return matchRoles(roles, user.roles);
    return requireRoles.some((role) => user.roles.includes(role));
  }
}


问:
Python Selenium on Mac: Download Chromedriver not needed anymore?
I recently switched from Windows to Mac and I was wondering why my Selenium script is working without giving it any path to the executable chromedriver file and without downloading any chromedriver executable.

Is that not needed anymore? I also don't find any executable chromedriver file on my whole system. How is that possible? I like it but I would like to understand why that is. If that's the normal behavior, will it also use the correct version of Chromedriver in the future then so that I don't have to use webdriver-manager or download the newest version every time my browser updates anymore?

```<code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")
</code>```

I already searched on the Selenium Website and found that the Getting Startet tutorial also does not define any executable path. Was that ever needed or did it change in the past?

Body:
I recently switched from Windows to Mac and I was wondering why my Selenium script is working without giving it any path to the executable chromedriver file and without downloading any chromedriver executable.

Is that not needed anymore? I also don't find any executable chromedriver file on my whole system. How is that possible? I like it but I would like to understand why that is. If that's the normal behavior, will it also use the correct version of Chromedriver in the future then so that I don't have to use webdriver-manager or download the newest version every time my browser updates anymore?

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")

I already searched on the Selenium Website and found that the Getting Startet tutorial also does not define any executable path. Was that ever needed or did it change in the past?


问:
How to see lombok source code in NetBeans?
I have the Lombok plugin setup in NetBeans IDE and my code builds fine. I can see the Lombok generated methods in the structure view. What I want is some way to actually see the source Lombok generates for each of the methods. I realize I can delombok the file, but I'm wondering if there is some way I can flip a switch to show or hide the Lombok generated code (How to delombok in NetBeans?).

Procedure to see the source code of Lombok methods.


问:
FFMPEG : Add video (partial video effect) under the image with ffmpeg
I have a video, video.mp4, and an image, artwork.png

I would like, to use FFmpeg:

To display the video.mp4 effect inside the image artwork.png

If possible, resize output.mp4 as per the demo demo_output.mp4

Is this possible?

Resources: https://www.dropbox.com/transfer/AAAAAGgUAt5aTw0W5DYH75y-CvJTKQUqxXatnMPNjHBxpz4DDiOH9IM

Have tried :
ffmpeg -i video.mp4 -i artwork.jpg -filter_complex '[1:v][0:v]scale2ref[ckout][vid];[vid][ckout]blend=all_mode='lighten'[out]' -map '[out]' output.mp4


问:
Is there a way to tell SSLStreams to validate the remote certificate based on the certificate present in path rather than Windows keystore?
When using SSLStreams with AuthenticateAsClient, i think RemoteCertificateValidationCallback function checks if the public key of the server certificate is present in the "Trusted Root Certification Authority" of Windows Keystore, if not present then the SSLPolicyErrors gets updated.

Now is there a way to say to SSLStreams that try to validate the Server certificate based on the public key present in a directory rather than Windows keystore.


问:
Visual Studio Code as combined Workspace editor and general purpose editor
I'm using Visual Studio Code (VSC) as both a general purpose text editor and other times as a programming IDE.

When VSC is used as general purpose editor I often have 6-8 files I need to edit on a regularly basis.

When using VSC as a programming IDE I tend to use workspace features.

I tried to pin "general purpose text files", but when I get into a workspace I seem to loose the pinned files.

Is there a way to ask VSC to try to open "general purpose text files" even if I open it in workspace mode? Or not to loose the pinned files when entering workspace mode?


问:
Do not allow gcc to compile invalid dereference in debug mode
The code below tries to dereference the first entry of a zero size vector

```<code>#include <iostream>
#include <vector>

#define WATCH(a) std::cout << #a << ": " << a << std::endl;

int main(int argc, char** argv)
{
    std::vector<int> A(0, 0);

    WATCH(&A[0])

    return 0;
}
</code>```

This is invalid but compile and run with gcc-11.3.0 for both debug and release build. The build command in debug mode is

```<code>g++ -g -rdynamic main.o -o main
</code>```

Is there a way to tell gcc to not allow this?

Body:
The code below tries to dereference the first entry of a zero size vector

#include <iostream>
#include <vector>

#define WATCH(a) std::cout << #a << ": " << a << std::endl;

int main(int argc, char** argv)
{
    std::vector<int> A(0, 0);

    WATCH(&A[0])

    return 0;
}

This is invalid but compile and run with gcc-11.3.0 for both debug and release build. The build command in debug mode is

g++ -g -rdynamic main.o -o main

Is there a way to tell gcc to not allow this?


问:
Making a variable available to all application Reactjs
I am using fingerprints to get the visitorID of the page, and I need to supply that to all the applications or some components. this is what I am doing.

in my App.tsx

```<code>  .....
  const [visitorId, setVisitorId] = useState("");
  const { clearCache } = useContext(FpjsContext)

  const {
    isLoading,
    data,
  } = useVisitorData();

  useEffect(() => {
    console.log("LOADING")
    if (!isLoading && data) {
      setVisitorId(data.visitorId)
    }
  }, [data, isLoading]);
</code>```

and I am passing that visitorId Below.

```<code>  return (
    <ThemeProvider theme={theme()}>
      <Router history={history}>
        <RedirectProvider>
          <ApolloProvider client={client}>
            <Auth0Provider>
              <Elements stripe={stripePromise}>
                <CustomModalProvider>
                  <UpsellProvider>
                    <Switch>
                      <Redirect exact from='/' to='/dashboard' />
                      <Route path='/signup' component={() => <OnboardApp visitorId={visitorId} />}/>
</code>```

the above is in App.tsx.

but OnboardApp goes further with

```<code>export const OnboardApp = ({ visitorId }: any) => {
  return <Switch>
    <Redirect exact from='/signup' to='/signup/provider' />
    <Route path='/signup/provider' component={ProviderOnboard} />
    <Route path='/signup/seeker/:companyId' component={() => <SeekerOnboard visitorId={visitorId} />} />
    <Route path='/signup/seeker' component={() => <SeekerOnboard visitorId={visitorId} />} />
    <Route path='/signup/user' component={UserOnboard} />
    <Route path='/signup/vendor' component={() => <VendorOnboard visitorId={visitorId} />} />
  </Switch>;
}
</code>```

so I just to pass on this value of visitorId to these components using a better way. I am learning react at the moment so any help would be great. thank you

Body:
I am using fingerprints to get the visitorID of the page, and I need to supply that to all the applications or some components. this is what I am doing.

in my App.tsx

  .....
  const [visitorId, setVisitorId] = useState("");
  const { clearCache } = useContext(FpjsContext)

  const {
    isLoading,
    data,
  } = useVisitorData();

  useEffect(() => {
    console.log("LOADING")
    if (!isLoading && data) {
      setVisitorId(data.visitorId)
    }
  }, [data, isLoading]);

and I am passing that visitorId Below.

  return (
    <ThemeProvider theme={theme()}>
      <Router history={history}>
        <RedirectProvider>
          <ApolloProvider client={client}>
            <Auth0Provider>
              <Elements stripe={stripePromise}>
                <CustomModalProvider>
                  <UpsellProvider>
                    <Switch>
                      <Redirect exact from='/' to='/dashboard' />
                      <Route path='/signup' component={() => <OnboardApp visitorId={visitorId} />}/>

the above is in App.tsx.

but OnboardApp goes further with

export const OnboardApp = ({ visitorId }: any) => {
  return <Switch>
    <Redirect exact from='/signup' to='/signup/provider' />
    <Route path='/signup/provider' component={ProviderOnboard} />
    <Route path='/signup/seeker/:companyId' component={() => <SeekerOnboard visitorId={visitorId} />} />
    <Route path='/signup/seeker' component={() => <SeekerOnboard visitorId={visitorId} />} />
    <Route path='/signup/user' component={UserOnboard} />
    <Route path='/signup/vendor' component={() => <VendorOnboard visitorId={visitorId} />} />
  </Switch>;
}

so I just to pass on this value of visitorId to these components using a better way. I am learning react at the moment so any help would be great. thank you


问:
JEST compatibility for Angular-4
I am working on angular project with version-4 & as per the requirement need to implement JEST framework for Unit testing, I have tried with latest version of JEST:29.3.1 but getting below error:

ERROR : while running : ng run test

TypeError: Cannot read property 'split' of undefined at isAfterVersion
\node_modules\jest-preset-angular\build\ngtsc\ts compatibility\src\ts_cross_version_utils.js:87:67) at Object.
\node_modules\jest-preset-angular\build\ngtsc\ts_compatibility\src\ts_cross_version_utils.js:13:24)
at Module. compile (internal/modules/cjs/loader.js:1085:14)

Tried with lower version of JEST as well but getting same error.

package.json

```<code>dependencies": {
    "@angular/aninations": "^4.4.6",
    "@angular/cdk": "^2.0.0-beta.12",
    "@angular/cli": "1.0.0"
    "@angular/common": "^4.0.0",
    "@angular/compile": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.8",
    "@angular/material": "^2.0.0-beta.12",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic":"4.8.8",
    "@angular/router": "^4.0.8",
    "bootstrap": "3.5.7",
    "core-js": "2.4.1",
    "enhanced-resolve": "^3.3.0",
    "Jest": "29.3.1",
    "jest-preset-anguler: 12.2.3"
}
</code>```

Title: JEST compatibility for Angular-4

Body:
I am working on angular project with version-4 & as per the requirement need to implement JEST framework for Unit testing, I have tried with latest version of JEST:29.3.1 but getting below error:

ERROR : while running : ng run test

TypeError: Cannot read property 'split' of undefined at isAfterVersion
\node_modules\jest-preset-angular\build\ngtsc\ts compatibility\src\ts_cross_version_utils.js:87:67) at Object.
\node_modules\jest-preset-angular\build\ngtsc\ts_compatibility\src\ts_cross_version_utils.js:13:24)
at Module. compile (internal/modules/cjs/loader.js:1085:14)

Tried with lower version of JEST as well but getting same error.

package.json

dependencies": {
    "@angular/aninations": "^4.4.6",
    "@angular/cdk": "^2.0.0-beta.12",
    "@angular/cli": "1.0.0"
    "@angular/common": "^4.0.0",
    "@angular/compile": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.8",
    "@angular/material": "^2.0.0-beta.12",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic":"4.8.8",
    "@angular/router": "^4.0.8",
    "bootstrap": "3.5.7",
    "core-js": "2.4.1",
    "enhanced-resolve": "^3.3.0",
    "Jest": "29.3.1",
    "jest-preset-anguler: 12.2.3"
}


问:
How to select and drag the top item when overlapped
I have two sprites in the world space. Both have box colliders. They are both set to the default sorting layer.
I made a drag n drop script attached to them.
They are int the same size and they are on each other, they have the same z index(0). When I drag the top one (I draw a line renderer around its bounds as it is selected) and I set another sorting layer (which is on the top) for which is dragged.
The problem is when I try to drag the top one only the bottom item moves.

How could I select the top object and drag it?


问:
PHP spreadsheet not exporting ion server
The PHP spreadsheet is working fine in the localhost. But When I uploaded in to the production server. The following error boots up. I have attached the following browser loading error

```<code>
<?php

session_start();
include "includes/db.php";
require '..\vendor\autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Csv;

 if(isset($_POST['export_csv_data']))
 {
    $export     = $_POST['export'];
    $filename   =  "Adjudication-Sheet";

      $search_query="SELECT * FROM `adjudication_team` WHERE document_reviewed_by = '".$_SESSION['username']."'";
      $result=mysqli_query($connection,$search_query);
      if($result)
 {

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'USER ID');
$sheet->setCellValue('C1', 'PATIENT NAME');
$sheet->setCellValue('D1', 'DOCUMENT BY');
$sheet->setCellValue('E1', 'DOCUMENT RECEIVED DATE');
$sheet->setCellValue('F1', 'UHID NUMBER');
$sheet->setCellValue('G1', 'ACTUAL DATE');
$sheet->setCellValue('H1', 'ACTUAL DISCHARGE');
$sheet->setCellValue('I1', 'HOSPITAL BILL');
$sheet->setCellValue('J1', 'MAIN BILL');
$sheet->setCellValue('K1', 'PHARMACY BILL EXCLUDED');
$sheet->setCellValue('L1', 'ADVANCE PAYMENT');
$sheet->setCellValue('M1', 'PHARMACY BILL');
$sheet->setCellValue('N1', 'PRE HOSPITALIZATION');
$sheet->setCellValue('O1', 'POST HOSPITALIZATION');
$sheet->setCellValue('P1', 'OUTSIDE HOSPITALIZATION');
$sheet->setCellValue('Q1', 'TOTAL BILL AMOUNT');
$sheet->setCellValue('R1', 'DOCUMENT REVIEWED DATE');
$sheet->setCellValue('S1', 'DOCUMENT REVIEWED BY');
$sheet->setCellValue('T1', 'HOSPITAL PAID RECIEPT');
$sheet->setCellValue('U1', 'INVESTIGATION BILL');
$sheet->setCellValue('V1', 'PRE HOSPITALIZATION BILL');
$sheet->setCellValue('W1', 'POST HOSPITALIZATION BILL');
$sheet->setCellValue('X1', 'OUTSIDE HOSPITALIZATION BILL');
$sheet->setCellValue('Y1', 'INVESTIGATION BILL');
$sheet->setCellValue('Z1', 'DATE IN');

$rowcount = 2;
foreach($result as $row)
{
$sheet->setCellValue('A'.$rowcount,$row['id']);
$sheet->setCellValue('B'.$rowcount,$row['user_id']);
$sheet->setCellValue('C'.$rowcount,$row['patient_name']);
$sheet->setCellValue('D'.$rowcount,$row['document_by']);
$sheet->setCellValue('E'.$rowcount,$row['document_received_date']);
$sheet->setCellValue('F'.$rowcount,$row['uhid_number']);
$sheet->setCellValue('G'.$rowcount,$row['actual_date']);
$sheet->setCellValue('H'.$rowcount,$row['actual_discharge']);
$sheet->setCellValue('I'.$rowcount,$row['hospital_bill']);
$sheet->setCellValue('J'.$rowcount,$row['main_bill']);
$sheet->setCellValue('K'.$rowcount,$row['pharmacy_bill_excluded']);
$sheet->setCellValue('L'.$rowcount,$row['advance_payment']);
$sheet->setCellValue('M'.$rowcount,$row['pharmacy_bill']);
$sheet->setCellValue('N'.$rowcount,$row['pre_hospitalization']);
$sheet->setCellValue('O'.$rowcount,$row['post_hospitalization']);
$sheet->setCellValue('P'.$rowcount,$row['outside_hospitalization']);
$sheet->setCellValue('Q'.$rowcount,$row['total_bill_amount']);
$sheet->setCellValue('R'.$rowcount,$row['document_reviewed_date']);
$sheet->setCellValue('S'.$rowcount,$row['document_reviewed_by']);
$sheet->setCellValue('T'.$rowcount,$row['hospital_paid_reciept']);
$sheet->setCellValue('U'.$rowcount,$row['investigation_bill']);
$sheet->setCellValue('V'.$rowcount,$row['pre_hospitalisation_bill']);
$sheet->setCellValue('W'.$rowcount,$row['post_hospitalisation_bill']);
$sheet->setCellValue('X'.$rowcount,$row['outside_hospitalisation_bill']);
$sheet->setCellValue('Y'.$rowcount,$row['discharge_summary']);
$sheet->setCellValue('Z'.$rowcount,$row['date_in']);
$rowcount++;
}

if($export == 'csv')
{
$writer = new Csv($spreadsheet);
$final_filename = $filename.'.csv';

}

header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:attachment;filename="'.urlencode($final_filename).'"');
$writer->save('php://output');

// $writer->save($final_filename);
}
else
{
 print_r(mysqli_error($connection));
}
  }

?>
</code>```

The PHP spreadsheet is working fine in the local host. But When I uploaded it to the production server. The following error boots up. I have attached the following browser loading error
I have attached the code in the above text.

Body:
The PHP spreadsheet is working fine in the localhost. But When I uploaded in to the production server. The following error boots up. I have attached the following browser loading error

<?php

session_start();
include "includes/db.php";
require '..\vendor\autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Csv;

 if(isset($_POST['export_csv_data']))
 {
    $export     = $_POST['export'];
    $filename   =  "Adjudication-Sheet";

      $search_query="SELECT * FROM `adjudication_team` WHERE document_reviewed_by = '".$_SESSION['username']."'";
      $result=mysqli_query($connection,$search_query);
      if($result)
 {

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'USER ID');
$sheet->setCellValue('C1', 'PATIENT NAME');
$sheet->setCellValue('D1', 'DOCUMENT BY');
$sheet->setCellValue('E1', 'DOCUMENT RECEIVED DATE');
$sheet->setCellValue('F1', 'UHID NUMBER');
$sheet->setCellValue('G1', 'ACTUAL DATE');
$sheet->setCellValue('H1', 'ACTUAL DISCHARGE');
$sheet->setCellValue('I1', 'HOSPITAL BILL');
$sheet->setCellValue('J1', 'MAIN BILL');
$sheet->setCellValue('K1', 'PHARMACY BILL EXCLUDED');
$sheet->setCellValue('L1', 'ADVANCE PAYMENT');
$sheet->setCellValue('M1', 'PHARMACY BILL');
$sheet->setCellValue('N1', 'PRE HOSPITALIZATION');
$sheet->setCellValue('O1', 'POST HOSPITALIZATION');
$sheet->setCellValue('P1', 'OUTSIDE HOSPITALIZATION');
$sheet->setCellValue('Q1', 'TOTAL BILL AMOUNT');
$sheet->setCellValue('R1', 'DOCUMENT REVIEWED DATE');
$sheet->setCellValue('S1', 'DOCUMENT REVIEWED BY');
$sheet->setCellValue('T1', 'HOSPITAL PAID RECIEPT');
$sheet->setCellValue('U1', 'INVESTIGATION BILL');
$sheet->setCellValue('V1', 'PRE HOSPITALIZATION BILL');
$sheet->setCellValue('W1', 'POST HOSPITALIZATION BILL');
$sheet->setCellValue('X1', 'OUTSIDE HOSPITALIZATION BILL');
$sheet->setCellValue('Y1', 'INVESTIGATION BILL');
$sheet->setCellValue('Z1', 'DATE IN');

$rowcount = 2;
foreach($result as $row)
{
$sheet->setCellValue('A'.$rowcount,$row['id']);
$sheet->setCellValue('B'.$rowcount,$row['user_id']);
$sheet->setCellValue('C'.$rowcount,$row['patient_name']);
$sheet->setCellValue('D'.$rowcount,$row['document_by']);
$sheet->setCellValue('E'.$rowcount,$row['document_received_date']);
$sheet->setCellValue('F'.$rowcount,$row['uhid_number']);
$sheet->setCellValue('G'.$rowcount,$row['actual_date']);
$sheet->setCellValue('H'.$rowcount,$row['actual_discharge']);
$sheet->setCellValue('I'.$rowcount,$row['hospital_bill']);
$sheet->setCellValue('J'.$rowcount,$row['main_bill']);
$sheet->setCellValue('K'.$rowcount,$row['pharmacy_bill_excluded']);
$sheet->setCellValue('L'.$rowcount,$row['advance_payment']);
$sheet->setCellValue('M'.$rowcount,$row['pharmacy_bill']);
$sheet->setCellValue('N'.$rowcount,$row['pre_hospitalization']);
$sheet->setCellValue('O'.$rowcount,$row['post_hospitalization']);
$sheet->setCellValue('P'.$rowcount,$row['outside_hospitalization']);
$sheet->setCellValue('Q'.$rowcount,$row['total_bill_amount']);
$sheet->setCellValue('R'.$rowcount,$row['document_reviewed_date']);
$sheet->setCellValue('S'.$rowcount,$row['document_reviewed_by']);
$sheet->setCellValue('T'.$rowcount,$row['hospital_paid_reciept']);
$sheet->setCellValue('U'.$rowcount,$row['investigation_bill']);
$sheet->setCellValue('V'.$rowcount,$row['pre_hospitalisation_bill']);
$sheet->setCellValue('W'.$rowcount,$row['post_hospitalisation_bill']);
$sheet->setCellValue('X'.$rowcount,$row['outside_hospitalisation_bill']);
$sheet->setCellValue('Y'.$rowcount,$row['discharge_summary']);
$sheet->setCellValue('Z'.$rowcount,$row['date_in']);
$rowcount++;
}

if($export == 'csv')
{
$writer = new Csv($spreadsheet);
$final_filename = $filename.'.csv';

}

header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:attachment;filename="'.urlencode($final_filename).'"');
$writer->save('php://output');

// $writer->save($final_filename);
}
else
{
 print_r(mysqli_error($connection));
}
  }

?>

The PHP spreadsheet is working fine in the local host. But When I uploaded it to the production server. The following error boots up. I have attached the following browser loading error
I have attached the code in the above text.


问:
docker-compose mysql 8.0.23 refuses to allow external access
I apologize if this is already answered, or is a poor/poorly worded question.

I recently restarted a mysql-server:8.0.23 container running on docker versoon 20.10.21 on an Ubuntu 20.04.5 LTS server, and the mysql container suddenly began to reject all connections with ERROR 1130 (HY000): Host '<ip address>' is not allowed to connect to this MySQL server. This happens for all attempts, localhost, and external.

Ive spent a few days trying to fix this by modifying the docker-compose and the docker entrypoint files, deleted the contents of the container's volume to start over, but it still continues to reject any attempt from any user to connect to it. I see no errors when starting up the container, and from file contents, databases and users seem to be created.
All attempts to connect with it continue to fail.

My current docker-compose looks like this:

```<code>version: '3'

services:

 mysql-stuff:
   image: mysql/mysql-server:8.0.23
   #image: mysql/mysql-server
   restart: unless-stopped
   ports:
     - "3306:3306"
   environment:
     MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
     MYSQL_ROOT_PASSWORD: "rootpwd"
     MYSQL_DATABASE: "thing_one"
     MYSQL_USER: "thing_one"
     MYSQL_PASSWORD: "thing_one_pwd"
   volumes:
     - mysql-stuff-volume:/var/lib/mysql
     - ./mysql/conf/db_init:/docker-entrypoint-initdb.d
   command:
      --default-authentication-plugin=mysql_native_password
      --bind-address=0.0.0.0

   healthcheck:
     test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
     timeout: 10s
     retries: 10

volumes:
  mysql-stuff-volume:
    external: true

</code>```

And my 01.sql file in /docker-entrypoint-initdb.d looks like this:

```<code>/* CREATE USER 'thing_one'@'%' IDENTIFIED BY 'thing_one_pwd'; */
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'rootpwd';
FLUSH PRIVILEGES;
ALTER USER 'thing_one'@'%' IDENTIFIED WITH mysql_native_password BY 'thing_one_pwd';
CREATE DATABASE IF NOT EXISTS thing_one;
GRANT ALL PRIVILEGES ON thing_one.* TO 'thing_one'@'%';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
CREATE USER 'stuff'@'%' IDENTIFIED WITH mysql_native_password BY  'rootpwd';
GRANT ALL PRIVILEGES ON *.* TO 'stuff'@'%' WITH GRANT OPTION;
UPDATE mysql.user SET host='%' WHERE user='root';
UPDATE mysql.user SET host='%' WHERE user='thing_one';
UPDATE mysql.user SET host='%' WHERE user='stuff';
FLUSH PRIVILEGES;
</code>```

Please what am I doing wrong?
Thanks in advance!

Body:
I apologize if this is already answered, or is a poor/poorly worded question.

I recently restarted a mysql-server:8.0.23 container running on docker versoon 20.10.21 on an Ubuntu 20.04.5 LTS server, and the mysql container suddenly began to reject all connections with ERROR 1130 (HY000): Host '<ip address>' is not allowed to connect to this MySQL server. This happens for all attempts, localhost, and external.

Ive spent a few days trying to fix this by modifying the docker-compose and the docker entrypoint files, deleted the contents of the container's volume to start over, but it still continues to reject any attempt from any user to connect to it. I see no errors when starting up the container, and from file contents, databases and users seem to be created.
All attempts to connect with it continue to fail.

My current docker-compose looks like this:

version: '3'

services:

 mysql-stuff:
   image: mysql/mysql-server:8.0.23
   #image: mysql/mysql-server
   restart: unless-stopped
   ports:
     - "3306:3306"
   environment:
     MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
     MYSQL_ROOT_PASSWORD: "rootpwd"
     MYSQL_DATABASE: "thing_one"
     MYSQL_USER: "thing_one"
     MYSQL_PASSWORD: "thing_one_pwd"
   volumes:
     - mysql-stuff-volume:/var/lib/mysql
     - ./mysql/conf/db_init:/docker-entrypoint-initdb.d
   command:
      --default-authentication-plugin=mysql_native_password
      --bind-address=0.0.0.0

   healthcheck:
     test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
     timeout: 10s
     retries: 10

volumes:
  mysql-stuff-volume:
    external: true

And my 01.sql file in /docker-entrypoint-initdb.d looks like this:

/* CREATE USER 'thing_one'@'%' IDENTIFIED BY 'thing_one_pwd'; */
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'rootpwd';
FLUSH PRIVILEGES;
ALTER USER 'thing_one'@'%' IDENTIFIED WITH mysql_native_password BY 'thing_one_pwd';
CREATE DATABASE IF NOT EXISTS thing_one;
GRANT ALL PRIVILEGES ON thing_one.* TO 'thing_one'@'%';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
CREATE USER 'stuff'@'%' IDENTIFIED WITH mysql_native_password BY  'rootpwd';
GRANT ALL PRIVILEGES ON *.* TO 'stuff'@'%' WITH GRANT OPTION;
UPDATE mysql.user SET host='%' WHERE user='root';
UPDATE mysql.user SET host='%' WHERE user='thing_one';
UPDATE mysql.user SET host='%' WHERE user='stuff';
FLUSH PRIVILEGES;

Please what am I doing wrong?
Thanks in advance!


问:
Spatie Laravel Twitter Streaming Api not dipslaying tweets
I'm trying to use the spatie Twitter Streaming api for laravel to display tweets for a specific hashtag. I'm using a console command but whenever I try to use, it keeps showing nothing on terminal or gives me the error "Client error: GET https://api.twitter.com/2/tweets/search/stream resulted in a 429 Too Many Requests response".

This is my TweetsStream command:

```<code>
namespace App\Console\Commands;

use Illuminate\Console\Command;
use TwitterStreamingApi;

class TweetsStream extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tweets:stream';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Stream the tweets';
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        TwitterStreamingApi::publicStream()
            ->whenHears('#laravel', function (array $tweet) {
                dump("{$tweet['user']['screen_name']} tweeted {$tweet['text']}");
            })
            ->startListening();
    }
}

</code>```

Body:
I'm trying to use the spatie Twitter Streaming api for laravel to display tweets for a specific hashtag. I'm using a console command but whenever I try to use, it keeps showing nothing on terminal or gives me the error "Client error: GET https://api.twitter.com/2/tweets/search/stream resulted in a 429 Too Many Requests response".

This is my TweetsStream command:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use TwitterStreamingApi;

class TweetsStream extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tweets:stream';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Stream the tweets';
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        TwitterStreamingApi::publicStream()
            ->whenHears('#laravel', function (array $tweet) {
                dump("{$tweet['user']['screen_name']} tweeted {$tweet['text']}");
            })
            ->startListening();
    }
}


问:
Laravel Swagger API App Crashed on refreshing multiple times and then restart
The Laravel latest app crashed once we hit Waterondoor APIs multiple times and then restart while running perfectly on local. On server side it is handled by Nginx.

Server side directory: it is residing in /wms-web

What we have tried:

On local it is running fine

When we are using only APIs call from the postman, it is running fine

We cleared the cache, and config on the production side

We tried to change many things on Nginx as well but didn’t workout

here is the complete demo of this error: https://www.loom.com/share/e2139fad9a6248d4a96126dd335ef4c2?focus_title=1&muted=1&from_recorder=1


问:
Convert hex to integer value from measurement data of CO2 sensor in C
I'm reading hex values from a CO2 sensor that communication through UART (https://www.co2meter.com/products/explorir-10-co2-smart-led-sensor?variant=20504457773174), and I would like to convert hex value in ppm value or percentage, since CO2 value are measured in this way. I'm using STM32 microcontroller and this is my C code:

```<code>  ret_uart = HAL_UART_Receive(&huart3, (uint8_t *)RdBuffer, BUFFSIZE, 2000);
  if (ret_uart != HAL_OK){
      strcpy((char*)buf_uart, "Error Rx\r\n");
  }
  else{
      ret_uart = HAL_UART_Transmit(&huart3, (uint8_t *)RdBuffer, BUFFSIZE, 2000);
      if (ret_uart != HAL_OK){
          strcpy((char*)buf_uart, "Error Tx\r\n");
      }
      else{
          return 1;
      }
  }
</code>```

For instance the masured value is 0x20, but how I can convert into an integer value?

Since I got mesurement inside an office, I expect a CO2 concentration of around 400pm which is equal to 0.04%, which may depends from the sea level.

Body:
I'm reading hex values from a CO2 sensor that communication through UART (https://www.co2meter.com/products/explorir-10-co2-smart-led-sensor?variant=20504457773174), and I would like to convert hex value in ppm value or percentage, since CO2 value are measured in this way. I'm using STM32 microcontroller and this is my C code:

  ret_uart = HAL_UART_Receive(&huart3, (uint8_t *)RdBuffer, BUFFSIZE, 2000);
  if (ret_uart != HAL_OK){
      strcpy((char*)buf_uart, "Error Rx\r\n");
  }
  else{
      ret_uart = HAL_UART_Transmit(&huart3, (uint8_t *)RdBuffer, BUFFSIZE, 2000);
      if (ret_uart != HAL_OK){
          strcpy((char*)buf_uart, "Error Tx\r\n");
      }
      else{
          return 1;
      }
  }

For instance the masured value is 0x20, but how I can convert into an integer value?

Since I got mesurement inside an office, I expect a CO2 concentration of around 400pm which is equal to 0.04%, which may depends from the sea level.