问:
Why do I get `Cannot read properties of undefined (reading 'collection')` when running 'db.collections' in js code
I'm a very beginner with MongoDB and JS

i'm running nodemon app in the terminal
running MONGODB COMPASS in the background

I'm getting the error:

TypeError: Cannot read properties of undefined (reading 'collection')
at D:\Coding\MongoDB\MongoDB Tutorial\app.js:23:24`

afaik I'm supposed to write db.collections and not db.books directly like I do it in Mongo Shell

db.js

```<code>const { MongoClient } = require('mongodb')

let dbConnection;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

let dbName = 'bookstore'
module.exports = {
  // establish connection to the db
  connectToDb: async (cb) => {
    await client.connect()
      .then(client => {
        dbConnection = client.db(dbName)
        return cb()
      })
      .catch(err => {
        console.log(err);
        return cb()
      })
  },

  // return connection to the db
  getDb: () => dbConnection
}
</code>```

app.js

```<code>const express = require('express');
const { connectToDb, getDb } = require('./db')

// init app & middleware
const app = express();

// db connection
let db
let PORT = 3000;
connectToDb((err)=>{
  if (!err) {
    app.listen(PORT, () => {
      console.log(`app listening on port ${PORT}`);
    });
  db = getDb();
  }
})

// routes
app.get('/books', async (req, res) => {

  // db.books   in mongosh
  const abc = await db.collection('books').find({});
  console.log(abc);

  res.json({ msg: 'Welcome to the api' })
})
</code>```

Body:
I'm a very beginner with MongoDB and JS

i'm running nodemon app in the terminal
running MONGODB COMPASS in the background

I'm getting the error:

TypeError: Cannot read properties of undefined (reading 'collection')
at D:\Coding\MongoDB\MongoDB Tutorial\app.js:23:24`

afaik I'm supposed to write db.collections and not db.books directly like I do it in Mongo Shell

db.js

const { MongoClient } = require('mongodb')

let dbConnection;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

let dbName = 'bookstore'
module.exports = {
  // establish connection to the db
  connectToDb: async (cb) => {
    await client.connect()
      .then(client => {
        dbConnection = client.db(dbName)
        return cb()
      })
      .catch(err => {
        console.log(err);
        return cb()
      })
  },

  // return connection to the db
  getDb: () => dbConnection
}

app.js

const express = require('express');
const { connectToDb, getDb } = require('./db')

// init app & middleware
const app = express();

// db connection
let db
let PORT = 3000;
connectToDb((err)=>{
  if (!err) {
    app.listen(PORT, () => {
      console.log(`app listening on port ${PORT}`);
    });
  db = getDb();
  }
})

// routes
app.get('/books', async (req, res) => {

  // db.books   in mongosh
  const abc = await db.collection('books').find({});
  console.log(abc);

  res.json({ msg: 'Welcome to the api' })
})


来源: stackexchange

问:
Apps Script - Google Sheets 'Unable to Load File' after a script is run to generate a Combo chart
I've been looking for an answer, but couldn't find one. I'm quite new to the platform and I have an issue with a script generating a Combo chart in Google Sheets. The script runs successfully from the Script Editor, however when I attempt to go back to the Spreadsheet itself, I get the following error. Issue persists after reloading, clearing cache, using a different browser (Chrome default). The only way I can access the file again is by removing the tabs with another script run from a separate file. When another user opens the file, the issue is still there.

Error

Initial data is generated dynamically, therefore I can't set the range and columns to static values. It looks like this:

Data table

Initial part of the code:

```<code>
function prepareData() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName("Sorted data2023-01-04 1"); //
  var dataRange = dataSheet.getDataRange();
  var data = dataRange.getValues();

  var headers = data[0];
  var userCol = headers.indexOf("User");
  var dateCol = headers.indexOf("Date");
  var hourlyTimeframeCol = headers.indexOf("Hourly Timeframe");
  var appIdentifiedCol = headers.indexOf("App identified");
  var subjectCol = headers.indexOf("Subject");
  var potentialPassiveCol = headers.indexOf("Potential passive");
  var potentialActiveCol = headers.indexOf("Potential active");

  var userData = {};

  for (var i = 1; i < data.length; i++) {
    var row = data[i];
    var user = row[userCol];
    var date = Utilities.formatDate(new Date(row[dateCol]),"GMT+7","yyyy-MM-dd");
    var hourlyTimeframe = row[hourlyTimeframeCol];
    var appIdentified = row[appIdentifiedCol];
    var subject = row[subjectCol];
    var potentialPassive = row[potentialPassiveCol];
    var potentialActive = row[potentialActiveCol];
    potentialPassive = Number(potentialPassive);
    potentialActive = Number(potentialActive);
    if (!userData[user]) {
      userData[user] = {};
    }
    if (!userData[user][date]) {
      userData[user][date] = {};
    }
    if (!userData[user][date][hourlyTimeframe]) {
      userData[user][date][hourlyTimeframe] = {
        "potentialPassive": 0,
        "potentialActive": {},
        "count": 0
      };
    }
    if (!userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject]) {
    userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] = 0;
    }
    userData[user][date][hourlyTimeframe]["potentialPassive"] += potentialPassive;
    if (!userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject]) {
      userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] = 0;
    }
    userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] += potentialActive;
    userData[user][date][hourlyTimeframe]["count"]++;
  }
  Logger.log(userData);
for (var user in userData) {
    for (var date in userData[user]) {
        var newSheet = ss.insertSheet(user + "_" + date);
        var hourlyTimeframes = Object.keys(userData[user][date]);
        hourlyTimeframes.sort(function(a, b) {
            return a - b;
        });
var headers = ["Hourly Timeframe", "Potential passive"];
  for (var hourlyTimeframe in userData[user][date]) {
    for (var appSubject in userData[user][date][hourlyTimeframe]["potentialActive"]) {
      if (!headers.includes(appSubject)) {
        headers.push(appSubject);
      }
    }
  }
  headers.push("Count");
var rows = [headers];
for (var hourlyTimeframe in userData[user][date]) {
    var rowData = [hourlyTimeframe, userData[user][date][hourlyTimeframe]["potentialPassive"]];
    for (var appSubject in userData[user][date][hourlyTimeframe]["potentialActive"]) {
        var index = headers.indexOf(appSubject);
        if (index != -1) {
            rowData[index] = userData[user][date][hourlyTimeframe]["potentialActive"][appSubject];
        }
    }
    rowData[headers.length-1] = userData[user][date][hourlyTimeframe]["count"];
    rows.push(rowData);
    }
}
rows.sort(function(a, b) { return a[0] - b[0]; });
var index = rows[0].indexOf("Passive_Passive");
if(index>-1) for (var i=0;i<rows.length;i++) rows[i].splice(index,1);
newSheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
</code>```

Problematic code:

```<code>var chartRange = newSheet.getDataRange();
  var chartBuilder = newSheet.newChart();
  // Add the data range for the chart
  chartBuilder.addRange(chartRange);

  // Set the chart type
  chartBuilder.setChartType(Charts.ChartType.COMBO);

  // set the chart to use the first column as x-axis
  chartBuilder.setOption('useFirstColumnAsDomain', true);

  // Set the position of the chart
  chartBuilder.setPosition(3,3,0,0);

  // Set the chart title
  chartBuilder.setOption('title', 'Hourly Usage Data');

  // Set the chart options
  chartBuilder.setOption('vAxis', {
    title: 'Stacked hourly time spent'
  });

  chartBuilder.setOption('hAxis', {
    title: 'Hours'
  });

  // chartBuilder.setOption('height', 400);
  // chartBuilder.setOption('width', 600);
  chartBuilder.setOption('backgroundColor', '#f1f8e9');

  // Set the series type and series options
  chartBuilder.setOption('series', [{
      type: 'bars',
      targetAxisIndex: 0,
      // color: 'red',
      data: {
        sourceRange: {
          sheetId: newSheet.getSheetId(),
          startRowIndex: 0,
          endRowIndex: chartRange.getNumRows(),
          startColumnIndex: 1,
          endColumnIndex: chartRange.getNumColumns()-1
        }
      }
    },{
        type: 'line',
        targetAxisIndex: 1,
        color: 'blue',
        data: {
          sourceRange: {
            sheetId: newSheet.getSheetId(),
            startRowIndex: 0,
            endRowIndex: chartRange.getNumRows(),
            startColumnIndex: chartRange.getNumColumns(),
            endColumnIndex: chartRange.getNumColumns()
          }
        }
    }
  ]);

  // Build and insert the chart
  var chart = chartBuilder.build();
  newSheet.insertChart(chart);
}
}
</code>```

