问:
Regular expression troubles, escaped quotes
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

```<code>"Hello\" World" "Hello Universe" Hi
</code>```

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

```<code>public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}
</code>```

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

答:
I think if you use pattern like this:

```<code>Pattern pattern = Pattern.compile("\".*?(?<!\\\\)\"|'.*?(?<!\\\\)'|[A-Za-z']+");
</code>```

Then it will give you desired output. When I ran with your input data I got this list:

```<code>["Hello\" World", "Hello Universe", Hi]
</code>```

I used [A-Za-z']+ from your own question but shouldn't it be just : [A-Za-z]+

EDIT

Change your opts.add(token); line to:

```<code>opts.add(token.replaceAll("^\"|\"$|^'|'$", ""));
</code>```

Body:
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

"Hello\" World" "Hello Universe" Hi

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

Body:
I think if you use pattern like this:

Pattern pattern = Pattern.compile("\".*?(?<!\\\\)\"|'.*?(?<!\\\\)'|[A-Za-z']+");

Then it will give you desired output. When I ran with your input data I got this list:

["Hello\" World", "Hello Universe", Hi]

I used [A-Za-z']+ from your own question but shouldn't it be just : [A-Za-z]+

EDIT

Change your opts.add(token); line to:

opts.add(token.replaceAll("^\"|\"$|^'|'$", ""));


来源: stackexchange

问:
Is there a posibility to export a SVF from a DWG in an InventorPlugin
I am currently triying to use an Inventor Automation to modify a drawing and then export it to the SVF Format for the Viewer. Therefore I used this sample project from an Autodesk developer:

https://github.com/akenson/da-extract-params

I tried the code for exporting a 3D Drawing as SVF and that works fine. But when I tried to export a 2D drawing (like a DWG) to SVF, the SVF Addin doesn't create a file.

The Problem appears in the Method CreateForgeViewable() in the SampleAutomation Class in the ExtractParamsPlugin Projekt. I think the problem could be the configuration of the options for the Addin... But I couldn't find a Documentation for the SVF Addin.

```<code>// Setup SVF options
if (oAddin.get_HasSaveCopyAsOptions(doc, oContext, oOptions))
    {
        oOptions.set_Value("GeometryType", 1);
        oOptions.set_Value("EnableExpressTranslation", true);
        oOptions.set_Value("SVFFileOutputDir", sessionDir);
        oOptions.set_Value("ExportFileProperties", false);
        oOptions.set_Value("ObfuscateLabels", true);
    }
</code>```

Is there any parameter, that I should set for exporting a DWG to a SVF? Or is there somewhere a documentation for this Plugin?

I would be really thankfull for a reply.

Best regards

Sebastian

答: Currently, we only support SVF for 3D from Design Automation of Inventor (DA4I). If you want SVF for 2D DWG you can either go through Model Derivatives, or output to PDF by DA4I and use it in Forge Viewer (by pdf.js), or output DWG from DA4I and then go to Design Automation of AutoCAD (DA4A) to export. </p>

ContentLicense: CC BY-SA 4.0

Body:
I am currently triying to use an Inventor Automation to modify a drawing and then export it to the SVF Format for the Viewer. Therefore I used this sample project from an Autodesk developer:

https://github.com/akenson/da-extract-params

I tried the code for exporting a 3D Drawing as SVF and that works fine. But when I tried to export a 2D drawing (like a DWG) to SVF, the SVF Addin doesn't create a file.

The Problem appears in the Method CreateForgeViewable() in the SampleAutomation Class in the ExtractParamsPlugin Projekt. I think the problem could be the configuration of the options for the Addin... But I couldn't find a Documentation for the SVF Addin.

// Setup SVF options
if (oAddin.get_HasSaveCopyAsOptions(doc, oContext, oOptions))
    {
        oOptions.set_Value("GeometryType", 1);
        oOptions.set_Value("EnableExpressTranslation", true);
        oOptions.set_Value("SVFFileOutputDir", sessionDir);
        oOptions.set_Value("ExportFileProperties", false);
        oOptions.set_Value("ObfuscateLabels", true);
    }

Is there any parameter, that I should set for exporting a DWG to a SVF? Or is there somewhere a documentation for this Plugin?

I would be really thankfull for a reply.

Best regards

Sebastian


问:
How can I fix the error "Cannot create Swift scratch context" when using LLDB
Whenever I run an LLDB expression in swift mode I get the following error.

Cannot create Swift scratch context (couldn't load the Swift
  stdlib)Cannot create Swift scratch context (couldn't load the Swift
  stdlib)Stack dump:
  0.    Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb [1]    77539
  segmentation fault  lldb

it does not matter what I try to import.

```<code>~ ❯❯❯ lldb
(lldb) expression -l swift -- import AppKit
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    6665 segmentation fault  lldb
~ ❯❯❯ lldb                                                                                ✘ 139
(lldb) expression -l swift -- import Foundation
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    7122 segmentation fault  lldb
~ ❯❯❯ lldb                                                                                ✘ 139
(lldb) expression -l swift -- import UIKit
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    7225 segmentation fault  lldb
~ ❯❯❯                                                                                ✘ 139
</code>```

What's interesting is the very same commands work when using the LLDB within Xcode.

答:
The following conversation works in my Terminal:

```<code>themini:~ mattneubelcap$ swift
Welcome to Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15).
Type :help for assistance.
  1> :
(lldb) expr -lSwift -- import Foundation
(lldb) expr -lSwift -- "howdy" as NSString
</code>```

The success of the second command proves that Foundation was successfully imported. If not, we'd have received error: use of undeclared type 'NSString'.

Note the lack of space between -l and Swift. I do not know why "the very same commands" work using LLDB in Xcode, i.e. with the space. Certainly if you type help expr, you get the impression that -l Swift should work. Nevertheless, experimentation shows that in the Terminal it has to be either -lSwift (no space) or --language Swift (space), just like most command-line commands. Could it be that the Xcode LLDB is more forgiving or follows different syntax rules (uses a different parser)? I have no idea.

Body:
Whenever I run an LLDB expression in swift mode I get the following error.

Cannot create Swift scratch context (couldn't load the Swift
  stdlib)Cannot create Swift scratch context (couldn't load the Swift
  stdlib)Stack dump:
  0.    Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb [1]    77539
  segmentation fault  lldb

it does not matter what I try to import.

~ ❯❯❯ lldb
(lldb) expression -l swift -- import AppKit
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    6665 segmentation fault  lldb
~ ❯❯❯ lldb                                                                                ✘ 139
(lldb) expression -l swift -- import Foundation
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    7122 segmentation fault  lldb
~ ❯❯❯ lldb                                                                                ✘ 139
(lldb) expression -l swift -- import UIKit
Cannot create Swift scratch context (couldn't load the Swift stdlib)Cannot create Swift scratch context (couldn't load the Swift stdlib)Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/usr/bin/lldb
[1]    7225 segmentation fault  lldb
~ ❯❯❯                                                                                ✘ 139

What's interesting is the very same commands work when using the LLDB within Xcode.

Body:
The following conversation works in my Terminal:

themini:~ mattneubelcap$ swift
Welcome to Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15).
Type :help for assistance.
  1> :
(lldb) expr -lSwift -- import Foundation
(lldb) expr -lSwift -- "howdy" as NSString

The success of the second command proves that Foundation was successfully imported. If not, we'd have received error: use of undeclared type 'NSString'.

Note the lack of space between -l and Swift. I do not know why "the very same commands" work using LLDB in Xcode, i.e. with the space. Certainly if you type help expr, you get the impression that -l Swift should work. Nevertheless, experimentation shows that in the Terminal it has to be either -lSwift (no space) or --language Swift (space), just like most command-line commands. Could it be that the Xcode LLDB is more forgiving or follows different syntax rules (uses a different parser)? I have no idea.


问:
Is it possible to share both text and a photo from Flutter image_picker using flutter_share or another share plugin?
Using the flutter_share plugin I can successfully share text from my firestore collections in my Flutter ListView with:

```<code>child: IconButton(
icon: Icon(
  Icons.share,
   onPressed: () => Share.share(
   '${(snapshot.data.documents[index]['title'])}',
       ))),
</code>```

I have now added a new flutter listtile section to the ListView that includes a photo from the image_picker plugin, where users can select a photo from their gallery or take a new photo and append it beneath the firestore data text.

```<code> void _openImagePicker(BuildContext context) {
 showModalBottomSheet(context: context, builder: (BuildContext context) {
   return Container(
     height: 180.0,
     padding: EdgeInsets.all(10.0),
   child: Column(
     children: [
     Text('Choose photo',
       style:TextStyle(fontWeight: FontWeight.bold),),
       SizedBox(height: 10.0),
       FlatButton(
         textColor: Theme.of(context).primaryColor,
         child: Text('Use Camera'),
       onPressed: () {
           _getImage(context, ImageSource.camera);
       },),
       FlatButton(
         textColor: Theme.of(context).primaryColor,child:
       Text('Open Gallery'),
         onPressed: () {
           _getImage(context, ImageSource.gallery);
         },),

     ]
   ),);
 });
 }
 @override
 Widget build(BuildContext context) {
 return Column(
   children: <Widget>[
     OutlineButton(
     onPressed: () {
       _openImagePicker(context);
     },
     child:Row(
         mainAxisAlignment: MainAxisAlignment.start,
         children: <Widget>[
           Icon(Icons.camera_alt),
           SizedBox(
             width:1.0,
           ),
           // Text('Add Image'),
         ]
     ),//Row
 ),//outline button

    SizedBox(height: 10.0),
     _imageFile == null ?  Text('Add an Image') : Image.file(_imageFile,
         fit: BoxFit.cover,
         height: 200.0,
      width: 200.0,
       alignment: Alignment.topCenter,
     ),
   ],
 );}}
</code>```

My question is, is there a way with either this flutter_share plugin or another plugin to combine both the new image with the original shared firestore text, so users can share both text and the photo combined, instead of just the text? Or is it only possible to send one or another?

The image won't be stored in Firestore, only the text, so the image could be taken with the users camera or uploaded from their gallery, then appended to the shared text.

Here is full code with esys share added, it is not sending the image_picker image

```<code>class ImageInput extends StatefulWidget {

 @override
 _ImageInputState createState() => _ImageInputState();
    }

class _ImageInputState extends State<ImageInput> {

  File _imageFile;

  void _getImage(BuildContext context, ImageSource source){
   ImagePicker.pickImage(source: source, maxWidth: 200.0).then((File image){
   setState((){
    _imageFile = image;
  //        _imageFile = await ImagePicker.pickImage(source: source);
  //        List<int> imageBytes = await _imageFile.readAsBytes();
  //        var uint8List = Uint8List.fromList(imageBytes);

  });
  Navigator.pop(context);

  });
 }

  void _openImagePicker(BuildContext context) {

  showModalBottomSheet(context: context, builder: (BuildContext context) {
  return Container(
    height: 180.0,
    padding: EdgeInsets.all(10.0),
  child: Column(
    children: [
    Text('Choose photo',
      style:TextStyle(fontWeight: FontWeight.bold),),
      SizedBox(height: 10.0),
      FlatButton(
        textColor: Theme.of(context).primaryColor,
        child: Text('Use Camera'),
      onPressed: () {
          _getImage(context, ImageSource.camera);
      },),
      FlatButton(
        textColor: Theme.of(context).primaryColor,child:
      Text('Open Gallery'),
        onPressed: () {
          _getImage(context, ImageSource.gallery);
        },)

    ]
  ),);
 });
 }

 @override
 Widget build(BuildContext context) {
 return Column(
 children: <Widget>[
    OutlineButton(
    onPressed: () {
      _openImagePicker(context);
    },
    child:Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(Icons.camera_alt),
          SizedBox(
            width:1.0,
          ),
          // Text('Add Image'),
        ]
    ),//Row
  ),//outline button

   SizedBox(height: 10.0),
    _imageFile == null ?  Text('Add an Image') : Image.file(_imageFile,
        fit: BoxFit.cover,
        height: 200.0,
     width: 200.0,
     // width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
    ),

    MaterialButton(
      child: Text('Share mixed'),
      onPressed: () async => await _shareMixed(),
    ),

  ],
);
}
}

Future<void> _shareMixed() async {
try {
final ByteData bytes1 = await rootBundle.load('_imageFile');
//final ByteData bytes2 = await rootBundle.load('assets/image2.png');
// final ByteData bytes3 = await rootBundle.load('assets/addresses.csv');

await Share.files(
    'esys images',
    {
      '_imageFile': bytes1.buffer.asUint8List(),
      //'bluedan.png': bytes2.buffer.asUint8List(),
      //'addresses.csv': bytes3.buffer.asUint8List(),
    },
    '*/*',
    text: 'My optional text.');
} catch (e) {
print('error: $e');
}
}
</code>```

答:
You can copy paste run full code below

You can use package https://pub.dev/packages/esys_flutter_share

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:typed_data';

class ImageInput extends StatefulWidget {
  @override
  _ImageInputState createState() => _ImageInputState();
}

class _ImageInputState extends State<ImageInput> {
  File _imageFile;

  void _getImage(BuildContext context, ImageSource source) {
    ImagePicker.pickImage(source: source, maxWidth: 200.0).then((File image) {
      setState(() {
        _imageFile = image;
        //        _imageFile = await ImagePicker.pickImage(source: source);
        //        List<int> imageBytes = await _imageFile.readAsBytes();
        //        var uint8List = Uint8List.fromList(imageBytes);
      });
      Navigator.pop(context);
    });
  }

  Future<void> _shareImageAndText() async {
    try {
      List<int> imageBytes = await _imageFile.readAsBytes();
      var uint8List = Uint8List.fromList(imageBytes);
      await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
          text: 'My optional text.');
    } catch (e) {
      print('error: $e');
    }
  }

  void _openImagePicker(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 180.0,
            padding: EdgeInsets.all(10.0),
            child: Column(children: [
              Text(
                'Choose photo',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10.0),
              FlatButton(
                textColor: Theme.of(context).primaryColor,
                child: Text('Use Camera'),
                onPressed: () {
                  _getImage(context, ImageSource.camera);
                },
              ),
              FlatButton(
                textColor: Theme.of(context).primaryColor,
                child: Text('Open Gallery'),
                onPressed: () {
                  _getImage(context, ImageSource.gallery);
                },
              )
            ]),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        OutlineButton(
          onPressed: () {
            _openImagePicker(context);
          },
          child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Icon(Icons.camera_alt),
                SizedBox(
                  width: 1.0,
                ),
                // Text('Add Image'),
              ]), //Row
        ), //outline button

        SizedBox(height: 10.0),
        _imageFile == null
            ? Text('Add an Image')
            : Image.file(
                _imageFile,
                fit: BoxFit.cover,
                height: 200.0,
                width: 200.0,
                // width: MediaQuery.of(context).size.width,
                alignment: Alignment.topCenter,
              ),

        MaterialButton(
          child: Text('Share mixed'),
          onPressed: () async => await _shareImageAndText(),
        ),
      ],
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ImageInput(),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
Using the flutter_share plugin I can successfully share text from my firestore collections in my Flutter ListView with:

child: IconButton(
icon: Icon(
  Icons.share,
   onPressed: () => Share.share(
   '${(snapshot.data.documents[index]['title'])}',
       ))),

I have now added a new flutter listtile section to the ListView that includes a photo from the image_picker plugin, where users can select a photo from their gallery or take a new photo and append it beneath the firestore data text.

 void _openImagePicker(BuildContext context) {
 showModalBottomSheet(context: context, builder: (BuildContext context) {
   return Container(
     height: 180.0,
     padding: EdgeInsets.all(10.0),
   child: Column(
     children: [
     Text('Choose photo',
       style:TextStyle(fontWeight: FontWeight.bold),),
       SizedBox(height: 10.0),
       FlatButton(
         textColor: Theme.of(context).primaryColor,
         child: Text('Use Camera'),
       onPressed: () {
           _getImage(context, ImageSource.camera);
       },),
       FlatButton(
         textColor: Theme.of(context).primaryColor,child:
       Text('Open Gallery'),
         onPressed: () {
           _getImage(context, ImageSource.gallery);
         },),

     ]
   ),);
 });
 }
 @override
 Widget build(BuildContext context) {
 return Column(
   children: <Widget>[
     OutlineButton(
     onPressed: () {
       _openImagePicker(context);
     },
     child:Row(
         mainAxisAlignment: MainAxisAlignment.start,
         children: <Widget>[
           Icon(Icons.camera_alt),
           SizedBox(
             width:1.0,
           ),
           // Text('Add Image'),
         ]
     ),//Row
 ),//outline button

    SizedBox(height: 10.0),
     _imageFile == null ?  Text('Add an Image') : Image.file(_imageFile,
         fit: BoxFit.cover,
         height: 200.0,
      width: 200.0,
       alignment: Alignment.topCenter,
     ),
   ],
 );}}

My question is, is there a way with either this flutter_share plugin or another plugin to combine both the new image with the original shared firestore text, so users can share both text and the photo combined, instead of just the text? Or is it only possible to send one or another?

The image won't be stored in Firestore, only the text, so the image could be taken with the users camera or uploaded from their gallery, then appended to the shared text.

Here is full code with esys share added, it is not sending the image_picker image

class ImageInput extends StatefulWidget {

 @override
 _ImageInputState createState() => _ImageInputState();
    }

class _ImageInputState extends State<ImageInput> {

  File _imageFile;

  void _getImage(BuildContext context, ImageSource source){
   ImagePicker.pickImage(source: source, maxWidth: 200.0).then((File image){
   setState((){
    _imageFile = image;
  //        _imageFile = await ImagePicker.pickImage(source: source);
  //        List<int> imageBytes = await _imageFile.readAsBytes();
  //        var uint8List = Uint8List.fromList(imageBytes);

  });
  Navigator.pop(context);

  });
 }

  void _openImagePicker(BuildContext context) {

  showModalBottomSheet(context: context, builder: (BuildContext context) {
  return Container(
    height: 180.0,
    padding: EdgeInsets.all(10.0),
  child: Column(
    children: [
    Text('Choose photo',
      style:TextStyle(fontWeight: FontWeight.bold),),
      SizedBox(height: 10.0),
      FlatButton(
        textColor: Theme.of(context).primaryColor,
        child: Text('Use Camera'),
      onPressed: () {
          _getImage(context, ImageSource.camera);
      },),
      FlatButton(
        textColor: Theme.of(context).primaryColor,child:
      Text('Open Gallery'),
        onPressed: () {
          _getImage(context, ImageSource.gallery);
        },)

    ]
  ),);
 });
 }

 @override
 Widget build(BuildContext context) {
 return Column(
 children: <Widget>[
    OutlineButton(
    onPressed: () {
      _openImagePicker(context);
    },
    child:Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(Icons.camera_alt),
          SizedBox(
            width:1.0,
          ),
          // Text('Add Image'),
        ]
    ),//Row
  ),//outline button

   SizedBox(height: 10.0),
    _imageFile == null ?  Text('Add an Image') : Image.file(_imageFile,
        fit: BoxFit.cover,
        height: 200.0,
     width: 200.0,
     // width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
    ),

    MaterialButton(
      child: Text('Share mixed'),
      onPressed: () async => await _shareMixed(),
    ),

  ],
);
}
}

