问:
Export docx to pdf with vba
I would like to export docx file to pdf file from excel vba.
Document file.docx is opened correctly.
However, an error occurred while calling the method ExportAsFixedFormat: Run-time error '5': Invalid procedure call or argument.
I think arguments are ok.

Next little bug: ActiveDocument.Path does not work. There is an error "Run-time error '424': Object required" Therefore I used WordApp.Documents(myFileName).ExportAsFixedFormat instead ActiveDocument.ExportAsFixedFormat.

This code is executed from file Macro.xlsm. I use Microsoft Office 2021.

Method exportasfixedformat

```<code>Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp

Set WordApp = CreateObject("Word.Application")
FileNameDoc = "D:\rd\file.docx"

WordApp.Documents.Open FileNameDoc
WordApp.Visible = True
WordApp.Documents(FileNameDoc).Activate ' <- activation doesn't work

fileNamePdf = "D:\rd\file.pdf"
'fileNamePdf = ActiveDocument.Path & "\" & "file.pdf"

' https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
' here is error: Run-time error '5': Invalid procedure call or argument
WordApp.Documents(myFileName).ExportAsFixedFormat OutputFileName:=fileNamePdf, _
                                                             ExportFormat:=wdExportFormatPDF, _
                                                             OpenAfterExport:=False, _
                                                             OptimizeFor:=wdExportOptimizeForPrint, _
                                                             Range:=wdExportAllDocument, _
                                                             Item:=wdExportDocumentWithMarkup, _
                                                             IncludeDocProps:=False, _
                                                             CreateBookmarks:=wdExportCreateNoBookmarks, _
                                                             BitmapMissingFonts:=True

' https://learn.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordApp.Documents(myFileName).Close _
'ActiveDocument.Close _
    SaveChanges:=wdSaveChanges, _
    OriginalFormat:=wdOriginalDocumentFormat
</code>```

Any idea for a solution?

答:
The code that you have used is for Word and uses a lot of Word constants e.g. wdExportFormatPDF, wdExportOptimizeForPrint, wdExportDocumentWithMarkup, wdExportCreateNoBookmarks, wdSaveChanges, wdOriginalDocumentFormat. Excel does not understand what these are.

You have two options. The best option is to set a reference to the Word library. In the Visual Basic Editor select References from the Tools menu. In the resulting dialog page down (approx 16 times) until you see the entry for the Microsoft Word Object library and check the box next to it.

Your other option is to create constants in your code for each Word constant you want to use. You'll need to use the object browser in Word, or the online help, to look up the values.

Similarly, Excel does not understand ActiveDocument. You need to prefix any Word objects you wish to use with WordApp. However, it would be better if you used a variable to point to the document you open:

```<code>Set WordDoc = WordApp.Documents.Open(FileNameDoc)
</code>```

You can then use the WordDoc variable instead of ActiveDocument

```<code>Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp As Word.Application
Dim WordDoc As Word.Document

Set WordApp = CreateObject("Word.Application")
fileNameDoc = "D:\rd\file.docx"

Set WordDoc = WordApp.Documents.Open(fileNameDoc)
WordApp.Visible = True

fileNamePdf = WordDoc.Path & "\" & "file.pdf"

' https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
WordDoc.ExportAsFixedFormat OutputFileName:=fileNamePdf, _
    ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=False, _
    OptimizeFor:=wdExportOptimizeForPrint, _
    Range:=wdExportAllDocument, _
    Item:=wdExportDocumentWithMarkup, _
    IncludeDocProps:=False, _
    CreateBookmarks:=wdExportCreateNoBookmarks, _
    BitmapMissingFonts:=True

' https://learn.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordDoc.Close _
 SaveChanges:=wdSaveChanges, _
 OriginalFormat:=wdOriginalDocumentFormat
</code>```

Title: Export docx to pdf with vba

Body:
I would like to export docx file to pdf file from excel vba.
Document file.docx is opened correctly.
However, an error occurred while calling the method ExportAsFixedFormat: Run-time error '5': Invalid procedure call or argument.
I think arguments are ok.

Next little bug: ActiveDocument.Path does not work. There is an error "Run-time error '424': Object required" Therefore I used WordApp.Documents(myFileName).ExportAsFixedFormat instead ActiveDocument.ExportAsFixedFormat.

This code is executed from file Macro.xlsm. I use Microsoft Office 2021.

Method exportasfixedformat

Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp

Set WordApp = CreateObject("Word.Application")
FileNameDoc = "D:\rd\file.docx"

WordApp.Documents.Open FileNameDoc
WordApp.Visible = True
WordApp.Documents(FileNameDoc).Activate ' <- activation doesn't work

fileNamePdf = "D:\rd\file.pdf"
'fileNamePdf = ActiveDocument.Path & "\" & "file.pdf"

' https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
' here is error: Run-time error '5': Invalid procedure call or argument
WordApp.Documents(myFileName).ExportAsFixedFormat OutputFileName:=fileNamePdf, _
                                                             ExportFormat:=wdExportFormatPDF, _
                                                             OpenAfterExport:=False, _
                                                             OptimizeFor:=wdExportOptimizeForPrint, _
                                                             Range:=wdExportAllDocument, _
                                                             Item:=wdExportDocumentWithMarkup, _
                                                             IncludeDocProps:=False, _
                                                             CreateBookmarks:=wdExportCreateNoBookmarks, _
                                                             BitmapMissingFonts:=True

' https://learn.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordApp.Documents(myFileName).Close _
'ActiveDocument.Close _
    SaveChanges:=wdSaveChanges, _
    OriginalFormat:=wdOriginalDocumentFormat

Any idea for a solution?

Body:
The code that you have used is for Word and uses a lot of Word constants e.g. wdExportFormatPDF, wdExportOptimizeForPrint, wdExportDocumentWithMarkup, wdExportCreateNoBookmarks, wdSaveChanges, wdOriginalDocumentFormat. Excel does not understand what these are.

You have two options. The best option is to set a reference to the Word library. In the Visual Basic Editor select References from the Tools menu. In the resulting dialog page down (approx 16 times) until you see the entry for the Microsoft Word Object library and check the box next to it.

Your other option is to create constants in your code for each Word constant you want to use. You'll need to use the object browser in Word, or the online help, to look up the values.

Similarly, Excel does not understand ActiveDocument. You need to prefix any Word objects you wish to use with WordApp. However, it would be better if you used a variable to point to the document you open:

Set WordDoc = WordApp.Documents.Open(FileNameDoc)

You can then use the WordDoc variable instead of ActiveDocument

Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp As Word.Application
Dim WordDoc As Word.Document

Set WordApp = CreateObject("Word.Application")
fileNameDoc = "D:\rd\file.docx"

Set WordDoc = WordApp.Documents.Open(fileNameDoc)
WordApp.Visible = True

fileNamePdf = WordDoc.Path & "\" & "file.pdf"

' https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
WordDoc.ExportAsFixedFormat OutputFileName:=fileNamePdf, _
    ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=False, _
    OptimizeFor:=wdExportOptimizeForPrint, _
    Range:=wdExportAllDocument, _
    Item:=wdExportDocumentWithMarkup, _
    IncludeDocProps:=False, _
    CreateBookmarks:=wdExportCreateNoBookmarks, _
    BitmapMissingFonts:=True

' https://learn.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordDoc.Close _
 SaveChanges:=wdSaveChanges, _
 OriginalFormat:=wdOriginalDocumentFormat


来源: stackexchange

问:
Adding shadows to widgets in Flutter
I was trying to add a border shadow effect to a Container in a way that resembles exactly the same design as in the picture below. My initial idea was of using the CustomPaint class feature to do so. However, it hasn't worked out the way I wanted it to. I would honestly like to know how this can be achieved through the use of the CustomPaint class and I apologize for the code that I've written as I'm still trying to get used to CustomPaint. The code and the pictures are as follows:

This is what I intend to achieve:

This is what I have. You can see that the border goes well beyond where it should be and also, the border at the bottom gets clipped and despite adjusting the bottom padding:

This is the code:

