问:
Unhandled Exception: [firebase_functions/internal] INTERNAL
I've a Flutter App Project which contains levels of permission, so, my main objective with this is allow an manager delete a user, making him not allowed anymore to login, deleting from FirebaseAuth.

I've a permission called "Deactivated" to prevent the user from logging in, but i really want to remove from FirebaseAuth too.

The only way I've found is using the Firebase Cloud Functions, so I tried to do very similar to FlutterFire Docs

When i execute using PostMan, it works perfectly, the user test is deleted as expected:
METHOD: Post
Url: https://us-central1-<DATABASE_NAME>.cloudfunctions.net/deleteUserByEmail/
Body -> Raw:

```<code>{
    "userEmail": "test@gmail.com"
}
</code>```

My index.js

```<code>const functions = require("firebase-functions");
const admin = require('firebase-admin');

admin.initializeApp();

exports.deleteUserByEmail = functions.https.onRequest(async (request, response) => {
    try {
        const userEmail = request.body.userEmail;
        admin.auth().getUserByEmail(userEmail)
            .then(userRecord => {
                const uid = userRecord.uid
                return admin.auth().deleteUser(uid)
                    .then(() => {
                        console.log("Successfully deleted user");
                        response.status(200).send('Delete User');
                        return
                    })
            }).catch(error => {
                throw new functions.https.HttpsError('invalid-argument', error.HttpsError);

            });
    } catch (err) {
        throw new functions.https.HttpsError('invalid-argument', "Error passing arguments into");
    }

})

</code>```

Part of my code that calls the code Flutter code:

```<code>HttpsCallable callable =
          FirebaseFunctions.instance.httpsCallable('deleteUserByEmail');
      try {
        final resp = await callable.call(<String, dynamic>{
          "userEmail" : userModel.email,
        });
      } on FirebaseFunctionsException catch (e) {
        debugPrint(e.toString());
      }
</code>```

Once i tap the button, i receive this error code:

```<code>E/flutter (20323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_functions/internal] INTERNAL
E/flutter (20323):
E/flutter (20323): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2      MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #3      HttpsCallable.call
package:cloud_functions/src/https_callable.dart:49
E/flutter (20323): <asynchronous suspension>
E/flutter (20323):
E/flutter (20323): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2      MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
</code>```

After some research I've found that some people had that problem when their code wasn't inside a tryCatch block, but mine was since ever...

I've tried to start admin.initializeApp() parsing the credentials and databaseURL even though my FlutterFire CLI is configured, but didn't work too.

Body:
I've a Flutter App Project which contains levels of permission, so, my main objective with this is allow an manager delete a user, making him not allowed anymore to login, deleting from FirebaseAuth.

I've a permission called "Deactivated" to prevent the user from logging in, but i really want to remove from FirebaseAuth too.

The only way I've found is using the Firebase Cloud Functions, so I tried to do very similar to FlutterFire Docs

When i execute using PostMan, it works perfectly, the user test is deleted as expected:
METHOD: Post
Url: https://us-central1-<DATABASE_NAME>.cloudfunctions.net/deleteUserByEmail/
Body -> Raw:

{
    "userEmail": "test@gmail.com"
}

My index.js

const functions = require("firebase-functions");
const admin = require('firebase-admin');

admin.initializeApp();

exports.deleteUserByEmail = functions.https.onRequest(async (request, response) => {
    try {
        const userEmail = request.body.userEmail;
        admin.auth().getUserByEmail(userEmail)
            .then(userRecord => {
                const uid = userRecord.uid
                return admin.auth().deleteUser(uid)
                    .then(() => {
                        console.log("Successfully deleted user");
                        response.status(200).send('Delete User');
                        return
                    })
            }).catch(error => {
                throw new functions.https.HttpsError('invalid-argument', error.HttpsError);

            });
    } catch (err) {
        throw new functions.https.HttpsError('invalid-argument', "Error passing arguments into");
    }

})

Part of my code that calls the code Flutter code:

HttpsCallable callable =
          FirebaseFunctions.instance.httpsCallable('deleteUserByEmail');
      try {
        final resp = await callable.call(<String, dynamic>{
          "userEmail" : userModel.email,
        });
      } on FirebaseFunctionsException catch (e) {
        debugPrint(e.toString());
      }

Once i tap the button, i receive this error code:

E/flutter (20323): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_functions/internal] INTERNAL
E/flutter (20323):
E/flutter (20323): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2      MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #3      HttpsCallable.call
package:cloud_functions/src/https_callable.dart:49
E/flutter (20323): <asynchronous suspension>
E/flutter (20323):
E/flutter (20323): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter (20323): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter (20323): <asynchronous suspension>
E/flutter (20323): #2      MethodChannelHttpsCallable.call
package:cloud_functions_platform_interface/…/method_channel/method_channel_https_callable.dart:23

After some research I've found that some people had that problem when their code wasn't inside a tryCatch block, but mine was since ever...

I've tried to start admin.initializeApp() parsing the credentials and databaseURL even though my FlutterFire CLI is configured, but didn't work too.


来源: stackexchange

问:
clustered bar graphs not showing properly with respect to category in amcharts3 java script
I have a day-wise top 10 users data up to one week in JSON string. I want to display the top 10 users (repeated/different users) per day so it will be like 10 bar graphs per day and a total of 70 bar graphs.

and I can provide data with unique names and able to create graph content dynamically with amcharts 3 but the first and last data are not showing and the remaining day's data is not positioned properly on the corresponding y-axis.

Please help me with where I am doing wrong.

```<code><script src="../js/amcharts.js" type="text/javascript"></script>
<script src="../js/serial.js" type="text/javascript"></script>
<script src="../js/statistics.js" type="text/javascript"></script>

<style>
#chartdiv {
        width           : 100%;
        height          : 300px;
        font-size       : 11px;
}
</style>
<div id="chartdiv"></div>
</code>```

statistics.js

```<code>function generateGraphs(chartData){
        var graphData=[];
        var rowData = chartData.split("},");

        for(var i=0;i<rowData.length;i++){
                if(rowData[i]){
                        var rowData1 =rowData[i].split(",");
                        for(var j=0;j<rowData1.length;j++){
                                if(rowData1[j]){
                                        var rowData2 = rowData1[j].split(":");
                                        var totalKey = rowData2[0];
                                        totalKey = totalKey.replaceAll('"', '');
                                        totalKey = totalKey.replaceAll('[', '');
                                        totalKey = totalKey.replaceAll('{', '');
                                        if(totalKey.toLowerCase()=="day"){
                                                continue;
                                        }
                                        var originalKey =totalKey.split("~");

                                        graphData.push({
                                                "balloonText": "<b>Tenant Name: "+originalKey[0]+"</b><br><b>Day: [[category]]</b><br>  <b>Max Used Active Calls: [[value]]</b></span>",
                                                "category":"[[category]]",
                                                "fillAlphas": 1,
                                                "lineAlpha": 1,
                                                "title":totalKey,
                                                "type": "column",
                                                "valueField":totalKey,
                                                "columnWidth": 5
                                        });
                                }
                        }
                }
        }
        return graphData;
}

AmCharts.ready(function() {
    var weekData = "[
{"RSN14~0":900,"RSN13~0":800,"RSN12~0":300,"RSN17~0":320,"RSN16~0":350,"RSN5~0":300,"RSN3~0":800,"RSN11~0":700,"Day":"Friday","RSN10~0":350,"RSN7~0":500},
{"RSN14~1":400,"RSN11~1":400,"RSN1~1":990,"RSN18~1":650,"RSN16~1":500,"RSN5~1":700,"RSN3~1":800,"RSN19~1":670,"RSN9~1":500,"Day":"Saturday","RSN7~1":600},
{"RSN9~2":90,"RSN10~2":85,"RSN16~2":71,"RSN15~2":60,"RSN14~2":50,"RSN19~2":49,"RSN8~2":80,"Day":"Sunday","RSN7~2":70,"RSN6~2":66,"RSN5~2":55},
{"RSN10~3":850,"RSN16~3":710,"RSN15~3":600,"RSN14~3":500,"RSN13~3":400,"RSN19~3":490,"RSN17~3":470,"Day":"Monday","RSN6~3":660,"RSN5~3":550,"RSN4~3":450},
{"RSN2~4":100,"Day":"Tuesday","RSN4~4":100,"RSN3~4":100},
{"RSN9~5":900,"RSN8~5":800,"RSN7~5":700,"RSN6~5":600,"RSN14~5":550,"RSN13~5":450,"RSN15~5":650,"RSN5~5":500,"Day":"Wednesday","RSN4~5":400,"RSN19~5":440},
{"RSN5~6":6,"RSN4~6":17,"Day":"Thursday","RSN3~6":16,"RSN2~6":15,"RSN1~6":20}
]";

chart2=new AmCharts.AmSerialChart();
        chart2.theme="light";
        chart2.dataProvider=eval(weekData);
        chart2.valueAxes=[{
                "type": "serial",
                "axisAlpha": 0.1,
                "gridAlpha": 0.1,
                "minimum" : 0
        }];
        chart2.graphs=generateGraphs(weekData);
        chart2.categoryField="Day";
        chart2.columnSpacing=0;
        chart2.categoryAxis.gridPosition="start";
        chart2.categoryAxis.axisAlpha=0.1;
        chart2.categoryAxis.gridAlpha=0.1;
        chart2.categoryAxis.boldLabels = true;
        chart2.write('chartdiv');
});
</code>```

Note: i will get 10 unique names on each day but they can repeat in other days if they are in top 10 of that day for that i added extra character(~ followed by row number) to maintain uniqueness for graphs.

Please help me how to fix this issue in amcharts3 or 4 or 5 or in primefaces also

Thanks

ContentLicense: CC BY-SA 4.0

Body:
I have a day-wise top 10 users data up to one week in JSON string. I want to display the top 10 users (repeated/different users) per day so it will be like 10 bar graphs per day and a total of 70 bar graphs.