I have enabled the chart generation with another script in the same file.

```<code>function enableChartServices() {
  // Enabling Chart Services
  var advancedServices = PropertiesService.getScriptProperties().getProperty('services');
  if (!advancedServices) {
    PropertiesService.getScriptProperties().setProperty('services', JSON.stringify(['sheets','calendar','drive','charts']));
  } else {
    advancedServices = JSON.parse(advancedServices);
    if (advancedServices.indexOf('charts') == -1) {
      advancedServices.push('charts');
      PropertiesService.getScriptProperties().setProperty('services', JSON.stringify(advancedServices));
    }
  }
}
</code>```

Anyone has any idea what might be causing this?
Thank you in advance!

I have tried using a column chart and it seemed to have worked. However, I need this data to be represented in a combo chart for multiple users on a daily basis (circa 300 sheets).

Edit 1: Added data table
Edit 2: Added the initial part of the code (which works fine until the graph needs to be generated)

ContentLicense: CC BY-SA 4.0

Body:
I've been looking for an answer, but couldn't find one. I'm quite new to the platform and I have an issue with a script generating a Combo chart in Google Sheets. The script runs successfully from the Script Editor, however when I attempt to go back to the Spreadsheet itself, I get the following error. Issue persists after reloading, clearing cache, using a different browser (Chrome default). The only way I can access the file again is by removing the tabs with another script run from a separate file. When another user opens the file, the issue is still there.

Error

Initial data is generated dynamically, therefore I can't set the range and columns to static values. It looks like this:

Data table

Initial part of the code:

function prepareData() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName("Sorted data2023-01-04 1"); //
  var dataRange = dataSheet.getDataRange();
  var data = dataRange.getValues();

  var headers = data[0];
  var userCol = headers.indexOf("User");
  var dateCol = headers.indexOf("Date");
  var hourlyTimeframeCol = headers.indexOf("Hourly Timeframe");
  var appIdentifiedCol = headers.indexOf("App identified");
  var subjectCol = headers.indexOf("Subject");
  var potentialPassiveCol = headers.indexOf("Potential passive");
  var potentialActiveCol = headers.indexOf("Potential active");

  var userData = {};

  for (var i = 1; i < data.length; i++) {
    var row = data[i];
    var user = row[userCol];
    var date = Utilities.formatDate(new Date(row[dateCol]),"GMT+7","yyyy-MM-dd");
    var hourlyTimeframe = row[hourlyTimeframeCol];
    var appIdentified = row[appIdentifiedCol];
    var subject = row[subjectCol];
    var potentialPassive = row[potentialPassiveCol];
    var potentialActive = row[potentialActiveCol];
    potentialPassive = Number(potentialPassive);
    potentialActive = Number(potentialActive);
    if (!userData[user]) {
      userData[user] = {};
    }
    if (!userData[user][date]) {
      userData[user][date] = {};
    }
    if (!userData[user][date][hourlyTimeframe]) {
      userData[user][date][hourlyTimeframe] = {
        "potentialPassive": 0,
        "potentialActive": {},
        "count": 0
      };
    }
    if (!userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject]) {
    userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] = 0;
    }
    userData[user][date][hourlyTimeframe]["potentialPassive"] += potentialPassive;
    if (!userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject]) {
      userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] = 0;
    }
    userData[user][date][hourlyTimeframe]["potentialActive"][appIdentified + "_" + subject] += potentialActive;
    userData[user][date][hourlyTimeframe]["count"]++;
  }
  Logger.log(userData);
for (var user in userData) {
    for (var date in userData[user]) {
        var newSheet = ss.insertSheet(user + "_" + date);
        var hourlyTimeframes = Object.keys(userData[user][date]);
        hourlyTimeframes.sort(function(a, b) {
            return a - b;
        });
var headers = ["Hourly Timeframe", "Potential passive"];
  for (var hourlyTimeframe in userData[user][date]) {
    for (var appSubject in userData[user][date][hourlyTimeframe]["potentialActive"]) {
      if (!headers.includes(appSubject)) {
        headers.push(appSubject);
      }
    }
  }
  headers.push("Count");
var rows = [headers];
for (var hourlyTimeframe in userData[user][date]) {
    var rowData = [hourlyTimeframe, userData[user][date][hourlyTimeframe]["potentialPassive"]];
    for (var appSubject in userData[user][date][hourlyTimeframe]["potentialActive"]) {
        var index = headers.indexOf(appSubject);
        if (index != -1) {
            rowData[index] = userData[user][date][hourlyTimeframe]["potentialActive"][appSubject];
        }
    }
    rowData[headers.length-1] = userData[user][date][hourlyTimeframe]["count"];
    rows.push(rowData);
    }
}
rows.sort(function(a, b) { return a[0] - b[0]; });
var index = rows[0].indexOf("Passive_Passive");
if(index>-1) for (var i=0;i<rows.length;i++) rows[i].splice(index,1);
newSheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);

Problematic code:

var chartRange = newSheet.getDataRange();
  var chartBuilder = newSheet.newChart();
  // Add the data range for the chart
  chartBuilder.addRange(chartRange);

  // Set the chart type
  chartBuilder.setChartType(Charts.ChartType.COMBO);

  // set the chart to use the first column as x-axis
  chartBuilder.setOption('useFirstColumnAsDomain', true);

  // Set the position of the chart
  chartBuilder.setPosition(3,3,0,0);

  // Set the chart title
  chartBuilder.setOption('title', 'Hourly Usage Data');

  // Set the chart options
  chartBuilder.setOption('vAxis', {
    title: 'Stacked hourly time spent'
  });

  chartBuilder.setOption('hAxis', {
    title: 'Hours'
  });

  // chartBuilder.setOption('height', 400);
  // chartBuilder.setOption('width', 600);
  chartBuilder.setOption('backgroundColor', '#f1f8e9');

  // Set the series type and series options
  chartBuilder.setOption('series', [{
      type: 'bars',
      targetAxisIndex: 0,
      // color: 'red',
      data: {
        sourceRange: {
          sheetId: newSheet.getSheetId(),
          startRowIndex: 0,
          endRowIndex: chartRange.getNumRows(),
          startColumnIndex: 1,
          endColumnIndex: chartRange.getNumColumns()-1
        }
      }
    },{
        type: 'line',
        targetAxisIndex: 1,
        color: 'blue',
        data: {
          sourceRange: {
            sheetId: newSheet.getSheetId(),
            startRowIndex: 0,
            endRowIndex: chartRange.getNumRows(),
            startColumnIndex: chartRange.getNumColumns(),
            endColumnIndex: chartRange.getNumColumns()
          }
        }
    }
  ]);

  // Build and insert the chart
  var chart = chartBuilder.build();
  newSheet.insertChart(chart);
}
}

I have enabled the chart generation with another script in the same file.

function enableChartServices() {
  // Enabling Chart Services
  var advancedServices = PropertiesService.getScriptProperties().getProperty('services');
  if (!advancedServices) {
    PropertiesService.getScriptProperties().setProperty('services', JSON.stringify(['sheets','calendar','drive','charts']));
  } else {
    advancedServices = JSON.parse(advancedServices);
    if (advancedServices.indexOf('charts') == -1) {
      advancedServices.push('charts');
      PropertiesService.getScriptProperties().setProperty('services', JSON.stringify(advancedServices));
    }
  }
}

Anyone has any idea what might be causing this?
Thank you in advance!

I have tried using a column chart and it seemed to have worked. However, I need this data to be represented in a combo chart for multiple users on a daily basis (circa 300 sheets).

Edit 1: Added data table
Edit 2: Added the initial part of the code (which works fine until the graph needs to be generated)


问:
Error while creating a read replica in Cloud SQL
I am getting the error as below everytime I create a read replica.
tried with mysql 8 and postgresql 14

```<code>This instance is not responding. You can still restore a backup to a new instance or promote a cross region replica.
</code>```

I am attempting a Postgresql CLoud SQL cross region replica creation and disaster recovery.

LInk : https://cloud.google.com/solutions/cloud-sql-mysql-disaster-recovery-complete-failover-fallback

Logs show

```<code>2023-01-11 17:11:19.522 UTC [78]: [1-1] db=cloudsqladmin,user=cloudsqladmin ERROR:  cannot execute GRANT ROLE in a read-only transaction
</code>```

Body:
I am getting the error as below everytime I create a read replica.
tried with mysql 8 and postgresql 14

This instance is not responding. You can still restore a backup to a new instance or promote a cross region replica.

I am attempting a Postgresql CLoud SQL cross region replica creation and disaster recovery.