```<code>class ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return Scaffold(
      body: ListView(
        children: [
          Container(
            height: height * 1,
            width: width * 1,
            // color: Colors.red,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/filter.png'),
                    fit: BoxFit.cover)),
            child: Column(
              ......
                Padding(
                  padding: EdgeInsets.only(left: width * 0.035),
                  child: Container(
                    width: double.infinity,
                    height: height * 0.25,
                    padding: EdgeInsets.only(
                      left: width * 0.03,
                      top: height * 0.01,
                      // bottom: height * 0.01
                    ),
                    // color: Colors.yellow,
                    child: ProfilePageFavourite(),    //This here is the widget
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The ProfilePageFavourite widget:

```<code>class ProfilePageFavouriteState extends State<ProfilePageFavourite> {
  // final List<dynamic> _favouritesList = [

  // ];
  var favourite = false;

  void _onPressed() {
    setState(() => favourite = !favourite);
    print(favourite);
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) => Stack(
        children: [
          CustomPaint(                    //This is where I try using the CustomPaint class
            painter: OrangePainter(),
            child: Container(
              width: width * 0.75,
              margin: EdgeInsets.only(right: width * 0.09),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.yellow,
                  image: DecorationImage(
                      fit: BoxFit.fitWidth,
                      image: AssetImage('assets/images/pub screen 1 (1).png'))),
            ),
          ),
          Positioned(
            top: height * 0.16,
            child: Container(
              height: height * 0.07,
              width: width * 0.75,
              padding: EdgeInsets.only(top: height * 0.008),
              decoration: BoxDecoration(
                  color: Colors.black38,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              child: Column(
                children: [
                  Row(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: width * 0.05),
                        decoration: BoxDecoration(boxShadow: [
                          BoxShadow(
                              color: Colors.red,
                              blurRadius: 35,
                              spreadRadius: 8,
                              offset: Offset(0, 2))
                        ]),
                        child: Image.asset(
                          'assets/icons/dine.png',
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(
                        width: width * 0.02,
                      ),
                      Text(
                        'Sollicitudin',
                        textScaleFactor: textScale,
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            shadows: [
                              Shadow(
                                  color: Colors.red,
                                  blurRadius: 10,
                                  offset: Offset(0, 2))
                            ]),
                      )
                    ],
                  ),
                  Container(
                      width: double.infinity,
                      // color: Colors.red,
                      padding: EdgeInsets.only(left: width * 0.118),
                      child: CustomRatingBar(4.5))
                ],
              ),
            ),
          ),
          Positioned(
            left: width * 0.58,
            top: height * 0.01,
            child: Container(
              decoration: BoxDecoration(boxShadow: [
                BoxShadow(
                  color: Colors.pink,
                  blurRadius: 80,
                  spreadRadius: 6,
                )
              ]),
              child: !favourite
                  ? IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite,
                        // color: Color.fromRGBO(247, 180, 230, 0.8),
                        color: Colors.pink,
                        size: 50,
                      ))
                  : IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite_border_outlined,
                        color: Colors.pink,
                        size: 50,
                      )),
            ),
          ),
        ],
      ),
      itemCount: 5,
    );
  }
}
</code>```

The CustomPaint Class

```<code>class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(Offset(0, 2) & size, Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
</code>```

答:
I have retained the initial customPaint and used it here.This code combines your ProfilePageState and ProfilePageFavourite to give you the appearance below. I've just built it on my phone's dartpad so you can do the editing so it matches. I included comments:

```<code> @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        height: 250,
        width: double.infinity,
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          itemCount: 5,
          separatorBuilder: (ctx, index) => const SizedBox(width: 10),
          itemBuilder: (ctx, index) => ClipRRect(
            child: CustomPaint(
              painter: OrangePainter(),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal:10,vertical:15),//increase padding to your liking
                width: 350,
                decoration: BoxDecoration(
//                 image: DecorationImage(image: AssetImage('')), add your image here and remove color below
                  color: Colors.black54,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  mainAxisAlignment:MainAxisAlignment.spaceBetween,
                  children: [
                    Row(

                      mainAxisAlignment: MainAxisAlignment.end,
                      children: const [
                        Icon(Icons.favorite, size: 40),
                      ],
                    ),
                    Row(
                      children: [
                        const Icon(Icons.restaurant),
                        const SizedBox(width:10),
                        Column(
                          children: const [
                            Text(
                              'Sollicitudin',
//                         textScaleFactor: textScale,
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 20,
                                shadows: [
                                  Shadow(
                                      color: Colors.red,
                                      blurRadius: 10,
                                      offset: Offset(0, 2))
                                ],
                              ),
                            ),
                            Icon(Icons.star),//Replace with your CustomRation()
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, const Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(const Offset(0, 2) & size, const Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding shadows to widgets in Flutter

Body:
I was trying to add a border shadow effect to a Container in a way that resembles exactly the same design as in the picture below. My initial idea was of using the CustomPaint class feature to do so. However, it hasn't worked out the way I wanted it to. I would honestly like to know how this can be achieved through the use of the CustomPaint class and I apologize for the code that I've written as I'm still trying to get used to CustomPaint. The code and the pictures are as follows:

This is what I intend to achieve:

This is what I have. You can see that the border goes well beyond where it should be and also, the border at the bottom gets clipped and despite adjusting the bottom padding:

This is the code:

class ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return Scaffold(
      body: ListView(
        children: [
          Container(
            height: height * 1,
            width: width * 1,
            // color: Colors.red,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/filter.png'),
                    fit: BoxFit.cover)),
            child: Column(
              ......
                Padding(
                  padding: EdgeInsets.only(left: width * 0.035),
                  child: Container(
                    width: double.infinity,
                    height: height * 0.25,
                    padding: EdgeInsets.only(
                      left: width * 0.03,
                      top: height * 0.01,
                      // bottom: height * 0.01
                    ),
                    // color: Colors.yellow,
                    child: ProfilePageFavourite(),    //This here is the widget
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

The ProfilePageFavourite widget:

class ProfilePageFavouriteState extends State<ProfilePageFavourite> {
  // final List<dynamic> _favouritesList = [

  // ];
  var favourite = false;

  void _onPressed() {
    setState(() => favourite = !favourite);
    print(favourite);
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) => Stack(
        children: [
          CustomPaint(                    //This is where I try using the CustomPaint class
            painter: OrangePainter(),
            child: Container(
              width: width * 0.75,
              margin: EdgeInsets.only(right: width * 0.09),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.yellow,
                  image: DecorationImage(
                      fit: BoxFit.fitWidth,
                      image: AssetImage('assets/images/pub screen 1 (1).png'))),
            ),
          ),
          Positioned(
            top: height * 0.16,
            child: Container(
              height: height * 0.07,
              width: width * 0.75,
              padding: EdgeInsets.only(top: height * 0.008),
              decoration: BoxDecoration(
                  color: Colors.black38,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              child: Column(
                children: [
                  Row(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: width * 0.05),
                        decoration: BoxDecoration(boxShadow: [
                          BoxShadow(
                              color: Colors.red,
                              blurRadius: 35,
                              spreadRadius: 8,
                              offset: Offset(0, 2))
                        ]),
                        child: Image.asset(
                          'assets/icons/dine.png',
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(
                        width: width * 0.02,
                      ),
                      Text(
                        'Sollicitudin',
                        textScaleFactor: textScale,
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            shadows: [
                              Shadow(
                                  color: Colors.red,
                                  blurRadius: 10,
                                  offset: Offset(0, 2))
                            ]),
                      )
                    ],
                  ),
                  Container(
                      width: double.infinity,
                      // color: Colors.red,
                      padding: EdgeInsets.only(left: width * 0.118),
                      child: CustomRatingBar(4.5))
                ],
              ),
            ),
          ),
          Positioned(
            left: width * 0.58,
            top: height * 0.01,
            child: Container(
              decoration: BoxDecoration(boxShadow: [
                BoxShadow(
                  color: Colors.pink,
                  blurRadius: 80,
                  spreadRadius: 6,
                )
              ]),
              child: !favourite
                  ? IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite,
                        // color: Color.fromRGBO(247, 180, 230, 0.8),
                        color: Colors.pink,
                        size: 50,
                      ))
                  : IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite_border_outlined,
                        color: Colors.pink,
                        size: 50,
                      )),
            ),
          ),
        ],
      ),
      itemCount: 5,
    );
  }
}

The CustomPaint Class

class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(Offset(0, 2) & size, Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

Body:
I have retained the initial customPaint and used it here.This code combines your ProfilePageState and ProfilePageFavourite to give you the appearance below. I've just built it on my phone's dartpad so you can do the editing so it matches. I included comments:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        height: 250,
        width: double.infinity,
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          itemCount: 5,
          separatorBuilder: (ctx, index) => const SizedBox(width: 10),
          itemBuilder: (ctx, index) => ClipRRect(
            child: CustomPaint(
              painter: OrangePainter(),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal:10,vertical:15),//increase padding to your liking
                width: 350,
                decoration: BoxDecoration(
//                 image: DecorationImage(image: AssetImage('')), add your image here and remove color below
                  color: Colors.black54,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  mainAxisAlignment:MainAxisAlignment.spaceBetween,
                  children: [
                    Row(

                      mainAxisAlignment: MainAxisAlignment.end,
                      children: const [
                        Icon(Icons.favorite, size: 40),
                      ],
                    ),
                    Row(
                      children: [
                        const Icon(Icons.restaurant),
                        const SizedBox(width:10),
                        Column(
                          children: const [
                            Text(
                              'Sollicitudin',
//                         textScaleFactor: textScale,
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 20,
                                shadows: [
                                  Shadow(
                                      color: Colors.red,
                                      blurRadius: 10,
                                      offset: Offset(0, 2))
                                ],
                              ),
                            ),
                            Icon(Icons.star),//Replace with your CustomRation()
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, const Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(const Offset(0, 2) & size, const Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}


问:
Add new Text Field dynamically on Submit event
this is Antika. I have started learning to code since a few days back, and am only familiar with HTML/CSS/JS, and basics of dart/flutter

Developer Level: Beginner

Project type & language: I'm developing a Simple Notepad App, using flutter.

In my Project,
I want to dynamically add new TextField widgets on the screen,
once the user hits enter or clicks the next button ('➡'), in mobile devices, Just after the TextField in focus, and not to the end of the List.

Outline

User types text >> Clicks Submit
    >> Keeping in mind TextField  in focus >> Add another TextField just after this one.
        >> The User feels like entering a new line.

For e.g., as is shown in the image below.

答:
You could use a list with initially one TextField widget and onSubmitted adds another TextField to the list.

```<code>class MyWidget

 extends StatefulWidget {
  MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  List<TextField> textFields = [];

  @override
  void initState(){
    super.initState();
    textFields.add(_buildTextField());
  }
  @override
  Widget build(BuildContext context) {
    return ListView(
        children: textFields
    );
  }

  TextField _buildTextField(){
    return TextField(
      autofocus: true,
      onSubmitted: (_){
        setState((){
          textFields.add(_buildTextField());
        });
      }
    );
  }
}
</code>```

Body:
You could use a list with initially one TextField widget and onSubmitted adds another TextField to the list.

class MyWidget

 extends StatefulWidget {
  MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  List<TextField> textFields = [];

  @override
  void initState(){
    super.initState();
    textFields.add(_buildTextField());
  }
  @override
  Widget build(BuildContext context) {
    return ListView(
        children: textFields
    );
  }

  TextField _buildTextField(){
    return TextField(
      autofocus: true,
      onSubmitted: (_){
        setState((){
          textFields.add(_buildTextField());
        });
      }
    );
  }
}


问:
Facebook Graph API call not working in iOS application
So I'm trying to write an iPhone application that allows a user to "Check-in" to a store using the Graph API method; something like

```<code>NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
app_id, @"app_id",
@"111664535537155", @"place",
@"I just Checked Into A Retail Store", @"message", nil];

[appDelegate.facebook requestWithGraphPath:@"me/checkins" andParams: params     andHttpMethod:@"POST" andDelegate:self];
</code>```

but I'm having no luck. I know I've setup the rest of the Facebook Connect stuff fine, since my dialog calls such as

```<code>NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               app_id, @"app_id",
                               @"Facebook Dialogs", @"name",
                               @"Test Post", @"caption",
                               @"Check out my Test Post", @"message",
                               nil];

[appDelegate.facebook dialog:@"feed" andParams:params andDelegate:self];
</code>```

works fine.  According to This tutorial Facebook Connect supports Graph API calls, and the authentication should be enough.

Am I missing something? What should I try doing to fix this?  I've taken a look at the other related questions on Stack Overflow, but none of the solutions seems to solve my problem.

Thanks

答: You also need to pass in the "coordinates" parameter. See https://developers.facebook.com/docs/reference/api/user/ and look for checkins</p>

ContentLicense: CC BY-SA 3.0

Body:
So I'm trying to write an iPhone application that allows a user to "Check-in" to a store using the Graph API method; something like

NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
app_id, @"app_id",
@"111664535537155", @"place",
@"I just Checked Into A Retail Store", @"message", nil];

[appDelegate.facebook requestWithGraphPath:@"me/checkins" andParams: params     andHttpMethod:@"POST" andDelegate:self];

but I'm having no luck. I know I've setup the rest of the Facebook Connect stuff fine, since my dialog calls such as

NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               app_id, @"app_id",
                               @"Facebook Dialogs", @"name",
                               @"Test Post", @"caption",
                               @"Check out my Test Post", @"message",
                               nil];

[appDelegate.facebook dialog:@"feed" andParams:params andDelegate:self];

works fine.  According to This tutorial Facebook Connect supports Graph API calls, and the authentication should be enough.

Am I missing something? What should I try doing to fix this?  I've taken a look at the other related questions on Stack Overflow, but none of the solutions seems to solve my problem.

Thanks


问:
Problems Using New Firebase 9.0
I am doing a Udemy course where we are attempting to build an e-commerce site.
The course uses Firebase V6 but I discovered that a very different more modular V9 was just released. I decided that the new modular system would be better to learn and I attempted to use this to achieve the same results as the course in one of my personal projects.

I was able to add data to the Firestore database but am now attempting to create snapshots and work from them and am having some issues.

Here is my Firebase.utils component

```<code>const firebaseApp = initializeApp(firebaseConfig);

const db = getFirestore(firebaseApp);
const usersCollectionRef = collection(db, 'users');

const createUserProfileDocument = async (userAuth, aditionalData) => {
    if (!userAuth) return;
    const userRef = doc(db, `users/${userAuth.uid}`);
    console.log(userAuth.uid);
    const docSnap = await getDoc(userRef);

    if (!docSnap.exists()) {
        const { displayName, email } = userAuth;
        const createdAt = new Date();

        try {
          await setDoc(userRef,  {
            displayName,
            email,
            createdAt,
            // ...additionalData
          });
        } catch (error) {
          console.log('error creating user', error.message);
        }
      }
      console.log('test');
      console.log(userRef);
      console.log(docSnap.exists());
      console.log(docSnap.data());
      console.log(userAuth.uid);
      return userRef;

    }

const provider = new GoogleAuthProvider();
provider.setCustomParameters({
    prompt: 'select_account'
});

const auth = getAuth();

    const google = async () => {
        signInWithPopup(auth, provider)
            .then((result) => {
                // This gives you a Google Access Token. You can use it to access the Google API.
                const credential = GoogleAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                // The signed-in user info.
                const user = result.user;
                // ...
            }).catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.email;
                // The AuthCredential type that was used.
                const credential = GoogleAuthProvider.credentialFromError(error);
                // ...
            });
    }
</code>```

This seems to work well. It Authenticates my user and sets a doc as I want it.

My problem occurs when I try to add the following code to my App.js component:

```<code> const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = onAuthStateChanged(async userAuth => {
      if (userAuth) {

        const userRef = await createUserProfileDocument(userAuth);
        onSnapshot(userRef, (docSnap) => {
          console.log(docSnap.data());
          setCurrentUser({
            id: docSnap.id,
            ...docSnap.data()
          });
        })
      } else {
        setCurrentUser({userAuth});
      }
      return () => {
        unsubscribeFromAuth();
      }
    })
  },[]);
</code>```

This is the error I receive

I feel like I'm really close to the solution here but I'm doing something minor wrong. Any help or advice would be great, thanks.

I have changed my code to this

```<code>  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
      if (userAuth) {
        const userRef = await createUserProfileDocument(userAuth);
        console.log('ur: ' + userRef);
        onSnapshot(doc(db, `users/${userAuth.uid}`), docSnap => {
          setCurrentUser({
            id: docSnap.id,
            ...docSnap.data()
          });
        })
      }
    })
  });
</code>```

答:
I had the exact same problem.</p>
```<code>import React, { useState } from "react";

import FormInput from "../form-input/form-input.component";
import CustomButton from "../custom-button/custom-button.component";

import { auth, createUserProfileDocument } from "../../firebase/firebase.utils";
import "./sign-up.styles.scss";
import { createUserWithEmailAndPassword } from "firebase/auth";

const SignUp = () => {
  const [currentUser, setCurrentUser] = useState({
    displayName: "",
    email: "",
    password: "",
    confirmPassword: ""
  });

  const handleSubmit = async (event) => {
    event.preventDefault();

    const { displayName, email, password, confirmPassword } = currentUser;

    if (password !== confirmPassword) {
      alert("passwords don't match");
      return;
    }

    try {
      const { user } = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      );

      await createUserProfileDocument(user, { displayName });

      setCurrentUser({
        displayName: "",
        email: "",
        password: "",
        confirmPassword: ""
      });
    } catch (error) {
      console.error(error);
    }
  };

  const handleChange = (event) => {
    const { name, value } = event.target;

    setCurrentUser((prevValue) => {
      return { ...prevValue, [name]: value };
    });
  };

  return (
    <div className="sign-up">
      <h2 className="title">I do not have a account</h2>
      <span>Sign up with your email and password</span>
      <form className="sign-up-form" onSubmit={handleSubmit}>
        <FormInput
          type="text"
          name="displayName"
          value={currentUser.displayName}
          onChange={handleChange}
          label="Display Name"
          required
        />
        <FormInput
          type="email"
          name="email"
          value={currentUser.email}
          onChange={handleChange}
          label="Email"
          required
        />
        <FormInput
          type="password"
          name="password"
          value={currentUser.password}
          onChange={handleChange}
          label="Password"
          required
        />
        <FormInput
          type="password"
          name="confirmPassword"
          value={currentUser.confirmPassword}
          onChange={handleChange}
          label="Confirm Password"
          required
        />
        <CustomButton type="submit">SIGN UP</CustomButton>
      </form>
    </div>
  );
};

export default SignUp;
</code>```

Title: Problems Using New Firebase 9.0

Body:
I am doing a Udemy course where we are attempting to build an e-commerce site.
The course uses Firebase V6 but I discovered that a very different more modular V9 was just released. I decided that the new modular system would be better to learn and I attempted to use this to achieve the same results as the course in one of my personal projects.

I was able to add data to the Firestore database but am now attempting to create snapshots and work from them and am having some issues.

Here is my Firebase.utils component

const firebaseApp = initializeApp(firebaseConfig);

const db = getFirestore(firebaseApp);
const usersCollectionRef = collection(db, 'users');

const createUserProfileDocument = async (userAuth, aditionalData) => {
    if (!userAuth) return;
    const userRef = doc(db, `users/${userAuth.uid}`);
    console.log(userAuth.uid);
    const docSnap = await getDoc(userRef);

    if (!docSnap.exists()) {
        const { displayName, email } = userAuth;
        const createdAt = new Date();

        try {
          await setDoc(userRef,  {
            displayName,
            email,
            createdAt,
            // ...additionalData
          });
        } catch (error) {
          console.log('error creating user', error.message);
        }
      }
      console.log('test');
      console.log(userRef);
      console.log(docSnap.exists());
      console.log(docSnap.data());
      console.log(userAuth.uid);
      return userRef;

    }

const provider = new GoogleAuthProvider();
provider.setCustomParameters({
    prompt: 'select_account'
});

const auth = getAuth();

    const google = async () => {
        signInWithPopup(auth, provider)
            .then((result) => {
                // This gives you a Google Access Token. You can use it to access the Google API.
                const credential = GoogleAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                // The signed-in user info.
                const user = result.user;
                // ...
            }).catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.email;
                // The AuthCredential type that was used.
                const credential = GoogleAuthProvider.credentialFromError(error);
                // ...
            });
    }

This seems to work well. It Authenticates my user and sets a doc as I want it.

My problem occurs when I try to add the following code to my App.js component:

 const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = onAuthStateChanged(async userAuth => {
      if (userAuth) {

        const userRef = await createUserProfileDocument(userAuth);
        onSnapshot(userRef, (docSnap) => {
          console.log(docSnap.data());
          setCurrentUser({
            id: docSnap.id,
            ...docSnap.data()
          });
        })
      } else {
        setCurrentUser({userAuth});
      }
      return () => {
        unsubscribeFromAuth();
      }
    })
  },[]);

This is the error I receive

I feel like I'm really close to the solution here but I'm doing something minor wrong. Any help or advice would be great, thanks.

I have changed my code to this

  useEffect(() => {
    let unsubscribeFromAuth = null;
    unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
      if (userAuth) {
        const userRef = await createUserProfileDocument(userAuth);
        console.log('ur: ' + userRef);
        onSnapshot(doc(db, `users/${userAuth.uid}`), docSnap => {
          setCurrentUser({
            id: docSnap.id,
            ...docSnap.data()
          });
        })
      }
    })
  });

Body:
I had the exact same problem.

import React, { useState } from "react";

import FormInput from "../form-input/form-input.component";
import CustomButton from "../custom-button/custom-button.component";

import { auth, createUserProfileDocument } from "../../firebase/firebase.utils";
import "./sign-up.styles.scss";
import { createUserWithEmailAndPassword } from "firebase/auth";

const SignUp = () => {
  const [currentUser, setCurrentUser] = useState({
    displayName: "",
    email: "",
    password: "",
    confirmPassword: ""
  });

  const handleSubmit = async (event) => {
    event.preventDefault();

    const { displayName, email, password, confirmPassword } = currentUser;

    if (password !== confirmPassword) {
      alert("passwords don't match");
      return;
    }

    try {
      const { user } = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      );

      await createUserProfileDocument(user, { displayName });

      setCurrentUser({
        displayName: "",
        email: "",
        password: "",
        confirmPassword: ""
      });
    } catch (error) {
      console.error(error);
    }
  };

  const handleChange = (event) => {
    const { name, value } = event.target;

    setCurrentUser((prevValue) => {
      return { ...prevValue, [name]: value };
    });
  };

  return (
    <div className="sign-up">
      <h2 className="title">I do not have a account</h2>
      <span>Sign up with your email and password</span>
      <form className="sign-up-form" onSubmit={handleSubmit}>
        <FormInput
          type="text"
          name="displayName"
          value={currentUser.displayName}
          onChange={handleChange}
          label="Display Name"
          required
        />
        <FormInput
          type="email"
          name="email"
          value={currentUser.email}
          onChange={handleChange}
          label="Email"
          required
        />
        <FormInput
          type="password"
          name="password"
          value={currentUser.password}
          onChange={handleChange}
          label="Password"
          required
        />
        <FormInput
          type="password"
          name="confirmPassword"
          value={currentUser.confirmPassword}
          onChange={handleChange}
          label="Confirm Password"
          required
        />
        <CustomButton type="submit">SIGN UP</CustomButton>
      </form>
    </div>
  );
};

export default SignUp;


问:
pyparsing - one of keywords from big list
I need to check for the presence of one keyword from the list of words.
If the list is small, I can explicitly list all the keywords

```<code>ticker = CaselessKeyword('SPY') | CaselessKeyword('QQQ')
ticker.run_tests(['SPY', 'QQQ'])
</code>```

But what is the correct solution if the list is really large (10k-100k keywords) and  we want to be sure that in this place there is one of these words and only it?

答:
Rather than create thousands of CaselessKeywords in a big MatchFirst, you are probably better off writing an expression that just matches a word of characters, and then validates against a set of strings that are known ticker symbols.

See the code below, that uses a parse action to upcase the found words, and then a condition to filter for valid ticker symbols.

I defined ticker_symbols using a space-delimited string to make it easy to add new symbols. Just add new symbols to this list, separated by spaces, and add line breaks as needed.

But no matter what, when the list of symbols gets up into the thousands (and hundred-thousands!), this process will be pretty slow.

```<code>import pyparsing as pp

# define all valid ticker symbols - save in a set for fast "in" testing
ticker_symbols = set("""\
AAPL IBM GE F TTT QQQ SPY GOOG INTL TI HP AMD
""".split())

# parse action condition to see if a word matches any ticker symbol
def is_ticker(t):
    return t[0] in ticker_symbols

# expression to match any word of characters, detecting word breaks
ticker = pp.Regex(r"\b[A-Za-z]+\b")

# add upper-casing parse action and ticker-validating condition
ticker.addParseAction(pp.common.upcaseTokens)
ticker.addCondition(is_ticker)

# try it out
print(ticker.searchString("AAA SPYY QQQ INTL1 A AAPL ge zaapl"))
</code>```

Prints

```<code>[['QQQ'], ['AAPL'], ['GE']]
</code>```

Body:
I need to check for the presence of one keyword from the list of words.
If the list is small, I can explicitly list all the keywords

ticker = CaselessKeyword('SPY') | CaselessKeyword('QQQ')
ticker.run_tests(['SPY', 'QQQ'])

But what is the correct solution if the list is really large (10k-100k keywords) and  we want to be sure that in this place there is one of these words and only it?

Body:
Rather than create thousands of CaselessKeywords in a big MatchFirst, you are probably better off writing an expression that just matches a word of characters, and then validates against a set of strings that are known ticker symbols.

See the code below, that uses a parse action to upcase the found words, and then a condition to filter for valid ticker symbols.

I defined ticker_symbols using a space-delimited string to make it easy to add new symbols. Just add new symbols to this list, separated by spaces, and add line breaks as needed.

But no matter what, when the list of symbols gets up into the thousands (and hundred-thousands!), this process will be pretty slow.

import pyparsing as pp

# define all valid ticker symbols - save in a set for fast "in" testing
ticker_symbols = set("""\
AAPL IBM GE F TTT QQQ SPY GOOG INTL TI HP AMD
""".split())

# parse action condition to see if a word matches any ticker symbol
def is_ticker(t):
    return t[0] in ticker_symbols

# expression to match any word of characters, detecting word breaks
ticker = pp.Regex(r"\b[A-Za-z]+\b")

# add upper-casing parse action and ticker-validating condition
ticker.addParseAction(pp.common.upcaseTokens)
ticker.addCondition(is_ticker)

# try it out
print(ticker.searchString("AAA SPYY QQQ INTL1 A AAPL ge zaapl"))

Prints

[['QQQ'], ['AAPL'], ['GE']]


问:
How to get feature importances of a multi-label classification problem?
I am learning how to use Scikit-Learn and I am trying to get the feature importance of a multi-label classification problem.
I defined and trained the model in the following way:

```<code>classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)
classifier.classes_ = classes
y_train_pred = cross_val_predict(classifier, X_train_prepared, y_train, cv=3)
</code>```

The code seems to be working fine until I try to get the feature importance. This is what I tried:

```<code>classifier.feature_importances_
</code>```

But I get the following error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-98-a9c91f6f2504> in <module>
----> 1 classifier.feature_importances_

AttributeError: 'OneVsRestClassifier' object has no attribute 'feature_importances_'
</code>```

I tried also the solution proposed in this question but I think it is outdated.
Would you be able to propose a newer smart and elegant solution to display the feature importances of a multi-label classification problem?

答:
I would say that the solution within the referenced post is not outdated; instead, you have a slightly different setting to take care of.

The estimator that you're passing to OneVsRestClassifier is a Pipeline; in the referenced post it was a RandomForestClassifier directly.

Therefore you'll have to access one of the pipeline's steps to get to the RandomForestClassifier instance on which you'll be finally able to access the feature_importances_ attribute. That's one way of proceeding:

```<code>classifier.estimators_[0].named_steps['randomforestclassifier'].feature_importances_
</code>```

Eventually, be aware that you'll have to fit your OneVsRestClassifier instance to be able to access its estimators_ attribute. Indeed, though cross_val_predict already takes care of fitting the estimator as you might see here, cross_val_predict does not return the estimator instance, as .fit() method does. Therefore, outside cross_val_predict the  fact that classifier was fit is not known, reason why you're not able to access the estimators_ attribute.

Here is a toy example:

```<code>from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_predict

iris = datasets.load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)

classifier.fit(X_train, y_train)
y_train_pred = cross_val_predict(classifier, X_train, y_train, cv=3)
classifier.estimators_[0].named_steps['randomforestclassifier'].feature_importances_
</code>```

Body:
I am learning how to use Scikit-Learn and I am trying to get the feature importance of a multi-label classification problem.
I defined and trained the model in the following way:

classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)
classifier.classes_ = classes
y_train_pred = cross_val_predict(classifier, X_train_prepared, y_train, cv=3)

The code seems to be working fine until I try to get the feature importance. This is what I tried:

classifier.feature_importances_

But I get the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-98-a9c91f6f2504> in <module>
----> 1 classifier.feature_importances_

AttributeError: 'OneVsRestClassifier' object has no attribute 'feature_importances_'

I tried also the solution proposed in this question but I think it is outdated.
Would you be able to propose a newer smart and elegant solution to display the feature importances of a multi-label classification problem?

Body:
I would say that the solution within the referenced post is not outdated; instead, you have a slightly different setting to take care of.

The estimator that you're passing to OneVsRestClassifier is a Pipeline; in the referenced post it was a RandomForestClassifier directly.

Therefore you'll have to access one of the pipeline's steps to get to the RandomForestClassifier instance on which you'll be finally able to access the feature_importances_ attribute. That's one way of proceeding:

classifier.estimators_[0].named_steps['randomforestclassifier'].feature_importances_

Eventually, be aware that you'll have to fit your OneVsRestClassifier instance to be able to access its estimators_ attribute. Indeed, though cross_val_predict already takes care of fitting the estimator as you might see here, cross_val_predict does not return the estimator instance, as .fit() method does. Therefore, outside cross_val_predict the  fact that classifier was fit is not known, reason why you're not able to access the estimators_ attribute.

Here is a toy example:

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_predict

iris = datasets.load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)

classifier.fit(X_train, y_train)
y_train_pred = cross_val_predict(classifier, X_train, y_train, cv=3)
classifier.estimators_[0].named_steps['randomforestclassifier'].feature_importances_


问:
Get last date of current Hijri month with JavaScript
is there any way to get first and last date of current Hijri month with JavaScript?</p>

答:
The following function will return information about the Hijri Date as 7 elements in an array given a Gregorian date. This can be the current date or any other date.

```<code>The information returned by the function is:

[0] The Gregorian Date (the input date) in YYYY-MM-DD format
[1] The Hijri Day (Number) (1-30)
[2] The Hijri Month (String)
[3] The Hijri Year (Number)
[4] Total Days in the Hijri Month (Number) (29 or 30)
[5] The Gregorian Date that the Hijri Month starts on (Date object)
[6] The Gregorian Date that the Hijri Month ends on   (Date object)
</code>```

The test case examples provide the information on today's Hijri Date (and month) and another date.

/*********************************************************************
* @function      : getHijriMonthInfo(date)
* @purpose       : Returns information on a Hijri Month for a given Gregorian Date
* @version       : 1.00
* @author        : Mohsen Alyafei
* @date          : 06 Feb 2022
* @Licence       : MIT
* @param         : {date} a valid Date Object
* @returns       : An Array of seven (7) elements with the following data:
*                  [0] The Gregorian Date (the input date) in YYYY-MM-DD format
*                  [1] The Hijri Day (Number) (1-30)
*                  [2] The Hijri Month (String)
*                  [3] The Hijri Year (Number)
*                  [4] Total Days in the Hijri Month (Number) (29 or 30)
*                  [5] The Gregorian Date that the Hijri Month starts on (Date object)
*                  [6] The Gregorian Date that the Hijri Month ends on   (Date object)
**********************************************************************/

function getHijriMonthInfo(date) {
let startDate= new Date(date),
    c= 'en-u-ca-islamic-umalqura-nu-latn',  // use 'islamic-umalqura' calendar for the islamic date
    d= startDate, gDays=0, iMonthTotalDays= 0, i_Day, n='numeric',
    iDay  =new Intl.DateTimeFormat(c,{day  :n}).format(startDate),
    iMonth=new Intl.DateTimeFormat(c,{month:'long'}).format(startDate),
    iYear =new Intl.DateTimeFormat(c,{year :n}).format(startDate).split(" ")[0];
for (let i=0; i<32; i++) {
    i_Day= new Intl.DateTimeFormat(c,{day:n}).format(d); // Hijri day
    if (+i_Day>iMonthTotalDays) iMonthTotalDays= i_Day, gDays++;
    else break;
    d= new Date(d.setDate(d.getDate()+1));               // next Gregorian day
    }
let gEndT = new Date(startDate.setDate(startDate.getDate()+gDays-2)),
    gEnd  = new Date(gEndT),
    gStart= new Date(gEndT.setDate(gEndT.getDate()-iMonthTotalDays+1));
return [new Date(date).toISOString().split("T")[0],+iDay,iMonth,+iYear,iMonthTotalDays,gStart,gEnd];
}
//==================================================================
// Test Cases
//==================================================================
output(getHijriMonthInfo(new Date(Date.now()))); // today's date
output(getHijriMonthInfo("2022-04-22"));         // 22 April 2022
//==================
function output([gDate, iDay, iMonth, iYear, iMonthTotalDays, gStart, gEnd]) {

console.log(`
Gregorian Date            : ${gDate}
Hijri Day                 : ${iDay}
Hijri Month               : ${iMonth}
Hijri Year                : ${iYear}
Total Days in Hijri Month : ${iMonthTotalDays}
Hijri Month Starts on     : ${gStart}
Hijri Month Ends on       : ${gEnd}
`
);
}
//==================```

Body:
The following function will return information about the Hijri Date as 7 elements in an array given a Gregorian date. This can be the current date or any other date.

The information returned by the function is:

[0] The Gregorian Date (the input date) in YYYY-MM-DD format
[1] The Hijri Day (Number) (1-30)
[2] The Hijri Month (String)
[3] The Hijri Year (Number)
[4] Total Days in the Hijri Month (Number) (29 or 30)
[5] The Gregorian Date that the Hijri Month starts on (Date object)
[6] The Gregorian Date that the Hijri Month ends on   (Date object)

The test case examples provide the information on today's Hijri Date (and month) and another date.

/*********************************************************************
* @function      : getHijriMonthInfo(date)
* @purpose       : Returns information on a Hijri Month for a given Gregorian Date
* @version       : 1.00
* @author        : Mohsen Alyafei
* @date          : 06 Feb 2022
* @Licence       : MIT
* @param         : {date} a valid Date Object
* @returns       : An Array of seven (7) elements with the following data:
*                  [0] The Gregorian Date (the input date) in YYYY-MM-DD format
*                  [1] The Hijri Day (Number) (1-30)
*                  [2] The Hijri Month (String)
*                  [3] The Hijri Year (Number)
*                  [4] Total Days in the Hijri Month (Number) (29 or 30)
*                  [5] The Gregorian Date that the Hijri Month starts on (Date object)
*                  [6] The Gregorian Date that the Hijri Month ends on   (Date object)
**********************************************************************/

function getHijriMonthInfo(date) {
let startDate= new Date(date),
    c= 'en-u-ca-islamic-umalqura-nu-latn',  // use 'islamic-umalqura' calendar for the islamic date
    d= startDate, gDays=0, iMonthTotalDays= 0, i_Day, n='numeric',
    iDay  =new Intl.DateTimeFormat(c,{day  :n}).format(startDate),
    iMonth=new Intl.DateTimeFormat(c,{month:'long'}).format(startDate),
    iYear =new Intl.DateTimeFormat(c,{year :n}).format(startDate).split(" ")[0];
for (let i=0; i<32; i++) {
    i_Day= new Intl.DateTimeFormat(c,{day:n}).format(d); // Hijri day
    if (+i_Day>iMonthTotalDays) iMonthTotalDays= i_Day, gDays++;
    else break;
    d= new Date(d.setDate(d.getDate()+1));               // next Gregorian day
    }
let gEndT = new Date(startDate.setDate(startDate.getDate()+gDays-2)),
    gEnd  = new Date(gEndT),
    gStart= new Date(gEndT.setDate(gEndT.getDate()-iMonthTotalDays+1));
return [new Date(date).toISOString().split("T")[0],+iDay,iMonth,+iYear,iMonthTotalDays,gStart,gEnd];
}
//==================================================================
// Test Cases
//==================================================================
output(getHijriMonthInfo(new Date(Date.now()))); // today's date
output(getHijriMonthInfo("2022-04-22"));         // 22 April 2022
//==================
function output([gDate, iDay, iMonth, iYear, iMonthTotalDays, gStart, gEnd]) {

console.log(`
Gregorian Date            : ${gDate}
Hijri Day                 : ${iDay}
Hijri Month               : ${iMonth}
Hijri Year                : ${iYear}
Total Days in Hijri Month : ${iMonthTotalDays}
Hijri Month Starts on     : ${gStart}
Hijri Month Ends on       : ${gEnd}
`
);
}
//==================


问:
SQL schema design question around relating 2 different types of ID's to one piece of information
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

```<code>Events
--------
event_id
</code>```

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

```<code>EventUsers
----------
event_id
user_id
</code>```

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

```<code>EventUsers
----------
event_id
participant_id
participant_type
</code>```

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

```<code>select event_id
from EventUsers
where participant_id = 10
and participant_type = 1
</code>```

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

```<code>EventParticipants
-----------------
event_id
user_id
group_id
</code>```

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?

答:
Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables

This is the good logical way to do it. Create a junction table for each many-to-many relationship; one for events and users, the other for events and groups.

Body:
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

Events
--------
event_id

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

EventUsers
----------
event_id
user_id

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

EventUsers
----------
event_id
participant_id
participant_type

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

select event_id
from EventUsers
where participant_id = 10
and participant_type = 1

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

EventParticipants
-----------------
event_id
user_id
group_id

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?


问:
How do I set a proportional value for row height in a listView so it occupies the entire screen?
I need the items in my listView to have a height so it the list exactly fits the screen. Here's my code given below. I tried setting the Height of rows in my grid to a custom value, but that would work well, fitting the screen in some devices, while there would be an empty space in other devices due to a different screen size.

```<code>       <ListView
              ItemsSource="{Binding PenStocks}"
              ItemSelected="Event_ItemSelected"
              ItemTapped="Event_ItemTapped"
              SeparatorVisibility="None"
              Margin="5,5,5,0"
              >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="9" ColumnSpacing="0" RowSpacing="0" HorizontalOptions="FillAndExpand" >
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.408*"/>
                        <ColumnDefinition Width="0.051*"/>
                        <ColumnDefinition Width="0.252*"/>
                        <ColumnDefinition Width="0.033*"/>
                        <ColumnDefinition Width="0.153*"/>
                        <ColumnDefinition Width="0.102*"/>
                    </Grid.ColumnDefinitions>
</code>```

What can I do for this? Please help me and thank you!

答:
EDIT:
Rewrote this to use a bindablelayout.

View:

```<code> <StackLayout x:Name="ParentFlexLayout" BindableLayout.ItemsSource="{Binding Colors}" HorizontalOptions="FillAndExpand" >
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Frame BackgroundColor="{Binding .}" VerticalOptions="FillAndExpand"/>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>
</code>```

Here we use a bindablelayout - it's very flexible, so you could give it at go and see it it meets your needs

Codebehind:

```<code>  public ObservableCollection<Color> Colors { get; set; } = new ObservableCollection<Color>();
    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
        Colors.Add(Color.Blue);
        Colors.Add(Color.Red);
        Colors.Add(Color.Green);
        Colors.Add(Color.Yellow);
    }
</code>```

Result:

Body:
I need the items in my listView to have a height so it the list exactly fits the screen. Here's my code given below. I tried setting the Height of rows in my grid to a custom value, but that would work well, fitting the screen in some devices, while there would be an empty space in other devices due to a different screen size.

       <ListView
              ItemsSource="{Binding PenStocks}"
              ItemSelected="Event_ItemSelected"
              ItemTapped="Event_ItemTapped"
              SeparatorVisibility="None"
              Margin="5,5,5,0"
              >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="9" ColumnSpacing="0" RowSpacing="0" HorizontalOptions="FillAndExpand" >
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.408*"/>
                        <ColumnDefinition Width="0.051*"/>
                        <ColumnDefinition Width="0.252*"/>
                        <ColumnDefinition Width="0.033*"/>
                        <ColumnDefinition Width="0.153*"/>
                        <ColumnDefinition Width="0.102*"/>
                    </Grid.ColumnDefinitions>

What can I do for this? Please help me and thank you!

Body:
EDIT:
Rewrote this to use a bindablelayout.

View:

 <StackLayout x:Name="ParentFlexLayout" BindableLayout.ItemsSource="{Binding Colors}" HorizontalOptions="FillAndExpand" >
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Frame BackgroundColor="{Binding .}" VerticalOptions="FillAndExpand"/>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

Here we use a bindablelayout - it's very flexible, so you could give it at go and see it it meets your needs

Codebehind:

  public ObservableCollection<Color> Colors { get; set; } = new ObservableCollection<Color>();
    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
        Colors.Add(Color.Blue);
        Colors.Add(Color.Red);
        Colors.Add(Color.Green);
        Colors.Add(Color.Yellow);
    }

Result:


问:
Python exercise: lists sorting removing the nums
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

```<code>def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))
</code>```

but gives me this output:

```<code>[1, 2, 4, 7, 3]
</code>```

what did I do wrong? (only list comprehension should be used)

答:
Not fancy solution but might be quicker than some as it limits the number of access by indices.</p>
```<code>def filtra_ordinati(entries):
    if not entries: # take care of empty entry
        return

    ## initialization
    result = [entries[0]] # the first element is always included in the result

    ## process the entries list items: beginning with the second one
    # set max_value initial
    max_value= entries[0]
    for entry in entries[1:]:

        if max_value < entry :
            result.append(entry)

            # set new max_value
            max_value = entry

    return result
</code>```
```<code>>>> L1 = [1, 2, 5, 4, 7, 8, 3, 9]
>>> filtra_ordinati(L1)
[1, 2, 5, 7, 8, 9]
</code>```

Body:
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))