and I can provide data with unique names and able to create graph content dynamically with amcharts 3 but the first and last data are not showing and the remaining day's data is not positioned properly on the corresponding y-axis.

Please help me with where I am doing wrong.

statistics.js

function generateGraphs(chartData){
        var graphData=[];
        var rowData = chartData.split("},");

        for(var i=0;i<rowData.length;i++){
                if(rowData[i]){
                        var rowData1 =rowData[i].split(",");
                        for(var j=0;j<rowData1.length;j++){
                                if(rowData1[j]){
                                        var rowData2 = rowData1[j].split(":");
                                        var totalKey = rowData2[0];
                                        totalKey = totalKey.replaceAll('"', '');
                                        totalKey = totalKey.replaceAll('[', '');
                                        totalKey = totalKey.replaceAll('{', '');
                                        if(totalKey.toLowerCase()=="day"){
                                                continue;
                                        }
                                        var originalKey =totalKey.split("~");

                                        graphData.push({
                                                "balloonText": "Tenant Name: "+originalKey[0]+"
Day: [[category]]
  Max Used Active Calls: [[value]]",
                                                "category":"[[category]]",
                                                "fillAlphas": 1,
                                                "lineAlpha": 1,
                                                "title":totalKey,
                                                "type": "column",
                                                "valueField":totalKey,
                                                "columnWidth": 5
                                        });
                                }
                        }
                }
        }
        return graphData;
}

AmCharts.ready(function() {
    var weekData = "[
{"RSN14~0":900,"RSN13~0":800,"RSN12~0":300,"RSN17~0":320,"RSN16~0":350,"RSN5~0":300,"RSN3~0":800,"RSN11~0":700,"Day":"Friday","RSN10~0":350,"RSN7~0":500},
{"RSN14~1":400,"RSN11~1":400,"RSN1~1":990,"RSN18~1":650,"RSN16~1":500,"RSN5~1":700,"RSN3~1":800,"RSN19~1":670,"RSN9~1":500,"Day":"Saturday","RSN7~1":600},
{"RSN9~2":90,"RSN10~2":85,"RSN16~2":71,"RSN15~2":60,"RSN14~2":50,"RSN19~2":49,"RSN8~2":80,"Day":"Sunday","RSN7~2":70,"RSN6~2":66,"RSN5~2":55},
{"RSN10~3":850,"RSN16~3":710,"RSN15~3":600,"RSN14~3":500,"RSN13~3":400,"RSN19~3":490,"RSN17~3":470,"Day":"Monday","RSN6~3":660,"RSN5~3":550,"RSN4~3":450},
{"RSN2~4":100,"Day":"Tuesday","RSN4~4":100,"RSN3~4":100},
{"RSN9~5":900,"RSN8~5":800,"RSN7~5":700,"RSN6~5":600,"RSN14~5":550,"RSN13~5":450,"RSN15~5":650,"RSN5~5":500,"Day":"Wednesday","RSN4~5":400,"RSN19~5":440},
{"RSN5~6":6,"RSN4~6":17,"Day":"Thursday","RSN3~6":16,"RSN2~6":15,"RSN1~6":20}
]";

chart2=new AmCharts.AmSerialChart();
        chart2.theme="light";
        chart2.dataProvider=eval(weekData);
        chart2.valueAxes=[{
                "type": "serial",
                "axisAlpha": 0.1,
                "gridAlpha": 0.1,
                "minimum" : 0
        }];
        chart2.graphs=generateGraphs(weekData);
        chart2.categoryField="Day";
        chart2.columnSpacing=0;
        chart2.categoryAxis.gridPosition="start";
        chart2.categoryAxis.axisAlpha=0.1;
        chart2.categoryAxis.gridAlpha=0.1;
        chart2.categoryAxis.boldLabels = true;
        chart2.write('chartdiv');
});

Note: i will get 10 unique names on each day but they can repeat in other days if they are in top 10 of that day for that i added extra character(~ followed by row number) to maintain uniqueness for graphs.

Please help me how to fix this issue in amcharts3 or 4 or 5 or in primefaces also

Thanks


问:
Problem in R trying to use Keras with Caret
I have to use Caret to fit a keras model. I am using the "mlpKerasDropout" model in Caret. I have already installed keras and tensorflow. I have the following code:

```<code>grid = expand.grid(activation = "relu", batch_size = 32, rho = 0.9, decay = 0,
                   lambda=0, lr = 2e-06, size = c(3,4,5))

control <- trainControl(method='cv',
                        number=5,
                        classProbs = TRUE,
                        selectionFunctio = 'oneSE',
                        savePredictions = "all",
                        search='grid')

model <- train(Class ~ .,
                       data = data,
                       method = 'mlpKerasDecay',
                       preProc = c("center", "scale"),
                       metric = "Accuracy",
                       trControl = control,
                       tuneGrid = grid,
                       epoch = 100)
</code>```

The think is that when I try to execute this code I get this error:

```<code>WARNING:absl:`lr` is deprecated, please use `learning_rate` instead, or use the legacy optimizer, e.g.,tf.keras.optimizers.legacy.RMSprop.
Warning: model fit failed for Fold1: activation=relu, batch_size=32, rho=0.9, decay=0, lambda=0, lr=2e-06, size=4 Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: decay is deprecated in the new Keras optimizer, pleasecheck the docstring for valid arguments, or use the legacy optimizer, e.g., tf.keras.optimizers.legacy.RMSprop.
</code>```

I can't change lr to learning_rate in the gris because caret gives me an error, and I can't remove the decay hyperparameter neither.

So how do I use this? I checked that I have caret updated, so thats not the problem. It is possible to use it or I have to downgrade keras and tensorflow so I can use caret? I don't really know how to downgrade those libraries and use them in R normally.

Body:
I have to use Caret to fit a keras model. I am using the "mlpKerasDropout" model in Caret. I have already installed keras and tensorflow. I have the following code:

grid = expand.grid(activation = "relu", batch_size = 32, rho = 0.9, decay = 0,
                   lambda=0, lr = 2e-06, size = c(3,4,5))

control <- trainControl(method='cv',
                        number=5,
                        classProbs = TRUE,
                        selectionFunctio = 'oneSE',
                        savePredictions = "all",
                        search='grid')

model <- train(Class ~ .,
                       data = data,
                       method = 'mlpKerasDecay',
                       preProc = c("center", "scale"),
                       metric = "Accuracy",
                       trControl = control,
                       tuneGrid = grid,
                       epoch = 100)

The think is that when I try to execute this code I get this error:

WARNING:absl:`lr` is deprecated, please use `learning_rate` instead, or use the legacy optimizer, e.g.,tf.keras.optimizers.legacy.RMSprop.
Warning: model fit failed for Fold1: activation=relu, batch_size=32, rho=0.9, decay=0, lambda=0, lr=2e-06, size=4 Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: decay is deprecated in the new Keras optimizer, pleasecheck the docstring for valid arguments, or use the legacy optimizer, e.g., tf.keras.optimizers.legacy.RMSprop.

I can't change lr to learning_rate in the gris because caret gives me an error, and I can't remove the decay hyperparameter neither.

So how do I use this? I checked that I have caret updated, so thats not the problem. It is possible to use it or I have to downgrade keras and tensorflow so I can use caret? I don't really know how to downgrade those libraries and use them in R normally.


问:
"You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file". Electron+Vue
I am trying to use the npm package "Typeorm" in my Electron + Vue project, but when I run it I have this error:

```<code>    Module parse failed: Unexpected character '' (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { EntitySchema } from "typeorm"
>
| export default new EntitySchema({
|     name: "Post", // Will use table name `post` as default behaviour.
</code>```

But I don't even have a webpack.config.js in my project. Not even inside files from frameworks that i'm using. So I can't follow the tips of this https://webpack.js.org/concepts#loaders.

The file that contains this import:
Category.js

```<code>import { EntitySchema } from "typeorm"

export default new EntitySchema({
    name: "Category", // Will use table name `category` as default behaviour.
    tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true,
        },
        name: {
            type: "varchar",
        },
    },
})
</code>```

This is my Babel.config:

```<code>module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
}
</code>```

To try to make it work, in my vue.config.js I added this "transpileDependecies", as suggested in @vue/cli-plugin-babel/preset . But it stills the same error.

vue.config.js

```<code>const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: [
   'typeorm'
  ],
  configureWebpack: {
    devtool: 'source-map',
  },

  pluginOptions: {
    vuetify: {
            // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vuetify-loader
        }
  }
})
</code>```

Other similar questions did not help..

Body:
I am trying to use the npm package "Typeorm" in my Electron + Vue project, but when I run it I have this error:

    Module parse failed: Unexpected character '' (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { EntitySchema } from "typeorm"
>
| export default new EntitySchema({
|     name: "Post", // Will use table name `post` as default behaviour.

But I don't even have a webpack.config.js in my project. Not even inside files from frameworks that i'm using. So I can't follow the tips of this https://webpack.js.org/concepts#loaders.

The file that contains this import:
Category.js

import { EntitySchema } from "typeorm"

export default new EntitySchema({
    name: "Category", // Will use table name `category` as default behaviour.
    tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true,
        },
        name: {
            type: "varchar",
        },
    },
})

This is my Babel.config:

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
}

To try to make it work, in my vue.config.js I added this "transpileDependecies", as suggested in @vue/cli-plugin-babel/preset . But it stills the same error.

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: [
   'typeorm'
  ],
  configureWebpack: {
    devtool: 'source-map',
  },

  pluginOptions: {
    vuetify: {
            // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vuetify-loader
        }
  }
})

Other similar questions did not help..


问:
How to pass array HTML elements to AJAX POST to C# controller
I have this form in HTML.

```<code><input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">
</code>```

myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName

```<code>document.getElementById('myForm').onsubmit = function ()
{
    var model = new FormData();
    model.append("myID", $('#myID').val());
    model.append("myName", $('#myName').val());

    $.ajax({
        url: "/MyController/MyMethod",
        type: "POST",
        data: model,
        contentType: false,
        processData: false,
        success: function (response) {
            Do_Something_Here;
        },
        error: function (xhr, error, thrown) {
            alert(xhr.responseText);
        }
    });
}
</code>```