Future<void> _shareMixed() async {
try {
final ByteData bytes1 = await rootBundle.load('_imageFile');
//final ByteData bytes2 = await rootBundle.load('assets/image2.png');
// final ByteData bytes3 = await rootBundle.load('assets/addresses.csv');

await Share.files(
    'esys images',
    {
      '_imageFile': bytes1.buffer.asUint8List(),
      //'bluedan.png': bytes2.buffer.asUint8List(),
      //'addresses.csv': bytes3.buffer.asUint8List(),
    },
    '*/*',
    text: 'My optional text.');
} catch (e) {
print('error: $e');
}
}

Body:
You can copy paste run full code below

You can use package https://pub.dev/packages/esys_flutter_share

working demo

full code

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:typed_data';

class ImageInput extends StatefulWidget {
  @override
  _ImageInputState createState() => _ImageInputState();
}

class _ImageInputState extends State<ImageInput> {
  File _imageFile;

  void _getImage(BuildContext context, ImageSource source) {
    ImagePicker.pickImage(source: source, maxWidth: 200.0).then((File image) {
      setState(() {
        _imageFile = image;
        //        _imageFile = await ImagePicker.pickImage(source: source);
        //        List<int> imageBytes = await _imageFile.readAsBytes();
        //        var uint8List = Uint8List.fromList(imageBytes);
      });
      Navigator.pop(context);
    });
  }

  Future<void> _shareImageAndText() async {
    try {
      List<int> imageBytes = await _imageFile.readAsBytes();
      var uint8List = Uint8List.fromList(imageBytes);
      await Share.file('esys image', 'esys.jpg', uint8List, 'image/jpeg',
          text: 'My optional text.');
    } catch (e) {
      print('error: $e');
    }
  }

  void _openImagePicker(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 180.0,
            padding: EdgeInsets.all(10.0),
            child: Column(children: [
              Text(
                'Choose photo',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10.0),
              FlatButton(
                textColor: Theme.of(context).primaryColor,
                child: Text('Use Camera'),
                onPressed: () {
                  _getImage(context, ImageSource.camera);
                },
              ),
              FlatButton(
                textColor: Theme.of(context).primaryColor,
                child: Text('Open Gallery'),
                onPressed: () {
                  _getImage(context, ImageSource.gallery);
                },
              )
            ]),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        OutlineButton(
          onPressed: () {
            _openImagePicker(context);
          },
          child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Icon(Icons.camera_alt),
                SizedBox(
                  width: 1.0,
                ),
                // Text('Add Image'),
              ]), //Row
        ), //outline button

        SizedBox(height: 10.0),
        _imageFile == null
            ? Text('Add an Image')
            : Image.file(
                _imageFile,
                fit: BoxFit.cover,
                height: 200.0,
                width: 200.0,
                // width: MediaQuery.of(context).size.width,
                alignment: Alignment.topCenter,
              ),

        MaterialButton(
          child: Text('Share mixed'),
          onPressed: () async => await _shareImageAndText(),
        ),
      ],
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ImageInput(),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
AWS Document DB MultiRegion replication
I know that the AWS DocumentDB doesnot support multiregion replication even the snapshot cannot be shared across regions.

Please suggest how we can manually do the replication

答: Thank you for the feedback, Sam. A couple of options are to use change streams + Lambda/worker to replicate the data or to take take backups to S3 with mongodump and utilize S3's cross-region replication capabilities.</p>

Title: AWS Document DB MultiRegion replication


问:
Why cannot import sub module?
My project structure like this:

```<code>/project
    main.py
    /a_module
        __init__.py
        /sub_module
            __init__.py
            some_file.py
</code>```

main.py

```<code>from a_module import main_api
</code>```

a_module/__init__.py

```<code>from sub_module import sub_api
</code>```

sub_module/__init__.py

```<code>from some_file import detail_api
</code>```

In a_module/__init__.py gives Unable to import 'sub_module' error.

Why I cannot import 'sub_module'?

When I change to the relative path solve the error.

```<code>from .sub_module import sub_api
</code>```

But I don't understand, does __init__.py design for public the API of the module? Why don't treat sub_module as a module instead of a directory? it's such a bad design to me...

答:
__init__.py is executed when you import the package that contains it. But it's not your problem. Your problem is that module imports are always absolute unless explicitly relative. That means that they must chain from some directory in sys.path. By default this includes the working directory, so when you run main.py from within project, it can find a_module, and nothing else.

```<code>from sub_module import sub_api
</code>```

In a_module/__init__.py doesn't work though, because imports are always absolute unless explicitly relative. So that import says "starting from some sys.path root, find a top level package named sub_module and import sub_api from it". Since no such module exists you get an error. from .sub_module import sub_api works because you opted into relative imports, so it doesn't start over from sys.path.

For an example of why you would do this, I'll give you something that broke in our own code back in the Python 2 days before absolute import by default was the law (from __future__ import absolute_import enabled the Py3 behavior, which is how we fixed it, but despite what the docs say, it was never enabled by default in Py2, the only enabled by default behavior was relative imports). Our layout was:

```<code> teamnamespace/
               module.py
               math/
                    mathrelatedsubmodule.py
                    othermathsubmodule.py
</code>```

Now, we innocently thought hey, we'll put all our packages under a single shared top level namespace, and subpackages cover broad categories within them, and since we had a lot of additional utilities for basic mathematics, we put them under teamnamespace.math. Problem was, for the non-math modules, like teamnamespace.module, when they did:

```<code>import math  # or
from math import ceil
</code>```