but gives me this output:

[1, 2, 4, 7, 3]

what did I do wrong? (only list comprehension should be used)

Body:
Not fancy solution but might be quicker than some as it limits the number of access by indices.

def filtra_ordinati(entries):
    if not entries: # take care of empty entry
        return

    ## initialization
    result = [entries[0]] # the first element is always included in the result

    ## process the entries list items: beginning with the second one
    # set max_value initial
    max_value= entries[0]
    for entry in entries[1:]:

        if max_value < entry :
            result.append(entry)

            # set new max_value
            max_value = entry

    return result

>>> L1 = [1, 2, 5, 4, 7, 8, 3, 9]
>>> filtra_ordinati(L1)
[1, 2, 5, 7, 8, 9]


答:
If you just want to drop rows where the column conserve_score has value ".", you can simply subset your dataframe to include rows that are not equal to ".".

```<code>data = data.loc[data["conserve_score"] != "."].astype(float)
</code>```

Title: How to remove rows with "." in python?

Body:
here is my data:

>>> data
            chr      1t        2                 exp        conserve_score       cd         re
1013       chr1     142200     142220          -0.121027      0.0270625         0.0  0.000000
1014       chr1     142220     142240          -0.120995  0.02331578947         0.0  0.000000
1015       chr1     142240     142260          -0.149517  0.03235294118         0.0  0.000000
1308       chr1     169180     169200          -0.182448              .         0.0  0.000000
2046       chr1     439360     439380          -0.112148          0.142         0.0  0.803303
...         ...        ...        ...                ...            ...         ...       ...
150209142  chr5  180756500  180756520           0.145244        0.28205         0.0  0.968969
150209143  chr5  180756520  180756540           0.164834         0.3497         0.0  0.968969
150209144  chr5  180756540  180756560           0.160763   0.3825555556         0.0  0.968969
150209145  chr5  180756560  180756580           0.160709   0.3932857143         0.0  0.968969
150209146  chr5  180756580  180756600           0.160709   0.3829444444         0.0  0.968969