LInk : https://cloud.google.com/solutions/cloud-sql-mysql-disaster-recovery-complete-failover-fallback

Logs show

2023-01-11 17:11:19.522 UTC [78]: [1-1] db=cloudsqladmin,user=cloudsqladmin ERROR:  cannot execute GRANT ROLE in a read-only transaction


问:
Ecto association on_replace action raises constraint error
I have a schema, which roughly resembles this:

```<code>beehives
   has many(bees)

bees
   has many(honeypots)

honeypots
   belongs_to(bees)
</code>```

The beehives to bees relation has on_replace: :delete. Our app updates bees by updating a beehive record.

However, once a bee has a honeypot relation, a constraint prevents the on_replace: :delete. This is by design and works as intended.

The issue I'm having, is that I can't make Ecto handle the constraint as intended (i.e. return it as an error), but no matter how much I include assoc_constraint(), no_assoc_constraint() and foreign_key_constraint() in the various changesets, an update always ends up as a raised error.

My hypothesis is that Ecto simply can't handle this situation gracefully and performs the on_replace with a delete from bees where beehive = X as part of the transaction, causing the constraint to fail the query. But this is conjecture.

The issue can certainly be solved by means of explicit checks before an update that will remove an associated bee and refusing to attempt it when appropriate, or by updating (and removing) individual bee records on their own, but going via the beehive is convenient for our use-case and if possible would our preferred choice.

Body:
I have a schema, which roughly resembles this:

beehives
   has many(bees)

bees
   has many(honeypots)

honeypots
   belongs_to(bees)

The beehives to bees relation has on_replace: :delete. Our app updates bees by updating a beehive record.

However, once a bee has a honeypot relation, a constraint prevents the on_replace: :delete. This is by design and works as intended.

The issue I'm having, is that I can't make Ecto handle the constraint as intended (i.e. return it as an error), but no matter how much I include assoc_constraint(), no_assoc_constraint() and foreign_key_constraint() in the various changesets, an update always ends up as a raised error.

My hypothesis is that Ecto simply can't handle this situation gracefully and performs the on_replace with a delete from bees where beehive = X as part of the transaction, causing the constraint to fail the query. But this is conjecture.

The issue can certainly be solved by means of explicit checks before an update that will remove an associated bee and refusing to attempt it when appropriate, or by updating (and removing) individual bee records on their own, but going via the beehive is convenient for our use-case and if possible would our preferred choice.


问:
How to edit bad gateway page on traefik
I want to edit the Bad Gateway page from traefik to issue a command like
docker restart redis
Does anyone have an idea on how to do this?

A bit of background:
I have a somewhat broken setup of Traefik v2.5 and Authelia on my development server, where sometimes I get a Bad Gateway Error when accessing a page. Usually this is fixed by clearing all sessions from redis. I tried to locate the bug, but the error logs aren't helpful and I don't have the time and skills to make the bug reproduceable or find the broken configuration. So instead I always use ssh into the maschine and reset redis manually

Title: How to edit bad gateway page on traefik


问:
Is there a way to find all dual-socket AWS instance types?
I'm interested in running NUMA experiments on various hardware. Ideally there'd be documentation by AWS listing how many physical cores each instance has, but I haven't been able to find such information.

Is there a way to get such information without spinning up each instance type and running lscpu to see the socket count?

Thank you.


问:
Mongoose post hook with typescript interface
I was following a tutorial using typescript with mongoose. Code looks like following

Interface

```<code>export default interface IBook extends Document {
  title: string;
  author: string;
  extraInformation: string;

}

</code>```

Schema post save hook

```<code>BookSchema.post<IBook>('save', function(){
  this.extraInformation = "this is some extra information to put into this entry after the save!"
});
</code>```

Correct me if I am wrong
Here for the hook we use IBook interface as generic and inside the has a callback function that is using "this" what is it pointing to how can this be used inside a function with no params

BTW perfectly working code

Body:
I was following a tutorial using typescript with mongoose. Code looks like following

Interface

export default interface IBook extends Document {
  title: string;
  author: string;
  extraInformation: string;

}

Schema post save hook

BookSchema.post<IBook>('save', function(){
  this.extraInformation = "this is some extra information to put into this entry after the save!"
});

Correct me if I am wrong
Here for the hook we use IBook interface as generic and inside the has a callback function that is using "this" what is it pointing to how can this be used inside a function with no params

BTW perfectly working code


问:
Accumulate in MPI_Send and MPI_Recv using C++
Here is my entire code first (the code is correct):

```<code>#include <iostream>
#include <mpi.h>
using namespace std;

int main(int argc, char**argv)
{
    int mynode, totalnodes;
    int sum,starval,endval,accum;
    MPI_Status status;

    MPI_Init (&argc,&argv);
    MPI_Comm_size (MPI_COMM_WORLD, &totalnodes); //get totalnodes
    MPI_Comm_rank (MPI_COMM_WORLD, &mynode);    //get mynode

    sum=0; //zero sum for accumulation
    starval = 1000*mynode / totalnodes+1;
    endval = 1000*(mynode+1) / totalnodes;

    for (int i=starval; i <= endval; i=i+1)
        sum = sum + i;
    if(mynode!=0)
        MPI_Send(&sum,1,MPI_INT,0,7,MPI_COMM_WORLD);
    else
    for(int j=1; j < totalnodes; j=j+1){
        MPI_Recv(&accum,1,MPI_INT,j,7,MPI_COMM_WORLD, &status);
        sum=sum+accum;
    }
    if(mynode ==0)
        cout << "the sum from 1 to 1000 is: " << sum << endl;

    MPI_Finalize();
}

</code>```

We are trying to seperate the accumulating assignment to all different processors, and then accumulating result made by all processor (not the processor 0) to send the outcome to the processor 0. And the processor zero will accumulating all the outcomes receieved from other processors, and output a result of the summation from 1 to 1000 (As you can see in the code).

Now, my question is: what is the "accum" in the command of
sum = sum + accum;
There is no declearation of "accum". How does the operation system know that?

Please brifly explain the logic of

else

for(int j=1; j < totalnodes; j=j+1){

 MPI_Recv(&accum,1,MPI_INT,j,7,MPI_COMM_WORLD, &status);

sum=sum+accum;}

And what did the accum did in this code.

Thank you!

Body:
Here is my entire code first (the code is correct):

#include <iostream>
#include <mpi.h>
using namespace std;

int main(int argc, char**argv)
{
    int mynode, totalnodes;
    int sum,starval,endval,accum;
    MPI_Status status;

    MPI_Init (&argc,&argv);
    MPI_Comm_size (MPI_COMM_WORLD, &totalnodes); //get totalnodes
    MPI_Comm_rank (MPI_COMM_WORLD, &mynode);    //get mynode

    sum=0; //zero sum for accumulation
    starval = 1000*mynode / totalnodes+1;
    endval = 1000*(mynode+1) / totalnodes;

    for (int i=starval; i <= endval; i=i+1)
        sum = sum + i;
    if(mynode!=0)
        MPI_Send(&sum,1,MPI_INT,0,7,MPI_COMM_WORLD);
    else
    for(int j=1; j < totalnodes; j=j+1){
        MPI_Recv(&accum,1,MPI_INT,j,7,MPI_COMM_WORLD, &status);
        sum=sum+accum;
    }
    if(mynode ==0)
        cout << "the sum from 1 to 1000 is: " << sum << endl;

    MPI_Finalize();
}

We are trying to seperate the accumulating assignment to all different processors, and then accumulating result made by all processor (not the processor 0) to send the outcome to the processor 0. And the processor zero will accumulating all the outcomes receieved from other processors, and output a result of the summation from 1 to 1000 (As you can see in the code).

Now, my question is: what is the "accum" in the command of
sum = sum + accum;
There is no declearation of "accum". How does the operation system know that?

Please brifly explain the logic of

else

for(int j=1; j < totalnodes; j=j+1){

 MPI_Recv(&accum,1,MPI_INT,j,7,MPI_COMM_WORLD, &status);

sum=sum+accum;}

And what did the accum did in this code.

Thank you!


问:
auto pause iframe video and audio when another plays
I'm having difficulty figuring this out. I'm new to JS so I need some help!
I've managed to auto-pause audio when another audio plays BUT I now need more than that. I need this to include audio and iframe videos.

My ask is, is it possible to auto-pause an iframe video if audio starts playing, and vice versa?
Thanks in advance.

I've tried the below and it doesn't do exactly what I need. Please help.