Body:
I have this form in HTML.

<input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">

myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName

document.getElementById('myForm').onsubmit = function ()
{
    var model = new FormData();
    model.append("myID", $('#myID').val());
    model.append("myName", $('#myName').val());

    $.ajax({
        url: "/MyController/MyMethod",
        type: "POST",
        data: model,
        contentType: false,
        processData: false,
        success: function (response) {
            Do_Something_Here;
        },
        error: function (xhr, error, thrown) {
            alert(xhr.responseText);
        }
    });
}


问:
React.js files are minified and I cant make frontend changes
I have got web app which is built using laravel and react.js ; I need to change something in frontend but found that all react files are minified in app.js file, so changing frontend files does not have any effect. I don't have experience in react. Can you please suggest how to regenerate update minified app.js file?

thanks a lot!

I have tried changing frontend js files like normal but it was not working.


问:
can we share image to WhatsApp to a specific number by using intent in android studio?
I tried this code but did not get the image in WhatsApp. Do you have any other solutions?</p>
```<code>private final ActivityResultLauncher<String> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
 new ActivityResultCallback<Uri>() {
    @Override
    public void onActivityResult(Uri result) {
        Uri uri = Uri.parse("smsto:" + "01xxxx");
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
        sendIntent.putExtra(Intent.EXTRA_STREAM, result);
        sendIntent.setPackage("com.whatsapp");
        startActivity(sendIntent);
    }
});
</code>```

Body:
I tried this code but did not get the image in WhatsApp. Do you have any other solutions?

private final ActivityResultLauncher<String> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
 new ActivityResultCallback<Uri>() {
    @Override
    public void onActivityResult(Uri result) {
        Uri uri = Uri.parse("smsto:" + "01xxxx");
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
        sendIntent.putExtra(Intent.EXTRA_STREAM, result);
        sendIntent.setPackage("com.whatsapp");
        startActivity(sendIntent);
    }
});


问:
Intersection Observer API not working in ios device when opening a webview in it but working perfectly in web, android , safari browser
`Below mentioned is my code for intersection observer

useIntersectionObserver

```<code>/* eslint-disable @typescript-eslint/no-shadow */
import { RefObject, useEffect, useState } from 'react';

export default function useIntersectionObserver(
  elementRef: RefObject<Element>,
  { threshold = 0, root = null, rootMargin = '0%' }
) {
  const [entry, setEntry] = useState<IntersectionObserverEntry>();

  const callBackFunction = ([entry]: IntersectionObserverEntry[]): void => {
    setEntry(entry);
  };

  useEffect(() => {
    const node = elementRef?.current; // DOM Ref
    const isIOSupported = !!window.IntersectionObserver;
    if (!isIOSupported || !node) return;

    const observerOptions = { threshold, root, rootMargin };
    const observer = new IntersectionObserver(
      callBackFunction,
      observerOptions
    );

    observer.observe(node);

    return () => observer.disconnect();`your text`
  }, [elementRef, JSON.stringify(threshold), root, rootMargin]);
  return entry;
}
</code>```

Below is the code mentioned where I am calling useInterSectionObserver hook

```<code>const scrollDivElementRef = useRef<null | HTMLDivElement>(null);
const chatDivRef = useRef<null | HTMLDivElement>(null);
const entry = useIntersectionObserver(scrollDivElementRef, {});
const isVisible = !!entry?.isIntersecting;
</code>```

Here scrollDivElementRef is the ref of div which we are observing for the intersection.It is basically our sentinal element.

Below mentioned is the useEffect hook which is going to perform some action when isVisible will become true.

Below mentioned is a code in react-native webview ,basically we are opening our react web app inside ios app , but our intersection observer is not able to detect changes . We have implemented intersection observer for infinite  loading of messages. Every time user will scroll upwards , we will get "isVisible" as true and we will make an API call to fetch more messages.

```<code>  useEffect(() => {
    if (isVisible) {
      dispatch(
        getPostsForChannel(inputChannelId, true, channelMessages[0].timestamp)
      );
    }
  }, [isVisible]);
</code>```
```<code><View style={styles.container}>
        <WebView
          style={{ marginTop: 40 }}
          //TODO: Update the url
          source={{ uri: 'http://192.168.1.2:3000' }}
          onLoad={(syntheticEvent) => {
            const { nativeEvent } = syntheticEvent;
          }}
          javaScriptEnabled={true}
          onError={(e) => {
            const { nativeEvent } = e;
            setUrl(HOME_URL);
          }}
          onHttpError={() => {
            setUrl(HOME_URL);
          }}
          onMessage={onMessage}
          limitsNavigationsToAppBoundDomains={true}
          // injectedJavaScript="window.octNativeApp=true"
          injectedJavaScriptBeforeContentLoaded={initializeNativeApp}
          scalesPageToFit={false}
          setBuiltInZoomControls={false}
          useWebView2
          allowsInlineMediaPlayback={true}
          mediaPlaybackRequiresUserAction={false}
        ></WebView>
 </View>`
</code>```

It will be really very helpful , if you people can help me with this problem.

Thanks & Regards
Mohit

I tried giving the height & width to the webview but it is also not working.Tried almost every piece of advise available in other platforms but not able to fic this`

Body:
`Below mentioned is my code for intersection observer

useIntersectionObserver

/* eslint-disable @typescript-eslint/no-shadow */
import { RefObject, useEffect, useState } from 'react';

export default function useIntersectionObserver(
  elementRef: RefObject<Element>,
  { threshold = 0, root = null, rootMargin = '0%' }
) {
  const [entry, setEntry] = useState<IntersectionObserverEntry>();

  const callBackFunction = ([entry]: IntersectionObserverEntry[]): void => {
    setEntry(entry);
  };

  useEffect(() => {
    const node = elementRef?.current; // DOM Ref
    const isIOSupported = !!window.IntersectionObserver;
    if (!isIOSupported || !node) return;

    const observerOptions = { threshold, root, rootMargin };
    const observer = new IntersectionObserver(
      callBackFunction,
      observerOptions
    );

    observer.observe(node);

    return () => observer.disconnect();`your text`
  }, [elementRef, JSON.stringify(threshold), root, rootMargin]);
  return entry;
}

Below is the code mentioned where I am calling useInterSectionObserver hook

const scrollDivElementRef = useRef<null | HTMLDivElement>(null);
const chatDivRef = useRef<null | HTMLDivElement>(null);
const entry = useIntersectionObserver(scrollDivElementRef, {});
const isVisible = !!entry?.isIntersecting;

Here scrollDivElementRef is the ref of div which we are observing for the intersection.It is basically our sentinal element.

Below mentioned is the useEffect hook which is going to perform some action when isVisible will become true.

Below mentioned is a code in react-native webview ,basically we are opening our react web app inside ios app , but our intersection observer is not able to detect changes . We have implemented intersection observer for infinite  loading of messages. Every time user will scroll upwards , we will get "isVisible" as true and we will make an API call to fetch more messages.

  useEffect(() => {
    if (isVisible) {
      dispatch(
        getPostsForChannel(inputChannelId, true, channelMessages[0].timestamp)
      );
    }
  }, [isVisible]);

<View style={styles.container}>
        <WebView
          style={{ marginTop: 40 }}
          //TODO: Update the url
          source={{ uri: 'http://192.168.1.2:3000' }}
          onLoad={(syntheticEvent) => {
            const { nativeEvent } = syntheticEvent;
          }}
          javaScriptEnabled={true}
          onError={(e) => {
            const { nativeEvent } = e;
            setUrl(HOME_URL);
          }}
          onHttpError={() => {
            setUrl(HOME_URL);
          }}
          onMessage={onMessage}
          limitsNavigationsToAppBoundDomains={true}
          // injectedJavaScript="window.octNativeApp=true"
          injectedJavaScriptBeforeContentLoaded={initializeNativeApp}
          scalesPageToFit={false}
          setBuiltInZoomControls={false}
          useWebView2
          allowsInlineMediaPlayback={true}
          mediaPlaybackRequiresUserAction={false}
        ></WebView>
 </View>`

It will be really very helpful , if you people can help me with this problem.

Thanks & Regards
Mohit

I tried giving the height & width to the webview but it is also not working.Tried almost every piece of advise available in other platforms but not able to fic this`


问:
Cannot set cookie for parent domain
EDIT: I forgot to mention one important detail: even though the browser recieves it as system.client.com, the cookie is not sent on future requests to tat same backend

I have a site at system.client.com and another one for the same client at crm.client.com.

I want the users to be able to go to the system URL, log in, and have their sessions available at the CRM site.

As far as I can tell, that is very very easy. I just have to set the cookie's domain to '.client.com'

However it doesn't matter what I set (even random words, or another subdomain of system, or anything) the domain always arrives at my browser as "system.client.com".

(I believe this worked on my test system, but it's Saturday so I'm not at the office and can log in to check.)

I know the theory works and that both my browsers support it because I tested it with setcookie.net.

Go to a.setcookie.net, go to b.setcookie.net, from "a" set a cookie for ".setcookie.net", refresh "b" and the cookie will appear.

The one major difference between setcookie and my case is that for me, the front end's URL is 'client.com' and the backend is 'client.com:444'

So it has to be something with Express, or maybe IIS is messing with it?

I've set the cookies as a header with a string instead of using reponse.cookie() because I had no idea what else I could try. they both behaved the same way