some rows has values . and I want to remove those rows

I tried

>>> data[data.conserve_score.str.contains(".")==False]
Empty DataFrame
Index: []

but in float numbers, there are also "." ...
How to make it works?

Thanks

Body:
If you just want to drop rows where the column conserve_score has value ".", you can simply subset your dataframe to include rows that are not equal to ".".

data = data.loc[data["conserve_score"] != "."].astype(float)


问:
How can I access local variables from inside a C++11 anonymous function?
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});
</code>```

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

答:
You need to add tot to the "capture list":

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});
</code>```

Alternatively you can use a capture-default to capture tot implicitly:

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [=](float x)->float{return(x/tot);});
</code>```

Body:
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

Body:
You need to add tot to the "capture list":

float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});

Alternatively you can use a capture-default to capture tot implicitly:

float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [=](float x)->float{return(x/tot);});


问:
Can't create unique constraint in Neo4J
I am attempt to create a constraint like this:

```<code>CREATE CONSTRAINT ON (a:forecast) ASSERT a.match IS UNIQUE
</code>```

but I get this error:

Unable to create Constraint( name='constraint_9615361a',
type='UNIQUENESS', schema=(:forecast {match}) ):

I have the Neo4J community edition 4.2.3, but judging by the documentation I should be allowed to create this type of constraint. What gives?

答:
Late reply, but still.

I was struck by the same error now (with 4.4.3) and it was lack of free space on drive.

Wasted half an hour, digging in absolutely wrong direction.
I create database with --skip-duplicate-nodes=true flag, so of course there couldn't be any duplicates.

Title: Can't create unique constraint in Neo4J

Body:
I am attempt to create a constraint like this:

CREATE CONSTRAINT ON (a:forecast) ASSERT a.match IS UNIQUE

but I get this error:

Unable to create Constraint( name='constraint_9615361a',
type='UNIQUENESS', schema=(:forecast {match}) ):

I have the Neo4J community edition 4.2.3, but judging by the documentation I should be allowed to create this type of constraint. What gives?


问:
how to send token while post request
have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....

here is my token, which i received after login as response

```<code>{
  "token": "8d18265645a87d608868a127f373558ac2e131a6"
}
</code>```

Here, i have to implement in flutter

```<code>apiData.ApiData app = apiData.ApiData();
  final String apiURl = app.api;
  SharedPreferences pref = await SharedPreferences.getInstance();
  String? email = pref.getString("useremail");
  String? token = pref.getString('token');
  String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
  String time = DateFormat("Hms").format(DateTime.now());
  print(time);
  print(date);
  dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
    'user': email,
    'start_time': time,
    'start_date': date,
  });`
</code>```