```<code><script>
var audios = document.getElementsByTagName('audio');
for (var i = 0, len = audios.length; i < len;i++) {
  var audio = audios[i];
  audio.addEventListener('play', function() {
    var iframes = document.getElementsByTagName('iframe');
    for (var i = 0, len = iframes.length; i < len;i++) {
      var iframe = iframes[i];
      var src = iframe.src;
      if (src.indexOf('player.vimeo.com') > -1) {
        iframe.src = src + '&enablejsapi=1';
      }
    }
  });
}
</script>
</code>```

UPDATE: I got this to work BUT it doesn't pause the iframe video when the audio starts. The only thing that works is that when playing the audio, the video pauses. I need it both ways.

```<code> <script>
document.addEventListener('play', function(e) {
    var audios = document.getElementsByTagName('audio');
    var iframes = document.getElementsByTagName('iframe');
    if (e.target.tagName === 'IFRAME') {
        for (var i = 0, len = audios.length; i < len; i++) {
            audios[i].pause();
        }
    } else if(e.target.tagName === 'AUDIO'){
        for (var i = 0, len = iframes.length; i < len; i++) {
            iframes[i].contentWindow.postMessage('{"method":"pause"}','*');
        }
    }
}, true);
</script>
</code>```

Body:
I'm having difficulty figuring this out. I'm new to JS so I need some help!
I've managed to auto-pause audio when another audio plays BUT I now need more than that. I need this to include audio and iframe videos.

My ask is, is it possible to auto-pause an iframe video if audio starts playing, and vice versa?
Thanks in advance.

I've tried the below and it doesn't do exactly what I need. Please help.

UPDATE: I got this to work BUT it doesn't pause the iframe video when the audio starts. The only thing that works is that when playing the audio, the video pauses. I need it both ways.


问:
NoClassDefFoundError: Could not initialise class com.google.firebase.perf.session.SessionManager
When upgrading com.google.firebase:perf-plugin:1.4.2 and I run my unit tests I got this error

```<code>Could not initialize class com.google.firebase.perf.session.SessionManager
java.lang.NoClassDefFoundError: Could not initialize class com.google.firebase.perf.session.SessionManager
    at com.google.firebase.perf.metrics.NetworkRequestMetricBuilder.setRequestStartTimeMicros(NetworkRequestMetricBuilder.java:230)
    at com.google.firebase.perf.network.FirebasePerfOkHttpClient.sendNetworkMetric(FirebasePerfOkHttpClient.java:107)
    at com.google.firebase.perf.network.FirebasePerfOkHttpClient.execute(FirebasePerfOkHttpClient.java:46)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.refreshToken(TokenInterceptor.kt:119)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.handleRefreshTokenWhenPastRefreshTime(TokenInterceptor.kt:98)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.intercept(TokenInterceptor.kt:63)
    at uk.co.club.costa.costa.data.common.TokenInterceptorIntegrationTest.whenTokenDueToRefresh_thenRefreshToken(TokenInterceptorIntegrationTest.kt:95)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
</code>```

Here is my gradle file:

dependencies {

```<code>com.google.firebase:perf-plugin:1.4.2
</code>```

}

firebaseBomVersion = '31.1.1'

androidLibs = [

```<code>firebaseBoM: "com.google.firebase:firebase bom:$firebaseBomVersion",
firebaseAnalyticsKtx: "com.google.firebase:firebase-analytics-ktx",
firebaseCloudMessagingKtx: "com.google.firebase:firebase-messaging-ktx",
firebaseConfigKtx: "com.google.firebase:firebase-config-ktx",
firebaseCrashlytics: "com.google.firebase:firebase-crashlytics",
firebaseDynamicLinks: "com.google.firebase:firebase-dynamic-links",
firebasePerf: "com.google.firebase:firebase-perf"
</code>```

]

The app can build without any problem and more bizarrely, when you run the tests individually, the test passes without any errors However, when running in a suit the tests fails.

I tried to root out where is the error originated from and I know it's because I have upgraded to com.google.firebase:perf-plugin.

When I downgraded the version things seems to work well.

Body:
When upgrading com.google.firebase:perf-plugin:1.4.2 and I run my unit tests I got this error

Could not initialize class com.google.firebase.perf.session.SessionManager
java.lang.NoClassDefFoundError: Could not initialize class com.google.firebase.perf.session.SessionManager
    at com.google.firebase.perf.metrics.NetworkRequestMetricBuilder.setRequestStartTimeMicros(NetworkRequestMetricBuilder.java:230)
    at com.google.firebase.perf.network.FirebasePerfOkHttpClient.sendNetworkMetric(FirebasePerfOkHttpClient.java:107)
    at com.google.firebase.perf.network.FirebasePerfOkHttpClient.execute(FirebasePerfOkHttpClient.java:46)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.refreshToken(TokenInterceptor.kt:119)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.handleRefreshTokenWhenPastRefreshTime(TokenInterceptor.kt:98)
    at uk.co.club.costa.costa.data.common.TokenInterceptor.intercept(TokenInterceptor.kt:63)
    at uk.co.club.costa.costa.data.common.TokenInterceptorIntegrationTest.whenTokenDueToRefresh_thenRefreshToken(TokenInterceptorIntegrationTest.kt:95)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)

Here is my gradle file:

dependencies {

com.google.firebase:perf-plugin:1.4.2

}

firebaseBomVersion = '31.1.1'

androidLibs = [

firebaseBoM: "com.google.firebase:firebase bom:$firebaseBomVersion",
firebaseAnalyticsKtx: "com.google.firebase:firebase-analytics-ktx",
firebaseCloudMessagingKtx: "com.google.firebase:firebase-messaging-ktx",
firebaseConfigKtx: "com.google.firebase:firebase-config-ktx",
firebaseCrashlytics: "com.google.firebase:firebase-crashlytics",
firebaseDynamicLinks: "com.google.firebase:firebase-dynamic-links",
firebasePerf: "com.google.firebase:firebase-perf"

]

The app can build without any problem and more bizarrely, when you run the tests individually, the test passes without any errors However, when running in a suit the tests fails.

I tried to root out where is the error originated from and I know it's because I have upgraded to com.google.firebase:perf-plugin.

When I downgraded the version things seems to work well.


问:
Typescript conditionals with required arguments
I have a field validator helper that I'm refactoring to have conditional types. Here is what I have:

```<code>// this does not work unless I make acceptedLengths and anotherArg optional
interface ValidationRulesType {
  field1: (value: string, args: { acceptedLengths: [number] }) => string
  field2: (value: string) => string
  field3: (value: string, args: { anotherArg: string}) => string
}

type GetFieldValidationType<Type> = Type extends (
  ...args: infer Field
) => string
  ? Field
  : never

type ValidateFieldsType =
  | {
      name: 'field1'
      args: GetFieldValidationType<ValidationRulesType['field1']>[1]
    }
  | {
      name: 'field2'
      args: never
    }
  | {
      name: 'field3'
      args: GetFieldValidationType<ValidationRulesType['field3']>[1]
    }

const validateField = ({ name, value, args }: ValidateFieldsType): string => {
  return validationRules[name](value, args)
}
</code>```

When requiring acceptedLengths and anotherArg I get this error:

```<code>Argument of type '{ acceptedLengths: [number]; } | { anotherArg: boolean; }' is not assignable to parameter of type '{ acceptedLengths: [number]; } & { anotherArg: boolean; }'.
</code>```

Which makes sense, however, I'm hoping to have these arguments required when the name: field1 | field3. Is this possible?

Body:
I have a field validator helper that I'm refactoring to have conditional types. Here is what I have:

// this does not work unless I make acceptedLengths and anotherArg optional
interface ValidationRulesType {
  field1: (value: string, args: { acceptedLengths: [number] }) => string
  field2: (value: string) => string
  field3: (value: string, args: { anotherArg: string}) => string
}

type GetFieldValidationType<Type> = Type extends (
  ...args: infer Field
) => string
  ? Field
  : never

type ValidateFieldsType =
  | {
      name: 'field1'
      args: GetFieldValidationType<ValidationRulesType['field1']>[1]
    }
  | {
      name: 'field2'
      args: never
    }
  | {
      name: 'field3'
      args: GetFieldValidationType<ValidationRulesType['field3']>[1]
    }

const validateField = ({ name, value, args }: ValidateFieldsType): string => {
  return validationRules[name](value, args)
}

When requiring acceptedLengths and anotherArg I get this error:

Argument of type '{ acceptedLengths: [number]; } | { anotherArg: boolean; }' is not assignable to parameter of type '{ acceptedLengths: [number]; } & { anotherArg: boolean; }'.

Which makes sense, however, I'm hoping to have these arguments required when the name: field1 | field3. Is this possible?


