问:
Python3 subprocess PIPE is not blocked after child process exiting
I try to use subprocess.Popen to control thild-part process with stdout=PIPE.

Why popen.stdout.read(1) could still response b'' while the third-pard process has exited. Should not it be blocked or EOF?

import subprocess

gdb_process = subprocess.Popen(
    "/mnt/c/code/gdbserver/a.out",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    bufsize = 0
)

out = gdb_process.stdout

i = 0
while True:
    ans = out.read(1)
    print( i, ans)
    i += 1
```

Here is my test code, a.out is a program write "Hello World\n" to stdout.

Body:
I try to use subprocess.Popen to control thild-part process with stdout=PIPE.

Why popen.stdout.read(1) could still response b'' while the third-pard process has exited. Should not it be blocked or EOF?

import subprocess

gdb_process = subprocess.Popen(
    "/mnt/c/code/gdbserver/a.out",
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    bufsize = 0
)

out = gdb_process.stdout

i = 0
while True:
    ans = out.read(1)
    print( i, ans)
    i += 1

Here is my test code, a.out is a program write "Hello World\n" to stdout.


来源: stackexchange

问:
Record Video while doing Image processing through CameraX in Android
I am doing image processing by using CameraX, it is working fine. I want to record video too while doing image processing.
Is it possible? If yes then how?

I am doing image processing as:

```<code>ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
    builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
    analysisUseCase = builder.build();
    analysisUseCase.setAnalyzer(
            ContextCompat.getMainExecutor(SetAndGetData.getInstance().getContext()),
            imageProxy -> {
                 // doing image processing here.....
            });
    cameraProvider.bindToLifecycle(this, cameraSelector, analysisUseCase);
</code>```

I want to record video too while doing it.

ContentLicense: CC BY-SA 4.0

Body:
I am doing image processing by using CameraX, it is working fine. I want to record video too while doing image processing.
Is it possible? If yes then how?

I am doing image processing as:

ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
    builder.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST);
    analysisUseCase = builder.build();
    analysisUseCase.setAnalyzer(
            ContextCompat.getMainExecutor(SetAndGetData.getInstance().getContext()),
            imageProxy -> {
                 // doing image processing here.....
            });
    cameraProvider.bindToLifecycle(this, cameraSelector, analysisUseCase);

I want to record video too while doing it.


问:
multiselection list view with data from DB
I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.

(I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.)

```<code>**app_db.dart**

import 'package:postgres/postgres.dart';

class AppDatabase {
  PostgreSQLConnection? connection;
  PostgreSQLResult? _fetchSellerDataResult;

  AppDatabase() {
    connection = (connection == null || connection!.isClosed == true
        ? PostgreSQLConnection("10.0.2.2", 5432, "dev", username: "postgres", password: "admin")
        : connection);
    fetchDataFuture = [];
  }

  // Fetch Data Section
  List<dynamic> fetchDataFuture = [];
  Future<List<dynamic>> fetchSellerData() async {
    try {
      await connection!.open();
      await connection!.transaction((fetchDataConn) async {
        _fetchSellerDataResult = await fetchDataConn.query(
          "select cust_id, cust_name, mmt, available_amount, false AS isSelected from api_positionstest2",
          allowReuse: false,
          timeoutInSeconds: 30,
        );

        if (_fetchSellerDataResult!.affectedRowCount > 0) {
          fetchDataFuture = _fetchSellerDataResult!.toList(growable: true);
        } else {
          fetchDataFuture = [];
        } });
    } catch (exc) {
      fetchDataFuture = [];
      exc.toString();
    }
    return fetchDataFuture;
  }}

**model_positions.dart**

import 'package:e2/Models/app_db.dart';

class ModelsPositions {
  List<dynamic> sellerDataFuture = [];
  Future<List<dynamic>> fetchSellerData() async {
    sellerDataFuture = await AppDatabase().fetchSellerData();
    return sellerDataFuture;
  }}

**MasterPositions.dart**
        class MasterPositions {
          String custID;
          String custName;
          double mtm;
          double availableCash;
          bool isSelected = false;

          MasterPositions(
              {required this.custID,
              required this.custName,
              required this.mtm,
              required this.availableCash});}

**master_control.dart**

import 'package:flutter/material.dart';
import 'package:e2/Models/model_positions.dart';

class MasterControl extends StatefulWidget {
  const MasterControl({super.key});

  @override
  State<MasterControl> createState() => _MasterControlState();
}