答:
Here in the documentation you can found the following snippet, where the headers are sent with the HTTP request:</p>
```<code>    Future<http.Response> createAlbum(String title) {
  return http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
}
</code>```

Title: how to send token while post request

Body:
have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....

here is my token, which i received after login as response

{
  "token": "8d18265645a87d608868a127f373558ac2e131a6"
}

Here, i have to implement in flutter

apiData.ApiData app = apiData.ApiData();
  final String apiURl = app.api;
  SharedPreferences pref = await SharedPreferences.getInstance();
  String? email = pref.getString("useremail");
  String? token = pref.getString('token');
  String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
  String time = DateFormat("Hms").format(DateTime.now());
  print(time);
  print(date);
  dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
    'user': email,
    'start_time': time,
    'start_date': date,
  });`

Body:
Here in the documentation you can found the following snippet, where the headers are sent with the HTTP request:

    Future<http.Response> createAlbum(String title) {
  return http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
}


问:
Why does type int exist in Go
There's int, int32, int64 in Golang.

```<code>int32 has 32 bits,
int64 has 64 bits,
int has 32 or 64 or different number of bits according to the environment.
</code>```

I think int32 and int64 will be totally enough for the program.
I don't know why int type should exist, doesn't it will make the action of our code harder to predict?

And also in C++, type int and type long have uncertain length. I think it will make our program fragile. I'm quite confused.

答: The root cause for this is array addressability. If you came into a situation where you needed to call make([]byte, 5e9) your 32 bit executable would be unable to comply, while your 64 bit executable could continue to run. Addressing an array with int64 on a 32 bit build is wasteful. Addressing an array with int32 on a 64 bit build is insufficient. Using int you can address an array to its maximum allocation size on both architectures without having to code a distinction using int32/int64.

Title: Why does type int exist in Go

Body:
There's int, int32, int64 in Golang.

int32 has 32 bits,
int64 has 64 bits,
int has 32 or 64 or different number of bits according to the environment.

I think int32 and int64 will be totally enough for the program.
I don't know why int type should exist, doesn't it will make the action of our code harder to predict?

And also in C++, type int and type long have uncertain length. I think it will make our program fragile. I'm quite confused.


答:
Add header in the post method as below:</p>
```<code> var headers = {
        'authorization': token,
        "Accept": "application/json"
      };

 dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"),headers: headers), body: {
    ...
  });