function firmarYEncriptarCookie(reponse, cookie, value, origin) {
    try {
        let token = jwt.sign({ Dato: value.toString() }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_TIME })
        let iv = crypto.randomBytes(ivlength)
        let cipher = crypto.createCipheriv(algorithm, key, iv)
        let ciphered = cipher.update(token, inputEncoding, outputEncoding)
        ciphered += cipher.final(outputEncoding)
        let ciphertext = iv.toString(outputEncoding) + '-' + ciphered
        let tokenEncriptado = ciphertext
        let s = cookie+'='+tokenEncriptado+'; Path=/; Domain=.client.com; Secure; HttpOnly; SameSite=Lax'
        reponse.set('set-cookie',s)
        return true
    } catch (error) {
        throw new ErrorHandler('No se pudo firmar la cookie', 500, error.message)
    }
}
```

Title: Cannot set cookie for parent domain


问:
react-native-clı app run app at background
ı made react-native-clı app , ı have android homescreen widget . ı can send data to widget. ı am sending data every second to widget , it have to be constant . but when app closed ,app doesnt sends data. ı have to run app at background. ı dont understant headless js. ı find react-native-background-actions library but is it can work for me ? and how ı can do it ?
this is my code</p>
```<code>    import {View, Text, Button, NativeModules, TextInput} from 'react-native';
import React, {useEffect, useState} from 'react';
import moment from 'moment';
import Numeral from 'numeral';
import SharedGroupPreferences from 'react-native-shared-group-preferences';
const group = 'group.asap';

const MomentCountDown = props => {
  const SharedStorage = NativeModules.SharedStorage;
  const [now, setNow] = useState(moment());
  const dieDate = moment(props.birthDate).add(73.2, 'year');
  const untilDie = moment.duration(dieDate.diff(now));
  const age = moment.duration(now.diff(props.birthDate));
  const entireLive = moment.duration(80, 'years');

  //* percentage
  const percentage = (age.asSeconds() / entireLive.asSeconds()) * 100;
  const percentageString = Numeral(percentage).format('00.000000000');

  //* widget
  const [text, setText] = useState('');
  const widgetData = {text};
  const sendWidget = async () => {
    setText(percentageString);
    //* ios
    try {
      await SharedGroupPreferences.setItem('widgetKey', widgetData, group);
    } catch (error) {
      console.log({error});
    }
    //* android
    const tText = JSON.stringify({text});
    console.log(tText);
    SharedStorage.set(JSON.stringify({text}));
  };

  //* every second update date
  useEffect(() => {
    const GeriSayım = setInterval(() => {
      setNow(moment());
      //* send data to widget
      sendWidget();
    }, 100);
    return () => clearInterval(GeriSayım);
  }, [age]);

  return (
    <View className="">
      <Button title="ffff" onPress={() => sendWidget()} />
      <Text>% {percentageString}</Text>

      <View>
        <Text>you Lived</Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.years()} year
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.months()} month
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.days()} day
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.minutes()} min
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.seconds()} seconds
        </Text>
      </View>

      <View>
        <Text>you'll Live</Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.years()} year
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.months()} month
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.days()} day
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.minutes()} min
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.seconds()} seconds
        </Text>
      </View>
    </View>
  );
};

export default MomentCountDown;
</code>```

Body:
ı made react-native-clı app , ı have android homescreen widget . ı can send data to widget. ı am sending data every second to widget , it have to be constant . but when app closed ,app doesnt sends data. ı have to run app at background. ı dont understant headless js. ı find react-native-background-actions library but is it can work for me ? and how ı can do it ?
this is my code

    import {View, Text, Button, NativeModules, TextInput} from 'react-native';
import React, {useEffect, useState} from 'react';
import moment from 'moment';
import Numeral from 'numeral';
import SharedGroupPreferences from 'react-native-shared-group-preferences';
const group = 'group.asap';

const MomentCountDown = props => {
  const SharedStorage = NativeModules.SharedStorage;
  const [now, setNow] = useState(moment());
  const dieDate = moment(props.birthDate).add(73.2, 'year');
  const untilDie = moment.duration(dieDate.diff(now));
  const age = moment.duration(now.diff(props.birthDate));
  const entireLive = moment.duration(80, 'years');

  //* percentage
  const percentage = (age.asSeconds() / entireLive.asSeconds()) * 100;
  const percentageString = Numeral(percentage).format('00.000000000');

  //* widget
  const [text, setText] = useState('');
  const widgetData = {text};
  const sendWidget = async () => {
    setText(percentageString);
    //* ios
    try {
      await SharedGroupPreferences.setItem('widgetKey', widgetData, group);
    } catch (error) {
      console.log({error});
    }
    //* android
    const tText = JSON.stringify({text});
    console.log(tText);
    SharedStorage.set(JSON.stringify({text}));
  };

  //* every second update date
  useEffect(() => {
    const GeriSayım = setInterval(() => {
      setNow(moment());
      //* send data to widget
      sendWidget();
    }, 100);
    return () => clearInterval(GeriSayım);
  }, [age]);

  return (
    <View className="">
      <Button title="ffff" onPress={() => sendWidget()} />
      <Text>% {percentageString}</Text>

      <View>
        <Text>you Lived</Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.years()} year
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.months()} month
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.days()} day
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.minutes()} min
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {age.seconds()} seconds
        </Text>
      </View>

      <View>
        <Text>you'll Live</Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.years()} year
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.months()} month
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.days()} day
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.minutes()} min
        </Text>
        <Text className="text-2xl font-semibold text-left ">
          {untilDie.seconds()} seconds
        </Text>
      </View>
    </View>
  );
};

export default MomentCountDown;


问:
Laravel merge compressed PDF files without ghostscript
I have a problem with pdfMerger. I can't merge pdf files higher than the 1.4 version. I guess this problem is because I am using FPDI free version. How can I merge 1.5 PDF files without using Ghostscript? I don't have shell access to the hosting that I am using.

I tried to find different PDF classes to fix my problem, but I can't.


问:
how do i Join a List of DataFrames with each other based on two indexes (parent index and child index)
I have a List of DataFrames.
Each DataFrame has a parent index field and a child index field, both indexes contain UUIDs.

The first df has no parent and the index is 0 but all the other dfs have a parent.
Some dfs with multiple rows might not have a match in a child df, but there will always be at least one row that matches.

for example:

```<code>df_list[0] = pd.DataFrame({'a':[1,2,3,4],    'b':[4,5,6,7], 'parent_index':[0,0,0,0],'child_index':['index1','index2','index3','index4']})
df_list[1] = pd.DataFrame({'c':[11,12,13,14],'d':[4,5,6,7], 'parent_index':['index1','index1','index1','index1'],'child_index':['index11','index12','index13','index14']})
df_list[2] = pd.DataFrame({'e':[21,22,23,24],'f':[4,5,6,7], 'parent_index':['index14','index14','index14','index14'],'child_index':['index21','index22','index23','index24']})
df_list[3] = pd.DataFrame({'g':[31,32,33,34],'h':[4,5,6,7], 'parent_index':['index22','index22','index22','index22'],'child_index':['index31','index32','index33','index34']})
</code>```

Is there a function that accepts a list of dfs and returns one or multiple dfs after trying to merge each one with each other one?

If there is a function, the rest of the problem will be solved easily, if not, here are the other details.
The other main problem is that I want to merge the first df until it get to a child df that has multiple rows. Then, instead of repeating rows, I want it to continue by using the df with the multiple rows as if it is the parent df.
I was able to merge the first df correctly with the following code:

```<code># df = None
# last_merged_df_i = 0

list_of_dfs_w_many_rows = []

# current_index = '0_1'

df = df_list[0]

merges_count = 0

df.rename(columns={'parent_index':f'parent_index_{merges_count}','index_row':f'index_row_{merges_count}'}, inplace=True)

df_for_next_round = df_list[1:].copy()

at_least_one_merge = True

for j in range(1,15):
    if not at_least_one_merge:
        break

    at_least_one_merge = False

    # current_index = current_index + '_' + str(j+1)

    dfs_left = df_for_next_round.copy()
    df_for_next_round = []

    for temp_df in dfs_left:

        run_for_this_temp_df = False
        for c in temp_df.columns:
            if 'index' not in c:
                run_for_this_temp_df = True
        if not run_for_this_temp_df:
            df_for_next_round.append(temp_df)
            continue

#         print(current_index)
#         print(at_least_one_merge)
#         display(temp_df)
        if (temp_df.shape[0] == 1):

            display(temp_df)
            if (temp_df.iloc[0]['parent_index'] == df.iloc[0][f'index_row_{merges_count}']):

                temp_df.rename(columns={'parent_index':f'parent_index_{merges_count+1}','index_row':f'index_row_{merges_count+1}'}, inplace=True)

#                 print('df: ')
#                 display(df)
#                 print('temp_df: ')
#                 display(temp_df)

                df = df.merge(temp_df, how='left', left_on=f'index_row_{merges_count}', right_on=f'parent_index_{merges_count+1}')

                merges_count += 1

                at_least_one_merge = True
            else:
                df_for_next_round.append(temp_df)
        else:
            if j == 1:
                list_of_dfs_w_many_rows.append(temp_df)
</code>```

but the second part does not seem to work:

```<code># at_least_one_merge = True
for i in range(5):
    for temp_df2 in list_of_dfs_w_many_rows:

        merges_count = 0

        temp_df2.rename(columns={'parent_index':f'parent_index_{merges_count}','index_row':f'index_row_{merges_count}'}, inplace=True)

#         if not at_least_one_merge:
#             break

#         at_least_one_merge = False

#         current_index = temp_df2.iloc[0]['index_row'] + '_' + str(len(str(temp_df2.iloc[0]['index_row']).replace('_','')))

        dfs_left = df_for_next_round.copy()
        df_for_next_round = []

        for temp_df in dfs_left:

    #         run_for_this_temp_df = False
    #         for c in temp_df.columns:
    #             if 'index' not in c:
    #                 run_for_this_temp_df = True
    #         if not run_for_this_temp_df: continue

#             print(current_index)
#             print(at_least_one_merge)
#             display(temp_df)
            if (temp_df.shape[0] == 1):
#                 if (temp_df.iloc[0]['index_row'] == current_index):
#                     temp_df2 = temp_df2.merge(temp_df, how='left', on='index')