问:
Unabe to Start Jenkins on Gradle installed Server
I installed Gradle with following versions and was working perfectly fine,
 Gradle server has Java version,

openjdk version "1.8.0_342"

OpenJDK Runtime Environment (build 1.8.0_342-b07)

OpenJDK 64-Bit Server VM (build 25.342-b07, mixed mode)

and gradle version:

Gradle 6.8.3

I would be able to run "./gradlew build" to build our github repository successfully.

But,
 When I tried Installing Jenkins on the same server,I'm not able start jenkins i,e. systemctl start jenkins
this is throwing below error:

"Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details."

I wonder, this would be because Java version , because jenkins requires "Java-jdk11".

I tried to installed java-jdk11, jenkins was running up and fine , but not able to run gradle command  - "./gradlew build" (we can run this command if java version is -openjdk version "1.8.0_342").

is there any way to come out this?

Thanks for your Help!


问:
How to modify Json file from power shell script gcp output
I have a GCP script below mentioned, running in power shell

```<code>$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://sqladmin.googleapis.com/v1/projects/source-project/instances/source-instance/backupRuns" | Select-Object -Expand Content
</code>```

getting output from above script like below

```<code>C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\third_party\urllib3\connectionpool.py:979: InsecureRequestWarning: Unverified HTTPS request is being made to host 'oauth2.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  warnings.warn(
{
  "kind": "sql#backupRunsList",
  "items": [
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-11T00:33:21.903Z",
      "id": "1673391600000",
      "startTime": "2023-01-11T00:33:21.949Z",
      "endTime": "2023-01-11T00:38:47.459Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-10T23:00:00Z",
      "instance": "instance",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673391600000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-09T23:36:39.776Z",
      "id": "1673305200000",
      "startTime": "2023-01-09T23:36:39.826Z",
      "endTime": "2023-01-09T23:42:05.542Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-09T23:00:00Z",
      "instance": "instance ",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673305200000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },
</code>```

And I have a JSON file in the same folder like below

```<code>{
  "restoreBackupContext":
  {
    "backupRunId": 1673391600000,
    "project": "project",
    "instanceId": "instance"
  }
}
</code>```

I want to update " "id": " each time from output to json automatically while running first script
enter image description here

The " "id": "  value each time getting new.

Let me know how to achieve it

thanks

Body:
I have a GCP script below mentioned, running in power shell

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
    -Method GET `
    -Headers $headers `
    -Uri "https://sqladmin.googleapis.com/v1/projects/source-project/instances/source-instance/backupRuns" | Select-Object -Expand Content

getting output from above script like below

C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\third_party\urllib3\connectionpool.py:979: InsecureRequestWarning: Unverified HTTPS request is being made to host 'oauth2.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  warnings.warn(
{
  "kind": "sql#backupRunsList",
  "items": [
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-11T00:33:21.903Z",
      "id": "1673391600000",
      "startTime": "2023-01-11T00:33:21.949Z",
      "endTime": "2023-01-11T00:38:47.459Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-10T23:00:00Z",
      "instance": "instance",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673391600000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-09T23:36:39.776Z",
      "id": "1673305200000",
      "startTime": "2023-01-09T23:36:39.826Z",
      "endTime": "2023-01-09T23:42:05.542Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-09T23:00:00Z",
      "instance": "instance ",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673305200000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },

And I have a JSON file in the same folder like below

{
  "restoreBackupContext":
  {
    "backupRunId": 1673391600000,
    "project": "project",
    "instanceId": "instance"
  }
}

I want to update " "id": " each time from output to json automatically while running first script
enter image description here

The " "id": "  value each time getting new.

Let me know how to achieve it

thanks


问:
Typescript: Why does Array.include(arg) flag the *possibility* that arg is not included?
Here's a sketch of my code:

```<code>const wordTypes = ['noun', 'verb', 'conjunction'] as const;
type TWordType = wordTypes[number];

const grammarTypes = ['pronunciation', 'etymology', ...wordTypes] as const;
type TGrammarType = grammarTypes[number];

// Later in my code:
const willReturnUnknownInAdvanceMemberOfGrammarTypes = ():TGrammarType => {...};
const test: TGrammarType = willReturnUnknownInAdvanceMemberOfGrammarTypes();

// Now I want to know if test is a member of wordTypes array
const isWord = wordTypes.includes(test); // !!!
</code>```

The problem is that the line above marked // !!! gets flagged with the message:

```<code>Argument of type '"pronunciation" | "etymology" | "noun" | "verb" | "conjunction" is not assignable to parameter of type '"noun" | "verb" | "conjunction"'.
  Type 'etymology' is not assignable to type '"noun" | "verb" | "conjunction"'. ts(2345)
</code>```

What the?! This seems ridiculous -- as though typescript is essentially saying that test might have a value such as not to be included in an array and, therefore, I must be in error; but isn't that the whole point of the .includes() method -- to test whether it is included or not?

Can someone please help me understand the motivation for this strange tsc behavior, and perhaps suggest a clean way to rearrange my types/logic to avoid this flag? Thanks!

Body:
Here's a sketch of my code:

const wordTypes = ['noun', 'verb', 'conjunction'] as const;
type TWordType = wordTypes[number];

const grammarTypes = ['pronunciation', 'etymology', ...wordTypes] as const;
type TGrammarType = grammarTypes[number];

// Later in my code:
const willReturnUnknownInAdvanceMemberOfGrammarTypes = ():TGrammarType => {...};
const test: TGrammarType = willReturnUnknownInAdvanceMemberOfGrammarTypes();

// Now I want to know if test is a member of wordTypes array
const isWord = wordTypes.includes(test); // !!!

The problem is that the line above marked // !!! gets flagged with the message:

Argument of type '"pronunciation" | "etymology" | "noun" | "verb" | "conjunction" is not assignable to parameter of type '"noun" | "verb" | "conjunction"'.
  Type 'etymology' is not assignable to type '"noun" | "verb" | "conjunction"'. ts(2345)

What the?! This seems ridiculous -- as though typescript is essentially saying that test might have a value such as not to be included in an array and, therefore, I must be in error; but isn't that the whole point of the .includes() method -- to test whether it is included or not?

Can someone please help me understand the motivation for this strange tsc behavior, and perhaps suggest a clean way to rearrange my types/logic to avoid this flag? Thanks!


问:
post request with requests in python, data does not work
I need to connect to www.france-ioi.org with python to get informations.
I use the python requests library. The problem is that I can't connect.
Here is the code:

```<code>import requests

with requests.Session() as s:
    payload = {
        "login": 'mylogin',
        "password": 'mypassword',
    }
    s.get('https://login.france-ioi.org/login')

    # login france ioi
    s.post("https://login.france-ioi.org/login", data=payload)

    r = s.get("http://www.france-ioi.org/algo/chapters.php")
    print(r.text)
    s.close()
</code>```

I tried adding headers but it didn't help.

Thank you in advance

Body:
I need to connect to www.france-ioi.org with python to get informations.
I use the python requests library. The problem is that I can't connect.
Here is the code:

import requests

with requests.Session() as s:
    payload = {
        "login": 'mylogin',
        "password": 'mypassword',
    }
    s.get('https://login.france-ioi.org/login')

    # login france ioi
    s.post("https://login.france-ioi.org/login", data=payload)

    r = s.get("http://www.france-ioi.org/algo/chapters.php")
    print(r.text)
    s.close()

I tried adding headers but it didn't help.

Thank you in advance


问:
How to write tests with Google's PubSubLite?
With Google's PubSub there is an embedded broker available for writing tests: embedded-google-pubsub (https://github.com/PlaytikaOSS/testcontainers-spring-boot/blob/develop/embedded-google-pubsub/README.adoc)

Can I use this also for PubSubLite? Probably not, since I do not find any indication in the documentation. But what am I going to use for writing integration tests then? It seems there is not even a Docker image available for PubSubLite?


问:
Get mat-step inner contents angular material
I am using angular material stepper I want to get mat-step inner contents when stepper (selectionChange) event fired.

Ts

```<code>import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-stepper',
  templateUrl: './stepper.component.html',
  styleUrls: ['./stepper.component.css']
})
export class StepperComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
  handleSelectionChange(event: StepperSelectionEvent){
    // I want selected mat-step inner contents here.
  }
}
</code>```

Html Template

```<code><mat-horizontal-stepper [linear]="false" #stepper (selectionChange)="handleSelectionChange($event)">
  <mat-step label="Step 1">
      <app-form></app-form>
      <p>testing</p>
      <!-- I want <app-form> component and other contents when (selctionChange) event fired-->
  </mat-step>
  <mat-step  label="Step 2">
    <reactiveForm></reactiveForm>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    <p>You are now done.</p>
    <div>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>
    </div>
  </mat-step>
</mat-horizontal-stepper>
</code>```

Body:
I am using angular material stepper I want to get mat-step inner contents when stepper (selectionChange) event fired.

Ts

import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-stepper',
  templateUrl: './stepper.component.html',
  styleUrls: ['./stepper.component.css']
})
export class StepperComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
  handleSelectionChange(event: StepperSelectionEvent){
    // I want selected mat-step inner contents here.
  }
}