</code>```

Title: how to send token while post request

Body:
Add header in the post method as below:

 var headers = {
        'authorization': token,
        "Accept": "application/json"
      };

 dynamic response =
      await http.post(Uri.parse(apiURl + "/api/user-log/"),headers: headers), body: {
    ...
  });


问:
How do I retrieve the photographs taken by the camera on a phone running Android OS?
I am developing an Android application that retrieves the photographs taken by the phone camera and converts it to an alternative format. How can I retrieve the photograph that has just been shot as well as those that have been shot some time ago but still exists on the phone?</p>

答:
Converting the image format for existing images is just a matter of recursing file storage for images, usually the sd card but not limited to it. As far as hooking into the existing camera application you'll have to review its source to see if that is possible but you can have a service listen for the camera button and start checking for new images to convert.  Android does not keep a central database of images or discriminate between "camera" and "other sources" meaning someone or something will have to decide what to convert.

You also may want to consider using the existing camera app as a library and extending it so that you are guaranteed to get the image right after its created.


问:
Check if elements from array are in a string
I want to check if there is one of my elements in my array in an string
Like: ['12', '13', '14'] is my array and my string is '123456789' and if one of my Array elements is in my string then it should be True

Is there a way to do this?

答:
Chester's comment have it all.

But if you'd like a more readable version, something like that might help :

```<code>def include(lst = ['12','13','14'], search_string = '123456789'):
  for e in lst:
    if e in search_string:
      print(f'found {e}')
      return True
  return False