#                 print(temp_df2.iloc[0][f'index_row_{merges_count}'])
#                 print(temp_df.iloc[0]['parent_index'])

                if (temp_df.iloc[0]['parent_index'] == temp_df2.iloc[0][f'index_row_{merges_count}']):

                    display(temp_df)
                    display(temp_df2)

                    temp_df.rename(columns={'parent_index':f'parent_index_{merges_count+1}','index_row':f'index_row_{merges_count+1}'}, inplace=True)

#                     print('temp_df2: ')
#                     display(temp_df2)
#                     print('temp_df: ')
#                     display(temp_df)

                    temp_df2 = dtemp_df2f.merge(temp_df, how='left', left_on=f'index_row_{merges_count}', right_on=f'parent_index_{merges_count+1}')

                    merges_count += 1
#                     at_least_one_merge = True
                else:
                    df_for_next_round.append(temp_df)
</code>```

Any ideas or suggestion would be most appreciated.

```<code></code>```

Body:
I have a List of DataFrames.
Each DataFrame has a parent index field and a child index field, both indexes contain UUIDs.

The first df has no parent and the index is 0 but all the other dfs have a parent.
Some dfs with multiple rows might not have a match in a child df, but there will always be at least one row that matches.

for example:

df_list[0] = pd.DataFrame({'a':[1,2,3,4],    'b':[4,5,6,7], 'parent_index':[0,0,0,0],'child_index':['index1','index2','index3','index4']})
df_list[1] = pd.DataFrame({'c':[11,12,13,14],'d':[4,5,6,7], 'parent_index':['index1','index1','index1','index1'],'child_index':['index11','index12','index13','index14']})
df_list[2] = pd.DataFrame({'e':[21,22,23,24],'f':[4,5,6,7], 'parent_index':['index14','index14','index14','index14'],'child_index':['index21','index22','index23','index24']})
df_list[3] = pd.DataFrame({'g':[31,32,33,34],'h':[4,5,6,7], 'parent_index':['index22','index22','index22','index22'],'child_index':['index31','index32','index33','index34']})

Is there a function that accepts a list of dfs and returns one or multiple dfs after trying to merge each one with each other one?

If there is a function, the rest of the problem will be solved easily, if not, here are the other details.
The other main problem is that I want to merge the first df until it get to a child df that has multiple rows. Then, instead of repeating rows, I want it to continue by using the df with the multiple rows as if it is the parent df.
I was able to merge the first df correctly with the following code:

# df = None
# last_merged_df_i = 0

list_of_dfs_w_many_rows = []

# current_index = '0_1'

df = df_list[0]

merges_count = 0

df.rename(columns={'parent_index':f'parent_index_{merges_count}','index_row':f'index_row_{merges_count}'}, inplace=True)

df_for_next_round = df_list[1:].copy()

at_least_one_merge = True

for j in range(1,15):
    if not at_least_one_merge:
        break

    at_least_one_merge = False

    # current_index = current_index + '_' + str(j+1)

    dfs_left = df_for_next_round.copy()
    df_for_next_round = []

    for temp_df in dfs_left:

        run_for_this_temp_df = False
        for c in temp_df.columns:
            if 'index' not in c:
                run_for_this_temp_df = True
        if not run_for_this_temp_df:
            df_for_next_round.append(temp_df)
            continue

#         print(current_index)
#         print(at_least_one_merge)
#         display(temp_df)
        if (temp_df.shape[0] == 1):

            display(temp_df)
            if (temp_df.iloc[0]['parent_index'] == df.iloc[0][f'index_row_{merges_count}']):

                temp_df.rename(columns={'parent_index':f'parent_index_{merges_count+1}','index_row':f'index_row_{merges_count+1}'}, inplace=True)

#                 print('df: ')
#                 display(df)
#                 print('temp_df: ')
#                 display(temp_df)

                df = df.merge(temp_df, how='left', left_on=f'index_row_{merges_count}', right_on=f'parent_index_{merges_count+1}')

                merges_count += 1

                at_least_one_merge = True
            else:
                df_for_next_round.append(temp_df)
        else:
            if j == 1:
                list_of_dfs_w_many_rows.append(temp_df)

but the second part does not seem to work:

# at_least_one_merge = True
for i in range(5):
    for temp_df2 in list_of_dfs_w_many_rows:

        merges_count = 0

        temp_df2.rename(columns={'parent_index':f'parent_index_{merges_count}','index_row':f'index_row_{merges_count}'}, inplace=True)

#         if not at_least_one_merge:
#             break

#         at_least_one_merge = False

#         current_index = temp_df2.iloc[0]['index_row'] + '_' + str(len(str(temp_df2.iloc[0]['index_row']).replace('_','')))

        dfs_left = df_for_next_round.copy()
        df_for_next_round = []

        for temp_df in dfs_left:

    #         run_for_this_temp_df = False
    #         for c in temp_df.columns:
    #             if 'index' not in c:
    #                 run_for_this_temp_df = True
    #         if not run_for_this_temp_df: continue

#             print(current_index)
#             print(at_least_one_merge)
#             display(temp_df)
            if (temp_df.shape[0] == 1):
#                 if (temp_df.iloc[0]['index_row'] == current_index):
#                     temp_df2 = temp_df2.merge(temp_df, how='left', on='index')

#                 print(temp_df2.iloc[0][f'index_row_{merges_count}'])
#                 print(temp_df.iloc[0]['parent_index'])

                if (temp_df.iloc[0]['parent_index'] == temp_df2.iloc[0][f'index_row_{merges_count}']):

                    display(temp_df)
                    display(temp_df2)

                    temp_df.rename(columns={'parent_index':f'parent_index_{merges_count+1}','index_row':f'index_row_{merges_count+1}'}, inplace=True)

#                     print('temp_df2: ')
#                     display(temp_df2)
#                     print('temp_df: ')
#                     display(temp_df)

                    temp_df2 = dtemp_df2f.merge(temp_df, how='left', left_on=f'index_row_{merges_count}', right_on=f'parent_index_{merges_count+1}')

                    merges_count += 1
#                     at_least_one_merge = True
                else:
                    df_for_next_round.append(temp_df)

Any ideas or suggestion would be most appreciated.


问:
Check data from a database in discord.py
I am implementing a documentation system and it was necessary that the user can only register his data once, so I create a database to store the data given by the subject through the command. So, I need to find a way to verify that the subject used the command and if he does, then prohibit him from doing it again.

Create a function which would be in charge of taking the data and comparing if the user ID is in the database, then if it is, the command is prohibited. My function did not work.

Does anyone have a solution to check and ban the user from using the command? Thank you.

```<code>async def on_BDLA(ctx):
    user = ctx.author.id
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            datos = cursor.fetchall()
    if datos[4] == user:
        await ctx.send("Tu dni ya está registrado, no puedes hacerte otro.")