Html Template

<mat-horizontal-stepper [linear]="false" #stepper (selectionChange)="handleSelectionChange($event)">
  <mat-step label="Step 1">
      <app-form></app-form>

testing

  </mat-step>
  <mat-step  label="Step 2">
    <reactiveForm></reactiveForm>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>

You are now done.

      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>

  </mat-step>
</mat-horizontal-stepper>


问:
r-mice: pass argument to glm.fit in mice call
I ran into the same issue presented in mice: glm.fit: algorithm did not converge and originally adopted the solution that the question asker did (and it worked ok). My imputation procedure takes a longer time than is acceptable to me, though, so I've tried using futuremice. The problem is the the solution that I was using locally defines a function that cannot be found when using futuremice. I've opted to try a suggestion provided in the comments, passing an argument though mice::mice to glm.fit to try to get around this problem (instead of cloning the mice package and redefining the method parameters there).

I've tried several different ways to pass the maxit=100 argument, and I get errors for each way I try. Reprex below:

```<code>test_data <- data.frame(x = as.factor(round(rnorm(100))),
                        y = as.factor(round(rnorm(100, 1,1))),
                        z = rnorm(100,5,1))
test_data[3:4, 1] <- NA
test_data[5:8, 2] <- NA

test_init <- mice(test_data, max = 0, print = F, vis = "monotone",
                  defaultMethod = c("pmm", "logreg", "polyreg", "polr"))

predictor_matrix <- quickpred(test_data)

# try 1
test_data_mice <- mice::mice(test_data, print = F,
                        predictorMatrix = predictor_matrix,
                        method = test_init$method,
                        vis = test_init$visitSequence,
                        glm.fit(control = list(glm.control(maxit = 100)))
)
#ERROR:Error in glm.control(list(epsilon = 1e-08, maxit = 100, trace = FALSE)) :
 # value of 'epsilon' must be > 0

#try 2
test_data_mice <- mice::mice(test_data, print = F,
                        predictorMatrix = predictor_matrix,
                        method = test_init$method,
                        vis = test_init$visitSequence,
                        glm.fit(control = list(maxit = 100))
)
#ERROR: Error in as.matrix(x) : argument "x" is missing, with no default
</code>```

I'm pretty sure that Try 1 should be correct, so I don't get what's happening there. I tried explicitly defining epsilon and it didn't change the error.

Body:
I ran into the same issue presented in mice: glm.fit: algorithm did not converge and originally adopted the solution that the question asker did (and it worked ok). My imputation procedure takes a longer time than is acceptable to me, though, so I've tried using futuremice. The problem is the the solution that I was using locally defines a function that cannot be found when using futuremice. I've opted to try a suggestion provided in the comments, passing an argument though mice::mice to glm.fit to try to get around this problem (instead of cloning the mice package and redefining the method parameters there).

I've tried several different ways to pass the maxit=100 argument, and I get errors for each way I try. Reprex below:

test_data <- data.frame(x = as.factor(round(rnorm(100))),
                        y = as.factor(round(rnorm(100, 1,1))),
                        z = rnorm(100,5,1))
test_data[3:4, 1] <- NA
test_data[5:8, 2] <- NA

test_init <- mice(test_data, max = 0, print = F, vis = "monotone",
                  defaultMethod = c("pmm", "logreg", "polyreg", "polr"))

predictor_matrix <- quickpred(test_data)

# try 1
test_data_mice <- mice::mice(test_data, print = F,
                        predictorMatrix = predictor_matrix,
                        method = test_init$method,
                        vis = test_init$visitSequence,
                        glm.fit(control = list(glm.control(maxit = 100)))
)
#ERROR:Error in glm.control(list(epsilon = 1e-08, maxit = 100, trace = FALSE)) :
 # value of 'epsilon' must be > 0

#try 2
test_data_mice <- mice::mice(test_data, print = F,
                        predictorMatrix = predictor_matrix,
                        method = test_init$method,
                        vis = test_init$visitSequence,
                        glm.fit(control = list(maxit = 100))
)
#ERROR: Error in as.matrix(x) : argument "x" is missing, with no default

I'm pretty sure that Try 1 should be correct, so I don't get what's happening there. I tried explicitly defining epsilon and it didn't change the error.


问:
Multi Tenant database access using PostgreSQL and Node JS
I have a database which is shared amongst multiple tenants/users. However, I want to add row-level-security protection so that any given tenant can only see those rows that belong to them.

As such, for each tenant I have a user in PostgreSQL, such as "client_1" and "client_2". In each table, there is a column "tenant_id", the default value of which is "session_user".

Then, I have row level security as such:

```<code>CREATE POLICY policy_warehouse_user ON warehouse FOR ALL
TO PUBLIC USING (tenant_id = current_user);
ALTER TABLE warehouse ENABLE ROW LEVEL SECURITY;
</code>```

This works great, and if I set the user "SET ROLE client_1" I can only access those rows in which the tenant_id = "client_1".

However, I am struggling with how to best set this up in the Node JS back-end. Imortantly, for each tenant, such as "client_1", there can be multiple users connected. So several users on our system, all who work at company X, will connect to the database as "client_1".

What I am currently doing is this:

```<code>let config = {
        user: 'test_client2',
        host: process.env.PGHOST,
        database: process.env.PGDATABASE,
        max: 10, //default value
        password: 'test_client2',
        port: process.env.PGPORT,
    }

const pool = new Pool(config);
const client = await pool.connect()

await client.query('sql...')

client.release();
</code>```

I feel like this is a bad solution, especially since I am creating a new Pool each time a query is executed. So the question is, how can I best ensure that each user executes queries in the database using the ROLE that corresponds to their tenant?

Body:
I have a database which is shared amongst multiple tenants/users. However, I want to add row-level-security protection so that any given tenant can only see those rows that belong to them.

As such, for each tenant I have a user in PostgreSQL, such as "client_1" and "client_2". In each table, there is a column "tenant_id", the default value of which is "session_user".

Then, I have row level security as such:

CREATE POLICY policy_warehouse_user ON warehouse FOR ALL
TO PUBLIC USING (tenant_id = current_user);
ALTER TABLE warehouse ENABLE ROW LEVEL SECURITY;

This works great, and if I set the user "SET ROLE client_1" I can only access those rows in which the tenant_id = "client_1".

However, I am struggling with how to best set this up in the Node JS back-end. Imortantly, for each tenant, such as "client_1", there can be multiple users connected. So several users on our system, all who work at company X, will connect to the database as "client_1".

What I am currently doing is this:

let config = {
        user: 'test_client2',
        host: process.env.PGHOST,
        database: process.env.PGDATABASE,
        max: 10, //default value
        password: 'test_client2',
        port: process.env.PGPORT,
    }

const pool = new Pool(config);
const client = await pool.connect()

await client.query('sql...')

client.release();

I feel like this is a bad solution, especially since I am creating a new Pool each time a query is executed. So the question is, how can I best ensure that each user executes queries in the database using the ROLE that corresponds to their tenant?


问:
How can I implement round-robin prioritization in a celery queue?
I have a celery queue that does computation tasks that take about a minute each.

If one user_id submits 10 jobs at the same time, they expect to wait 10 minutes.

If another user_id submits a single job 30 seconds later, I don't want them to wait 10 minutes before it can start.

In effect I'd like celery to treat tasks from each user_id as a separate queue, and rotate around any user_ids currently submitting tasks.  Is this a thing?

Everything is working nicely in celery as normal, but I haven't done any prioritization of tasks, as I don't yet know a good scheme to achieve what I want.


问:
How to format Scientific Notation output in PowerApps
I have a PowerApps application with tables that have different types of values in it. One example is (Simplified for the Question):
|RO|E|
|:-|-:|
|2.765e+3|0.53|

I would like to format the value displayed in RO to have a leading 0 after the letter e, if it is less than 10, and display both digits if it is greater than or equal to 10.

The code I am currently using in MS PowerApps gives me the output that is shown in the question. The code is:

```<code>If(Text(First(t24_data).RO) = "-", First(t24_data).RO, Value(First(t24_data).RO) >= 1, Round(Value(First(t24_data).RO) / (Power(10,(Len(Text(RoundDown(Value(First(t24_data).RO),0)))-1))),3) & "e+" & Text(Len(Text(RoundDown (Value(First(t24_data).RO),0)))-1), Round(Power(10,Len(Text(RoundDown(1 / Value(First(t24_data).RO),0)))) * Value(First(t24_data).RO),3) & "e-" & Len(Text(RoundDown(1 / Value(First(t24_data).RO),0))))
</code>```

Please let me know what format changes I would need to do in order to accomplish this.

Body:
I have a PowerApps application with tables that have different types of values in it. One example is (Simplified for the Question):
|RO|E|
|:-|-:|
|2.765e+3|0.53|

I would like to format the value displayed in RO to have a leading 0 after the letter e, if it is less than 10, and display both digits if it is greater than or equal to 10.

The code I am currently using in MS PowerApps gives me the output that is shown in the question. The code is:

If(Text(First(t24_data).RO) = "-", First(t24_data).RO, Value(First(t24_data).RO) >= 1, Round(Value(First(t24_data).RO) / (Power(10,(Len(Text(RoundDown(Value(First(t24_data).RO),0)))-1))),3) & "e+" & Text(Len(Text(RoundDown (Value(First(t24_data).RO),0)))-1), Round(Power(10,Len(Text(RoundDown(1 / Value(First(t24_data).RO),0)))) * Value(First(t24_data).RO),3) & "e-" & Len(Text(RoundDown(1 / Value(First(t24_data).RO),0))))

Please let me know what format changes I would need to do in order to accomplish this.


问:
Using Serilog to Application Insights - requests logging but not traces
UPDATE

By shutting down the application using ctrl + c in the console, the "finally" block of program.cs is executed, logs are flushed and saved to Application Insights. However, if the application is stopped abruptly, (browser window closed for example) logs are not sent to Application Insights and the information is lost, which isn't ideal.
Does anyone have method or suggestion to make logs flush more frequently or how to safeguard in the event of the application terminating unexpectedly

ORIGINAL

I'm trying to configure C# web application project to log files to Application Insights using Serilog. I have followed the documentation to configure the logger to read for the appsetting.json file and have been able to implement other sinks to write logs to the console, file SEQ etc, but the Application Insights won't work. Request data is available on application insights using the configuration below

Program.cs

```<code>var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
        .CreateBootstrapLogger();

Log.Information("Application Starting up");

try
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddApplicationInsightsTelemetry();

   builder.Host.UseSerilog();

    // Add services to the container.
    builder.Services.AddRazorPages();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios,   see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSerilogRequestLogging();

    app.UseRouting();

    app.UseAuthorization();

    app.MapRazorPages();

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "the application failed to start correctly");
}
finally
{
    Log.CloseAndFlush();
}
</code>```

appsettings.json

```<code>{
  "ApplicationInsights": {
    "connectionString": "MyConnectionString"

  },

  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "*MyConnectionString",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
        }
      }
      ,
      {
        "Name": "Console"
      }
    ],
    "Enrich": [ "FromLogcontext", "WithMachineName", "WithProcessId", "WithThreadId" ]

  }
}

</code>```

Requests are being saved to application insights, but I can't get the logs (traces) or exceptions to be saved. Am I missing something??

Edit
I have log events written in the index like so

```<code> public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {
        try
        {
            for (int i = 0; i < 10; i++)
            {
                if (i == 5)
                {
                    _logger.LogCritical("Serilog: Testing log critical");
                    throw new Exception("Serilog iLogger Exception");
                }
                else
                {
                    _logger.LogWarning("Serilog: The value of i is {LoopCountValue}", i);
                    _logger.LogWarning("Serilog: Testing log warning");

                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "exception in the index Get call");
        }
    }
}
</code>```

Adding .csproj file

```<code><Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Serilog" Version="2.12.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="6.1.0"/>
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
    <PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Serilog.Enrichers.AspNetCore" Version="1.0.0" />
    <PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="5.2.2" />
</ItemGroup>
</Project>
</code>```

Body:
UPDATE

By shutting down the application using ctrl + c in the console, the "finally" block of program.cs is executed, logs are flushed and saved to Application Insights. However, if the application is stopped abruptly, (browser window closed for example) logs are not sent to Application Insights and the information is lost, which isn't ideal.
Does anyone have method or suggestion to make logs flush more frequently or how to safeguard in the event of the application terminating unexpectedly

ORIGINAL

I'm trying to configure C# web application project to log files to Application Insights using Serilog. I have followed the documentation to configure the logger to read for the appsetting.json file and have been able to implement other sinks to write logs to the console, file SEQ etc, but the Application Insights won't work. Request data is available on application insights using the configuration below

Program.cs

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
        .CreateBootstrapLogger();

Log.Information("Application Starting up");

try
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddApplicationInsightsTelemetry();

   builder.Host.UseSerilog();

    // Add services to the container.
    builder.Services.AddRazorPages();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios,   see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSerilogRequestLogging();

    app.UseRouting();

    app.UseAuthorization();

    app.MapRazorPages();

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "the application failed to start correctly");
}
finally
{
    Log.CloseAndFlush();
}

appsettings.json

{
  "ApplicationInsights": {
    "connectionString": "MyConnectionString"

  },

  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "*MyConnectionString",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
        }
      }
      ,
      {
        "Name": "Console"
      }
    ],
    "Enrich": [ "FromLogcontext", "WithMachineName", "WithProcessId", "WithThreadId" ]

  }
}

Requests are being saved to application insights, but I can't get the logs (traces) or exceptions to be saved. Am I missing something??

Edit
I have log events written in the index like so

 public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {
        try
        {
            for (int i = 0; i < 10; i++)
            {
                if (i == 5)
                {
                    _logger.LogCritical("Serilog: Testing log critical");
                    throw new Exception("Serilog iLogger Exception");
                }
                else
                {
                    _logger.LogWarning("Serilog: The value of i is {LoopCountValue}", i);
                    _logger.LogWarning("Serilog: Testing log warning");

                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "exception in the index Get call");
        }
    }
}

Adding .csproj file

<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Serilog" Version="2.12.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="6.1.0"/>
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
    <PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Serilog.Enrichers.AspNetCore" Version="1.0.0" />
    <PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="5.2.2" />
</ItemGroup>
</Project>


问:
How to make the Pentaho Report Designer so that when exported to Excel, the text fits completely into the cell?
When exported to Excel, the text overflows the cell. However the PDF report version shows the text completely
enter image description here
enter image description here

I set the element height = 100% and dynamic-hegith = true and in excel properties wrap-text-override = true but it didn't help.

enter image description here
enter image description here


问:
Display Positive Infinity in console
Simply speaking console displays positive infinity as ? instead of ∞. Example code:

var a = double.PositiveInfinity;
Console.WriteLine(a); //displays ? instead of ∞
```

I have tried using Invariant Culture, Console.OutputEncoding = System.Text.Encoding.UTF8, and Console.OutputEncoding = System.Text.Encoding.Unicode. Always displays ?.

P.S

Writing it to a file does work and it displays correctly, but it would be nice if it also displayed properly on console.

Title: Display Positive Infinity in console

Body:
Simply speaking console displays positive infinity as ? instead of ∞. Example code:

var a = double.PositiveInfinity;
Console.WriteLine(a); //displays ? instead of ∞

I have tried using Invariant Culture, Console.OutputEncoding = System.Text.Encoding.UTF8, and Console.OutputEncoding = System.Text.Encoding.Unicode. Always displays ?.

P.S

Writing it to a file does work and it displays correctly, but it would be nice if it also displayed properly on console.


问:
PrimeFaces p:message shows error unreadable messages
I use PrimeFaces 7 with JSF 2.3 Mojarra and have the problem that sometimes error messages, which I place below an UI component are not readable, as shown below:

This is my xhtml code snippet, which is wrapped in a <h:body> and <h:form>:

```
<p>My bean snippet:</p>
<pre class="lang-java prettyprint-override"><code>UIComponent component = getUIComponentById("highestPriceAmountId");
String errorHeader = "blabla";
String errorMessage = "hahaha"