</code>```

Body:
Chester's comment have it all.

But if you'd like a more readable version, something like that might help :

def include(lst = ['12','13','14'], search_string = '123456789'):
  for e in lst:
    if e in search_string:
      print(f'found {e}')
      return True
  return False


答:
Use Series.ne with all:

```<code>data = data[data.ne('.').all(1)]
</code>```

Title: How to remove rows with "." in python?

Body:
Use Series.ne with all:

data = data[data.ne('.').all(1)]


问:
How to issue GET request to Google from an ESP32? (can't get it to work)
I´m trying to get an ESP32 to send GET requests to Google, but all I get is a -1 error response from the server. I'm using the Arduino IDE for this.

The reason behind the query to google is to get a basic setup on the ESP32 working. Based on that I will then need to modify it so that it sends a GET to our company's application running on App Engine.

After establishing a connection to my WiFi, I have the following code to generate the GET request:

```<code>if(WiFi.status()== WL_CONNECTED){
  HTTPClient http;

  // Domain name with URL path or IP address with path
  http.begin("google.com");

  // Send HTTP GET request
  int httpResponseCode = http.GET();

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    String payload = http.getString();
    Serial.println(payload);
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();
}
else {
  Serial.println("WiFi Disconnected");
}
</code>```

Any ideas what I'm doing wrong?

Once I have a way to get the above working, I would like to send a query to google. Would the following be the right way?

```<code>      http.begin("google.com?search=ESP32");
</code>```

Thanks!

Edited after first feedback:
I changed the following line to include full URI:

```<code>  // Domain name with URL path or IP address with path
  http.begin("google.com");