@bot.command()
@commands.check(on_BDLA)
async def crear_dni(ctx):
    status = True
    await ctx.send("Envía tu mensaje")
    respuesta = await bot.wait_for("message", timeout=60)
    respuesta = respuesta.content.split(", ")
    if status == False:
        await ctx.send("No tienes un DNI creado")
    elif status == True:
        dni_info = discord.Embed(title = f":card_index:DNI de {ctx.author.name}", description= f"**Nombre** \n➥ *{respuesta[0]}* \n**Apellido** \n➥ *{respuesta[1]}* \n**Nacimiento** \n➥ *{respuesta[2]}* \n**Nacionalidad** \n➥ *{respuesta[3]}* \n**ID** \n➥ *{ctx.author.id}*", color = discord.Color.purple() )
        dni_info.set_image(url="https://media.discordapp.net/attachments/1052061231680344134/1053135738180472832/banner.png")
        await ctx.send(embed = dni_info)
        async with aiosqlite.connect("main.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute(f"INSERT INTO users (nombre, apellido, nacimiento, nacionalidad, id) VALUES (?, ?, ?, ?, ?)", (respuesta[0], respuesta[1], respuesta[2], respuesta[3], ctx.author.id))
            await db.commit()
    return respuesta
</code>```
```<code>I hope to achieve a function that can help me verify the data and a way to prohibit it from using the command again.
</code>```

Body:
I am implementing a documentation system and it was necessary that the user can only register his data once, so I create a database to store the data given by the subject through the command. So, I need to find a way to verify that the subject used the command and if he does, then prohibit him from doing it again.

Create a function which would be in charge of taking the data and comparing if the user ID is in the database, then if it is, the command is prohibited. My function did not work.

Does anyone have a solution to check and ban the user from using the command? Thank you.

async def on_BDLA(ctx):
    user = ctx.author.id
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            datos = cursor.fetchall()
    if datos[4] == user:
        await ctx.send("Tu dni ya está registrado, no puedes hacerte otro.")

@bot.command()
@commands.check(on_BDLA)
async def crear_dni(ctx):
    status = True
    await ctx.send("Envía tu mensaje")
    respuesta = await bot.wait_for("message", timeout=60)
    respuesta = respuesta.content.split(", ")
    if status == False:
        await ctx.send("No tienes un DNI creado")
    elif status == True:
        dni_info = discord.Embed(title = f":card_index:DNI de {ctx.author.name}", description= f"**Nombre** \n➥ *{respuesta[0]}* \n**Apellido** \n➥ *{respuesta[1]}* \n**Nacimiento** \n➥ *{respuesta[2]}* \n**Nacionalidad** \n➥ *{respuesta[3]}* \n**ID** \n➥ *{ctx.author.id}*", color = discord.Color.purple() )
        dni_info.set_image(url="https://media.discordapp.net/attachments/1052061231680344134/1053135738180472832/banner.png")
        await ctx.send(embed = dni_info)
        async with aiosqlite.connect("main.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute(f"INSERT INTO users (nombre, apellido, nacimiento, nacionalidad, id) VALUES (?, ?, ?, ?, ?)", (respuesta[0], respuesta[1], respuesta[2], respuesta[3], ctx.author.id))
            await db.commit()
    return respuesta

I hope to achieve a function that can help me verify the data and a way to prohibit it from using the command again.


问:
Container Password Lost
I installed the docker container on Ubuntu 22.04.

I run the container with the following command:

```<code>docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v /opt/portainer:/data portainer/portainer
</code>```

I set-up a password. But for a reason I can't explain, I can no more log in the portainer interface.

I followed the steps on this page to reset my password.

```<code>docker stop d9f2424e6cde934b3134b310e486e545b4962e6ff334c890d1f16b9cf3ea584f
d9f2424e6cde934b3134b310e486e545b4962e6ff334c890d1f16b9cf3ea584f
user@Precision-T1700:~$ docker pull portainer/helper-reset-password
docker run --rm -v portainer_data:/data portainer/helper-reset-password
Using default tag: latest
latest: Pulling from portainer/helper-reset-password
Digest: sha256:c7a141cf048762901dd97d6f1558b6e57d1f6e2827c6b07d894bae805deb16fb
Status: Image is up to date for portainer/helper-reset-password:latest
docker.io/portainer/helper-reset-password:latest
time="2022-12-17T18:12:48Z" level=info msg="Loading PortainerDB: portainer.db"
2022/12/17 18:12:49 Unable to open the database, err: timeout
</code>```

I get the above error, and I can't figure out what is the issue.

Any help is welcome (an explanation would be a plus)

Title: Container Password Lost

Body:
I installed the docker container on Ubuntu 22.04.

I run the container with the following command:

docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v /opt/portainer:/data portainer/portainer

I set-up a password. But for a reason I can't explain, I can no more log in the portainer interface.

I followed the steps on this page to reset my password.

docker stop d9f2424e6cde934b3134b310e486e545b4962e6ff334c890d1f16b9cf3ea584f
d9f2424e6cde934b3134b310e486e545b4962e6ff334c890d1f16b9cf3ea584f
user@Precision-T1700:~$ docker pull portainer/helper-reset-password
docker run --rm -v portainer_data:/data portainer/helper-reset-password
Using default tag: latest
latest: Pulling from portainer/helper-reset-password
Digest: sha256:c7a141cf048762901dd97d6f1558b6e57d1f6e2827c6b07d894bae805deb16fb
Status: Image is up to date for portainer/helper-reset-password:latest
docker.io/portainer/helper-reset-password:latest
time="2022-12-17T18:12:48Z" level=info msg="Loading PortainerDB: portainer.db"
2022/12/17 18:12:49 Unable to open the database, err: timeout

I get the above error, and I can't figure out what is the issue.

Any help is welcome (an explanation would be a plus)


问:
Font rendering in Chrome is affected by focusing unrelated input element
When an input element is focused, Chrome changes the font rendering of other unrelated elements.

Here is a MCVE:

    <input value="Click here 1">

This text changes when you click input, then click white text

This text doesn't change (click here 2)

```

If you run the snippet, and you click between the input field and the white text element, you will see that the red text element font rendering changes.

I'm able to reproduce this issue in Chrome, but not in Firefox.

It does not make sense to me why the font rendering of the red element should change depending on which of these 2 other unrelated elements are being focused.

Also, it does not make sense to me why this issue affects only some color combinations (e.g. affects red on black, but does not affect white on black).

Also, it does not make sense to me why the "Computed" tab in Chrome dev tools is pretending to be rendering the text in the same manner in both cases, when clearly the text is being differently rendered in these cases.

I discovered from another answer that I'm able to "fix" the issue by setting backface-visibility: hidden; on the red element. When I set that, the font is now rendered the same way regardless of which element is being focused. However, it does not make sense to me why backface-visibility should have any effect in this case. Based on reading the spec, it sounds like this is a bug in Chrome.

I would like to understand if this is a bug in Chrome, or if I'm just misunderstanding something.

Body:
When an input element is focused, Chrome changes the font rendering of other unrelated elements.

Here is a MCVE:

    <input value="Click here 1">

This text changes when you click input, then click white text

This text doesn't change (click here 2)

If you run the snippet, and you click between the input field and the white text element, you will see that the red text element font rendering changes.

I'm able to reproduce this issue in Chrome, but not in Firefox.

It does not make sense to me why the font rendering of the red element should change depending on which of these 2 other unrelated elements are being focused.

Also, it does not make sense to me why this issue affects only some color combinations (e.g. affects red on black, but does not affect white on black).

Also, it does not make sense to me why the "Computed" tab in Chrome dev tools is pretending to be rendering the text in the same manner in both cases, when clearly the text is being differently rendered in these cases.

I discovered from another answer that I'm able to "fix" the issue by setting backface-visibility: hidden; on the red element. When I set that, the font is now rendered the same way regardless of which element is being focused. However, it does not make sense to me why backface-visibility should have any effect in this case. Based on reading the spec, it sounds like this is a bug in Chrome.

I would like to understand if this is a bug in Chrome, or if I'm just misunderstanding something.


问:
Dashboard not reachable after successfully deploying eclipse che on AKS cluster
I am installing the eclipse che in AKS using chectl. But, the dashboard page is not reachable even after the successful installation.

Command used for installation-

```<code>chectl server:deploy --platform=k8s --installer=operator --che-operator-cr-patch-yaml=C:\Users\Act9\Desktop\che.yaml --skip-oidc-provider-check --domain=impaktapps.com --k8spodreadytimeout=600000
</code>```

Complete details of the issue are mentioned here :
https://github.com/eclipse/che/issues/21886

Body:
I am installing the eclipse che in AKS using chectl. But, the dashboard page is not reachable even after the successful installation.

Command used for installation-

chectl server:deploy --platform=k8s --installer=operator --che-operator-cr-patch-yaml=C:\Users\Act9\Desktop\che.yaml --skip-oidc-provider-check --domain=impaktapps.com --k8spodreadytimeout=600000

Complete details of the issue are mentioned here :
https://github.com/eclipse/che/issues/21886


Title: Putting a big amount of data to a two dimentional 20x20 array in PHP crashes the program

Body:
I'm solving a programming problem from projecteuler and I've created a 2 dimensional array using the data provided which looks like this:

$data_array = array(
array(08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08),
array(49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00),
array(81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65),
array(52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91),
array(22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80),
array(24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50),
array(32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70),
array(67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21),
array(24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72),
array(21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95),
array(78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92),
array(16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57),
array(86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58),
array(19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40),
array(04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66),
array(88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69),
array(04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36),
array(20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16),
array(20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54),
array(01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48),
);

everything in the program works well but only this part whcih makes the program crash, I have ini_set('display_errors', 1); and error_reporting(E_ALL ^ E_NOTICE); set but no errors are shown, it's just a blank page. If I comment out the block I've written above then the rest of the program will be executed but when I un-comment it again it crashes.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
$data_array = array(
    array(08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08),
    array(49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00),
    array(81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65),
    array(52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91),
    array(22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80),
    array(24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50),
    array(32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70),
    array(67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21),
    array(24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72),
    array(21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95),
    array(78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92),
    array(16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57),
    array(86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58),
    array(19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40),
    array(04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66),
    array(88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69),
    array(04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36),
    array(20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16),
    array(20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54),
    array(01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48),
);
echo ("test1: works");
$biggest = 1788696;
    function check_horizontal_four()
    {
        global $biggest, $data_array;
        for ($row=0; $row < 20; $row++) {
            for ($column=0; $column <= 16; $column++) {
                $buffer =  $data_array[$row][$column] * $data_array[$row][$column + 1] * $data_array[$row][$column + 2]
                * $data_array[$row][$column + 3];
                if ( $buffer > $biggest) {
                $biggest = $buffer;
                echo ($buffer);
                }
            }
        }
    }
    function check_vertical_four()
    {
        global $biggest, $data_array;
        for ($column=0; $column < 20; $column++) {
            for ($row=0; $row <= 16; $row++) {
                $buffer =  $data_array[$row][$column] * $data_array[$row + 1][$column] * $data_array[$row + 2][$column]
                * $data_array[$row + 3][$column];
                if ( $buffer > $biggest) {
                $biggest = $buffer;
                echo ($buffer);
                }
            }
        }
    }
    function check_diagonal_four()
    {
        global $biggest, $data_array;
        for ($row=0; $row <= 16; $row++) {
            for ($column=0; $column <= 16; $column++) {
                $buffer =  $data_array[$row][$column] * $data_array[$row + 1][$column + 1] * $data_array[$row + 2][$column + 2]
                * $data_array[$row + 3][$column + 3];
                if ( $buffer > $biggest) {
                $biggest = $buffer;
                echo ($buffer);
                }
            }
        }
    }
check_vertical_four();
echo "
";
check_horizontal_four();
echo "
";
check_diagonal_four();
echo $buffer;
?>

<?php echo "test 2: works" ?>

edit: I'm using php7.4 and as KIKO Software mentioned numbers starting with a 0 are acted as octal (which I didn't know), there are some 09s and 08s in the array which causes the crash and fixing them solved the issue


问:
how to use module inside modul
so, i'am trying to make multi module app, and my app is having a module inside of another module. It looks like this :

And i want to navigate from feature-anime to favorite with navigation component. But when i implement favorite from feature-anime gradle failed because of circular dependencies, and if i don't implement from the favorite module, i can't link my navigation in feature-anime into favorite. So what should i do?

Title: how to use module inside modul


问:
attempt to index nil with fireserver - how to fix?
```<code>local remotevent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

script.Parent.MouseButton1Click:Connect(function()
    remoteevent:FireServer("mardukpt")
end)
</code>```

Players.Wolfzone72.PlayerGui.ScreenGui.Frame.marduktp.LocalScript:5: attempt to index nil with 'FireServer'  -  Client - LocalScript:5

Body:
local remotevent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

script.Parent.MouseButton1Click:Connect(function()
    remoteevent:FireServer("mardukpt")
end)

Players.Wolfzone72.PlayerGui.ScreenGui.Frame.marduktp.LocalScript:5: attempt to index nil with 'FireServer'  -  Client - LocalScript:5


问:
Achieving stateless, paginated, complex queries
I'm very new to backend design and RESTful APIs, and I'm trying to get my head around pagination when the query is more than a simple filter.