it defaulted to relative lookup, and imported teamnamespace.math as math (a thoroughly useless import, since it was a namespace package only, all the functionality was in the sub-modules), not the built-in math module. In fact, without the Python 3 behavior, there was no reasonable way to get the built-in math module from a module under teamnamespace. Whereas with the Python 3 behavior, you can get either one or both (by aliasing one or the other with as, with no ambiguity:

```<code># Gets built-in
import math

# Gets teamnamespace.math
from . import math
</code>```

Title: Why cannot import sub module?

Body:
My project structure like this:

/project
    main.py
    /a_module
        __init__.py
        /sub_module
            __init__.py
            some_file.py

main.py

from a_module import main_api

a_module/__init__.py

from sub_module import sub_api

sub_module/__init__.py

from some_file import detail_api

In a_module/__init__.py gives Unable to import 'sub_module' error.

Why I cannot import 'sub_module'?

When I change to the relative path solve the error.

from .sub_module import sub_api

But I don't understand, does __init__.py design for public the API of the module? Why don't treat sub_module as a module instead of a directory? it's such a bad design to me...

Body:
__init__.py is executed when you import the package that contains it. But it's not your problem. Your problem is that module imports are always absolute unless explicitly relative. That means that they must chain from some directory in sys.path. By default this includes the working directory, so when you run main.py from within project, it can find a_module, and nothing else.

from sub_module import sub_api

In a_module/__init__.py doesn't work though, because imports are always absolute unless explicitly relative. So that import says "starting from some sys.path root, find a top level package named sub_module and import sub_api from it". Since no such module exists you get an error. from .sub_module import sub_api works because you opted into relative imports, so it doesn't start over from sys.path.

For an example of why you would do this, I'll give you something that broke in our own code back in the Python 2 days before absolute import by default was the law (from __future__ import absolute_import enabled the Py3 behavior, which is how we fixed it, but despite what the docs say, it was never enabled by default in Py2, the only enabled by default behavior was relative imports). Our layout was:

 teamnamespace/
               module.py
               math/
                    mathrelatedsubmodule.py
                    othermathsubmodule.py

Now, we innocently thought hey, we'll put all our packages under a single shared top level namespace, and subpackages cover broad categories within them, and since we had a lot of additional utilities for basic mathematics, we put them under teamnamespace.math. Problem was, for the non-math modules, like teamnamespace.module, when they did:

import math  # or
from math import ceil

it defaulted to relative lookup, and imported teamnamespace.math as math (a thoroughly useless import, since it was a namespace package only, all the functionality was in the sub-modules), not the built-in math module. In fact, without the Python 3 behavior, there was no reasonable way to get the built-in math module from a module under teamnamespace. Whereas with the Python 3 behavior, you can get either one or both (by aliasing one or the other with as, with no ambiguity:

# Gets built-in
import math

# Gets teamnamespace.math
from . import math


问:
Trouble displaying image in python GUI
I am creating a GUI in python. I created different frames using classes, and each page has a designated class. I am trying to display a simple image but the image doesn't display, even though I get no errors. </p>

答:
Make sure to save a reference to your image, so that it does not get garbage collected.

Something like:

```<code>myframe.img = myimage
</code>```

You can add the image as an attribute to an existing object, like above, or

```<code>root.images = {}
root.images[str(myframe)] = myimage
</code>```

You just need to store a reference to the image so that the Python garbage collector will not try to dispose of it.  Just putting it into a frame or a button is actually not enough to protect the image.

Title: Trouble displaying image in python GUI

Body:
Make sure to save a reference to your image, so that it does not get garbage collected.

Something like:

myframe.img = myimage

You can add the image as an attribute to an existing object, like above, or

root.images = {}
root.images[str(myframe)] = myimage

You just need to store a reference to the image so that the Python garbage collector will not try to dispose of it.  Just putting it into a frame or a button is actually not enough to protect the image.


问:
PHP Docker image built in Atlassian Bamboo has permission errors
I have a build plan in Atlassian Bamboo that builds a Docker image of a PHP project. The image includes Apache2, PHP and dependencies, and of course the project itself. When I try to run the Docker image generated by this build plan, I get a permission denied error to the project.

I am using root as the primary user in the Docker container. I also tried to include a chown command in the Dockerfile for www-data:www-data for the PHP project directory but the problem did not go away.

This is what happens to the permission of the indicated file:

```<code>--w-------  1 root     root      582 Feb 18 12:17 index.php
</code>```

The contents of the Dockerfile

```<code>FROM php:apache

RUN apt-get update && export DEBIAN_FRONTEND=noninteractive && ln -fs /usr/share/zoneinfo/Asia/Manila /etc/localtime \
    && apt-get install -y libzip-dev libpng-dev unzip git tzdata libpq-dev && dpkg-reconfigure --frontend noninteractive tzdata \
    && docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
    && docker-php-ext-install pdo_pgsql pgsql zip gd \
    && rm -rf /var/lib/apt

WORKDIR /var/www/html

COPY composer.json .
COPY composer.lock .
COPY composer.phar .

RUN php composer.phar install

RUN chmod 775 -R /var/www/html

COPY . .
</code>```

答: I came across this post indicating that the problem was an internal change in Atlassian Bamboo. What I did then was to use 771 as the permission for all the files in the PHP project and changed the ownership as well through chown. This combination was the correct one apparently and allowed the application to run.

Body:
I have a build plan in Atlassian Bamboo that builds a Docker image of a PHP project. The image includes Apache2, PHP and dependencies, and of course the project itself. When I try to run the Docker image generated by this build plan, I get a permission denied error to the project.

I am using root as the primary user in the Docker container. I also tried to include a chown command in the Dockerfile for www-data:www-data for the PHP project directory but the problem did not go away.

This is what happens to the permission of the indicated file:

--w-------  1 root     root      582 Feb 18 12:17 index.php

The contents of the Dockerfile

FROM php:apache

RUN apt-get update && export DEBIAN_FRONTEND=noninteractive && ln -fs /usr/share/zoneinfo/Asia/Manila /etc/localtime \
    && apt-get install -y libzip-dev libpng-dev unzip git tzdata libpq-dev && dpkg-reconfigure --frontend noninteractive tzdata \
    && docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
    && docker-php-ext-install pdo_pgsql pgsql zip gd \
    && rm -rf /var/lib/apt

WORKDIR /var/www/html

COPY composer.json .
COPY composer.lock .
COPY composer.phar .

RUN php composer.phar install

RUN chmod 775 -R /var/www/html

COPY . .


问:
Macro definition clash between directx headers and winerror.h
I'm on windows 7 using Visual Studio 2012.

When I compile I get a lot of macro redefinition warnings caused by winerror.h versus dxgi.h, dxgitype.h, d3d11.h, d3d10.h; for example DXGI_STATUS_OCCLUDED, DXGI_STATUS_CLIPPED, DXGI_STATUS_NO_REDIRECTION etc.

I suppose this is because the windows sdk 8 is installed.
How can I avoid this? Is there a way I can exclude these new libraries from my project?

答:
Winerror.h includes DXGIType.h and Visual Studio found the DirectX SDK DXGIType.h instead of the Windows SDK one.

Following user2400203's answer, and renaming C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include\DXGIType.h worked for me.

ContentLicense: CC BY-SA 3.0


问:
Add line graph based on new data to series of boxplots
I have used the following R script to create two side-side boxplots. One for 1999 and one for 2008:

```<code>library(tidyverse)
mpg %>% ggplot(aes(as_factor(year), hwy))+geom_boxplot()
</code>```

I have a new data set for manufacturer XYZ that has two observations,one for 1999 and one for 2008:

```<code>manufacturer <- c("xyz", "xyz")
year <- c(1999, 2008)
hwy <- c(19, 30)
df <- data.frame(manufacturer, year, hwy)
</code>```

Is there a simple way to adding the two observations from the new data set (df) in my boxplot graph?
I have seen a few other similar posts (e.g., ggplot: adding new data to the existing grouped boxplot) but the problems/solutions seem to be more complicated and I could not follow them.
Thanks

答:
Is this something you are looking for? Basically you can assign a new data frame each time when you call a geom.

```<code>library(ggplot2)

ggplot(data = mpg, aes(as.factor(year), hwy)) +
  geom_boxplot() +
  geom_point(data = df) +
  geom_line(data = df, aes(group = manufacturer))
</code>```

Body:
I have used the following R script to create two side-side boxplots. One for 1999 and one for 2008:

library(tidyverse)
mpg %>% ggplot(aes(as_factor(year), hwy))+geom_boxplot()

I have a new data set for manufacturer XYZ that has two observations,one for 1999 and one for 2008:

manufacturer <- c("xyz", "xyz")
year <- c(1999, 2008)
hwy <- c(19, 30)
df <- data.frame(manufacturer, year, hwy)

Is there a simple way to adding the two observations from the new data set (df) in my boxplot graph?
I have seen a few other similar posts (e.g., ggplot: adding new data to the existing grouped boxplot) but the problems/solutions seem to be more complicated and I could not follow them.
Thanks

Body:
Is this something you are looking for? Basically you can assign a new data frame each time when you call a geom.

library(ggplot2)

ggplot(data = mpg, aes(as.factor(year), hwy)) +
  geom_boxplot() +
  geom_point(data = df) +
  geom_line(data = df, aes(group = manufacturer))


问:
How to add more then one array on same "for" in lua
how can I use "for k, j in pairs() do" for 2 arrays in lua?</p>

```<code> local blipmarker1 = {
      { x = 10 , y = 5, z = 3 },
      { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
      { x = 100, y= 150, z=30 }
}
function createtext(){
    local pos = GetEntityCoords(PlayerPedId(), true)
    for k, j in pairs(blipmarker1,blimarker2) do
        draw3DText(pos.x, pos.y, pos.z, j.x, j.y, j.z)
    end
 }
</code>```

答:
You could write your own stateful multipairs iterator.  Consult Chapter 9.3 “Coroutines as Iterators” of Programming in Lua for more details: https://www.lua.org/pil/9.3.html

local function multipairs(tables)
    return coroutine.wrap(function()
        for _, t in pairs(tables) do -- Maybe you want ipairs here
            for k, v in pairs(t) do
                coroutine.yield(k, v)
            end
        end
    end)
end

local blipmarker1 = {
    { x = 10 , y = 5, z = 3 },
    { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
    { x = 100, y= 150, z=30 }
}

for _, j in multipairs{blipmarker1, blipmarker2} do
    print(j.x, j.y, j.z)
end
```

Body:
how can I use "for k, j in pairs() do" for 2 arrays in lua?

 local blipmarker1 = {
      { x = 10 , y = 5, z = 3 },
      { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
      { x = 100, y= 150, z=30 }
}
function createtext(){
    local pos = GetEntityCoords(PlayerPedId(), true)
    for k, j in pairs(blipmarker1,blimarker2) do
        draw3DText(pos.x, pos.y, pos.z, j.x, j.y, j.z)
    end
 }


问:
Parsing Data in Google Sheets From an Object
I have thousands of rows of data in a Google Sheets File in a column that looks something like

[{"amountMax":49.99,"amountMin":49.99,"availability":"true","color":"Brown","currency":"USD","dateSeen":["2019-04-11T08:00:00Z"],"isSale":"false","offer":"Online only","sourceURLs":["https://www.walmart.com/ip/SadoTech-Model-CXR-Wireless-Doorbell-1-Remote-Button-2-Plugin-Receivers-Operating-500-feet-Range-50-Chimes-Batteries-Required-Receivers-Beige-Fixed-C/463989633"]}]

I would like to be able to return the max value, the currency, the color attributes. How can I do that in Google Sheets. Ideally would like to do something like being able to retrieve the data attributes how I would normally in javascript like in this link here https://repl.it/@alexhoy/WetSlateblueDribbleware

However this does not seem to work for me when creating a function in script.google.com

For example, here is a slugify function which takes an input (cell) and turns it into a slug/handle without the need for looping. In Google Sheets I can then call =slugify(b2) and turn that value into slug form

```<code>/**
* Converts value to slug
* @customfunction
*/
function slugify(value) {
  /*
   * Convert the the vs in a range of cells into slugs.
   * @customfunction
   */
  let slug = '';

  slug = value.substring(0, 100).toLowerCase();
  slug = slug.replace(/[^\w\s-]/g, '');
  slug = slug.replace(/\s+/g, '-');
  Logger.log(slug);

  return slug;
}
</code>```

I want to do the same thing without looping to parse the object data above or declaring a range of values and what not.

Any suggestions on how I can do this in a simple way like shown above without the need for declaring active spreadsheet, range values and looping.

答:
The following script will give you an idea about how to approach this task.

It assumes that:

the json data described in your question is in Cell A2.

the max value will be inserted into cell D2

the currency will be inserted into cell E2

the color will be inserted into cell F2

The script uses temporary arrays to capture the values and then assign it to a 2d array.

If you have many rows of data, then you will need to create a loop. I suggest that you build the arraydata progressively, and only update the target range at the end of the loop. This will give you the most efficient outcome.

```<code>function so6031098604() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet()
  var content = JSON.parse(sheet.getRange("A2").getValue());

  // temp arrar to capture the data
  var temparray = [];
  temparray.push(content[0]["amountMax"]);
  temparray.push(content[0]["currency"]);
  temparray.push(content[0]["color"]);

  // second array to accept the row data
  var arraydata =[];
  arraydata.push(temparray)

  // define the target range
  var targetrange = sheet.getRange(2, 4, 1, 3);
  // update with the arraydata
  targetrange.setValues(arraydata);

}
</code>```

Body:
I have thousands of rows of data in a Google Sheets File in a column that looks something like

[{"amountMax":49.99,"amountMin":49.99,"availability":"true","color":"Brown","currency":"USD","dateSeen":["2019-04-11T08:00:00Z"],"isSale":"false","offer":"Online only","sourceURLs":["https://www.walmart.com/ip/SadoTech-Model-CXR-Wireless-Doorbell-1-Remote-Button-2-Plugin-Receivers-Operating-500-feet-Range-50-Chimes-Batteries-Required-Receivers-Beige-Fixed-C/463989633"]}]

I would like to be able to return the max value, the currency, the color attributes. How can I do that in Google Sheets. Ideally would like to do something like being able to retrieve the data attributes how I would normally in javascript like in this link here https://repl.it/@alexhoy/WetSlateblueDribbleware

However this does not seem to work for me when creating a function in script.google.com

For example, here is a slugify function which takes an input (cell) and turns it into a slug/handle without the need for looping. In Google Sheets I can then call =slugify(b2) and turn that value into slug form

/**
* Converts value to slug
* @customfunction
*/
function slugify(value) {
  /*
   * Convert the the vs in a range of cells into slugs.
   * @customfunction
   */
  let slug = '';

  slug = value.substring(0, 100).toLowerCase();
  slug = slug.replace(/[^\w\s-]/g, '');
  slug = slug.replace(/\s+/g, '-');
  Logger.log(slug);

  return slug;
}

I want to do the same thing without looping to parse the object data above or declaring a range of values and what not.

Any suggestions on how I can do this in a simple way like shown above without the need for declaring active spreadsheet, range values and looping.

Body:
The following script will give you an idea about how to approach this task.

It assumes that:

the json data described in your question is in Cell A2.

the max value will be inserted into cell D2

the currency will be inserted into cell E2

the color will be inserted into cell F2

The script uses temporary arrays to capture the values and then assign it to a 2d array.

If you have many rows of data, then you will need to create a loop. I suggest that you build the arraydata progressively, and only update the target range at the end of the loop. This will give you the most efficient outcome.

function so6031098604() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet()
  var content = JSON.parse(sheet.getRange("A2").getValue());

  // temp arrar to capture the data
  var temparray = [];
  temparray.push(content[0]["amountMax"]);
  temparray.push(content[0]["currency"]);
  temparray.push(content[0]["color"]);

  // second array to accept the row data
  var arraydata =[];
  arraydata.push(temparray)

  // define the target range
  var targetrange = sheet.getRange(2, 4, 1, 3);
  // update with the arraydata
  targetrange.setValues(arraydata);

}


问:
Springboot Checkbox Values to Controller
A springboot-thymeleaf newbie, I have been reading many similar questions on this topic but I'm still missing something in the syntax and overall Springboot Thymeleaf paradigm.

The web application pulls project data from the backend database which is rendered by Thymeleaf templates. The user also can generate a pdf report of the data which is also rendered in the browser.

The entity:

```<code>@Entity
@Table(name = "REPORT_CS")
public class ReportItemCs {

    public ReportItemCs () {}

    @Id
    @Column(name = "ITEM_ID")
    private Long itemId;

    @Column(name = "PROJ_NUM")
    private String projectNumber;

    @Column(name = "REGION")
    private String region;

//  additional fields, getters, setters
</code>```

First, something that works:

A simple text field in thymeleaf is used to pass a string in post request. The controller picks it up where it's passed to the repo as a query parameter on projectNumber. The query returns a list of objects which thymeleaf renders in a table. Note there's no binding to any object - it's just posting the string from the UI then passing it as a query param.

Html:

```<code>//Works without binding to backend

<section layout:fragment="content">

    <p>Quick Project Search:</p>

    <form method="post">
        <input type="text" name="keyword"
            placeholder="Project number keywords" /> <input type="submit"
            value="Search" />
    </form>

    <br /> <span th:text=" ${noProjectsMessage}"></span>

</section>
</code>```

Controller:

```<code>@RequestMapping(value = "/", method = RequestMethod.POST)
    public String showProject(String keyword, ModelMap model) {

        List<ProjectView> p = repository.findByProjectsContaining(keyword);
            if (p.size() == 0) {

                model.put("noProjectsMessage",
                String.format("Project with id containing \"%s\" not found...", keyword));
                return "home";
            } else {

                model.put("projectViews", p);
            }
        return "show-projects";
    }
</code>```

Repository:

```<code>    @Query("SELECT p FROM ProjectView p WHERE p.projectNumber like %?1%")
    List<ProjectView> findByProjectsContaining(@Param("keyword") String keyword);
</code>```

So, now, I need to add some checkboxes to provide additional filtering by region, project category, etc. I plan to use the checkboxes in two ways: 1) to dynamically filter the project list in the UI using jQuery and, also, to pass the checkbox values back to the controller so they can be used to populate a pdf template header. I'd then either do another database query or use Stream() to filter the list that was generated by the original query and send the filtered list to the pdf service. When the user clicks the "PDF" button, the checkbox values are forwarded to the pdf service where the report header and report are generated and returned as a byte stream in a separate tab.

Html

```<code><div class="form-check">

<form th:action="@{/cs-report}" method="post">
<label for="form-check">Region</label>

<input class="form-check-input" type="checkbox" value="all" name="regions" id="allOffice" />
<label class="form-check-label" for="allOffice">Select All</label>

<input class="form-check-input" type="checkbox" value="region1" name="regions" id="region1"/>
<label class="form-check-label" for="region1">Region 1</label>

<input class="form-check-input" type="checkbox" value="region2" name="regions" id="region2"/>
<label class="form-check-label" for="region2">Region 2</label>

<input class="form-check-input" type="checkbox" value="region3" name= "regions" id="region3"/>
<label class="form-check-label" for="region1">Region 3</label>

<button type="submit" class="btn btn-primary">Test Checkboxes</button>
</form>

</div>
</code>```

Controller

```<code>//Test the post method

@RequestMapping(value = "/cs-report", method = RequestMethod.POST)

public void printCheckboxValues(List<String> regions)

{

regions.foreach(s -> System.out.println(s));

}
</code>```

Where, if this approach worked, the repo would look something like:

```<code>    @Query("SELECT p FROM ProjectView p WHERE p.region IN 1")
    List<ProjectView> findByRegion(@Param("regions") List<String> regions);
</code>```

I think the controller uses the name attribute to reference the list of checkbox values, but I'm unclear on how to set up the controller to do this. Most of the examples I've seen have had the checkboxes bound to their parent object, and maybe that's what needs to be done. I have the checkboxes hard coded as there aren't that many and I don't expect the values to change in the database. But if I do need to bind the checkbox "region" values to the reportCs entity, an example of syntax would be greatly appreciated.

Any other suggestions on approach are greatly appreciated, and big bonus if the code can be generalized to take multiple params from multiple checkbox groups. Thank you.

答:
OK, the checkboxes need to bind to a form-backing bean. It took some tinkering with the Thymeleaf syntax, but doing it this way is actually is quite convenient for binding multiple checkbox groups to multiple query parameters. Also, I've realized hard coding the checkbox values in the templates is a bad idea (Not loosely-coupled code and will create problems down the line) so my next step is to get the checkbox values dynamically from the database. Thank you for reading.

html:

```<code><div class="form-check">

<form action="#" th:action="@{/cs-report}" th:object="${queryDto}" method="post">
    <button type="submit" class="btn btn-primary">Get Report</button>

<input class="form-check-input" type="checkbox" value="all" name="all" id="all" />
<label class="form-check-label" for="all">Select All</label>

<input class="form-check-input" type="checkbox" value="region1" name="regions" th:field="*{regions}" id="region1" />
label class="form-check-label" for="region1">Region 1</label>

<input class="form-check-input" type="checkbox" value="region2" name="regions" th:field="*{regions}" id="region2" />
label class="form-check-label" for="region2">Region 2</label>

<input class="form-check-input" type="checkbox" value="region3" name="regions" th:field="*{regions}" id="region3" />
label class="form-check-label" for="region3">Region 3</label>

</form>

</div>
</code>```

The DTO object:

```<code>// Form-backing bean to hold checkbox values on post submission
public class QueryDto {

    private List<String> regions;
    // Getter, setters

</code>```

Controller

```<code>    @PostMapping(value = "/cs-report")
    public String testCheckboxes(@ModelAttribute QueryDto queryDto) throws IOException {

List<ReportDto> dtos = repository.findByRegion(queryDto.getRegions());

dtos.foreach(s -> System.out.println(s.getProjectRegion()));
}

</code>```

Repository

```<code>@Query("SELECT p FROM ProjectView p WHERE p.region IN :regions")
    List<ProjectView> findByRegion(@Param("regions") List<String> regions);

</code>```

Body:
A springboot-thymeleaf newbie, I have been reading many similar questions on this topic but I'm still missing something in the syntax and overall Springboot Thymeleaf paradigm.

The web application pulls project data from the backend database which is rendered by Thymeleaf templates. The user also can generate a pdf report of the data which is also rendered in the browser.

The entity:

@Entity
@Table(name = "REPORT_CS")
public class ReportItemCs {

    public ReportItemCs () {}

    @Id
    @Column(name = "ITEM_ID")
    private Long itemId;

    @Column(name = "PROJ_NUM")
    private String projectNumber;

    @Column(name = "REGION")
    private String region;

//  additional fields, getters, setters

First, something that works:

A simple text field in thymeleaf is used to pass a string in post request. The controller picks it up where it's passed to the repo as a query parameter on projectNumber. The query returns a list of objects which thymeleaf renders in a table. Note there's no binding to any object - it's just posting the string from the UI then passing it as a query param.

Html:

//Works without binding to backend

Quick Project Search:

    <form method="post">
        <input type="text" name="keyword"
            placeholder="Project number keywords" /> <input type="submit"
            value="Search" />
    </form>

Controller:

@RequestMapping(value = "/", method = RequestMethod.POST)
    public String showProject(String keyword, ModelMap model) {

        List<ProjectView> p = repository.findByProjectsContaining(keyword);
            if (p.size() == 0) {

                model.put("noProjectsMessage",
                String.format("Project with id containing \"%s\" not found...", keyword));
                return "home";
            } else {

                model.put("projectViews", p);
            }
        return "show-projects";
    }

Repository:

    @Query("SELECT p FROM ProjectView p WHERE p.projectNumber like %?1%")
    List<ProjectView> findByProjectsContaining(@Param("keyword") String keyword);

So, now, I need to add some checkboxes to provide additional filtering by region, project category, etc. I plan to use the checkboxes in two ways: 1) to dynamically filter the project list in the UI using jQuery and, also, to pass the checkbox values back to the controller so they can be used to populate a pdf template header. I'd then either do another database query or use Stream() to filter the list that was generated by the original query and send the filtered list to the pdf service. When the user clicks the "PDF" button, the checkbox values are forwarded to the pdf service where the report header and report are generated and returned as a byte stream in a separate tab.

Html

<form th:action="@{/cs-report}" method="post">
Region

<input class="form-check-input" type="checkbox" value="all" name="regions" id="allOffice" />
Select All

<input class="form-check-input" type="checkbox" value="region1" name="regions" id="region1"/>
Region 1

<input class="form-check-input" type="checkbox" value="region2" name="regions" id="region2"/>
Region 2

<input class="form-check-input" type="checkbox" value="region3" name= "regions" id="region3"/>
Region 3

<button type="submit" class="btn btn-primary">Test Checkboxes</button>
</form>

Controller

//Test the post method

@RequestMapping(value = "/cs-report", method = RequestMethod.POST)

public void printCheckboxValues(List<String> regions)

{

regions.foreach(s -> System.out.println(s));

}

Where, if this approach worked, the repo would look something like:

    @Query("SELECT p FROM ProjectView p WHERE p.region IN 1")
    List<ProjectView> findByRegion(@Param("regions") List<String> regions);

I think the controller uses the name attribute to reference the list of checkbox values, but I'm unclear on how to set up the controller to do this. Most of the examples I've seen have had the checkboxes bound to their parent object, and maybe that's what needs to be done. I have the checkboxes hard coded as there aren't that many and I don't expect the values to change in the database. But if I do need to bind the checkbox "region" values to the reportCs entity, an example of syntax would be greatly appreciated.

Any other suggestions on approach are greatly appreciated, and big bonus if the code can be generalized to take multiple params from multiple checkbox groups. Thank you.

Body:
OK, the checkboxes need to bind to a form-backing bean. It took some tinkering with the Thymeleaf syntax, but doing it this way is actually is quite convenient for binding multiple checkbox groups to multiple query parameters. Also, I've realized hard coding the checkbox values in the templates is a bad idea (Not loosely-coupled code and will create problems down the line) so my next step is to get the checkbox values dynamically from the database. Thank you for reading.

html:

<div class="form-check">

<form action="#" th:action="@{/cs-report}" th:object="${queryDto}" method="post">
    <button type="submit" class="btn btn-primary">Get Report</button>

<input class="form-check-input" type="checkbox" value="all" name="all" id="all" />
<label class="form-check-label" for="all">Select All</label>

<input class="form-check-input" type="checkbox" value="region1" name="regions" th:field="*{regions}" id="region1" />
label class="form-check-label" for="region1">Region 1</label>

<input class="form-check-input" type="checkbox" value="region2" name="regions" th:field="*{regions}" id="region2" />
label class="form-check-label" for="region2">Region 2</label>

<input class="form-check-input" type="checkbox" value="region3" name="regions" th:field="*{regions}" id="region3" />
label class="form-check-label" for="region3">Region 3</label>

</form>

</div>

The DTO object:

// Form-backing bean to hold checkbox values on post submission
public class QueryDto {

    private List<String> regions;
    // Getter, setters

Controller

    @PostMapping(value = "/cs-report")
    public String testCheckboxes(@ModelAttribute QueryDto queryDto) throws IOException {

List<ReportDto> dtos = repository.findByRegion(queryDto.getRegions());

dtos.foreach(s -> System.out.println(s.getProjectRegion()));
}

Repository

@Query("SELECT p FROM ProjectView p WHERE p.region IN :regions")
    List<ProjectView> findByRegion(@Param("regions") List<String> regions);


问:
How to add column if not exists on PostgreSQL?
Question is simple. How to add column x to table y, but only when x column doesn't exist  ? I found only solution here how to check if column exists.

```<code>SELECT column_name
FROM information_schema.columns
WHERE table_name='x' and column_name='y';
</code>```

答:
For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution</p>

```<code>ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>
</code>```

Body:
Question is simple. How to add column x to table y, but only when x column doesn't exist  ? I found only solution here how to check if column exists.

SELECT column_name
FROM information_schema.columns
WHERE table_name='x' and column_name='y';

Body:
For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution

ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>


问:
Converting ImageProxy to Bitmap
So, I wanted to explore new Google's Camera API - CameraX.
What I want to do, is take an image from camera feed every second and then pass it into a function that accepts bitmap for machine learning purposes.

I read the documentation on Camera X Image Analyzer:

The image analysis use case provides your app with a CPU-accessible
  image to perform image processing, computer vision, or machine
  learning inference on. The application implements an Analyzer method
  that is run on each frame.

..which basically is what I need. So, I implemented this image analyzer like this:

```<code>imageAnalysis.setAnalyzer { image: ImageProxy, _: Int ->
    viewModel.onAnalyzeImage(image)
}
</code>```

What I get is image: ImageProxy. How can I transfer this ImageProxy to Bitmap?

I tried to solve it like this:

```<code>fun decodeBitmap(image: ImageProxy): Bitmap? {
    val buffer = image.planes[0].buffer
    val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) }
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
</code>```

But it returns null - because decodeByteArray does not receive valid (?) bitmap bytes. Any ideas?

答:
Inspired from the answer by @mike-a

```<code>private fun ImageProxy.toMat(): Mat {
  val graySourceMatrix = Mat(height, width, CvType.CV_8UC1)
  val yBuffer = planes[0].buffer
  val ySize = yBuffer.remaining()
  val yPlane = ByteArray(ySize)
  yBuffer[yPlane, 0, ySize]
  graySourceMatrix.put(0, 0, yPlane)
  return graySourceMatrix
}
</code>```

This will directly take you to gray-matrix-land, if you intend to use OpenCV, and colors don't matter to you anymore.

For performance you can move the initialization of the Mat outside if you're doing this on every frame.

Title: Converting ImageProxy to Bitmap

Body:
So, I wanted to explore new Google's Camera API - CameraX.
What I want to do, is take an image from camera feed every second and then pass it into a function that accepts bitmap for machine learning purposes.

I read the documentation on Camera X Image Analyzer:

The image analysis use case provides your app with a CPU-accessible
  image to perform image processing, computer vision, or machine
  learning inference on. The application implements an Analyzer method
  that is run on each frame.

..which basically is what I need. So, I implemented this image analyzer like this:

imageAnalysis.setAnalyzer { image: ImageProxy, _: Int ->
    viewModel.onAnalyzeImage(image)
}

What I get is image: ImageProxy. How can I transfer this ImageProxy to Bitmap?

I tried to solve it like this:

fun decodeBitmap(image: ImageProxy): Bitmap? {
    val buffer = image.planes[0].buffer
    val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) }
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}

But it returns null - because decodeByteArray does not receive valid (?) bitmap bytes. Any ideas?

Body:
Inspired from the answer by @mike-a

private fun ImageProxy.toMat(): Mat {
  val graySourceMatrix = Mat(height, width, CvType.CV_8UC1)
  val yBuffer = planes[0].buffer
  val ySize = yBuffer.remaining()
  val yPlane = ByteArray(ySize)
  yBuffer[yPlane, 0, ySize]
  graySourceMatrix.put(0, 0, yPlane)
  return graySourceMatrix
}

This will directly take you to gray-matrix-land, if you intend to use OpenCV, and colors don't matter to you anymore.

For performance you can move the initialization of the Mat outside if you're doing this on every frame.


问:
Is there a shorter way to increment bd_address in python?
I wrote a python's function to increment BT device BD_ADDR by any value but my function can only work up to xx:xx:xx:xx:FE:FF.  For example, original BD_ADDR = AA:BB:CC:DD:EE:FF --> incremented by 1 BD_ADDR = AA:BB:CC:DD:EF:00.  Also is there a shorter way to do this without all if statements?  any suggestions will be appreciated.
 Below is the script:</p>

```<code>def ba_incr(mac,incr):
        old_bytes = mac[12:].split(":")
        if (old_bytes[0] != "00"):
             if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
             elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]

                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
                else:
                        old_hex = str(old_bytes[0] + old_bytes[1])
                        incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                        #print ("incremented hex",incr_hex)
                        new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = "01" + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":0" + str(incr_hex)
        elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
        print ("mac after:", mac[:12] + new_bytes.upper())
</code>```

答:
You can probably try something like this:

Remove the ':' from the mac address

Convert the mac address to integer

Increment the integer value

Convert the integer to hex string

Insert back the ':' at the appropriate positions

Sample code that worked for me (for simplicity I am incrementing by 1). You may need to modify it to handle corner cases.

```<code>s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)
</code>```

Output:

```<code>AABBCCDDEEFF
AA:BB:CC:DD:EF:00
</code>```

Body:
I wrote a python's function to increment BT device BD_ADDR by any value but my function can only work up to xx:xx:xx:xx:FE:FF.  For example, original BD_ADDR = AA:BB:CC:DD:EE:FF --> incremented by 1 BD_ADDR = AA:BB:CC:DD:EF:00.  Also is there a shorter way to do this without all if statements?  any suggestions will be appreciated.
 Below is the script:

def ba_incr(mac,incr):
        old_bytes = mac[12:].split(":")
        if (old_bytes[0] != "00"):
             if (old_bytes[0] != "01" and old_bytes[0] != "0F"):
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
             elif (old_bytes[0] == "0F" and old_bytes[1] == "FF") :
                  old_hex = str(old_bytes[0] + old_bytes[1])
                  incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]

                  new_bytes = str(incr_hex[:2]) + ":" + str(incr_hex[2:])
                else:
                        old_hex = str(old_bytes[0] + old_bytes[1])
                        incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                        #print ("incremented hex",incr_hex)
                        new_bytes = "0" + str(incr_hex[:1]) + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1] == "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = "01" + ":" + str(incr_hex[1:])
        elif (old_bytes[0] == "00" and old_bytes[1][:1] == "0") and old_bytes[1][1:] != "F":
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":0" + str(incr_hex)
        elif (old_bytes[0] == "00" and old_bytes[1] != "FF"):
                old_hex = old_bytes[1]
                #print ("old hex:",old_hex)
                incr_hex = hex(int(str(int(old_hex, base=16) + incr)))[2:]
                #print ("incremented hex:",incr_hex)
                new_bytes = old_bytes[0] + ":" + str(incr_hex)[:2]
        print ("mac after:", mac[:12] + new_bytes.upper())

Body:
You can probably try something like this:

Remove the ':' from the mac address

Convert the mac address to integer

Increment the integer value

Convert the integer to hex string

Insert back the ':' at the appropriate positions

Sample code that worked for me (for simplicity I am incrementing by 1). You may need to modify it to handle corner cases.

s = 'AA:BB:CC:DD:EE:FF'
s = s.replace(':', '')
val = int(s, 16)
val = val + 1
incr_s = hex(val)
incr_s = incr_s[2:].upper()
incr_s = ':'.join(incr_s[i:i+2] for i in range(0, len(incr_s), 2))
print(s)
print(incr_s)

Output:

AABBCCDDEEFF
AA:BB:CC:DD:EF:00


问:
jquery dialog button to do the same as asp.net mvc submit button
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

```<code><input type="submit" value="Create" />
</code>```

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

```<code>       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType
</code>```

However, the method requires a model parameter

```<code>    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)
</code>```

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

答:
The only thing you have to do is make sure that your post data has the same names as the property values of ClientDetail. So if ClientDetail has two properties: Name and Age, then make sure that the data you post looks like this:

```<code>var data = { Name: 'ClientName', Age: 24 };
</code>```

ASP.NET MVC's DefaultModelBinder will bind the posted data to your ClientDetail object.

Body:
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

<input type="submit" value="Create" />

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType

However, the method requires a model parameter

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

Body:
The only thing you have to do is make sure that your post data has the same names as the property values of ClientDetail. So if ClientDetail has two properties: Name and Age, then make sure that the data you post looks like this:

var data = { Name: 'ClientName', Age: 24 };

ASP.NET MVC's DefaultModelBinder will bind the posted data to your ClientDetail object.


问:
Azure authentification for multiple audience using WithExtraScopesToConsent and AcquireTokenSilent
I am building an app that let user manipulate Azure resource and Azure storage therefore I need to access multiple audiences, however, it's not possible to have one toke with multiple audience in azure. So I am using this tutorial

https://learn.microsoft.com/bs-latn-ba/azure/active-directory/develop/msal-net-user-gets-consent-for-multiple-resources

and my code look like :

```<code>         IPublicClientApplication client = PublicClientApplicationBuilder.Create(clientId)
                    .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                    .WithDefaultRedirectUri()
                //  .WithRedirectUri($"msal{clientId}://auth")
                .Build();

        var accounts = client.GetAccountsAsync().Result;
            string[] scopes = { "https://management.azure.com/user_impersonation" };
            string[] scopestorage = { "https://storage.azure.com/user_impersonation" };

            var result = client.AcquireTokenInteractive(scopes)
                                  .WithAccount(accounts.FirstOrDefault())
                                  .WithExtraScopesToConsent(scopestorage)
                                  .ExecuteAsync().Result;
          var result2=  client.AcquireTokenSilent(scopestorage, accounts.FirstOrDefault()).ExecuteAsync();