</code>```

And now I get a 404 error:

HTTP Response code: 404

That’s an error
The requested URL ./1.1 was not found on this server.  That’s all we know

(Omitted the css tags for brevity)

答:
If you read the example code, then you'll notice that it specifies the address as an absolute URI (http://example.com/index.html), not a domain name only (example.com).

```<code>        http.begin("http://example.com/index.html"); //HTTP
</code>```

Body:
I´m trying to get an ESP32 to send GET requests to Google, but all I get is a -1 error response from the server. I'm using the Arduino IDE for this.

The reason behind the query to google is to get a basic setup on the ESP32 working. Based on that I will then need to modify it so that it sends a GET to our company's application running on App Engine.

After establishing a connection to my WiFi, I have the following code to generate the GET request:

if(WiFi.status()== WL_CONNECTED){
  HTTPClient http;

  // Domain name with URL path or IP address with path
  http.begin("google.com");

  // Send HTTP GET request
  int httpResponseCode = http.GET();

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    String payload = http.getString();
    Serial.println(payload);
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();
}
else {
  Serial.println("WiFi Disconnected");
}

Any ideas what I'm doing wrong?

Once I have a way to get the above working, I would like to send a query to google. Would the following be the right way?

      http.begin("google.com?search=ESP32");

Thanks!

Edited after first feedback:
I changed the following line to include full URI:

  // Domain name with URL path or IP address with path
  http.begin("google.com");

And now I get a 404 error:

HTTP Response code: 404

That’s an error
The requested URL ./1.1 was not found on this server.  That’s all we know

(Omitted the css tags for brevity)

Body:
If you read the example code, then you'll notice that it specifies the address as an absolute URI (http://example.com/index.html), not a domain name only (example.com).

        http.begin("http://example.com/index.html"); //HTTP


答:
You could replace . with np.nan and then use dropna:

```<code>df = df.replace('.', np.nan).dropna()
</code>```

Title: How to remove rows with "." in python?

Body:
You could replace . with np.nan and then use dropna:

df = df.replace('.', np.nan).dropna()


问:
is it possible to make only one volume control for multiple audio
I'm working on an interactive video website project for personal use. here I want to make one volume control for multiple audio at once, how can I do it?

I've tried to make one volume control for one audio and it worked :

```<code>var audio = document.getElementById('bgsound1');
var volumeControl = document.getElementById('vol-control');

var setVolume = function(){
audio.volume = this.value / 100;
};

volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);
</code>```

and here my audio tag :

```<code><audio src="asset/sound/M2.mp3" id="bgsound1"></audio>
<audio src="asset/sound/sound2.mp3" id="bgsound2"></audio>
<audio src="asset/sound/sound3.mp3" id="bgsound3"></audio>
</code>```

答:
Sure, you have to loop throught each audio elements. See comments in the code below.

let volumeControl = document.getElementById('vol-control');

function setVolume (){

  console.clear()
  console.log(volumeControl.value)

  // Get the array of audio element and loop through them to set the new volume value
  Array.from(document.querySelectorAll("audio")).forEach(function(audio){

      //  if the input value is "", use zero
      audio.volume = volumeControl.value == "" ? 0 : volumeControl.value / 100;
    })
};

volumeControl.addEventListener('change', setVolume);
volumeControl.addEventListener('input', setVolume);

// On load
setVolume()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="vol-control" type="number" min="0" max="100" value="25">
<br>

<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" id="bgsound1" controls></audio>
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3" id="bgsound2" controls></audio>
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-16.mp3" id="bgsound3" controls></audio></code>```

Body:
I'm working on an interactive video website project for personal use. here I want to make one volume control for multiple audio at once, how can I do it?

I've tried to make one volume control for one audio and it worked :

var audio = document.getElementById('bgsound1');
var volumeControl = document.getElementById('vol-control');

var setVolume = function(){
audio.volume = this.value / 100;
};

volumeControl.addEventListener('change',setVolume);
volumeControl.addEventListener('input',setVolume);

and here my audio tag :

<audio src="asset/sound/M2.mp3" id="bgsound1"></audio>
<audio src="asset/sound/sound2.mp3" id="bgsound2"></audio>
<audio src="asset/sound/sound3.mp3" id="bgsound3"></audio>

Body:
Sure, you have to loop throught each audio elements. See comments in the code below.

let volumeControl = document.getElementById('vol-control');

function setVolume (){

  console.clear()
  console.log(volumeControl.value)

  // Get the array of audio element and loop through them to set the new volume value
  Array.from(document.querySelectorAll("audio")).forEach(function(audio){

      //  if the input value is "", use zero
      audio.volume = volumeControl.value == "" ? 0 : volumeControl.value / 100;
    })
};

volumeControl.addEventListener('change', setVolume);
volumeControl.addEventListener('input', setVolume);

// On load
setVolume()

<input id="vol-control" type="number" min="0" max="100" value="25">
<br>

<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" id="bgsound1" controls></audio>
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3" id="bgsound2" controls></audio>
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-16.mp3" id="bgsound3" controls></audio>


问:
RackSpace Cloudfiles api error 'Undefined offset: 8'
When trying to upload files to rackspace cloudfiles, I am getting this error.
I tried to trace the source of error and I assume that it is coming from this line of code:

$container = $conn->get_container('test');

This is the complete error that I am getting:

```<code>Notice
Undefined offset: 8
File: /dm/cloudfiles/cloudfiles.php, Line: 1588
</code>```

And this is the code for upload:

```<code><?php
// include the Cloud API.
require('cloudfiles/cloudfiles.php');

// Rackspace Connection Details;
// cloud info
$username = "tariehk"; // username
$key = ""; // api key

// Connect to Rackspace
$auth = new CF_Authentication($username, $key);

$auth->authenticate();
$conn = new CF_Connection($auth);

//Set the Container you want to use
$container = $conn->get_container('dm');

//Temp store the file
$localfile = $_FILES['uploadfile']['tmp_name'];
$filename = $_FILES['uploadfile']['name'];

 //exit();
//Uploading to Rackspace Cloud
$object = $container->create_object($filename);
$object->load_from_filename($localfile);

echo "Your file has been uploaded";
?>
</code>```

答:
This problem has been fixed in their repo but it still exists in the download version.

The fixes can be found here

https://github.com/towynlin/php-cloudfiles/commit/02a8c658db7e9969b35bb57c47ede232521a6617

and

https://github.com/towynlin/php-cloudfiles/commit/78c5d612fb5a7037e92f61acfaf10b59e09239e8

bug report is here
https://github.com/rackspace/php-cloudfiles/pull/23

Its just a few lines, I just patched it myself.

Body:
When trying to upload files to rackspace cloudfiles, I am getting this error.
I tried to trace the source of error and I assume that it is coming from this line of code:

$container = $conn->get_container('test');

This is the complete error that I am getting:

Notice
Undefined offset: 8
File: /dm/cloudfiles/cloudfiles.php, Line: 1588

And this is the code for upload:

<?php
// include the Cloud API.
require('cloudfiles/cloudfiles.php');

// Rackspace Connection Details;
// cloud info
$username = "tariehk"; // username
$key = ""; // api key

// Connect to Rackspace
$auth = new CF_Authentication($username, $key);

$auth->authenticate();
$conn = new CF_Connection($auth);

//Set the Container you want to use
$container = $conn->get_container('dm');

//Temp store the file
$localfile = $_FILES['uploadfile']['tmp_name'];
$filename = $_FILES['uploadfile']['name'];

 //exit();
//Uploading to Rackspace Cloud
$object = $container->create_object($filename);
$object->load_from_filename($localfile);

echo "Your file has been uploaded";
?>