Say for example the request should:

Pull data according to query A

Pull data according to query B

Sort both lists according to their overall relevance to both query A & query B

Return a limited response and an identifier for the next set of responses.

I see two ways of doing this:

Store the list in step 3, but that's not scalable for many users.

Repeat steps 1,2,3, slicing and return a different section each time.

A workaround could be to sort the results from query A and B, merge them in step 3, assuming it won't change either list's inner order, then send an identifier with the last ID in both lists, to cut down the processing time.

I'm wondering how a query like this is done in practice and if there's a more direct approach to achieving this both statelessly and efficiently.


问:
google docs extension shortcut
Im tried to write a post with code in google docs.

I have codeblock extension, but it‘s a little bit annoying to add code blocks-several clicks are needed…

I want google docs‘s code block extension keyboard shortcut.
anyone knows how to?
also, is there any method to put code blocks easy in google docs like other editors(notion etc.)?

Title: google docs extension shortcut


问:
What is the error in this python pygame script?
An error occured in the code below. The error happened in the function Sinewave and the line

```<code>sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))
</code>```

Sinewave function:

```<code>def SineWave(freq=1000, volume=16000, length=1):

num_steps = length * 22050
s = []

for n in range(num_steps):
    value = int(math.sin(n * freq * (6.28318/22050) * length) * volume)
    s.append( [value, value] )
return s
</code>```

I am trying to make sine waves in different frequencies to make scales.

```<code>import pygame
import math

#Set the frequency for each note in the scale
scale = {
    'C': 261.63,
    'D': 293.66,
    'E': 329.63,
    'F': 349.23,
    'G': 392.00,
    'A': 440.00,
    'B': 493.88
}

#Set the duration of each note (in seconds)
duration = 0.5

#Initialize the pygame library
pygame.init()
def SineWave(freq=1000, volume=16000, length=1):

num_steps = length * 22050
s = []

for n in range(num_steps):
    value = int(math.sin(n * freq * (6.28318/22050) * length) * volume)
    s.append( [value, value] )
return s

#Set the volume
pygame.mixer.music.set_volume(1.0)

#Play the scale
for note in scale:
    frequency=scale[note]
    # Generate a sine wave for the note
    sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))

# Play the note
sine_wave.play()
# Wait for the note to finish playing
pygame.time.wait(int(duration * 1000))

#Quit pygame
pygame.quit()
</code>```

It produces the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/(username)/AppData/Local/Programs/Python/Python310/Scripts/scales.py", line 36, in <module>
    sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))
  File "C:\Users\(username)\AppData\Local\Programs\Python\Python310\lib\site-packages\pygame\sndarray.py", line 92, in make_sound
    return mixer.Sound(array=array)
ValueError: list object does not export an array buffer
</code>```

Body:
An error occured in the code below. The error happened in the function Sinewave and the line

sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))

Sinewave function:

def SineWave(freq=1000, volume=16000, length=1):

num_steps = length * 22050
s = []

for n in range(num_steps):
    value = int(math.sin(n * freq * (6.28318/22050) * length) * volume)
    s.append( [value, value] )
return s

I am trying to make sine waves in different frequencies to make scales.

import pygame
import math

#Set the frequency for each note in the scale
scale = {
    'C': 261.63,
    'D': 293.66,
    'E': 329.63,
    'F': 349.23,
    'G': 392.00,
    'A': 440.00,
    'B': 493.88
}

#Set the duration of each note (in seconds)
duration = 0.5

#Initialize the pygame library
pygame.init()
def SineWave(freq=1000, volume=16000, length=1):

num_steps = length * 22050
s = []

for n in range(num_steps):
    value = int(math.sin(n * freq * (6.28318/22050) * length) * volume)
    s.append( [value, value] )
return s

#Set the volume
pygame.mixer.music.set_volume(1.0)

#Play the scale
for note in scale:
    frequency=scale[note]
    # Generate a sine wave for the note
    sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))

# Play the note
sine_wave.play()
# Wait for the note to finish playing
pygame.time.wait(int(duration * 1000))

#Quit pygame
pygame.quit()

It produces the following error:

Traceback (most recent call last):
  File "C:/Users/(username)/AppData/Local/Programs/Python/Python310/Scripts/scales.py", line 36, in <module>
    sine_wave = pygame.sndarray.make_sound(SineWave(frequency,16000,2))
  File "C:\Users\(username)\AppData\Local\Programs\Python\Python310\lib\site-packages\pygame\sndarray.py", line 92, in make_sound
    return mixer.Sound(array=array)
ValueError: list object does not export an array buffer


问:
Get all videos from an Official Artist Channel
It has been almost 5 years since YouTube rolled out Official Artist Channel. I'm surprised that this is not supported anywhere in the YouTube Data API.

What I'm trying to achieve is simple: Given a channel ID of an Official Artist Channel, retrieve all videos of the artist available on its page.

The typical solution to this problem would be to fetch a list of videos that has the channel ID:

search = build_youtube_api().search()
request = search.list(
    part="snippet",
    channelId=self.id,
    maxResults=50,
    order="date",
    type="video",
)

# and then keep calling list_next() until reaching the end
```

The problem is that this method only lists some of the videos, while other videos listed on the page are still linked to the original channel before the combination.

For instance, Adele - I Drink Wine is listed on Adele's official artist channel with a channel ID of UCsRM0YB_dabtEPGPTKo-gcw. However, the video can not be fetched with the method above since the channel of that video is UComP_epzeKzvBX156r6pm1Q, which is AdeleVEVO.

Another method I tried is to use a hacky way mentioned here, to find all channels that have been combined, then combine uploaded video from these channels. Sadly, this is also not working since not all artist put their old channels into the Featured Channels list (more horribly, some even place other unrelated artists in this section, which complicates the situation).

Moreover, there is no known method to distinguish whether a channel is an official artist channel or a regular video channel.

TL;DR for the API engineers: We need more granular API fields to support usage related to Official Artist Channel and music channels.

Body:
It has been almost 5 years since YouTube rolled out Official Artist Channel. I'm surprised that this is not supported anywhere in the YouTube Data API.

What I'm trying to achieve is simple: Given a channel ID of an Official Artist Channel, retrieve all videos of the artist available on its page.

The typical solution to this problem would be to fetch a list of videos that has the channel ID:

search = build_youtube_api().search()
request = search.list(
    part="snippet",
    channelId=self.id,
    maxResults=50,
    order="date",
    type="video",
)

# and then keep calling list_next() until reaching the end

The problem is that this method only lists some of the videos, while other videos listed on the page are still linked to the original channel before the combination.

For instance, Adele - I Drink Wine is listed on Adele's official artist channel with a channel ID of UCsRM0YB_dabtEPGPTKo-gcw. However, the video can not be fetched with the method above since the channel of that video is UComP_epzeKzvBX156r6pm1Q, which is AdeleVEVO.

Another method I tried is to use a hacky way mentioned here, to find all channels that have been combined, then combine uploaded video from these channels. Sadly, this is also not working since not all artist put their old channels into the Featured Channels list (more horribly, some even place other unrelated artists in this section, which complicates the situation).

Moreover, there is no known method to distinguish whether a channel is an official artist channel or a regular video channel.

TL;DR for the API engineers: We need more granular API fields to support usage related to Official Artist Channel and music channels.


问:
Regex Parse nltk rules confution
Hello I would like to create some rules using the nltk python library to check whenever a city name is the origin or the destination in a flight sentence. For example: "I would like 3 tickets from Qatar to Mexico" should return Qatar as the first city name so it would be the origin and Mexico should be the destination. I have tuples tagging each word with the propper taggers so for Qatar and Mexico i have the tagger 'np000g0' and I'm trying to set the rule to check for this tagg. My rules are defined as followed:

```<code>rules = r'''
origin: {}
destination: {<np000g0>.*?(<np000g0>)}
quantity: {<mccp00>|<z>} '''
</code>```

But it's not working; any ideas how to fix it?

Title: Regex Parse nltk rules confution

Body:
Hello I would like to create some rules using the nltk python library to check whenever a city name is the origin or the destination in a flight sentence. For example: "I would like 3 tickets from Qatar to Mexico" should return Qatar as the first city name so it would be the origin and Mexico should be the destination. I have tuples tagging each word with the propper taggers so for Qatar and Mexico i have the tagger 'np000g0' and I'm trying to set the rule to check for this tagg. My rules are defined as followed:

rules = r'''
origin: {}
destination: {<np000g0>.*?(<np000g0>)}
quantity: {<mccp00>|<z>} '''

But it's not working; any ideas how to fix it?


问:
Trying to upload my project to pythonanywhere.com and getting errors
I need help. I'm trying to upload my project to pythonanywhere.com and getting errors. Who knows the solution?

I tried to google and find a solution to the problem. But the results were in vain, like Sisyphean labor
errors


问:
Postgres local volumes gets deleted when using golang air
I am getting the failed to initialize error whenever I start up my docker container service.

```<code>version: '3'

services:
  app:
    container_name: api
    build:
      context: .
      dockerfile: local.Dockerfile
    ports:
      - "9090:9090"
      - "40000:40000"
    security_opt:
      - "seccomp:unconfined"
    cap_add:
      - SYS_PTRACE
    restart: on-failure
    environment:
      PORT: 9090
      DB_CONN: "postgres://admin:pass@db:5432/test?sslmode=disable"
    volumes:
      - .:/app
    depends_on:
      - db
    links:
      - db

  db:
    image: postgres
    container_name: db
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: "admin"
      POSTGRES_PASSWORD: "pass"
      POSTGRES_DB: "test"
      TZ: "UTC"
      PGTZ: "UTC"
    volumes:
      - ./tmp:/var/lib/postgresql/data
</code>```

I am using air for live reload, please find the air.toml file