class _MasterControlState extends State<MasterControl> {
  List<MasterPositions> selectedContacts = [];
  List<MasterPositions> fetchedPositions = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        body: FutureBuilder<List<dynamic>>(
            future: ModelsPositions().fetchSellerData(),
            builder: (context, snapshot) {
              final positions = snapshot.data ?? [];
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError) {
                    return Center(child: Text('Error while loading Master Positions screen'));
                  } else {
                    return buildPositions(positions);
                  } } }), );

  Widget buildPositions(List<dynamic> positions) {
    return ListView.builder(
        physics: BouncingScrollPhysics(),
        itemCount: positions.length,
        itemBuilder: (context, index) {
          final pos = positions[index];
          final custID = pos.elementAt(0).toString();
          final custName = pos.elementAt(1).toString();
          final mtm = double.tryParse(pos.elementAt(2)) ?? 0.0;
          final availableCash = double.tryParse(pos.elementAt(3)) ?? 0.0;
          final isSelected = pos.elementAt(4);

          return ListTile(
            horizontalTitleGap: -5,
            title: Card(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Text(custID),
                        const SizedBox(height: 5),
                        Text(custName)],),),],),),

            leading: isSelected
                ? Icon( Icons.check_circle, color: Colors.green[700],)
                : const Icon(Icons.check_circle_outline, color: Colors.grey,),
            onTap: () {
              setState(() {
                positions[index].elementAt(4) = !positions[index].elementAt(4); `**--> suggestion needed here**`
                if (positions[index] == true) {
                  selectedContacts.add(
                      MasterPositions(custID: custID, custName: custName, mtm: mtm, availableCash: availableCash));
                } else if (positions[index] == false) {
                  selectedContacts.removeWhere(
                      (element) => element.custID == pos[index].custID);
                }}); }, );});}
}
</code>```

Body:
I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.

(I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.)

**app_db.dart**

import 'package:postgres/postgres.dart';

class AppDatabase {
  PostgreSQLConnection? connection;
  PostgreSQLResult? _fetchSellerDataResult;

  AppDatabase() {
    connection = (connection == null || connection!.isClosed == true
        ? PostgreSQLConnection("10.0.2.2", 5432, "dev", username: "postgres", password: "admin")
        : connection);
    fetchDataFuture = [];
  }

  // Fetch Data Section
  List<dynamic> fetchDataFuture = [];
  Future<List<dynamic>> fetchSellerData() async {
    try {
      await connection!.open();
      await connection!.transaction((fetchDataConn) async {
        _fetchSellerDataResult = await fetchDataConn.query(
          "select cust_id, cust_name, mmt, available_amount, false AS isSelected from api_positionstest2",
          allowReuse: false,
          timeoutInSeconds: 30,
        );

        if (_fetchSellerDataResult!.affectedRowCount > 0) {
          fetchDataFuture = _fetchSellerDataResult!.toList(growable: true);
        } else {
          fetchDataFuture = [];
        } });
    } catch (exc) {
      fetchDataFuture = [];
      exc.toString();
    }
    return fetchDataFuture;
  }}

**model_positions.dart**

import 'package:e2/Models/app_db.dart';

class ModelsPositions {
  List<dynamic> sellerDataFuture = [];
  Future<List<dynamic>> fetchSellerData() async {
    sellerDataFuture = await AppDatabase().fetchSellerData();
    return sellerDataFuture;
  }}

**MasterPositions.dart**
        class MasterPositions {
          String custID;
          String custName;
          double mtm;
          double availableCash;
          bool isSelected = false;

          MasterPositions(
              {required this.custID,
              required this.custName,
              required this.mtm,
              required this.availableCash});}

**master_control.dart**

import 'package:flutter/material.dart';
import 'package:e2/Models/model_positions.dart';

class MasterControl extends StatefulWidget {
  const MasterControl({super.key});

  @override
  State<MasterControl> createState() => _MasterControlState();
}

class _MasterControlState extends State<MasterControl> {
  List<MasterPositions> selectedContacts = [];
  List<MasterPositions> fetchedPositions = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        body: FutureBuilder<List<dynamic>>(
            future: ModelsPositions().fetchSellerData(),
            builder: (context, snapshot) {
              final positions = snapshot.data ?? [];
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError) {
                    return Center(child: Text('Error while loading Master Positions screen'));
                  } else {
                    return buildPositions(positions);
                  } } }), );

  Widget buildPositions(List<dynamic> positions) {
    return ListView.builder(
        physics: BouncingScrollPhysics(),
        itemCount: positions.length,
        itemBuilder: (context, index) {
          final pos = positions[index];
          final custID = pos.elementAt(0).toString();
          final custName = pos.elementAt(1).toString();
          final mtm = double.tryParse(pos.elementAt(2)) ?? 0.0;
          final availableCash = double.tryParse(pos.elementAt(3)) ?? 0.0;
          final isSelected = pos.elementAt(4);

          return ListTile(
            horizontalTitleGap: -5,
            title: Card(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Text(custID),
                        const SizedBox(height: 5),
                        Text(custName)],),),],),),

            leading: isSelected
                ? Icon( Icons.check_circle, color: Colors.green[700],)
                : const Icon(Icons.check_circle_outline, color: Colors.grey,),
            onTap: () {
              setState(() {
                positions[index].elementAt(4) = !positions[index].elementAt(4); `**--> suggestion needed here**`
                if (positions[index] == true) {
                  selectedContacts.add(
                      MasterPositions(custID: custID, custName: custName, mtm: mtm, availableCash: availableCash));
                } else if (positions[index] == false) {
                  selectedContacts.removeWhere(
                      (element) => element.custID == pos[index].custID);
                }}); }, );});}
}


问:
How to get paginated_data_table to respect the parent widget's maxWidth property?
If I have long text in a PaginatedDataTable widget the text is not wrapped like in a DataTable.  Usually, for a widget I'd fix this by adding BoxConstraints to set a max width of the parent.  However PaginatedDataTable internally surrounds a DataTable with a SingleChildScrollView and removes the parent's max width constraints.

Here is part of the PaginatedDataTable's code

```<code>          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            primary: widget.primary,
            controller: widget.controller,
            dragStartBehavior: widget.dragStartBehavior,
            child: ConstrainedBox(
              constraints: BoxConstraints(minWidth: constraints.minWidth),
              child: DataTable(
                key: _tableKey,
</code>```

I want to wrap the long text in the 2nd column when it gets too big, exactly as DataTable does automatically.  How do I do this?  As you can see with PaginatedDataTable more text is lost and the third column is too far on the right.

I've created a gist & dartpad to show the different behaviours.

https://dartpad.dev/?id=0559d2989c161fdbc13995ef508c56ea

Body:
If I have long text in a PaginatedDataTable widget the text is not wrapped like in a DataTable.  Usually, for a widget I'd fix this by adding BoxConstraints to set a max width of the parent.  However PaginatedDataTable internally surrounds a DataTable with a SingleChildScrollView and removes the parent's max width constraints.

Here is part of the PaginatedDataTable's code

          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            primary: widget.primary,
            controller: widget.controller,
            dragStartBehavior: widget.dragStartBehavior,
            child: ConstrainedBox(
              constraints: BoxConstraints(minWidth: constraints.minWidth),
              child: DataTable(
                key: _tableKey,

I want to wrap the long text in the 2nd column when it gets too big, exactly as DataTable does automatically.  How do I do this?  As you can see with PaginatedDataTable more text is lost and the third column is too far on the right.

I've created a gist & dartpad to show the different behaviours.

https://dartpad.dev/?id=0559d2989c161fdbc13995ef508c56ea


问:
About Linkedin Post Api Organization Mentions
I saw that you are included in the contributors of LinkedIn Post API documents. I would like to ask one quick question: I'm trying to get posts by URN for a mentioned Organization. Doc says "use URNs such as: ugcPostUrn (urn:li:ugcPost:{id}) or shareUrn (urn:li:share:{id})". That id is posts' id? If yes, how could I know a post's id which I'm trying to collect via API. When I tried to run this with organization id, it doesn't work. I need to collect feeds which mention specific organization.

https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/posts-api?view=li-lms-2022-12&tabs=curl#sample-request-5

I need to collect feeds which mention specific organization


问:
Rails + Scheduled Job executed successfully Still says Scheduled Job Failed: <JOBNAME>
In Rails App, I have added one job to update the User status from created to processing.

```<code>class UserStatusCreatedToProcessingJob < ApplicationScheduledJob

  def perform
    title = "[UserStatusCreatedToProcessingJob]"
    Rails.logger.info "==> #{title} - Start"

    users = User.where(status: 'created')
    total = users.count

    if total == 0
      Rails.logger.info "==> #{title} : User Count Is Zero."
    else
      users.update_all(status: 'processing')
      Rails.logger.info "==> #{title} : User Count : #{total} Changed to Processing."
    end
  end

end
</code>```

If the Job gets any Users, the system updates the status from Created To Processing.
But if the job does not get any users, the system enters into the IF condition and prints the User Count is Zero.

But, In end status of Job becomes Failed.

```<code>[xxxxx] Scheduled Job Failed: UserStatusCreatedToProcessingJob 13493
</code>```

Job ran successfully, but still getting Job as Failed. Please suggest.

Body:
In Rails App, I have added one job to update the User status from created to processing.

class UserStatusCreatedToProcessingJob < ApplicationScheduledJob

  def perform
    title = "[UserStatusCreatedToProcessingJob]"
    Rails.logger.info "==> #{title} - Start"

    users = User.where(status: 'created')
    total = users.count

    if total == 0
      Rails.logger.info "==> #{title} : User Count Is Zero."
    else
      users.update_all(status: 'processing')
      Rails.logger.info "==> #{title} : User Count : #{total} Changed to Processing."
    end
  end

end

If the Job gets any Users, the system updates the status from Created To Processing.
But if the job does not get any users, the system enters into the IF condition and prints the User Count is Zero.

But, In end status of Job becomes Failed.

[xxxxx] Scheduled Job Failed: UserStatusCreatedToProcessingJob 13493

Job ran successfully, but still getting Job as Failed. Please suggest.


问:
Ag Grid - related column filters
I came across a situation where I need to make two or more of my custom column filters of Ag Grid React based table, to be aware of the currently applied filtering on the table.

Here is a very simple example of what I am trying to achieve:

if we have a table with columns “Athlete” and “Country”, and custom filters comprised of checkboxes representing the values available on the table, is there a way so that
If we apply a filter on the first column “Athlete”, the filter on the second column - “Country” to only show checkboxes for the filtered values currently present on the table

Plunker example

See files: index.jsx, athleteFilter.jsx, countryFilter.jsx

Column definition excerpt (see full example on Plunker above):

```<code>const columnDefs = [
 { field: 'athlete', minWidth: 150, filter: AthleteFilter },
 { field: 'country', minWidth: 150, filter: CountryFilter }
];

const rowData = [
  {athlete: 'Michael Phelps', country: 'United States'},
  {athlete: 'Sun Yang', country: 'China'},
  {athlete: 'Inge de Bruijn', country: 'Netherlands'},
];
</code>```

Title: Ag Grid - related column filters

Body:
I came across a situation where I need to make two or more of my custom column filters of Ag Grid React based table, to be aware of the currently applied filtering on the table.

Here is a very simple example of what I am trying to achieve:

if we have a table with columns “Athlete” and “Country”, and custom filters comprised of checkboxes representing the values available on the table, is there a way so that
If we apply a filter on the first column “Athlete”, the filter on the second column - “Country” to only show checkboxes for the filtered values currently present on the table

Plunker example

See files: index.jsx, athleteFilter.jsx, countryFilter.jsx

Column definition excerpt (see full example on Plunker above):

const columnDefs = [
 { field: 'athlete', minWidth: 150, filter: AthleteFilter },
 { field: 'country', minWidth: 150, filter: CountryFilter }
];

const rowData = [
  {athlete: 'Michael Phelps', country: 'United States'},
  {athlete: 'Sun Yang', country: 'China'},
  {athlete: 'Inge de Bruijn', country: 'Netherlands'},
];


问:
Setting MALLOC_ARENA_MAX value in development.rb, production.rb etc in rails?
Can we set the property MALLOC_ARENA_MAX in the Rails environment files (like development.rb)?
Does rails pick up the property when written inside these files?

The way I am setting it (in development.rb):

```<code>ENV["MALLOC_ARENA_MAX"]="2" if ENV["MALLOC_ARENA_MAX"].nil?
</code>```

Body:
Can we set the property MALLOC_ARENA_MAX in the Rails environment files (like development.rb)?
Does rails pick up the property when written inside these files?

The way I am setting it (in development.rb):

ENV["MALLOC_ARENA_MAX"]="2" if ENV["MALLOC_ARENA_MAX"].nil?


问:
Change a tag of metadata from jpg with python
I would to know if is it posible to change the tag mark on the image with python:

I've tried using pyexif and directly PIL but i cant found the tag or the way to change it in python.

Thanks


问:
How to call TextField with writeable property as default in qml
i have a custom keyboard in qml and has a textField for it so i can use that value somewhere else. When qml page is initialized in application, textfield needs to be clicked to type inside. What i want is when qml initialized should be able to push buttons without clicking textfield first.  Here is what i am using

```<code>    TextField {
        id:inputValueArea
        width:200;height:35
        anchors.fill : parent
        background:
        font.pixelSize: 20
        placeholderText: ""
        color: "#FFFFFF"
        echoMode: TextInput.Normal
        onAccepted: focus = false
        Keys.onEscapePressed: undo()
    }
</code>```

I tried to use activeFocusOnPress and inputMethodComposing  but it did not work.
(source: https://doc.qt.io/qt-5/qml-qtquick-controls-textfield.html#activeFocusOnPress-prop)

What can i code for that? Since i have keyboard as a seperated qml, i couldn't use this solution as a solution (Qt QML Focus an Item (TextField) when showing a StackView Page)

Body:
i have a custom keyboard in qml and has a textField for it so i can use that value somewhere else. When qml page is initialized in application, textfield needs to be clicked to type inside. What i want is when qml initialized should be able to push buttons without clicking textfield first.  Here is what i am using

    TextField {
        id:inputValueArea
        width:200;height:35
        anchors.fill : parent
        background:
        font.pixelSize: 20
        placeholderText: ""
        color: "#FFFFFF"
        echoMode: TextInput.Normal
        onAccepted: focus = false
        Keys.onEscapePressed: undo()
    }

I tried to use activeFocusOnPress and inputMethodComposing  but it did not work.
(source: https://doc.qt.io/qt-5/qml-qtquick-controls-textfield.html#activeFocusOnPress-prop)

What can i code for that? Since i have keyboard as a seperated qml, i couldn't use this solution as a solution (Qt QML Focus an Item (TextField) when showing a StackView Page)


问:
Validate top level domain in Qt6
The obsolete Qt5 QUrl::topLevelDomain was a nice, straight forward way to validate top level domains in Qt. It has been deprecated withough a replacement from 5.12 on afaik. How can we validate top level domains in Qt6?</p>

Title: Validate top level domain in Qt6


问:
Is it possible to send text as hyperlink using python without the use of html?
Through whatsapp both text and link (in the form of https://www.google.co.in) can be shared programmatically using python and cloud api tokens.
Is it possible to send text as hyperlink through whatsapp?

I tried sending a link but couldn't.


问:
Error input size in adaptive_avg_pool2d() MONAI
I'm using MONAI to build a U-Net for a segmentation task. I want to crop the input images with "CropForegroundd" as follow:

```<code>monai_load = [
    LoadImaged(keys=["image","segmentation"],image_only=False,reader=PILReader()),
    EnsureTyped(keys=["image", "segmentation"], data_type="numpy"),
    AddChanneld(keys=["segmentation","image"]),
    RepeatChanneld(keys=["image"],repeats=3),
    AsChannelFirstd(keys=["image"], channel_dim = 0),
    ]

monai_transforms =[
    AsDiscreted(keys=["segmentation"],threshold=0.5),
    CropForegroundd(keys=["image","segmentation"], source_key="image", margin=20),
    Resized(keys=["image","segmentation"],spatial_size=(240,240)),
    ToTensord(keys=["image","segmentation"]),
    ]

train_transforms = Compose(monai_load  + monai_transforms)
train_ds = IterableDataset(data = train_data, transform = train_transforms)
train_loader = DataLoader(dataset = train_ds, batch_size = batch_size, num_workers = 0, pin_memory = True)

</code>```

While training running, it stops in a certain step number and give me this error:

```<code>RuntimeError: adaptive_avg_pool2d(): Expected input to have non-zero size for non-batch dimensions, but input has sizes [1, 3, 0, 0] with dimension 2 being empty
</code>```

I think that the problem is not CropForegroundd margin parameter but I'm not able to solve this error.

Thank you in advance for getting back to me.

Federico

Body:
I'm using MONAI to build a U-Net for a segmentation task. I want to crop the input images with "CropForegroundd" as follow:

monai_load = [
    LoadImaged(keys=["image","segmentation"],image_only=False,reader=PILReader()),
    EnsureTyped(keys=["image", "segmentation"], data_type="numpy"),
    AddChanneld(keys=["segmentation","image"]),
    RepeatChanneld(keys=["image"],repeats=3),
    AsChannelFirstd(keys=["image"], channel_dim = 0),
    ]

monai_transforms =[
    AsDiscreted(keys=["segmentation"],threshold=0.5),
    CropForegroundd(keys=["image","segmentation"], source_key="image", margin=20),
    Resized(keys=["image","segmentation"],spatial_size=(240,240)),
    ToTensord(keys=["image","segmentation"]),
    ]

train_transforms = Compose(monai_load  + monai_transforms)
train_ds = IterableDataset(data = train_data, transform = train_transforms)
train_loader = DataLoader(dataset = train_ds, batch_size = batch_size, num_workers = 0, pin_memory = True)

While training running, it stops in a certain step number and give me this error:

RuntimeError: adaptive_avg_pool2d(): Expected input to have non-zero size for non-batch dimensions, but input has sizes [1, 3, 0, 0] with dimension 2 being empty

I think that the problem is not CropForegroundd margin parameter but I'm not able to solve this error.

Thank you in advance for getting back to me.

Federico


问:
i want use firebase express get
This is my first time using Firebase, so I am new to JavaScript.

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

admin.initializeApp(functions.config().firebase);

let db = admin.firestore();

express().get('/ActiveTime/:id', (req, res) =>
{
    db.collection('TestA').doc(req.params.id).get().then(doc =>
    {
        functions.logger.info("Hello logs!", { structuredData: true });
        response.send(doc.data().Date);
    });
});
</code>```

this doesn't work

i want goto url "hompage/ActiveTime/TestUserName" Print the firestore data of the doc with the name TestUserName

What should I do?

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

admin.initializeApp(functions.config().firebase);

let db = admin.firestore();

exports.helloWorld = functions.region("asia-northeast3").https.onRequest((request, response) =>
{
    db.collection('TestA').doc('TestUserName').get().then(doc =>
    {
        functions.logger.info("Hello logs!", { structuredData: true });
        response.send(doc.data().Date);
    });
});

</code>```

this works fine
but i want goto url "hompage/ActiveTime/TestUserName" Print the firestore data of the doc with the name TestUserName

Title: i want use firebase express get

Body:
This is my first time using Firebase, so I am new to JavaScript.

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

admin.initializeApp(functions.config().firebase);

let db = admin.firestore();

express().get('/ActiveTime/:id', (req, res) =>
{
    db.collection('TestA').doc(req.params.id).get().then(doc =>
    {
        functions.logger.info("Hello logs!", { structuredData: true });
        response.send(doc.data().Date);
    });
});

this doesn't work

i want goto url "hompage/ActiveTime/TestUserName" Print the firestore data of the doc with the name TestUserName

What should I do?

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

admin.initializeApp(functions.config().firebase);

let db = admin.firestore();

exports.helloWorld = functions.region("asia-northeast3").https.onRequest((request, response) =>
{
    db.collection('TestA').doc('TestUserName').get().then(doc =>
    {
        functions.logger.info("Hello logs!", { structuredData: true });
        response.send(doc.data().Date);
    });
});

this works fine
but i want goto url "hompage/ActiveTime/TestUserName" Print the firestore data of the doc with the name TestUserName


问:
How to resolve 'T' could be instantiated with an arbitrary type which could be unrelated to 'X' in this TypeScript example?
I have this TypeScript playground, which errors at this isMesh function at the beginning:

```<code>export function isMesh<T extends Mesh>(
  object: unknown,
  type: T | Array<T>,
): object is MeshType<T> {
  type = Array.isArray(type) ? type : [type]
  return (
    object &&
    typeof object === 'object' &&
    'type' in object &&
    type.includes(object as MeshType<T>).type)
  )
}

export type MeshType<T extends Mesh> = MeshMappingType[T]

export type MeshMappingType = {
  'mesh-call': MeshCallType
  'mesh-callback': MeshCallbackType
  'mesh-class': MeshClassType
}

export enum Mesh {
  Call = 'mesh-call',
  Callback = 'mesh-callback',
  Class = 'mesh-class',
}

export type MeshBaseType = {
  bound?: boolean
}

export type MeshCallType = MeshBaseType & {
  bind: Record<string, unknown>
  type: Mesh.Call
}

export type MeshCallbackType = MeshBaseType & {
  type: Mesh.Callback
}

export type MeshClassType = MeshBaseType & {
  type: Mesh.Class
}
</code>```

It says:

```<code>Argument of type 'MeshType<T>' is not assignable to parameter of type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'MeshType<T>'.(2345)
</code>```

This is a minimal viable example extracted from a larger compiler project.

Body:
I have <a href="https://www.typescriptlang.org/play?ssl=14&ssc=1&pln=1&pc=1#code/FAUwHgDg9gTgLgAgGYFcB2BjOBLKaHYDOAsiIQBYA8AKguHCGgCaEKkUB8AFMAglACMAViCwAuBOgDWaKAHc0AGl4I4ATwggJtAD4IAgjBgBDNTQ7KAlBMEisBVu3LUNIcwgDeK9ZoQBeAyNTADoiQxM1Lh8QSwQAflVXBAkAbWiAXRUYEDgUGHwePj5bUUQAMjKVPmioJH5hUv8-AIByEqwWhAqqhBbozux8dvLKosTNUMwAGxQmMi5hhGNHMmdXc0tg6MsVHYBfYFBIWERotlWXTRo6MAZmFc5-c4piYwgIQYBzS5AU6kyjtB4OMQM9yK93l8fk8vHwWgBbVYAWgwximUxaEicAGE0VMfioEcjUeiBMYMFJMWDcaTyVICXDERQUVNloQqTjWYRCASDoCTnQ0Ch4WDPCoaVMnkTmSSMco+BKyRSpUzyCi8UrKfKENiuaxWqqWWyWso+eAgackk4AELLEDQgKwhACKDoJhxCQuqBTEDGNDAM3HYFnHF4h1g22Ee1JMpivgCQZMCQAJVEsCYlEIcBgX0UkjQMnkaA43lcWNWwQlAcO5oFIdWirp4Ztduhsad0XLFErGrp1f5watDb1zdWkejvnbpc0XfIlb11aAA" rel="nofollow noreferrer">this TypeScript playground, which errors at this isMesh function at the beginning:

export function isMesh<T extends Mesh>(
  object: unknown,
  type: T | Array<T>,
): object is MeshType<T> {
  type = Array.isArray(type) ? type : [type]
  return (
    object &&
    typeof object === 'object' &&
    'type' in object &&
    type.includes(object as MeshType<T>).type)
  )
}

export type MeshType<T extends Mesh> = MeshMappingType[T]

export type MeshMappingType = {
  'mesh-call': MeshCallType
  'mesh-callback': MeshCallbackType
  'mesh-class': MeshClassType
}

export enum Mesh {
  Call = 'mesh-call',
  Callback = 'mesh-callback',
  Class = 'mesh-class',
}

export type MeshBaseType = {
  bound?: boolean
}

export type MeshCallType = MeshBaseType & {
  bind: Record<string, unknown>
  type: Mesh.Call
}

export type MeshCallbackType = MeshBaseType & {
  type: Mesh.Callback
}

export type MeshClassType = MeshBaseType & {
  type: Mesh.Class
}

It says:

Argument of type 'MeshType<T>' is not assignable to parameter of type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'MeshType<T>'.(2345)

This is a minimal viable example extracted from a larger compiler project.


问:
Trying to copy data from cell A4:U of all sheets apart from 'Master', 'Index' and 'Tracker Template' to where column A shows 'Totals'
Basically, I'm trying to create a VBA but really struggling to find how I would create the dynamic range where it searches every possible sheet and copies them into the master from A4:U(wherever the first word that says totals is). I also want to ensure there are no blank rows being copied across and the data doesn't duplicate when I do this. Is this possible?

I have tried to write the code, using other examples but I'm relatively new to building macro's so haven't fully understood it all.

    Sub CopySheetsToMaster()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim i, LastRowa, LastRowd As Long
    Dim WSname As String

    Set wb = ActiveWorkbook

    For Each ws In wb.Sheets

    If ws.Name = "Master" or "Index or "Tracker Template" Then

    WSname = ws.Name

    LastRowa = ws.Cells(Rows.Count, "A").End(xlUp).Row
    LastRowd = Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row

    ws.Range("A4:Q" & LastRowa).Copy
    Sheets("Master").Range("A" & LastRowd + 2).PasteSpecial Paste:=xlPasteValues
    Sheets("Master").Range("A" & LastRowd + 1).Value = WSname

    End If

    Next ws
```


问:
VS Code: JavaFX runtime components are missing, and are required to run this application
I am trying to run my project: App.java but this error pops up in VS Code terminal:

JavaFX runtime components are missing, and are required to run this application

I have actually completed this project: App.java in a year ago and I was able to run App.java smoothly without this error during that time. Since then, I have not run App.java for about 11 months and now I would like to run App.java again. However, this time, I got this error.

Here is my launch.json:

```<code>"vmArgs": "--module-path \"C:/Java/javafx-sdk-17.0.1/lib\" --add-modules javafx.controls,javafx.fxml"
</code>```

Environment Variables (User Variable):
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk-17.0.1

p.s. I have already set up all these a year ago when I complete this project and App.java was able to run without this error. I didn't change any part of the code including settings.json and launch.json. I really have no idea why this error pops up after a year when I want to run App.java again.

I have tried to restart my VS Code, run VS Code in Administrator Mode, uninstall and reinstall Extension Pack for Java in VS Code, disable and enable again all the extensions I have used in VS Code, followed all the other guides asked by other user who also faced this issue. Sadly, I still get this error.

Body:
I am trying to run my project: App.java but this error pops up in VS Code terminal:

JavaFX runtime components are missing, and are required to run this application

I have actually completed this project: App.java in a year ago and I was able to run App.java smoothly without this error during that time. Since then, I have not run App.java for about 11 months and now I would like to run App.java again. However, this time, I got this error.

Here is my launch.json:

"vmArgs": "--module-path \"C:/Java/javafx-sdk-17.0.1/lib\" --add-modules javafx.controls,javafx.fxml"

Environment Variables (User Variable):
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk-17.0.1

p.s. I have already set up all these a year ago when I complete this project and App.java was able to run without this error. I didn't change any part of the code including settings.json and launch.json. I really have no idea why this error pops up after a year when I want to run App.java again.

I have tried to restart my VS Code, run VS Code in Administrator Mode, uninstall and reinstall Extension Pack for Java in VS Code, disable and enable again all the extensions I have used in VS Code, followed all the other guides asked by other user who also faced this issue. Sadly, I still get this error.


问:
How to create a resizable SWT shell without title bar
I created a new shell using the following code:
Shell shell = new Shell( parent, SWT.RESIZE);

I am getting a resizable shell but with a small title bar on the top which I dont want.

This is what I am getting after using this code.

Is there any way to remove that title bar/border in the top but with retaining resizable functionality.
Help would be appreciated. Thanks!


问:
Torch onnx.export error for instance norm
I try to convert a pytorch model to the onnx format using torch.onnx.export().
Hower I get the following error:

```<code>.
.
.
     File "C:\Users\Markus\miniconda3\envs\ic-move\lib\site-packages\torch\onnx\symbolic_opset9.py", line 1395, in instance_norm
            raise RuntimeError("Unsupported: ONNX export of instance_norm for unknown "
        RuntimeError: Unsupported: ONNX export of instance_norm for unknown channel size.
</code>```

this is how I call the function:

```<code>torch.onnx.export(net,                       # model being run
                      x,                         # model input (or a tuple for multiple inputs)
                      ONNX_PATH,                 # where to save the model (can be a file or file-like object)
                      export_params=True,        # store the trained parameter weights inside the model file
                      opset_version=12,          # the ONNX version to export the model to
                      do_constant_folding=True,  # whether to execute constant folding for optimization
                      input_names = ['input'],   # the model's input names
                      output_names = ['output'], # the model's output names
                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes
                                    'output' : {0 : 'batch_size'}})
</code>```

and here is an example of how I call the instance norm in my model:

```<code>class Residual(nn.Module):
def __init__(self, inp_dim, out_dim):
    super(Residual, self).__init__()
    self.relu = nn.ReLU()
    self.bn1 = nn.InstanceNorm2d(inp_dim)
    self.conv1 = Conv(inp_dim, int(out_dim/2), 1, relu=False)
    self.bn2 = nn.InstanceNorm2d(int(out_dim/2))
    self.conv2 = Conv(int(out_dim/2), int(out_dim/2), 3, relu=False)
    self.bn3 = nn.InstanceNorm2d(int(out_dim/2))
    self.conv3 = Conv(int(out_dim/2), out_dim, 1, relu=False)
    self.skip_layer = Conv(inp_dim, out_dim, 1, relu=False)
    if inp_dim == out_dim:
        self.need_skip = False
    else:
        self.need_skip = True
</code>```

With the input_dim = 64. Aren't this the channels I set?

Body:
I try to convert a pytorch model to the onnx format using torch.onnx.export().
Hower I get the following error:

.
.
.
     File "C:\Users\Markus\miniconda3\envs\ic-move\lib\site-packages\torch\onnx\symbolic_opset9.py", line 1395, in instance_norm
            raise RuntimeError("Unsupported: ONNX export of instance_norm for unknown "
        RuntimeError: Unsupported: ONNX export of instance_norm for unknown channel size.

this is how I call the function:

torch.onnx.export(net,                       # model being run
                      x,                         # model input (or a tuple for multiple inputs)
                      ONNX_PATH,                 # where to save the model (can be a file or file-like object)
                      export_params=True,        # store the trained parameter weights inside the model file
                      opset_version=12,          # the ONNX version to export the model to
                      do_constant_folding=True,  # whether to execute constant folding for optimization
                      input_names = ['input'],   # the model's input names
                      output_names = ['output'], # the model's output names
                      dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes
                                    'output' : {0 : 'batch_size'}})

and here is an example of how I call the instance norm in my model:

class Residual(nn.Module):
def __init__(self, inp_dim, out_dim):
    super(Residual, self).__init__()
    self.relu = nn.ReLU()
    self.bn1 = nn.InstanceNorm2d(inp_dim)
    self.conv1 = Conv(inp_dim, int(out_dim/2), 1, relu=False)
    self.bn2 = nn.InstanceNorm2d(int(out_dim/2))
    self.conv2 = Conv(int(out_dim/2), int(out_dim/2), 3, relu=False)
    self.bn3 = nn.InstanceNorm2d(int(out_dim/2))
    self.conv3 = Conv(int(out_dim/2), out_dim, 1, relu=False)
    self.skip_layer = Conv(inp_dim, out_dim, 1, relu=False)
    if inp_dim == out_dim:
        self.need_skip = False
    else:
        self.need_skip = True

With the input_dim = 64. Aren't this the channels I set?


问:
Facebook API script Python
Hello my name is Vlad and I am a marketer with coding experience, I am proficient in Google Ads Scripts but I am having a hard time developing any scripts in Facebook Ads Manager (Scripts that use Facebook API).
I am either using outdated libraries of python or I don't understand how to use the Facebook API.
If any of you can help me, I would like to select 2 ads by ID and store the number of clicks that each ad has (using Today's data) and how to pause/enable an ad by ID.
Thank you for much for your assistance and I am looking forward to your response.

These are 2 examples of code that I have written that do not work:
Code 1:

```<code>import facebook

fb = facebook.GraphAPI(access_token='')

clicks_A = fb.get_object(id="", fields="clicks")['clicks']['value']
clicks_B = fb.get_object(id="", fields="clicks")['clicks']['value']

print(clicks_A)
print(clicks_B)

fb.put_object(id="", status="PAUSED")
fb.put_object(id="", status="ACTIVE")
</code>```

Code 2:

```<code>import time
import facebook
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.adobjects.ad import Ad

FacebookAdsApi.init(access_token=TOKEN_DE_ACCES)

account = AdAccount(ACCOUNT_ID)

    ads_insights_a = AdsInsights.get(
        fields=[
            AdsInsights.Field.ad_id,
            AdsInsights.Field.clicks,
        ],
        params={
            'level': 'ad',
            'time_range': {'since': 'today', 'until': 'today'},
            'filtering': [{'field': 'ad_id', 'operator': 'EQUAL', 'value': AD_ID_A}]
        }
    )

    ads_insights_b = AdsInsights.get(
        fields=[
            AdsInsights.Field.ad_id,
            AdsInsights.Field.clicks,
        ],
        params={
            'level': 'ad',
            'time_range': {'since': 'today', 'until': 'today'},
            'filtering': [{'field': 'ad_id', 'operator': 'EQUAL', 'value': AD_ID_B}]
        }
    )

    clicks_a = ads_insights_a[0]['clicks']

    clicks_b = ads_insights_b[0]['clicks']

    ad_a = Ad(AD_ID_A)
    ad_a.update(params={'status': 'PAUSED'})

    ad_b = Ad(AD_ID_B)
    ad_b.update(params={'status': 'ACTIVE'})
</code>```

Title: Facebook API script Python

Body:
Hello my name is Vlad and I am a marketer with coding experience, I am proficient in Google Ads Scripts but I am having a hard time developing any scripts in Facebook Ads Manager (Scripts that use Facebook API).
I am either using outdated libraries of python or I don't understand how to use the Facebook API.
If any of you can help me, I would like to select 2 ads by ID and store the number of clicks that each ad has (using Today's data) and how to pause/enable an ad by ID.
Thank you for much for your assistance and I am looking forward to your response.

These are 2 examples of code that I have written that do not work:
Code 1:

import facebook

fb = facebook.GraphAPI(access_token='')

clicks_A = fb.get_object(id="", fields="clicks")['clicks']['value']
clicks_B = fb.get_object(id="", fields="clicks")['clicks']['value']

print(clicks_A)
print(clicks_B)

fb.put_object(id="", status="PAUSED")
fb.put_object(id="", status="ACTIVE")

Code 2:

import time
import facebook
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.adobjects.ad import Ad

FacebookAdsApi.init(access_token=TOKEN_DE_ACCES)

account = AdAccount(ACCOUNT_ID)

    ads_insights_a = AdsInsights.get(
        fields=[
            AdsInsights.Field.ad_id,
            AdsInsights.Field.clicks,
        ],
        params={
            'level': 'ad',
            'time_range': {'since': 'today', 'until': 'today'},
            'filtering': [{'field': 'ad_id', 'operator': 'EQUAL', 'value': AD_ID_A}]
        }
    )

    ads_insights_b = AdsInsights.get(
        fields=[
            AdsInsights.Field.ad_id,
            AdsInsights.Field.clicks,
        ],
        params={
            'level': 'ad',
            'time_range': {'since': 'today', 'until': 'today'},
            'filtering': [{'field': 'ad_id', 'operator': 'EQUAL', 'value': AD_ID_B}]
        }
    )

    clicks_a = ads_insights_a[0]['clicks']

    clicks_b = ads_insights_b[0]['clicks']

    ad_a = Ad(AD_ID_A)
    ad_a.update(params={'status': 'PAUSED'})

    ad_b = Ad(AD_ID_B)
    ad_b.update(params={'status': 'ACTIVE'})


问:
How to display data frame in template page using django
I am trying to populate my data frame in Django, But I am getting a blank page.

Here I am sharing my sample code

```<code><html>
<head>
    <title>API Display</title>
</head>
<body>
    <h1>List of Data </h1>
    {% for i in d %}
    <strong>{{i}}</strong>
    {% endfor %}
</body>
</html>
</code>```
```<code>def index(request):
    url = "http://153.24.76.45:9000/abc/"
    response = requests.get(url)
    z = response.json()
    # df = z.reset_index().to_json(orient ='records')
    df = pd.DataFrame(z['Result']['LSData'])

    context = {'d': df}
    return render(request,'index.html',context)
</code>```

can anyone help me to solve this problem ?

Body:
I am trying to populate my data frame in Django, But I am getting a blank page.

Here I am sharing my sample code

    <title>API Display</title>

List of Data

    {% for i in d %}
    {{i}}
    {% endfor %}

def index(request):
    url = "http://153.24.76.45:9000/abc/"
    response = requests.get(url)
    z = response.json()
    # df = z.reset_index().to_json(orient ='records')
    df = pd.DataFrame(z['Result']['LSData'])

    context = {'d': df}
    return render(request,'index.html',context)

can anyone help me to solve this problem ?


问:
2 way repeated ANOVA did not show sphericity test
There were 4 levels of treatment over 11 sampling time points. Each treatment had 3 identical systems. And samples were analyzed for different parameters. So I used 2 way repeated measures anova, for example:

```<code>ezANOVA(data = WP4, dv = parameter1, wid = System, within = Time, between = Treatment, type=3)
</code>```

However, it produced anova table without sphericity test on some parameters, like below:

```<code>Warning: NaNs producedWarning: NaNs produced$ANOVA
          Effect DFn DFd         F            p p<.05       ges
2      Treatment   3   8  2.255871 1.590810e-01       0.2934692
3           Time  10  80 35.989273 1.524902e-25     * 0.6960297
4 Treatment:Time  30  80  7.574502 2.275032e-13     * 0.5911306
</code>```

Please let me know if you need more information to crack my problem. Thanks.

I would like to have the complete anova table with $Mauchly's Test for Sphericity and $Sphericity Corrections.

Body:
There were 4 levels of treatment over 11 sampling time points. Each treatment had 3 identical systems. And samples were analyzed for different parameters. So I used 2 way repeated measures anova, for example:

ezANOVA(data = WP4, dv = parameter1, wid = System, within = Time, between = Treatment, type=3)

However, it produced anova table without sphericity test on some parameters, like below:

Warning: NaNs producedWarning: NaNs produced$ANOVA
          Effect DFn DFd         F            p p<.05       ges
2      Treatment   3   8  2.255871 1.590810e-01       0.2934692
3           Time  10  80 35.989273 1.524902e-25     * 0.6960297
4 Treatment:Time  30  80  7.574502 2.275032e-13     * 0.5911306

Please let me know if you need more information to crack my problem. Thanks.

I would like to have the complete anova table with $Mauchly's Test for Sphericity and $Sphericity Corrections.


问:
Azure Function triggered by IoT Hub does not execute correctly
I am developping an Azure Function with the following structure:
Trigger: IoT Hub event.
Function: Gets the body of the telemetry message and applies some decoding to the data.
Output: Sends the processed data as json to en Event Hub.

IoT Hub ---> Az Function --->  Event Hub

When deployed to Azure, the function gets triggered correctly every time there is a telemetry message in the IoT Hub, but it does not execute correctly.

When triggered, the function executes with "success"=False.

On the other hand, when testing/debugging in the Azure portal, I proceed as specified in the answer of this question, entering as message body

```<code>{
    "input": "{\"SystemProperties\":{},\"SomeId\":\"123\",\"Status\":\"Available\"}"
}
</code>```

and I always get this error message when the function is finished executing:

Result: Failure Exception: NotImplementedError: unexpected Datum type: None Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 485, in _handle__invocation_request return_value = bindings.to_outgoing_proto( File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/bindings/meta.py", line 151, in to_outgoing_proto return datumdef.datum_as_proto(datum) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/bindings/datumdef.py", line 200, in datum_as_proto raise NotImplementedError(

Initially, I have tried to run the code that Microsoft provides as template for EventHub triggered functions:

```<code>def main(event: func.EventHubEvent):
    logging.info(f'Function triggered to process a message: {event.get_body().decode()}')
    logging.info(f'  EnqueuedTimeUtc = {event.enqueued_time}')
    logging.info(f'  SequenceNumber = {event.sequence_number}')
    logging.info(f'  Offset = {event.offset}')

    # Metadata
    for key in event.metadata:
        logging.info(f'Metadata: {key} = {event.metadata[key]}')
</code>```

The logging works propperly, and the info is displayed on the debugging monitor tab, but when it finishes logging the info it throws error mentioned above.

Body:
I am developping an Azure Function with the following structure:
Trigger: IoT Hub event.
Function: Gets the body of the telemetry message and applies some decoding to the data.
Output: Sends the processed data as json to en Event Hub.

IoT Hub ---> Az Function --->  Event Hub

When deployed to Azure, the function gets triggered correctly every time there is a telemetry message in the IoT Hub, but it does not execute correctly.

When triggered, the function executes with "success"=False.

On the other hand, when testing/debugging in the Azure portal, I proceed as specified in the answer of this question, entering as message body

{
    "input": "{\"SystemProperties\":{},\"SomeId\":\"123\",\"Status\":\"Available\"}"
}

and I always get this error message when the function is finished executing:

Result: Failure Exception: NotImplementedError: unexpected Datum type: None Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 485, in _handle__invocation_request return_value = bindings.to_outgoing_proto( File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/bindings/meta.py", line 151, in to_outgoing_proto return datumdef.datum_as_proto(datum) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/bindings/datumdef.py", line 200, in datum_as_proto raise NotImplementedError(

Initially, I have tried to run the code that Microsoft provides as template for EventHub triggered functions:

def main(event: func.EventHubEvent):
    logging.info(f'Function triggered to process a message: {event.get_body().decode()}')
    logging.info(f'  EnqueuedTimeUtc = {event.enqueued_time}')
    logging.info(f'  SequenceNumber = {event.sequence_number}')
    logging.info(f'  Offset = {event.offset}')

    # Metadata
    for key in event.metadata:
        logging.info(f'Metadata: {key} = {event.metadata[key]}')

The logging works propperly, and the info is displayed on the debugging monitor tab, but when it finishes logging the info it throws error mentioned above.


问:
I want to fetch third children data with query I try many ways but it is not working
I want to fetch third level children I try this ways but it is not working.

```<code>{
   "title": "box",
   "active": false,
   "level": "you",
   "children": [
        {
            "id": 1,
            "title": "hood",
            "type": "uod",
            "active": false,
            "level": "9",
            "children": [
             {
                 "id":1,
                "title": "New",
                "type": "hog",
                "active": false,
                "level": "3",
                 }
             ]
        }
   ]
}
</code>```

I want to find one nested record with Id in mongo db spring boot. But getting NullPointerException how to handle it with this code.

This my Get Apis

    @GetMapping("/menus/{id}/submenu/{subId}/children/{childId}")
    public List<?> findChildrenById(@PathVariable("id") long id,

        @PathVariable("subId") long subId, @PathVariable("childId") long childId) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(id).and("children.id").is(subId).and("children.children.id").is(childId));
            return operations.findOne(query, SubMenu.class).getChildren();

    }

```
<p>Error</p>
```"java.lang.NullPointerException: Cannot invoke "com.menu.entity.SubMenu.getChildren()" because the return value of "org.springframework.data.mongodb.core.MongoOperations.findOne(org.springframework.data.mongodb.core.query.Query, java.lang.Class)" is null\r\n\tat com..menu.controller.MenuItemsGetControlller.findChildrenById(MenuItemsGetControlller.java:84)\r\n\tat
```
``````

Body:
I want to fetch third level children I try this ways but it is not working.

{
   "title": "box",
   "active": false,
   "level": "you",
   "children": [
        {
            "id": 1,
            "title": "hood",
            "type": "uod",
            "active": false,
            "level": "9",
            "children": [
             {
                 "id":1,
                "title": "New",
                "type": "hog",
                "active": false,
                "level": "3",
                 }
             ]
        }
   ]
}

I want to find one nested record with Id in mongo db spring boot. But getting NullPointerException how to handle it with this code.

This my Get Apis

    @GetMapping("/menus/{id}/submenu/{subId}/children/{childId}")
    public List<?> findChildrenById(@PathVariable("id") long id,

        @PathVariable("subId") long subId, @PathVariable("childId") long childId) {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(id).and("children.id").is(subId).and("children.children.id").is(childId));
            return operations.findOne(query, SubMenu.class).getChildren();

    }

Error

"java.lang.NullPointerException: Cannot invoke "com.menu.entity.SubMenu.getChildren()" because the return value of "org.springframework.data.mongodb.core.MongoOperations.findOne(org.springframework.data.mongodb.core.query.Query, java.lang.Class)" is null\r\n\tat com..menu.controller.MenuItemsGetControlller.findChildrenById(MenuItemsGetControlller.java:84)\r\n\tat


问:
how to force overflow within a flex div parent
I am using the following code

<!DOCTYPE html>

```

This outputs a yellow screen because the child overlaps the parent, but no scroll bar is shown for the scroll parent. If I remove the display:flex scrolling happens. It also happens when I fill the child with text until it overflows. I would like the child to always make the parent overflow, even without text. Is this possible?

I need to do this because I use a script that adds an empty div at the end of the child in the parent to make the parent scroll until some elements is back in view.

Body:
I am using the following code

<!DOCTYPE html>

This outputs a yellow screen because the child overlaps the parent, but no scroll bar is shown for the scroll parent. If I remove the display:flex scrolling happens. It also happens when I fill the child with text until it overflows. I would like the child to always make the parent overflow, even without text. Is this possible?

I need to do this because I use a script that adds an empty div at the end of the child in the parent to make the parent scroll until some elements is back in view.


问:
How can I read data from SharePoint List using C#
I have to read some sensitive data from one of SharePoint site company has and insert those data back to SQL server.

I already tried with Power Automate but failed to implement solid solution due to the DB server authentication issue.

Now I have to implement new solution with C# but still haven't found a better way to do this.

Any help here


问:
R (Mac): installation of `cluster` package is failing
I am trying to set up R on a Mac and the installation of the cluster package is failing, possibly due to gfortran (or its library path). Below is the output for the failing package installation (sorry about the partly german output).

```<code>> install.packages("cluster", type = "source")
versuche URL 'https://cran.rstudio.com/src/contrib/cluster_2.1.4.tar.gz'
Content type 'application/x-gzip' length 352076 bytes (343 KB)
==================================================
downloaded 343 KB

* installing *source* package ‘cluster’ ...
** Paket ‘cluster’ erfolgreich entpackt und MD5 Summen überprüft
** using staged installation
** libs
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c clara.c -o clara.o
gfortran -fno-optimize-sibling-calls  -fPIC  -Wall -g -O2  -c daisy.f -o daisy.o
gfortran -fno-optimize-sibling-calls  -fPIC  -Wall -g -O2  -c dysta.f -o dysta.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c fanny.c -o fanny.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c init.c -o init.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c mona.c -o mona.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c pam.c -o pam.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c sildist.c -o sildist.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c spannel.c -o spannel.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c twins.c -o twins.o
clang -arch arm64 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/opt/R/arm64/lib -o cluster.so clara.o daisy.o dysta.o fanny.o init.o mona.o pam.o sildist.o spannel.o twins.o -L/usr/local/gfortran/lib -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: warning: -undefined dynamic_lookup may not work with chained fixups
ld: warning: ignoring file dysta.o, building for macOS-arm64 but attempting to link with file built for unknown-x86_64
ld: warning: ignoring file daisy.o, building for macOS-arm64 but attempting to link with file built for unknown-x86_64
installing to /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs
** R
** data
*** moving datasets to lazyload DB
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: Laden von Paket oder Namensraum für ‘cluster’ in dyn.load(file, DLLpath = DLLpath, ...): fehlgeschlagen
 kann shared object '/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs/cluster.so' nicht laden:
  dlopen(/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs/cluster.so, 0x0006): symbol not found in flat namespace '_dysta_'
Fehler: Laden fehlgeschlagen
Ausführung angehalten
ERROR: loading failed
* removing ‘/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/cluster’
* restoring previous ‘/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/cluster’
Warning in install.packages :
  Installation des Pakets ‘cluster’ hatte Exit-Status ungleich 0

Die heruntergeladenen Quellpakete sind in
    ‘/private/var/folders/vg/kjdqgj4j4d949_p782bz80rm0000gn/T/RtmpsJedpT/downloaded_packages’
</code>```

Could this be related to the architecture arm64?

gfortran is also installed.

Here is the output of sessionInfo() and the setting in ~/.R/Makevars

```<code>> sessionInfo()
R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.1

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.2.2 tools_4.2.2
</code>```
```<code># Makevars

FC = gfortran
F77 = gfortran
FLIBS = -L/usr/local/gfortran/lib
</code>```

I had to set gfortran in ~/.R/Makevars, otherwise R searches in an inconclusive place for gfortran and cannot find it. I checked the FLIBS path with gfortran -print-search-dirs, not sure if this is the correct setting.

Actually, the output seems as the package could be installed but not loaded. Does anybody have any ideas or faced a similar problem?

Thank you!

Body:
I am trying to set up R on a Mac and the installation of the cluster package is failing, possibly due to gfortran (or its library path). Below is the output for the failing package installation (sorry about the partly german output).

> install.packages("cluster", type = "source")
versuche URL 'https://cran.rstudio.com/src/contrib/cluster_2.1.4.tar.gz'
Content type 'application/x-gzip' length 352076 bytes (343 KB)
==================================================
downloaded 343 KB

* installing *source* package ‘cluster’ ...
** Paket ‘cluster’ erfolgreich entpackt und MD5 Summen überprüft
** using staged installation
** libs
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c clara.c -o clara.o
gfortran -fno-optimize-sibling-calls  -fPIC  -Wall -g -O2  -c daisy.f -o daisy.o
gfortran -fno-optimize-sibling-calls  -fPIC  -Wall -g -O2  -c dysta.f -o dysta.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c fanny.c -o fanny.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c init.c -o init.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c mona.c -o mona.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c pam.c -o pam.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c sildist.c -o sildist.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c spannel.c -o spannel.o
clang -arch arm64 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c twins.c -o twins.o
clang -arch arm64 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/opt/R/arm64/lib -o cluster.so clara.o daisy.o dysta.o fanny.o init.o mona.o pam.o sildist.o spannel.o twins.o -L/usr/local/gfortran/lib -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: warning: -undefined dynamic_lookup may not work with chained fixups
ld: warning: ignoring file dysta.o, building for macOS-arm64 but attempting to link with file built for unknown-x86_64
ld: warning: ignoring file daisy.o, building for macOS-arm64 but attempting to link with file built for unknown-x86_64
installing to /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs
** R
** data
*** moving datasets to lazyload DB
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: Laden von Paket oder Namensraum für ‘cluster’ in dyn.load(file, DLLpath = DLLpath, ...): fehlgeschlagen
 kann shared object '/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs/cluster.so' nicht laden:
  dlopen(/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/00LOCK-cluster/00new/cluster/libs/cluster.so, 0x0006): symbol not found in flat namespace '_dysta_'
Fehler: Laden fehlgeschlagen
Ausführung angehalten
ERROR: loading failed
* removing ‘/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/cluster’
* restoring previous ‘/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/cluster’
Warning in install.packages :
  Installation des Pakets ‘cluster’ hatte Exit-Status ungleich 0

Die heruntergeladenen Quellpakete sind in
    ‘/private/var/folders/vg/kjdqgj4j4d949_p782bz80rm0000gn/T/RtmpsJedpT/downloaded_packages’

Could this be related to the architecture arm64?

gfortran is also installed.

Here is the output of sessionInfo() and the setting in ~/.R/Makevars

> sessionInfo()
R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.1

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.2.2 tools_4.2.2

# Makevars

FC = gfortran
F77 = gfortran
FLIBS = -L/usr/local/gfortran/lib

I had to set gfortran in ~/.R/Makevars, otherwise R searches in an inconclusive place for gfortran and cannot find it. I checked the FLIBS path with gfortran -print-search-dirs, not sure if this is the correct setting.

Actually, the output seems as the package could be installed but not loaded. Does anybody have any ideas or faced a similar problem?

Thank you!


问:
compile pin tool with protobuf in makefile error
I have to include google protocol buffer in pintool in order to save trace data but when I compile with this makefile makefile.rules

```<code>TOOL_LIBS += -lprotobuf -pthread -lboost_system

$(OBJDIR)Source1$(OBJ_SUFFIX): trace.pb.cc
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

$(OBJDIR)Source2$(OBJ_SUFFIX): protoio.cc
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

$(OBJDIR)Source3$(OBJ_SUFFIX): tracerProto.cpp
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

# Build the tool as a dll (shared object).
$(OBJDIR)tracerProto$(PINTOOL_SUFFIX): $(OBJDIR)Source1$(OBJ_SUFFIX) trace.pb.h $(OBJDIR)Source2$(OBJ_SUFFIX) protoio.hh $(OBJDIR)Source3$(OBJ_SUFFIX)
    $(LINKER) $(TOOL_LDFLAGS_NOOPT) $(LINK_EXE)$@ $(^:%.h=) $(TOOL_LPATHS) $(TOOL_LIBS)
</code>```

but I got this error when run using this command  pin -t obj-intel64/tracerProto2.so -- /bin/ls

```<code>E: Unable to load tracerProto2.so: dlopen failed: library "libprotobuf.so.17" not found
</code>```

but protocol buffer library is installed already.

I have done using protobuf in another project which is built by cmake. It works correctly. How can I solve this problem?

Body:
I have to include google protocol buffer in pintool in order to save trace data but when I compile with this makefile makefile.rules

TOOL_LIBS += -lprotobuf -pthread -lboost_system

$(OBJDIR)Source1$(OBJ_SUFFIX): trace.pb.cc
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

$(OBJDIR)Source2$(OBJ_SUFFIX): protoio.cc
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

$(OBJDIR)Source3$(OBJ_SUFFIX): tracerProto.cpp
    $(CXX) $(TOOL_CXXFLAGS) $(COMP_OBJ)$@ $<

# Build the tool as a dll (shared object).
$(OBJDIR)tracerProto$(PINTOOL_SUFFIX): $(OBJDIR)Source1$(OBJ_SUFFIX) trace.pb.h $(OBJDIR)Source2$(OBJ_SUFFIX) protoio.hh $(OBJDIR)Source3$(OBJ_SUFFIX)
    $(LINKER) $(TOOL_LDFLAGS_NOOPT) $(LINK_EXE)$@ $(^:%.h=) $(TOOL_LPATHS) $(TOOL_LIBS)

but I got this error when run using this command  pin -t obj-intel64/tracerProto2.so -- /bin/ls

E: Unable to load tracerProto2.so: dlopen failed: library "libprotobuf.so.17" not found

but protocol buffer library is installed already.

I have done using protobuf in another project which is built by cmake. It works correctly. How can I solve this problem?


问:
How to get Java JNR-FFI work on Android emulator running on ARM mac?
I am trying to call some C code from my Android application.

I've built my native code into shared libraries for every abi.
I am using JNR FFI as an interface.
My libraries are properly located into src/main/jniLibs/<abi>/libXXX.so.
I followed the JNR FFI documentation and the Android app builds successfully.
I am testing on a ARM M1 mac running Monterey.

However when running on Android emulator (Pixel 4 API 31), I get the following error :

```<code>Could not invoke MyModule.myMethod

null

could not load FFI provider
jnr.ffi.provider.jffi.Provider

could not get native definition for type `POINTER`, original error message follows:
java.lang.UnsatisfiedLinkError: could not locate stub library in jar file.
Tried: [jni/aarch64-Linux/libjffi-1.2.so, /jni/aarch64-Linux/libjffi-1.2.so]
</code>```

By doing some googling it seems related to the M1 architecture.

Related discussions :

https://github.com/jnr/jnr-ffi/issues/215

https://github.com/jnr/jnr-ffi/issues/310

https://github.com/jnr/jnr-ffi/issues/155

Body:
I am trying to call some C code from my Android application.

I've built my native code into shared libraries for every abi.
I am using JNR FFI as an interface.
My libraries are properly located into src/main/jniLibs/<abi>/libXXX.so.
I followed the JNR FFI documentation and the Android app builds successfully.
I am testing on a ARM M1 mac running Monterey.

However when running on Android emulator (Pixel 4 API 31), I get the following error :

Could not invoke MyModule.myMethod

null

could not load FFI provider
jnr.ffi.provider.jffi.Provider

could not get native definition for type `POINTER`, original error message follows:
java.lang.UnsatisfiedLinkError: could not locate stub library in jar file.
Tried: [jni/aarch64-Linux/libjffi-1.2.so, /jni/aarch64-Linux/libjffi-1.2.so]

By doing some googling it seems related to the M1 architecture.

Related discussions :

https://github.com/jnr/jnr-ffi/issues/215

https://github.com/jnr/jnr-ffi/issues/310

https://github.com/jnr/jnr-ffi/issues/155


问:
Is it ok to use two different ReactJS Code bases for one project
As I'm starting my carrier as JavaScript developer I always have this question. Let's say I'm developing an App using ReactJS. And in that project, I want to create separate domains for Admin and Client.

Because the admin can log into the backend and check the inventory, it won't get mixed with the Client / User when using the same login. And the code is also getting smaller

As an Example.

Admin is logged using admin.site.com

User / Client is logged in using site.com/login

Now, I decided to go with NodeJs as the back-end for the project. For front-end of the back-end (UI), I thought of using REactJS. Also to use Admin LTE.

For Client-side I will be also using ReactJs.

So there will be two ReactJS code bases and one Node JS.

My Questions are,

Is this method ok?

Or can I do this on one ReactJS code base?

Do you guys have any suggestions for me?


问:
Embed QR Code in a Mail Merge Word Document with API call
I have the follwoing problem:
Our client has a Microsoft Word Mail Merge Template. We have an API that takes an address and returns a link that provides the recipient of this address with access to our website. Now I want to include the QR Code into the template. However, I am not sure how or when to call the our API.

The API can only see the addresses not other fields of the Mail Merge. We do not know what the Data Source of the Mail Merge is (database or excel ...). Therefore, I assumed that the only way to call the APIwas from inside Word.

My first attempt was to create a Word Add-In. However, it seems that the Javascript API is not able to access the Mail Merge Data Source.

I am currently trying the C# Word Interops API to extract the address data, but I am not sure if this is even possible.


问:
Exclude a particular type from a return type
Let suppose I want to exclude some type of a method that returns a "wide" type.

Something that would look like that but doesn't work :

```<code>type FooFn = {
    <T extends Record<string, any>>(): T extends Promise<any> ? never : T;
};

const foo: FooFn = () => ({ 'ok': 'ok' }); // should work
const foo2: FooFn = () => { return Promise.resolve({ 'ok': 'ok' }) }; // should fail
</code>```

Edit:
What I'm looking for is part of a wider problem.

```<code>type Fn = () => Record<string, any>; // should not allow Promises, Observables etc.
type AsyncFn = () => Promise<Record<string, any>>;

const foo: Fn = () => ({ 'ok': 'ok' }); // should work
const foo2: Fn = () => { return Promise.resolve({ 'ok': 'ok' }) }; // should fail
</code>```

Playground

Body:
Let suppose I want to exclude some type of a method that returns a "wide" type.

Something that would look like that but doesn't work :

type FooFn = {
    <T extends Record<string, any>>(): T extends Promise<any> ? never : T;
};

const foo: FooFn = () => ({ 'ok': 'ok' }); // should work
const foo2: FooFn = () => { return Promise.resolve({ 'ok': 'ok' }) }; // should fail

Edit:
What I'm looking for is part of a wider problem.

type Fn = () => Record<string, any>; // should not allow Promises, Observables etc.
type AsyncFn = () => Promise<Record<string, any>>;

const foo: Fn = () => ({ 'ok': 'ok' }); // should work
const foo2: Fn = () => { return Promise.resolve({ 'ok': 'ok' }) }; // should fail

Playground


问:
Angular 2: how to access ngFor of keyvalues inside an array, using the index of the wrapper ngFor
*see code below

in my first ngFor I am iterating over formsAr, works fine.

in the second ngFor I want to access an object in an inputsOnly array, with the same index of I in the top ngFor, and then iterate over the keys (unknown length between 1 and 8), then access formItem.inputType and formItem.inputLabel.

if I can iterate an object using : *ngFor="let formItem of someObject | keyvalue",
shouldn't it be possible to do : *ngFor="let formItem of inputsOnly[i] | keyvalue" - inputsOnly[i] being an object.

first I tried leaving the inputs object inside the formsAr, but then moved them to a seperate aray and try to access them using outer ngFor index. This the formsAr data looked like this:

export interface CustomFormModel {
formName: string,
inputs: {
inp1?: {inputLabel: string, inputType: string},
inp2?: {inputLabel: string, inputType: string},
inp3?: {inputLabel: string, inputType: string},
inp4?: {inputLabel: string, inputType: string},
inp5?: {inputLabel: string, inputType: string},
inp6?: {inputLabel: string, inputType: string},
inp7?: {inputLabel: string, inputType: string},
inp8?: {inputLabel: string, inputType: string},
},
key: string;
}

Now the inputs object is still the same, but in it's own arry. So I just need to match it with the index.

Is what I am trying to achieve even possible or am I trying to go to deep into my data with the ngFor?

I am building a component where a customer can manually create a form, and this is where I am trying to display all the forms they created, using the info about the forms saved on a database

     //here I am iterating over all the forms
```<code><div class="news-form-container form-container">
    <form [formGroup]="customForm" (submit)="onSubmit()">
        <h1>{{'form name: ' + form.formName}}</h1>
        <div *ngFor="let formItem of inputsOnly[i] | keyvalue; index as objI">

            <label for="forminput">{{formItem.inputLabel}}</label>
            <input
            type="{{formItem.inputType}}"
            required
            formControlName="{{'inp'+(objI+1)}}"
            class="w-full h-8"
            id="forminput"
            placeholder="no"
            >
            <br>

        </div>
        <div class="flex justify-center">
            <button mat-raised-button type="submit" class="w-full blbtn">Submit</button>
        </div>

    </form>

</div>
</code>```

Body:
*see code below

in my first ngFor I am iterating over formsAr, works fine.

in the second ngFor I want to access an object in an inputsOnly array, with the same index of I in the top ngFor, and then iterate over the keys (unknown length between 1 and 8), then access formItem.inputType and formItem.inputLabel.

if I can iterate an object using : *ngFor="let formItem of someObject | keyvalue",
shouldn't it be possible to do : *ngFor="let formItem of inputsOnly[i] | keyvalue" - inputsOnly[i] being an object.

first I tried leaving the inputs object inside the formsAr, but then moved them to a seperate aray and try to access them using outer ngFor index. This the formsAr data looked like this:

export interface CustomFormModel {
formName: string,
inputs: {
inp1?: {inputLabel: string, inputType: string},
inp2?: {inputLabel: string, inputType: string},
inp3?: {inputLabel: string, inputType: string},
inp4?: {inputLabel: string, inputType: string},
inp5?: {inputLabel: string, inputType: string},
inp6?: {inputLabel: string, inputType: string},
inp7?: {inputLabel: string, inputType: string},
inp8?: {inputLabel: string, inputType: string},
},
key: string;
}

Now the inputs object is still the same, but in it's own arry. So I just need to match it with the index.

Is what I am trying to achieve even possible or am I trying to go to deep into my data with the ngFor?

I am building a component where a customer can manually create a form, and this is where I am trying to display all the forms they created, using the info about the forms saved on a database

     //here I am iterating over all the forms

    <form [formGroup]="customForm" (submit)="onSubmit()">

{{'form name: ' + form.formName}}

            {{formItem.inputLabel}}
            <input
            type="{{formItem.inputType}}"
            required
            formControlName="{{'inp'+(objI+1)}}"
            class="w-full h-8"
            id="forminput"
            placeholder="no"
            >

            <button mat-raised-button type="submit" class="w-full blbtn">Submit</button>

    </form>


问:
how to know if a telegram chat is disabled using telethon?
I'm trying to know if a telegram chat was deleted \ disabled using telethon, the simplest way I found to do that is by trying to get the chat entity and see what errors come up, the problem is that when I ask for a chat entity that is disabled, I get its past entity from session cashing and don't get any indication for the chat is disabled. I tried to disable the session cashing but when I do that, I can't get chat entities using their ID  - I must have this ability for my project.
do you have any idea what can I do?</p>


问:
javascript how to keep refreshing a page using bookmarklet and check if a div is present
As the title says I need to create a bookmarklet in javascript that keeps refreshing a page and checks if a div is present on that page. Using the snippet of the code below the page is refreshing but when I log the div it is always undefined even if the div with the class container is present. How to do it?</p>
```<code>document.write(`<frameset><frame src="${location.href}"></frameset>`);
setInterval(() => {
    console.log(document.getElementsByClassName("container")[0].innerText);
    document.getElementsByTagName('frame')[0].src += ''

    },
    5000);
</code>```

Body:
As the title says I need to create a bookmarklet in javascript that keeps refreshing a page and checks if a div is present on that page. Using the snippet of the code below the page is refreshing but when I log the div it is always undefined even if the div with the class container is present. How to do it?

document.write(`<frameset><frame src="${location.href}"></frameset>`);
setInterval(() => {
    console.log(document.getElementsByClassName("container")[0].innerText);
    document.getElementsByTagName('frame')[0].src += ''

    },
    5000);


问:
How do I bind a float array with Uxml Attribute Description in Unity UI toolkit?
I'm trying to make a custom inspector in Unity which takes in a float[] array and plots it as a line graph.

I'm making a BindableElement called "LineGraph2D" to do just that which sits as an element in UI Builder.

I think I'm having particular trouble with the Uxml traits as I can't find any examples of how this is meant to be done with arrays. I'm trying to use UxmlTypeAttributeDescription<float[]> to do so.

Any ideas on how to get this working?

```<code>using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class LineGraph2D : BindableElement
{

    public new class UxmlFactory : UxmlFactory<LineGraph2D, UxmlTraits> { }
    public new class UxmlTraits : BindableElement.UxmlTraits
    {
        // TODO I want this to be an array bound by the user... not sure how this works.
        UxmlTypeAttributeDescription<float[]> array = new UxmlTypeAttributeDescription<float[]> { name = "array-data" };

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            var line2D = ve as LineGraph2D;
            // Unity Doesn't like this line below (Error: can't assign to property as its read only)
            line2D.arrayData = array.GetValueFromBag(bag, cc);
        }
    }

    VisualElement lineGraph;

    float[] array;

    public float[] arrayData => array;

    public LineGraph2D()
    {
        lineGraph = new VisualElement();
        lineGraph.generateVisualContent += DrawArray;
        Add(lineGraph);
    }

    void DrawArray(MeshGenerationContext ctx)
    {
        var painter = ctx.painter2D;
        painter.strokeColor = Color.red;
        painter.fillColor = Color.red;
        painter.lineWidth = 1f;

        painter.BeginPath();
        for (int i = 0; i < 100; i++)
            // TODO change for array data (and scale etc)
            painter.LineTo(new Vector2((float)i * 10f, 100f * Random.value));

        painter.Stroke();

    }

}
</code>```

Thanks in advance and sorry for my code stinks!

best, Rob

Body:
I'm trying to make a custom inspector in Unity which takes in a float[] array and plots it as a line graph.

I'm making a BindableElement called "LineGraph2D" to do just that which sits as an element in UI Builder.

I think I'm having particular trouble with the Uxml traits as I can't find any examples of how this is meant to be done with arrays. I'm trying to use UxmlTypeAttributeDescription<float[]> to do so.

Any ideas on how to get this working?

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class LineGraph2D : BindableElement
{

    public new class UxmlFactory : UxmlFactory<LineGraph2D, UxmlTraits> { }
    public new class UxmlTraits : BindableElement.UxmlTraits
    {
        // TODO I want this to be an array bound by the user... not sure how this works.
        UxmlTypeAttributeDescription<float[]> array = new UxmlTypeAttributeDescription<float[]> { name = "array-data" };

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            var line2D = ve as LineGraph2D;
            // Unity Doesn't like this line below (Error: can't assign to property as its read only)
            line2D.arrayData = array.GetValueFromBag(bag, cc);
        }
    }

    VisualElement lineGraph;

    float[] array;

    public float[] arrayData => array;

    public LineGraph2D()
    {
        lineGraph = new VisualElement();
        lineGraph.generateVisualContent += DrawArray;
        Add(lineGraph);
    }

    void DrawArray(MeshGenerationContext ctx)
    {
        var painter = ctx.painter2D;
        painter.strokeColor = Color.red;
        painter.fillColor = Color.red;
        painter.lineWidth = 1f;

        painter.BeginPath();
        for (int i = 0; i < 100; i++)
            // TODO change for array data (and scale etc)
            painter.LineTo(new Vector2((float)i * 10f, 100f * Random.value));

        painter.Stroke();

    }

}

Thanks in advance and sorry for my code stinks!

best, Rob


问:
How to get rsi with krakenex and talib?
I'm trying to implement a Trading bot in Kraken using Krakenex api and Talib, but the code does not work it has this error:

Traceback (most recent call last): File
"c:\Users\user1\OneDrive\tradingbot\krakenexBot.py", line 19, in
timestamps = ohlc['XXBTZUSD']['timestamp'] TypeError: string indices
must be integers

import krakenex
import talib
import time
import pandas as pd

# Set your Kraken API key and secret
api_key = 'cD8Jm4LaKHNuLHPxd1rotttPNwtVBp7iWzXl8hdqzFAPSaSTLhx3m5ZP'
api_secret = 'ynuaaCuD5h2JSu9FOfT1534qW0AYg9RoEhUvgwicrtALCkw88adQwjDORu+XDL3VDg5n8i4EgvHsduopa6f2jg=='

# Initialize the Kraken API client
kraken = krakenex.API(key=api_key, secret=api_secret)

pair = 'XXBTZEUR'
while True:
    # Get the daily OHLC data for BTC/USD
    ohlc, last = kraken.query_public('OHLC', data={"pair": "XXBTZUSD", "interval": 1440})

    # Extract the timestamp, open, high, low, and close prices from the OHLC data
    timestamps = ohlc['XXBTZUSD']['timestamp']
    opens = ohlc['XXBTZUSD']['open']
    highs = ohlc['XXBTZUSD']['high']
    lows = ohlc['XXBTZUSD']['low']
    closes = ohlc['XXBTZUSD']['close']
    rsi = talib.RSI(closes, timeperiod=14)
    # Check if the RSI is below 30 or above 70
    if rsi < 30:
        # Place a buy order
        #response = kraken.query_private('AddOrder', {'pair': pair, 'type': 'buy', 'ordertype': 'market', 'volume': '1'})
        print(f'Bought 1 unit at {price}')
    elif rsi > 70:
        # Place a sell order
        #response = kraken.query_private('AddOrder', {'pair': pair, 'type': 'sell', 'ordertype': 'market', 'volume': '1'})
        print(f'Sold 1 unit at {price}')

    # Sleep for a minute before checking again
    time.sleep(60)
```

I expected that the OHLC will get the data since its a dictionary, I think.

Title: How to get rsi with krakenex and talib?

Body:
I'm trying to implement a Trading bot in Kraken using Krakenex api and Talib, but the code does not work it has this error:

Traceback (most recent call last): File
"c:\Users\user1\OneDrive\tradingbot\krakenexBot.py", line 19, in
timestamps = ohlc['XXBTZUSD']['timestamp'] TypeError: string indices
must be integers

import krakenex
import talib
import time
import pandas as pd

# Set your Kraken API key and secret
api_key = 'cD8Jm4LaKHNuLHPxd1rotttPNwtVBp7iWzXl8hdqzFAPSaSTLhx3m5ZP'
api_secret = 'ynuaaCuD5h2JSu9FOfT1534qW0AYg9RoEhUvgwicrtALCkw88adQwjDORu+XDL3VDg5n8i4EgvHsduopa6f2jg=='

# Initialize the Kraken API client
kraken = krakenex.API(key=api_key, secret=api_secret)

pair = 'XXBTZEUR'
while True:
    # Get the daily OHLC data for BTC/USD
    ohlc, last = kraken.query_public('OHLC', data={"pair": "XXBTZUSD", "interval": 1440})

    # Extract the timestamp, open, high, low, and close prices from the OHLC data
    timestamps = ohlc['XXBTZUSD']['timestamp']
    opens = ohlc['XXBTZUSD']['open']
    highs = ohlc['XXBTZUSD']['high']
    lows = ohlc['XXBTZUSD']['low']
    closes = ohlc['XXBTZUSD']['close']
    rsi = talib.RSI(closes, timeperiod=14)
    # Check if the RSI is below 30 or above 70
    if rsi < 30:
        # Place a buy order
        #response = kraken.query_private('AddOrder', {'pair': pair, 'type': 'buy', 'ordertype': 'market', 'volume': '1'})
        print(f'Bought 1 unit at {price}')
    elif rsi > 70:
        # Place a sell order
        #response = kraken.query_private('AddOrder', {'pair': pair, 'type': 'sell', 'ordertype': 'market', 'volume': '1'})
        print(f'Sold 1 unit at {price}')

    # Sleep for a minute before checking again
    time.sleep(60)

I expected that the OHLC will get the data since its a dictionary, I think.


问:
Flutter Multiple Image to Video Slideshow with Audio converter Using FFmpegKit
I want to render a video file using some images with animation.

I have tried some solution out there and i did not get any solution either I don't know how to write command of FFmpegKit. I also tried to first implement a single image with mp3 but it was also not working.


问:
Calling VROUNDSS using Rust intrinsics
From what I see here:

I can call "roundss" (SSE 4.2) by using the Rust intrinsic: core::arch::x86_64::_mm_round_ss.

but I'm unable to find an equivalent for "vroundss" (AVX?). Is there a way to call this instruction in Rust?

I found no match in Rust documentation for this specific instruction.

Title: Calling VROUNDSS using Rust intrinsics


问:
bootstrap table not refreshing switch properly
I created two tables, one displays all items where the property "selected" is false and the other is "true"

To toggle between the two tables, I've used a dev extreme switch.
When a user switches from false to true (or on to off), the element will refresh and render properly on the correct table, however the switch seems to be stuck.

Example:

Initial Table

Table of False Elements

a - switch shows false

b - switch shows false

c - switch shows false

Table of True Elements

d - switch shows true

e - switch shows true

If a user clicks "a" in the first table, the following is what will be rendered

Table of False Elements

b - switch shows true

c - switch shows false

Table of True Elements

a - switch shows true

d - switch shows true

e - switch shows true

Furthermore, these tables have pagination, navigating between pages, the row in which the element was clicked will remain "true" from page to page.

```<code><b-table :fields="fields" :items="UnselectedAccounts" striped ref="UnselectedTable" :per-page="perPage" :current-page="currentPage">
                        <template slot="Selected" slot-scope="row">
                          <dx-switch type="checkbox" v-model:value="row.item.Selected" @value-changed="switchChange()"></dx-switch>
                        </template>
                      </b-table>

   <b-table :fields="fields" :items="SelectedAccounts" striped ref="SelectedTable">
                    <template slot="Selected" slot-scope="row">
                      <dx-switch type="checkbox" v-model="row.item.Selected" @value-changed="switchChange()"></dx-switch>
                    </template>
                  </b-table>
</code>```

My switch change method (I have tried creating the variables as computed but results are the same)

```<code>switchChange() {

        if (!this.EnterpriseData.AssociatedAccounts) {
          this.UnselectedAccounts = [...this.UnassignedAccounts].filter(r => r.Selected === false)
          this.SelectedAccounts = [...this.UnassignedAccounts].filter(r => r.Selected === true)
        } else {
          this.UnselectedAccounts = [...this.UnassignedAccounts, ...this.EnterpriseData.AssociatedAccounts].filter(r => r.Selected === false)
          this.SelectedAccounts = [...this.UnassignedAccounts, ...this.EnterpriseData.AssociatedAccounts].filter(r => r.Selected === true)
}
</code>```

Body:
I created two tables, one displays all items where the property "selected" is false and the other is "true"

To toggle between the two tables, I've used a dev extreme switch.
When a user switches from false to true (or on to off), the element will refresh and render properly on the correct table, however the switch seems to be stuck.

Example:

Initial Table

Table of False Elements

a - switch shows false

b - switch shows false

c - switch shows false

Table of True Elements

d - switch shows true

e - switch shows true

If a user clicks "a" in the first table, the following is what will be rendered

Table of False Elements

b - switch shows true

c - switch shows false

Table of True Elements

a - switch shows true

d - switch shows true

e - switch shows true

Furthermore, these tables have pagination, navigating between pages, the row in which the element was clicked will remain "true" from page to page.

                        <template slot="Selected" slot-scope="row">
                          <dx-switch type="checkbox" v-model:value="row.item.Selected" @value-changed="switchChange()"></dx-switch>
                        </template>

                    <template slot="Selected" slot-scope="row">
                      <dx-switch type="checkbox" v-model="row.item.Selected" @value-changed="switchChange()"></dx-switch>
                    </template>

My switch change method (I have tried creating the variables as computed but results are the same)

switchChange() {

        if (!this.EnterpriseData.AssociatedAccounts) {
          this.UnselectedAccounts = [...this.UnassignedAccounts].filter(r => r.Selected === false)
          this.SelectedAccounts = [...this.UnassignedAccounts].filter(r => r.Selected === true)
        } else {
          this.UnselectedAccounts = [...this.UnassignedAccounts, ...this.EnterpriseData.AssociatedAccounts].filter(r => r.Selected === false)
          this.SelectedAccounts = [...this.UnassignedAccounts, ...this.EnterpriseData.AssociatedAccounts].filter(r => r.Selected === true)
}


问:
Folder in Git is split
I have a folder called 'Development' with subfolders 'a' and 'b' in my Pycharm project. However, when I look at the folder structure in Gitlab with the browser, the folder is split into "Development" (Capital initial letter) with subfolder "a" and "development" (small initial letter) with subfolder "b". I tried to merge the folders in Gitlab using checkout main and push into main. But that didn't change anything and when I'm in the main branch with the Pycharm IDE, I can only see the folder 'Development' with the two subfolders 'a' and 'b'.

In Pycharm:

```<code>Project/
  Development/
    a/
    b/

</code>```

In Gitlab:

```<code>Project/
  Development/
    a/
  development/
    b/
</code>```

This structure was created automatically in Git. I never created it this way.

How can I merge the two folders in the Gitlab repository?

Title: Folder in Git is split

Body:
I have a folder called 'Development' with subfolders 'a' and 'b' in my Pycharm project. However, when I look at the folder structure in Gitlab with the browser, the folder is split into "Development" (Capital initial letter) with subfolder "a" and "development" (small initial letter) with subfolder "b". I tried to merge the folders in Gitlab using checkout main and push into main. But that didn't change anything and when I'm in the main branch with the Pycharm IDE, I can only see the folder 'Development' with the two subfolders 'a' and 'b'.

In Pycharm:

Project/
  Development/
    a/
    b/

In Gitlab:

Project/
  Development/
    a/
  development/
    b/

This structure was created automatically in Git. I never created it this way.

How can I merge the two folders in the Gitlab repository?