</code>```

but I am getting an exception while executing the AcquireTokenInteractive method

```<code>Microsoft.Identity.Client.MsalUiRequiredException: 'No account or login hint was passed to the AcquireTokenSilent call.'
</code>```

Also when I look in the locals my variable "accounts" i can see Count=0 and nothing in there.

Any pointer for a solutions would be greatly appreciated.

Regards

Vincent

答:
Your need to make some changes to your code. Here is the working sample for your reference:

```<code>string[] scopes = { "https://management.azure.com/user_impersonation" };
            string[] scopestorage = { "https://storage.azure.com/user_impersonation" };
            IPublicClientApplication client = PublicClientApplicationBuilder
                .Create("cbc32712-ac27-4532-802d-303998a6e712")
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .Build();

            var result = client.AcquireTokenInteractive(scopes)
                                  .ExecuteAsync().Result;
            var accounts = client.GetAccountsAsync().Result;
            var result2 = client.AcquireTokenSilent(scopestorage, accounts.FirstOrDefault()).ExecuteAsync().Result;
</code>```

Note:

1.As you will get access token for storage resource by using AcquireTokenSilent method, make sure you have granted user/admin consent for your application to access this resource.

2.You can not use WithExtraScopesToConsent method for different resource endpoints.

Body:
I am building an app that let user manipulate Azure resource and Azure storage therefore I need to access multiple audiences, however, it's not possible to have one toke with multiple audience in azure. So I am using this tutorial

https://learn.microsoft.com/bs-latn-ba/azure/active-directory/develop/msal-net-user-gets-consent-for-multiple-resources

and my code look like :

         IPublicClientApplication client = PublicClientApplicationBuilder.Create(clientId)
                    .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
                    .WithDefaultRedirectUri()
                //  .WithRedirectUri($"msal{clientId}://auth")
                .Build();

        var accounts = client.GetAccountsAsync().Result;
            string[] scopes = { "https://management.azure.com/user_impersonation" };
            string[] scopestorage = { "https://storage.azure.com/user_impersonation" };

            var result = client.AcquireTokenInteractive(scopes)
                                  .WithAccount(accounts.FirstOrDefault())
                                  .WithExtraScopesToConsent(scopestorage)
                                  .ExecuteAsync().Result;
          var result2=  client.AcquireTokenSilent(scopestorage, accounts.FirstOrDefault()).ExecuteAsync();

but I am getting an exception while executing the AcquireTokenInteractive method

Microsoft.Identity.Client.MsalUiRequiredException: 'No account or login hint was passed to the AcquireTokenSilent call.'

Also when I look in the locals my variable "accounts" i can see Count=0 and nothing in there.

Any pointer for a solutions would be greatly appreciated.

Regards

Vincent

Body:
Your need to make some changes to your code. Here is the working sample for your reference:

string[] scopes = { "https://management.azure.com/user_impersonation" };
            string[] scopestorage = { "https://storage.azure.com/user_impersonation" };
            IPublicClientApplication client = PublicClientApplicationBuilder
                .Create("cbc32712-ac27-4532-802d-303998a6e712")
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .Build();

            var result = client.AcquireTokenInteractive(scopes)
                                  .ExecuteAsync().Result;
            var accounts = client.GetAccountsAsync().Result;
            var result2 = client.AcquireTokenSilent(scopestorage, accounts.FirstOrDefault()).ExecuteAsync().Result;

Note:

1.As you will get access token for storage resource by using AcquireTokenSilent method, make sure you have granted user/admin consent for your application to access this resource.

2.You can not use WithExtraScopesToConsent method for different resource endpoints.


问:
Is it possible to calculate each all the numbers received on each day of the week from this list in Python? I don't understand splitting
```<code>import os
myFilePath = os.getcwd()
print(myFilePath)
calls = open('/Users/fake/Desktop/fakefolder/calls.txt')
mondayCalls = []
for adding in calls.readlines():
    mondayCalls.append(adding.strip())