```<code>root="."
tmp_dir="tmp"

[build]
cmd="go build -gcflags=\"all=-N -l\" -o ./bin/main ."
bin="/app/bin"
full_bin="/app/bin/main"
log="air_errors.log"
include_ext=["go", "yaml"]
exclude_dir=["tmp"]
delay=1000

[log]
time=true

[misc]
clean_on_exit=true

func main() {
    Instance, err = gorm.Open(postgres.Open(conn), &gorm.Config{
            Logger: logger.New(
                log.New(os.Stdout, "", log.LstdFlags), logger.Config{
                    LogLevel: logger.Info,
                    Colorful: true,
                }),
        })
        if err != nil {
            panic("Cannot connect to DB" + err.Error())
        }
    }
</code>```

Intially when the containers are up, the volumes are there, a tmp
folder gets generated in the local machine, but when we run docker compose down  the tmp folder gets deleted, it doesn't gets deleted if the air live reloads the code.

The volumes persists if air package  is removed and golang runs normally

Body:
I am getting the failed to initialize error whenever I start up my docker container service.

version: '3'

services:
  app:
    container_name: api
    build:
      context: .
      dockerfile: local.Dockerfile
    ports:
      - "9090:9090"
      - "40000:40000"
    security_opt:
      - "seccomp:unconfined"
    cap_add:
      - SYS_PTRACE
    restart: on-failure
    environment:
      PORT: 9090
      DB_CONN: "postgres://admin:pass@db:5432/test?sslmode=disable"
    volumes:
      - .:/app
    depends_on:
      - db
    links:
      - db

  db:
    image: postgres
    container_name: db
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: "admin"
      POSTGRES_PASSWORD: "pass"
      POSTGRES_DB: "test"
      TZ: "UTC"
      PGTZ: "UTC"
    volumes:
      - ./tmp:/var/lib/postgresql/data

I am using air for live reload, please find the air.toml file

root="."
tmp_dir="tmp"

[build]
cmd="go build -gcflags=\"all=-N -l\" -o ./bin/main ."
bin="/app/bin"
full_bin="/app/bin/main"
log="air_errors.log"
include_ext=["go", "yaml"]
exclude_dir=["tmp"]
delay=1000

[log]
time=true

[misc]
clean_on_exit=true

func main() {
    Instance, err = gorm.Open(postgres.Open(conn), &gorm.Config{
            Logger: logger.New(
                log.New(os.Stdout, "", log.LstdFlags), logger.Config{
                    LogLevel: logger.Info,
                    Colorful: true,
                }),
        })
        if err != nil {
            panic("Cannot connect to DB" + err.Error())
        }
    }

Intially when the containers are up, the volumes are there, a tmp
folder gets generated in the local machine, but when we run docker compose down  the tmp folder gets deleted, it doesn't gets deleted if the air live reloads the code.

The volumes persists if air package  is removed and golang runs normally


问:
I implemented ADS in recycler view every 3 items but repeats the first 3 items everytime
I tried implementing ADS in recycler view every 3 items but instead of following the next items in the list of items, it repeats the first 3 times over and over until the list.size() is over.
AdMob , ad item in Recycler View hides some items and creates spaces after the ad
For achieving this, i tried to implement this code abovein my own code and it works fine except for the repetition of the first 3 items. The code is modified to satisfy my needs, so it may seem strange.

```<code>open class AdsAdapter2(override val activity: FragmentActivity, var dataSet: MutableList<adslist>, protected var itemLayoutRes: Int,
    showSectionName: Boolean = true) : AbsMultiSelectAdapter<AdsAdapter2.ViewHolder, adslist>(activity, R.menu.menu_media_selection),
    PopupTextProvider {
    var onItemClick: ((adslist) -> Unit)? = null
    private var showSectionName = true

    init {
        this.showSectionName = showSectionName
        this.setHasStableIds(true)
    }

    open fun swapDataSet(dataSet: List<adslist>) {
        this.dataSet = ArrayList(dataSet)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (viewType == AD_VIEWTYPE){

            val v = LayoutInflater.from(activity).inflate(R.layout.item_favourite_card, parent, false)

            return ViewHolder(v)
        }
        else{
             val v = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)

             return ViewHolder(v)

        }
    }

 override fun onBindViewHolder(holder: ViewHolder, position: Int) {

       val card = getCardForPosition(position)
        if (card == null){
            Picasso.get().load(R.drawable.default_artist_art).into(holder.image)
        } else {

            // holder.courseNameTV.text = song.artistandname
            if (card.img == 0) {
                Picasso.get().load(card.img2).into(holder.img)
            } else {
                Picasso.get().load(card.img).into(holder.img)
            }
        }
    }

    override fun getItemCount() = dataSet.size + (dataSet.size / ITEMS_PER_AD)

    override fun getIdentifier(position: Int): adslist? {
        return getCardForPosition(position)
    }

open inner  class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) {

        protected open val adslist: adslist
            get() = dataSet[layoutPosition]

        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(getCardForPosition(position)!!) //WHEN AD CLICKED ==NULL
            }
        }

        val img: AppCompatImageView = itemView.findViewById(R.id.image)
        val layput: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)
        val layout: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        val image: AppCompatImageView = itemView.findViewById(R.id.image)
        val title: MaterialTextView = itemView.findViewById(R.id.title)

    }

    companion object {
        val TAG: String = AdsAdapter2::class.java.simpleName
        const val ITEMS_PER_AD = 3
        const val AD_FREQUENCY = ITEMS_PER_AD + 1
        const val AD_VIEWTYPE = 0
        const val CARD_VIEWTYPE = 1
    }

    override fun onMultipleItemAction(menuItem: MenuItem, selection: List<adslist>) {
        TODO("Not yet implemented")
    }

    override fun getPopupText(position: Int): String {
        TODO("Not yet implemented")
    }

    override fun getName(model: adslist): String? {
        TODO("Not yet implemented")
    }

    private fun isCard(position: Int) = (position + 1) % AD_FREQUENCY != 0

    private fun getCardForPosition(position: Int): adslist? {
        val offset = position / AD_FREQUENCY
        return if (isCard(position)) dataSet[position - offset] else null
    }

    override fun getItemViewType(position: Int) =
        if (isCard(position)) CARD_VIEWTYPE else AD_VIEWTYPE

}
</code>```

The logic of knowing which part of the list is gonna be an AD or a CARD is explained in the answer of the url above and it is applied on the last 3 functions and i do think the problem resides there but i cant see it clearly.

I'm not  a super developer so it could be something so simple

Body:
I tried implementing ADS in recycler view every 3 items but instead of following the next items in the list of items, it repeats the first 3 times over and over until the list.size() is over.
AdMob , ad item in Recycler View hides some items and creates spaces after the ad
For achieving this, i tried to implement this code abovein my own code and it works fine except for the repetition of the first 3 items. The code is modified to satisfy my needs, so it may seem strange.

open class AdsAdapter2(override val activity: FragmentActivity, var dataSet: MutableList<adslist>, protected var itemLayoutRes: Int,
    showSectionName: Boolean = true) : AbsMultiSelectAdapter<AdsAdapter2.ViewHolder, adslist>(activity, R.menu.menu_media_selection),
    PopupTextProvider {
    var onItemClick: ((adslist) -> Unit)? = null
    private var showSectionName = true

    init {
        this.showSectionName = showSectionName
        this.setHasStableIds(true)
    }

    open fun swapDataSet(dataSet: List<adslist>) {
        this.dataSet = ArrayList(dataSet)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (viewType == AD_VIEWTYPE){

            val v = LayoutInflater.from(activity).inflate(R.layout.item_favourite_card, parent, false)

            return ViewHolder(v)
        }
        else{
             val v = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)

             return ViewHolder(v)

        }
    }

 override fun onBindViewHolder(holder: ViewHolder, position: Int) {

       val card = getCardForPosition(position)
        if (card == null){
            Picasso.get().load(R.drawable.default_artist_art).into(holder.image)
        } else {

            // holder.courseNameTV.text = song.artistandname
            if (card.img == 0) {
                Picasso.get().load(card.img2).into(holder.img)
            } else {
                Picasso.get().load(card.img).into(holder.img)
            }
        }
    }

    override fun getItemCount() = dataSet.size + (dataSet.size / ITEMS_PER_AD)

    override fun getIdentifier(position: Int): adslist? {
        return getCardForPosition(position)
    }

open inner  class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) {

        protected open val adslist: adslist
            get() = dataSet[layoutPosition]

        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(getCardForPosition(position)!!) //WHEN AD CLICKED ==NULL
            }
        }

        val img: AppCompatImageView = itemView.findViewById(R.id.image)
        val layput: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        //  val layoutposition: LinearLayout = itemView.findViewById(R.id.layoutposition)
        val layout: MaterialCardView = itemView.findViewById(R.id.imageContainer)
        val image: AppCompatImageView = itemView.findViewById(R.id.image)
        val title: MaterialTextView = itemView.findViewById(R.id.title)

    }

    companion object {
        val TAG: String = AdsAdapter2::class.java.simpleName
        const val ITEMS_PER_AD = 3
        const val AD_FREQUENCY = ITEMS_PER_AD + 1
        const val AD_VIEWTYPE = 0
        const val CARD_VIEWTYPE = 1
    }

    override fun onMultipleItemAction(menuItem: MenuItem, selection: List<adslist>) {
        TODO("Not yet implemented")
    }

    override fun getPopupText(position: Int): String {
        TODO("Not yet implemented")
    }

    override fun getName(model: adslist): String? {
        TODO("Not yet implemented")
    }

    private fun isCard(position: Int) = (position + 1) % AD_FREQUENCY != 0

    private fun getCardForPosition(position: Int): adslist? {
        val offset = position / AD_FREQUENCY
        return if (isCard(position)) dataSet[position - offset] else null
    }

    override fun getItemViewType(position: Int) =
        if (isCard(position)) CARD_VIEWTYPE else AD_VIEWTYPE

}

The logic of knowing which part of the list is gonna be an AD or a CARD is explained in the answer of the url above and it is applied on the last 3 functions and i do think the problem resides there but i cant see it clearly.

I'm not  a super developer so it could be something so simple