getFacesContext().addMessage(component.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, errorHeader, errorMessage));
PrimeFaces.current().focus(uiComponentId, component);
</code>```

Why is the message shown like this?

Body:
I use PrimeFaces 7 with JSF 2.3 Mojarra and have the problem that sometimes error messages, which I place below an UI component are not readable, as shown below:

This is my xhtml code snippet, which is wrapped in a <h:body> and <h:form>:

My bean snippet:

UIComponent component = getUIComponentById("highestPriceAmountId");
String errorHeader = "blabla";
String errorMessage = "hahaha"

getFacesContext().addMessage(component.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, errorHeader, errorMessage));
PrimeFaces.current().focus(uiComponentId, component);

Why is the message shown like this?


问:
Sveltekit import component from dynamic route not working
I'm trying to import a component in Sveltekit but it is searching 3 folders back instead of 2.

```<code>import Search from '../../Search.svelte'
</code>```

But I get the error:

Failed to load url ../../../Search.velte

The folder structure is like this:

```<code>/[id]
  +page.svelte
  Search.svelte
  /[slug]
    /members
      +page.svelte
</code>```

[id]/[slug]/members/+page.svelte is where I am trying to perform the import.

Body:
I'm trying to import a component in Sveltekit but it is searching 3 folders back instead of 2.

import Search from '../../Search.svelte'

But I get the error:

Failed to load url ../../../Search.velte

The folder structure is like this:

/[id]
  +page.svelte
  Search.svelte
  /[slug]
    /members
      +page.svelte

[id]/[slug]/members/+page.svelte is where I am trying to perform the import.


问:
copy Resource folders files after deployment in spring boot app
```<code>    private static void copyRequiredCBAFiles(String sourceFileUrl, Path targetDirectory, String fileName, Boolean rename) throws IOException {
   File source = new File(new ClassPathResource(sourceFileUrl).getFile().getAbsolutePath());
        File destination = targetDirectory.toFile();
        for (File file : source.listFiles()) {
        if (file.isFile()) {
           if (rename && (StringUtils.equalsIgnoreCase(file.getName(),"template.txt") || StringUtils.equalsIgnoreCase(file.getName(), "mapping.json"))) {
                    copyAndRenameFileToDirectory(file, destination, fileName);
                } else {
                    FileUtils.copyFileToDirectory(file, destination);
                }
            }
        }
    }
</code>```

i have some files and subfolders inside resouces folder, Now after deploy the code im not able to access it im getting null pointer exception. Is it possible to access those files and folders.

Body:
    private static void copyRequiredCBAFiles(String sourceFileUrl, Path targetDirectory, String fileName, Boolean rename) throws IOException {
   File source = new File(new ClassPathResource(sourceFileUrl).getFile().getAbsolutePath());
        File destination = targetDirectory.toFile();
        for (File file : source.listFiles()) {
        if (file.isFile()) {
           if (rename && (StringUtils.equalsIgnoreCase(file.getName(),"template.txt") || StringUtils.equalsIgnoreCase(file.getName(), "mapping.json"))) {
                    copyAndRenameFileToDirectory(file, destination, fileName);
                } else {
                    FileUtils.copyFileToDirectory(file, destination);
                }
            }
        }
    }

i have some files and subfolders inside resouces folder, Now after deploy the code im not able to access it im getting null pointer exception. Is it possible to access those files and folders.


问:
Bokeh circle height is incorrect
When drawing a circle with Bokeh, I saw the dimensions were not quite right. Circle image

Here's the code I used to generate the circle, with two lines (one horizontal, one vertical) for comparison:

```<code>from bokeh.plotting import figure, show

plot = figure(width=800, height=800, x_range=(-100, 100), y_range=(-100, 100))

plot.circle(x=0, y=0, radius=90, line_color='black', color='black', fill_color=None)
plot.line([0, 90], [0, 0])
plot.line([0, 0], [0, 90])

show(plot)
</code>```

Any idea what the issue might be? Thank you!

Title: Bokeh circle height is incorrect

Body:
When drawing a circle with Bokeh, I saw the dimensions were not quite right. Circle image

Here's the code I used to generate the circle, with two lines (one horizontal, one vertical) for comparison:

from bokeh.plotting import figure, show

plot = figure(width=800, height=800, x_range=(-100, 100), y_range=(-100, 100))

plot.circle(x=0, y=0, radius=90, line_color='black', color='black', fill_color=None)
plot.line([0, 90], [0, 0])
plot.line([0, 0], [0, 90])

show(plot)

Any idea what the issue might be? Thank you!


问:
How do I get emmet support for react native?
I am currently working on a React Native project that uses TypeScript as the programming language. I am familiar with using Emmet in my text editor for web development and would like to know if it is possible to enable similar functionality for React Native development with TypeScript.

I have managed to make Emmet work for normal react but not react native because it isn't normal JSX.

Are there any specific plugins or configurations that I need to be aware of to enable Emmet support for React Native development with TypeScript?


问:
display dataviewgrid.datasource = dt; different form c#
```<code>private void button_search_Click(object sender, EventArgs e) {

            Searches form4 = new Searches();
            form4.dataGridView1.DataSource = dt;
            form4.Show();
            this.Hide();

}
</code>```


问:
Apollo - how to use cache.readFragment() on a filtered field?
I am trying to use cache.readFragment() to retrieve posts from the following cache entry:

```<code>{
    ...
    "PublisherType:37": {
        "__typename": "PublisherType",
        "id": "37",
        "posts({\"archived\":false,\"collection\":\"6\",\"sort\":\"-ordering\"})": {
            "__typename": "PostConnection",
            "totalCount": 8,
            "edges": [...]
        }
    }
    ...
}
</code>```

The following does not work and always returns null. I believe this is because there isn't a posts field in the cache:

```<code>const posts = cache.readFragment({
    id: "PublisherType:37",
    fragment: gql`
        fragment PublisherPosts on PublisherType {
            posts
        }
    `
});
</code>```

Is there a way I can retrieve the posts without knowing the filters?

It works fine if I change the fragment to:

```<code>fragment PublisherPosts on PublisherType {
    posts(archived:false, collection:6, sort: "-ordering")
}
</code>```

Is there a way I can query this data without having to know which filters are used? Something like posts* or even posts(*) (tried both BTW).

Body:
I am trying to use cache.readFragment() to retrieve posts from the following cache entry:

{
    ...
    "PublisherType:37": {
        "__typename": "PublisherType",
        "id": "37",
        "posts({\"archived\":false,\"collection\":\"6\",\"sort\":\"-ordering\"})": {
            "__typename": "PostConnection",
            "totalCount": 8,
            "edges": [...]
        }
    }
    ...
}

The following does not work and always returns null. I believe this is because there isn't a posts field in the cache:

const posts = cache.readFragment({
    id: "PublisherType:37",
    fragment: gql`
        fragment PublisherPosts on PublisherType {
            posts
        }
    `
});

Is there a way I can retrieve the posts without knowing the filters?

It works fine if I change the fragment to:

fragment PublisherPosts on PublisherType {
    posts(archived:false, collection:6, sort: "-ordering")
}

Is there a way I can query this data without having to know which filters are used? Something like posts* or even posts(*) (tried both BTW).


问:
Eventarc triggers for crossproject
I have created a cloud run service. My event arc is not triggering the cross project to read the data. How to give the event filter for resource name in event arc with insert job/Job completed to trigger to BQ table.

```<code>gcloud eventarc triggers create ${SERVICE}-test1\
  --location=${REGION} --service-account ${SVC_ACCOUNT} \
  --destination-run-service ${SERVICE}  \
  --destination-run-region=${REGION} \
  --event-filters type=google.cloud.audit.log.v1.written \
  --event-filters methodName=google.cloud.bigquery.v2.JobService.InsertJob \
  --event-filters serviceName=bigquery.googleapis.com \
  --event-filters-path-pattern resourceName="/projects/destinationproject/locations/us-central1/jobs/*"
</code>```

I have tried multiple options giving the resource name like:
"projects/projectname/datasets/outputdataset/tables/outputtable"

Title: Eventarc triggers for crossproject

Body:
I have created a cloud run service. My event arc is not triggering the cross project to read the data. How to give the event filter for resource name in event arc with insert job/Job completed to trigger to BQ table.

gcloud eventarc triggers create ${SERVICE}-test1\
  --location=${REGION} --service-account ${SVC_ACCOUNT} \
  --destination-run-service ${SERVICE}  \
  --destination-run-region=${REGION} \
  --event-filters type=google.cloud.audit.log.v1.written \
  --event-filters methodName=google.cloud.bigquery.v2.JobService.InsertJob \
  --event-filters serviceName=bigquery.googleapis.com \
  --event-filters-path-pattern resourceName="/projects/destinationproject/locations/us-central1/jobs/*"

I have tried multiple options giving the resource name like:
"projects/projectname/datasets/outputdataset/tables/outputtable"