calls.close()
print(mondayCalls)
</code>```

Here is the list that I generated from a txt file, I just want to add the total for all mondays, tuesdays etc. I would want to print

```<code>Monday = 29
Tuesday = 16 etc
</code>```

The list is longer but here is an example of the list that I have.

```<code>['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
</code>```

答:
It is possible with splitting and then recording values in a dictionary. You can iterate through the list and store the values in a dictionary where the key of the dictionary is the day. Pseudo code below:

```<code>record = {}
for entry in list:
    day = get_day(entry)
    val = get_val(entry)
    if day in record:
        record[day] += val
    else:
        record[day] = val
</code>```

Then your final record_dict will contain the values you want for each day.

Body:
import os
myFilePath = os.getcwd()
print(myFilePath)
calls = open('/Users/fake/Desktop/fakefolder/calls.txt')
mondayCalls = []
for adding in calls.readlines():
    mondayCalls.append(adding.strip())
calls.close()
print(mondayCalls)

Here is the list that I generated from a txt file, I just want to add the total for all mondays, tuesdays etc. I would want to print

Monday = 29
Tuesday = 16 etc

The list is longer but here is an example of the list that I have.

['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']

Body:
It is possible with splitting and then recording values in a dictionary. You can iterate through the list and store the values in a dictionary where the key of the dictionary is the day. Pseudo code below:

record = {}
for entry in list:
    day = get_day(entry)
    val = get_val(entry)
    if day in record:
        record[day] += val
    else:
        record[day] = val

Then your final record_dict will contain the values you want for each day.


问:
Can't exec "/bin/sh": Argument list too long at perl
Below command in perl script is failing if there are many file in @file_to_tar, but it is working fine if we have less files in the array (@file_to_tar).

my $tar_command = "cd $ProcVars->{dropbox_dir}; tar -cvzf SmartMiles.$ProcVars->{batch_nb}.tar.gz -P @file_to_tar --remove-files";

Can some one please help me to fix the issue.

答:
The best way is pass a very long list of files to tar is using the --from-file option:

```<code>tar -czf myarchive.tar.gz -P --from-file=$filelist --remove-files
</code>```

You can also make it read the list of files from standard input by using --from-file=-

See https://www.gnu.org/software/tar/manual/html_node/files.html for more information.

Body:
The best way is pass a very long list of files to tar is using the --from-file option:

tar -czf myarchive.tar.gz -P --from-file=$filelist --remove-files

You can also make it read the list of files from standard input by using --from-file=-

See https://www.gnu.org/software/tar/manual/html_node/files.html for more information.


问:
RxJS 6 - Cancel / End a Pipe
Working with the new version of RxJS 6 and the pipe operator in particular. Currently using the pipe  to take the results of an API call and pass them to a series of additional tasks.

All works great, but can't seem to find a way to cancel or end a pipe should I encounter an issue. For example, I'm using the tap operator to check if the value is null. I then throw an error, but the pipe still appears to move to the next task, in this case concatmap.

Therefore, how do you end or cancel a pipe prematurely? Thanks in advance.

getData(id: String): Observable<any[]> {
return this.http.get<any>(`${this.baseUrl}/path/${id}`).pipe(
   tap(evt => {
    if (evt == null) {
      return throwError(new Error("No data found..."));
    }
  }),
concatMap(
  evt =>
     <Observable<any[]>>(
        this.http.get<any[]>(
    `${this.baseUrl}/path/relatedby/${evt.child_id}`
      ).map(res =>( {"response1":evt, "response2":res}) )
 )
),
retry(3),
catchError(this.handleError("getData", []))
);}
```

答:
You can also cancel/end a pipe by using a signal Subject and the rxjs operator: takeUntil

Example

httpGetSafe(path: string): Observable<Data> {
  const stopSignal$ = new Subject();

  return this.http.get<Data>(path).pipe(
    map(data => {
      const isBad = data === null;
      if (isBad) {
        stopSignal$.next();
      }
      return data;
    }),
    takeUntil(stopSignal$)
  );
}
```

Sometimes it's a bit simpler and more flexible than throwing errors...

Title: RxJS 6 - Cancel / End a Pipe

Body:
You can also cancel/end a pipe by using a signal Subject and the rxjs operator: takeUntil

Example

httpGetSafe(path: string): Observable<Data> {
  const stopSignal$ = new Subject();

  return this.http.get<Data>(path).pipe(
    map(data => {
      const isBad = data === null;
      if (isBad) {
        stopSignal$.next();
      }
      return data;
    }),
    takeUntil(stopSignal$)
  );
}

Sometimes it's a bit simpler and more flexible than throwing errors...


问:
lambda with custom authorizer works on test with console but not with postman
I have a lambda function that works when testing on the AWS console. But once I test on Postman it gives me the following response

```<code>{
    "message": "Unauthorized"
}
</code>```

I basically have a Authorization on the header with a Bearer token like so

```<code>Bearer <my token>
</code>```

The body is empty as it's only a Get endpoint. Not sure what I'm missing on my request from postman. Any suggestion is appreciated.

答: Figured it out finally. If you're posting Authorization with a setup where you have "Authorization" as the token source and blank Token Validation (like below), you don't add the word "Bearer" on postman. Still have to research why that is and how that works (as i dont understand). Any help on where to look at as to why when you post with an Authorization header some apis require "Bearer" but this one does not.

Body:
I have a lambda function that works when testing on the AWS console. But once I test on Postman it gives me the following response

{
    "message": "Unauthorized"
}

I basically have a Authorization on the header with a Bearer token like so

Bearer <my token>

The body is empty as it's only a Get endpoint. Not sure what I'm missing on my request from postman. Any suggestion is appreciated.


问:
Launch android apps on pepper´s tablet in Naoqi 2.5
I installed an APK on my Pepper by following the instructions in this link.

I used the following command:
qicli call ALTabletService._installApk http://198.18.0.1/apps/app-debug.apk

And get:

```<code>[W] 1396590449.100437 3669 qimessaging.transportsocket: connect: Connection refused

true
</code>```

I don't know if this means that the installation succeeded or not but when using qicli call ALTabletService._listApks it doesn't show up in the list and I can't launch it using qicli call ALTabletService._launchApk com.android.app-debug.
I get the response:

```<code>[W] 1396590620.654268 3688 qimessaging.transportsocket: connect: Connection refused
false
</code>```

I don't know why I get "Connection refused" but I can launch a preinstalled APK while still getting the same message.

Does anyone know how to solve this?

答:
Whether the APK succeeds or fails to be installed seems to depend on the APK itself and I'm not yet sure why. Test with the below process and let me know how you go. I successfully installed this apk as a test, but was unable to install some others.

# copy the APK to the following location on Pepper
scp <apk-file>.apk nao@<nao-ip>:/home/nao/.local/share/PackageManager/apps

# listen for onApkInstalled event
qicli watch ALTabletService.onApkInstalled

# In a second terminal, try to install the apk
qicli call ALTabletService._installApk http://198.18.0.1/apps/<apk-file>.apk
```

If the installation was successful, you should see onApkInstalled:  "<apk-id>" printed in the first terminal. The app id should then appear when calling qicli call ALTabletService._listApks and you can then run the app using qicli call ALTabletService._launchApk <apk-id>.

If no apk installed message is received, there has been an error. I am currently unsure of the process for debugging the installation using ADB, as in this question, but that should reveal more about the reason for the installation failure.

Body:
I installed an APK on my Pepper by following the instructions in this link.

I used the following command:
qicli call ALTabletService._installApk http://198.18.0.1/apps/app-debug.apk

And get:

[W] 1396590449.100437 3669 qimessaging.transportsocket: connect: Connection refused

true

I don't know if this means that the installation succeeded or not but when using qicli call ALTabletService._listApks it doesn't show up in the list and I can't launch it using qicli call ALTabletService._launchApk com.android.app-debug.
I get the response:

[W] 1396590620.654268 3688 qimessaging.transportsocket: connect: Connection refused
false

I don't know why I get "Connection refused" but I can launch a preinstalled APK while still getting the same message.

Does anyone know how to solve this?

Body:
Whether the APK succeeds or fails to be installed seems to depend on the APK itself and I'm not yet sure why. Test with the below process and let me know how you go. I successfully installed this apk as a test, but was unable to install some others.

# copy the APK to the following location on Pepper
scp <apk-file>.apk nao@<nao-ip>:/home/nao/.local/share/PackageManager/apps

# listen for onApkInstalled event
qicli watch ALTabletService.onApkInstalled

# In a second terminal, try to install the apk
qicli call ALTabletService._installApk http://198.18.0.1/apps/<apk-file>.apk

If the installation was successful, you should see onApkInstalled:  "<apk-id>" printed in the first terminal. The app id should then appear when calling qicli call ALTabletService._listApks and you can then run the app using qicli call ALTabletService._launchApk <apk-id>.

If no apk installed message is received, there has been an error. I am currently unsure of the process for debugging the installation using ADB, as in this question, but that should reveal more about the reason for the installation failure.


问:
Aggregate and sum by one key and rest
It's hard for me to explain what I want to get, so I will show an example:

I have objects:

```<code>{name: 'steve', received: 100} {name: 'carolina', received: 70}
{name: 'steve', 'received: 30} {name: 'andrew', received: 10}
</code>```

I can do:

```<code>    { $group :
         { _id : '$name',
           sum : { "$sum" :'$received' },
         },
    },
</code>```

And i will get:

Steve received 130 (100 +30)

Carolina received 70

Andrew received 10

But
I need something like that:

Steve received 130 (100 +30)

Everyone else received 80 (70+10)

How can I get this effect?

答:
You can specify a condition with the $sum accumulator operator in the grouping:

```<code>db.test.aggregate( [
  {
      $group : {
          _id :  null,
          steve_received: {
              $sum: {
                  $cond: [ { $eq: [ "$name", "steve" ] }, "$received", 0 ]
              }
          },
          others_received: {
              $sum: {
                  $cond: [ { $ne: [ "$name", "steve" ] }, "$received", 0 ]
              }
          }
      }
  },
  {
      $project: { _id: 0 }
  }
] )
</code>```

The above aggregation returns: { "steve_received" : 130, "others_received" : 80 }

Title: Aggregate and sum by one key and rest

Body:
It's hard for me to explain what I want to get, so I will show an example:

I have objects:

{name: 'steve', received: 100} {name: 'carolina', received: 70}
{name: 'steve', 'received: 30} {name: 'andrew', received: 10}

I can do:

    { $group :
         { _id : '$name',
           sum : { "$sum" :'$received' },
         },
    },

And i will get:

Steve received 130 (100 +30)

Carolina received 70

Andrew received 10

But
I need something like that:

Steve received 130 (100 +30)

Everyone else received 80 (70+10)

How can I get this effect?

Body:
You can specify a condition with the $sum accumulator operator in the grouping:

db.test.aggregate( [
  {
      $group : {
          _id :  null,
          steve_received: {
              $sum: {
                  $cond: [ { $eq: [ "$name", "steve" ] }, "$received", 0 ]
              }
          },
          others_received: {
              $sum: {
                  $cond: [ { $ne: [ "$name", "steve" ] }, "$received", 0 ]
              }
          }
      }
  },
  {
      $project: { _id: 0 }
  }
] )

The above aggregation returns: { "steve_received" : 130, "others_received" : 80 }