问:
Flutter speech_to_text: ^2.2.0 package Not listening - initialisation problem?
To start using package I have tried the code provided by the developer.
I am on windows 7 64bit machine, have used nexus 4 and now nexus 5x virtual machine with android 5 and now with Android Q. Apart from that, also a real phone with android 7.0. The phone's on-board text to speech functionality works flawlessly.
In each of the configurations, the interface does not really appear to respond except when I click initialize - nothing happens with the app except in the Run window of Android Studio.
Here is the readout:

```<code>Launching lib\main.dart on Android SDK built for x86 64 in debug mode... Running Gradle task 'assembleDebug'... √ Built build\app\outputs\apk\debug\app-debug.apk. Installing build\app\outputs\apk\app.apk... Flutter is taking longer than expected to report its views. Still trying... Debug service listening on ws://127.0.0.1:53319/B_tNUT2pR7I=/ws Syncing files to device Android SDK built for x86 64... W/xample.flutter( 5738): Accessing hidden method Landroid/view/accessibility/AccessibilityNodeInfo;->getSourceNodeId()J (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden method Landroid/view/accessibility/AccessibilityRecord;->getSourceNodeId()J (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden field Landroid/view/accessibility/AccessibilityNodeInfo;->mChildNodeIds:Landroid/util/LongArray; (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden method Landroid/util/LongArray;->get(I)J (greylist, reflection, allowed) I/Choreographer( 5738): Skipped 53 frames!  The application may be doing too much work on its main thread. D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x70249825f180, tid 5786 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x702497d3e6a0, tid 5955 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 D/EGL_emulation( 5738): eglCreateContext: 0x702497d3e740: maj 3 min 0 rcv 3 D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 D/EGL_emulation( 5738): eglCreateContext: 0x70249825f220: maj 3 min 0 rcv 3 D/EGL_emulation( 5738): eglMakeCurrent: 0x70249825f220: ver 3 0 (tinfo 0x702498218680) W/Gralloc3( 5738): mapper 3.x is not supported D/HostConnection( 5738): createUnique: call D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x70249825f360, tid 5786 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/eglCodecCommon( 5738): allocate: Ask for block of size 0x1000 D/eglCodecCommon( 5738): allocate: ioctl allocate returned offset 0x3ff807000 size 0x2000 D/HostConnection( 5738): createUnique: call D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x702448a9ff00, tid 5955 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/EGL_emulation( 5738): eglMakeCurrent: 0x702497d3e740: ver 3 0 (tinfo 0x70244d193360) D/EGL_emulation( 5738): eglMakeCurrent: 0x70249825f220: ver 3 0 (tinfo 0x702498218680) D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 1 0 I/OpenGLRenderer( 5738): Davey! duration=16105ms; Flags=1, IntendedVsync=320862128930, Vsync=321745462228, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=321750930400, AnimationStart=321751011720, PerformTraversalsStart=321751071720, DrawStart=330820804190, SyncQueued=331199393480, SyncStart=331258181510, IssueDrawCommandsStart=331421431670, SwapBuffers=336112080650, FrameCompleted=337026255970, DequeueBufferDuration=550559000, QueueBufferDuration=35074000,  I/Choreographer( 5738): Skipped 953 frames!  The application may be doing too much work on its main thread. D/EGL_emulation( 5738): eglMakeCurrent: 0x702497d3e740: ver 3 0 (tinfo 0x70244d193360) D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 I/Choreographer( 5738): Skipped 40 frames!  The application may be doing too much work on its main thread. I/OpenGLRenderer( 5738): Davey! duration=782ms; Flags=0, IntendedVsync=349271346526, Vsync=349938013166, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=349954335870, AnimationStart=349954427840, PerformTraversalsStart=349997031300, DrawStart=349997268140, SyncQueued=349997407090, SyncStart=350019841510, IssueDrawCommandsStart=350019994270, SwapBuffers=350027291360, FrameCompleted=350076153750, DequeueBufferDuration=149000, QueueBufferDuration=9594000,  I/OpenGLRenderer( 5738): Davey! duration=818ms; Flags=0, IntendedVsync=350655153383, Vsync=350755153379, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=350758548020, AnimationStart=350758679460, PerformTraversalsStart=350933225780, DrawStart=351140119140, SyncQueued=351140550980, SyncStart=351159859490, IssueDrawCommandsStart=351159930940, SwapBuffers=351165057370, FrameCompleted=351492805850, DequeueBufferDuration=292974000, QueueBufferDuration=727000,  W/xample.flutter( 5738): Verification of androidx.core.view.DragAndDropPermissionsCompat androidx.core.app.ActivityCompat.requestDragAndDropPermissions(android.app.Activity, android.view.DragEvent) took 201.593ms E/flutter ( 5738): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(multipleRequests, Only one initialize at a time, null) E/flutter ( 5738): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7) E/flutter ( 5738): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18) E/flutter ( 5738): <asynchronous suspension> E/flutter ( 5738): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12) E/flutter ( 5738): #3      SpeechToText.initialize (package:speech_to_text/speech_to_text.dart:174:10) E/flutter ( 5738):
#4      _MyAppState.initSpeechState (package:flutter6/main.dart:34:35) E/flutter ( 5738): #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19) E/flutter ( 5738):
#6      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36) E/flutter ( 5738):
#7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter ( 5738): #8      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11) E/flutter ( 5738): #9   BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5) E/flutter ( 5738): #10   BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7) E/flutter ( 5738): #11   PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9) E/flutter ( 5738): #12     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12) E/flutter ( 5738): #13     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9) E/flutter ( 5738): #14     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8) E/flutter ( 5738): #15 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18) E/flutter ( 5738): #16     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7) E/flutter ( 5738): #17     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19) E/flutter ( 5738):
#18     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter ( 5738):
#19     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter ( 5738):
#20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter ( 5738):
#21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter ( 5738):
#22     _rootRunUnary (dart:async/zone.dart:1196:13) E/flutter ( 5738): #23     _CustomZone.runUnary (dart:async/zone.dart:1085:19) E/flutter ( 5738): #24     _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7) E/flutter ( 5738): #25     _invoke1 (dart:ui/hooks.dart:275:10) E/flutter ( 5738): #26
_dispatchPointerDataPacket (dart:ui/hooks.dart:184:5) E/flutter ( 5738):  I/Choreographer( 5738): Skipped 31 frames!  The application may be doing too much work on its main thread.
</code>```

Android Studio, flutter and node were installed 3 days ago, I have run the flutter doctor with -v and without the parameter. Previously, some licences unsigned, now that is sorted.

Here is the code I pasted from the above page:

```<code>import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _hasSpeech = false;
  double level = 0.0;
  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String lastWords = "";
  String lastError = "";
  String lastStatus = "";
  String _currentLocaleId = "";
  List<LocaleName> _localeNames = [];
  final SpeechToText speech = SpeechToText();

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

  Future<void> initSpeechState() async {
    bool hasSpeech = await speech.initialize(
        onError: errorListener, onStatus: statusListener);
    if (hasSpeech) {
      _localeNames = await speech.locales();

      var systemLocale = await speech.systemLocale();
      _currentLocaleId = systemLocale.localeId;
    }

    if (!mounted) return;

    setState(() {
      _hasSpeech = hasSpeech;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Speech to Text Example'),
        ),
        body: Column(children: [
          Center(
            child: Text(
              'Speech recognition available',
              style: TextStyle(fontSize: 22.0),
            ),
          ),
          Container(
            child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(
                      child: Text('Initialize'),
                      onPressed: _hasSpeech ? null : initSpeechState,
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(
                      child: Text('Start'),
                      onPressed: !_hasSpeech || speech.isListening
                          ? null
                          : startListening,
                    ),
                    FlatButton(
                      child: Text('Stop'),
                      onPressed: speech.isListening ? stopListening : null,
                    ),
                    FlatButton(
                      child: Text('Cancel'),
                      onPressed: speech.isListening ? cancelListening : null,
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    DropdownButton(
                      onChanged: (selectedVal) => _switchLang(selectedVal),
                      value: _currentLocaleId,
                      items: _localeNames
                          .map(
                            (localeName) => DropdownMenuItem(
                          value: localeName.localeId,
                          child: Text(localeName.name),
                        ),
                      )
                          .toList(),
                    ),
                  ],
                )
              ],
            ),
          ),
          Expanded(
            flex: 4,
            child: Column(
              children: <Widget>[
                Center(
                  child: Text(
                    'Recognized Words',
                    style: TextStyle(fontSize: 22.0),
                  ),
                ),
                Expanded(
                  child: Stack(
                    children: <Widget>[
                      Container(
                        color: Theme.of(context).selectedRowColor,
                        child: Center(
                          child: Text(
                            lastWords,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      Positioned.fill(
                        bottom: 10,
                        child: Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            width: 40,
                            height: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              boxShadow: [
                                BoxShadow(
                                    blurRadius: .26,
                                    spreadRadius: level * 1.5,
                                    color: Colors.black.withOpacity(.05))
                              ],
                              color: Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(50)),
                            ),
                            child: IconButton(icon: Icon(Icons.mic),

                                onPressed: () {
                              /*...*/
                            }
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Column(
              children: <Widget>[
                Center(
                  child: Text(
                    'Error Status',
                    style: TextStyle(fontSize: 22.0),
                  ),
                ),
                Center(
                  child: Text(lastError),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 20),
            color: Theme.of(context).backgroundColor,
            child: Center(
              child: speech.isListening
                  ? Text(
                "I'm listening...",
                style: TextStyle(fontWeight: FontWeight.bold),
              )
                  : Text(
                'Not listening',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ]),
      ),
    );
  }

  void startListening() {
    lastWords = "";
    lastError = "";
    speech.listen(
        onResult: resultListener,
        listenFor: Duration(seconds: 10),
        localeId: _currentLocaleId,
        onSoundLevelChange: soundLevelListener,
        cancelOnError: true,
        partialResults: true);
    setState(() {});
  }

  void stopListening() {
    speech.stop();
    setState(() {
      level = 0.0;
    });
  }

  void cancelListening() {
    speech.cancel();
    setState(() {
      level = 0.0;
    });
  }

  void resultListener(SpeechRecognitionResult result) {
    setState(() {
      lastWords = "${result.recognizedWords} - ${result.finalResult}";
    });
  }

  void soundLevelListener(double level) {
    minSoundLevel = min(minSoundLevel, level);
    maxSoundLevel = max(maxSoundLevel, level);
    //print("sound level $level: $minSoundLevel - $maxSoundLevel ");
    setState(() {
      this.level = level;
    });
  }

  void errorListener(SpeechRecognitionError error) {
    print("Received error status: $error, listening: ${speech.isListening}");
    setState(() {
      lastError = "${error.errorMsg} - ${error.permanent}";
    });
  }

  void statusListener(String status) {
    print(
        "Received listener status: $status, listening: ${speech.isListening}");
    setState(() {
      lastStatus = "$status";
    });
  }

  _switchLang(selectedVal) {
    setState(() {
      _currentLocaleId = selectedVal;
    });
    print(selectedVal);
  }
}
</code>```

I have imported the package by adding a dependency to yaml and importing the pub, and have run out of any further ideas. Please help.
Thank you.

答:
The application using the speech_to_text plugin requires user permission. You need to add the required keys for iOS in the Info.plist file. For Android, you need to add the record audio permission in the AndroidManifest.xml.

Here is the description of the package:
https://pub.dev/packages/speech_to_text
Scroll down to "permission". There you can see how to add all said things.

Body:
To start using package I have tried the code provided by the developer.
I am on windows 7 64bit machine, have used nexus 4 and now nexus 5x virtual machine with android 5 and now with Android Q. Apart from that, also a real phone with android 7.0. The phone's on-board text to speech functionality works flawlessly.
In each of the configurations, the interface does not really appear to respond except when I click initialize - nothing happens with the app except in the Run window of Android Studio.
Here is the readout:

Launching lib\main.dart on Android SDK built for x86 64 in debug mode... Running Gradle task 'assembleDebug'... √ Built build\app\outputs\apk\debug\app-debug.apk. Installing build\app\outputs\apk\app.apk... Flutter is taking longer than expected to report its views. Still trying... Debug service listening on ws://127.0.0.1:53319/B_tNUT2pR7I=/ws Syncing files to device Android SDK built for x86 64... W/xample.flutter( 5738): Accessing hidden method Landroid/view/accessibility/AccessibilityNodeInfo;->getSourceNodeId()J (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden method Landroid/view/accessibility/AccessibilityRecord;->getSourceNodeId()J (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden field Landroid/view/accessibility/AccessibilityNodeInfo;->mChildNodeIds:Landroid/util/LongArray; (greylist, reflection, allowed) W/xample.flutter( 5738): Accessing hidden method Landroid/util/LongArray;->get(I)J (greylist, reflection, allowed) I/Choreographer( 5738): Skipped 53 frames!  The application may be doing too much work on its main thread. D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x70249825f180, tid 5786 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x702497d3e6a0, tid 5955 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 D/EGL_emulation( 5738): eglCreateContext: 0x702497d3e740: maj 3 min 0 rcv 3 D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 D/EGL_emulation( 5738): eglCreateContext: 0x70249825f220: maj 3 min 0 rcv 3 D/EGL_emulation( 5738): eglMakeCurrent: 0x70249825f220: ver 3 0 (tinfo 0x702498218680) W/Gralloc3( 5738): mapper 3.x is not supported D/HostConnection( 5738): createUnique: call D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x70249825f360, tid 5786 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/eglCodecCommon( 5738): allocate: Ask for block of size 0x1000 D/eglCodecCommon( 5738): allocate: ioctl allocate returned offset 0x3ff807000 size 0x2000 D/HostConnection( 5738): createUnique: call D/HostConnection( 5738): HostConnection::get() New Host Connection established 0x702448a9ff00, tid 5955 D/HostConnection( 5738): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0  D/EGL_emulation( 5738): eglMakeCurrent: 0x702497d3e740: ver 3 0 (tinfo 0x70244d193360) D/EGL_emulation( 5738): eglMakeCurrent: 0x70249825f220: ver 3 0 (tinfo 0x702498218680) D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 1 0 I/OpenGLRenderer( 5738): Davey! duration=16105ms; Flags=1, IntendedVsync=320862128930, Vsync=321745462228, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=321750930400, AnimationStart=321751011720, PerformTraversalsStart=321751071720, DrawStart=330820804190, SyncQueued=331199393480, SyncStart=331258181510, IssueDrawCommandsStart=331421431670, SwapBuffers=336112080650, FrameCompleted=337026255970, DequeueBufferDuration=550559000, QueueBufferDuration=35074000,  I/Choreographer( 5738): Skipped 953 frames!  The application may be doing too much work on its main thread. D/EGL_emulation( 5738): eglMakeCurrent: 0x702497d3e740: ver 3 0 (tinfo 0x70244d193360) D/eglCodecCommon( 5738): setVertexArrayObject: set vao to 0 (0) 0 0 I/Choreographer( 5738): Skipped 40 frames!  The application may be doing too much work on its main thread. I/OpenGLRenderer( 5738): Davey! duration=782ms; Flags=0, IntendedVsync=349271346526, Vsync=349938013166, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=349954335870, AnimationStart=349954427840, PerformTraversalsStart=349997031300, DrawStart=349997268140, SyncQueued=349997407090, SyncStart=350019841510, IssueDrawCommandsStart=350019994270, SwapBuffers=350027291360, FrameCompleted=350076153750, DequeueBufferDuration=149000, QueueBufferDuration=9594000,  I/OpenGLRenderer( 5738): Davey! duration=818ms; Flags=0, IntendedVsync=350655153383, Vsync=350755153379, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=350758548020, AnimationStart=350758679460, PerformTraversalsStart=350933225780, DrawStart=351140119140, SyncQueued=351140550980, SyncStart=351159859490, IssueDrawCommandsStart=351159930940, SwapBuffers=351165057370, FrameCompleted=351492805850, DequeueBufferDuration=292974000, QueueBufferDuration=727000,  W/xample.flutter( 5738): Verification of androidx.core.view.DragAndDropPermissionsCompat androidx.core.app.ActivityCompat.requestDragAndDropPermissions(android.app.Activity, android.view.DragEvent) took 201.593ms E/flutter ( 5738): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(multipleRequests, Only one initialize at a time, null) E/flutter ( 5738): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7) E/flutter ( 5738): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18) E/flutter ( 5738): <asynchronous suspension> E/flutter ( 5738): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12) E/flutter ( 5738): #3      SpeechToText.initialize (package:speech_to_text/speech_to_text.dart:174:10) E/flutter ( 5738):
#4      _MyAppState.initSpeechState (package:flutter6/main.dart:34:35) E/flutter ( 5738): #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19) E/flutter ( 5738):
#6      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36) E/flutter ( 5738):
#7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter ( 5738): #8      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11) E/flutter ( 5738): #9   BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5) E/flutter ( 5738): #10   BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7) E/flutter ( 5738): #11   PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9) E/flutter ( 5738): #12     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12) E/flutter ( 5738): #13     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9) E/flutter ( 5738): #14     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8) E/flutter ( 5738): #15 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18) E/flutter ( 5738): #16     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7) E/flutter ( 5738): #17     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19) E/flutter ( 5738):
#18     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter ( 5738):
#19     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter ( 5738):
#20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter ( 5738):
#21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter ( 5738):
#22     _rootRunUnary (dart:async/zone.dart:1196:13) E/flutter ( 5738): #23     _CustomZone.runUnary (dart:async/zone.dart:1085:19) E/flutter ( 5738): #24     _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7) E/flutter ( 5738): #25     _invoke1 (dart:ui/hooks.dart:275:10) E/flutter ( 5738): #26
_dispatchPointerDataPacket (dart:ui/hooks.dart:184:5) E/flutter ( 5738):  I/Choreographer( 5738): Skipped 31 frames!  The application may be doing too much work on its main thread.

Android Studio, flutter and node were installed 3 days ago, I have run the flutter doctor with -v and without the parameter. Previously, some licences unsigned, now that is sorted.

Here is the code I pasted from the above page:

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _hasSpeech = false;
  double level = 0.0;
  double minSoundLevel = 50000;
  double maxSoundLevel = -50000;
  String lastWords = "";
  String lastError = "";
  String lastStatus = "";
  String _currentLocaleId = "";
  List<LocaleName> _localeNames = [];
  final SpeechToText speech = SpeechToText();

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

  Future<void> initSpeechState() async {
    bool hasSpeech = await speech.initialize(
        onError: errorListener, onStatus: statusListener);
    if (hasSpeech) {
      _localeNames = await speech.locales();

      var systemLocale = await speech.systemLocale();
      _currentLocaleId = systemLocale.localeId;
    }

    if (!mounted) return;

    setState(() {
      _hasSpeech = hasSpeech;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Speech to Text Example'),
        ),
        body: Column(children: [
          Center(
            child: Text(
              'Speech recognition available',
              style: TextStyle(fontSize: 22.0),
            ),
          ),
          Container(
            child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(
                      child: Text('Initialize'),
                      onPressed: _hasSpeech ? null : initSpeechState,
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(
                      child: Text('Start'),
                      onPressed: !_hasSpeech || speech.isListening
                          ? null
                          : startListening,
                    ),
                    FlatButton(
                      child: Text('Stop'),
                      onPressed: speech.isListening ? stopListening : null,
                    ),
                    FlatButton(
                      child: Text('Cancel'),
                      onPressed: speech.isListening ? cancelListening : null,
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    DropdownButton(
                      onChanged: (selectedVal) => _switchLang(selectedVal),
                      value: _currentLocaleId,
                      items: _localeNames
                          .map(
                            (localeName) => DropdownMenuItem(
                          value: localeName.localeId,
                          child: Text(localeName.name),
                        ),
                      )
                          .toList(),
                    ),
                  ],
                )
              ],
            ),
          ),
          Expanded(
            flex: 4,
            child: Column(
              children: <Widget>[
                Center(
                  child: Text(
                    'Recognized Words',
                    style: TextStyle(fontSize: 22.0),
                  ),
                ),
                Expanded(
                  child: Stack(
                    children: <Widget>[
                      Container(
                        color: Theme.of(context).selectedRowColor,
                        child: Center(
                          child: Text(
                            lastWords,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      Positioned.fill(
                        bottom: 10,
                        child: Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            width: 40,
                            height: 40,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              boxShadow: [
                                BoxShadow(
                                    blurRadius: .26,
                                    spreadRadius: level * 1.5,
                                    color: Colors.black.withOpacity(.05))
                              ],
                              color: Colors.white,
                              borderRadius:
                              BorderRadius.all(Radius.circular(50)),
                            ),
                            child: IconButton(icon: Icon(Icons.mic),

                                onPressed: () {
                              /*...*/
                            }
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Column(
              children: <Widget>[
                Center(
                  child: Text(
                    'Error Status',
                    style: TextStyle(fontSize: 22.0),
                  ),
                ),
                Center(
                  child: Text(lastError),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 20),
            color: Theme.of(context).backgroundColor,
            child: Center(
              child: speech.isListening
                  ? Text(
                "I'm listening...",
                style: TextStyle(fontWeight: FontWeight.bold),
              )
                  : Text(
                'Not listening',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ]),
      ),
    );
  }

  void startListening() {
    lastWords = "";
    lastError = "";
    speech.listen(
        onResult: resultListener,
        listenFor: Duration(seconds: 10),
        localeId: _currentLocaleId,
        onSoundLevelChange: soundLevelListener,
        cancelOnError: true,
        partialResults: true);
    setState(() {});
  }

  void stopListening() {
    speech.stop();
    setState(() {
      level = 0.0;
    });
  }

  void cancelListening() {
    speech.cancel();
    setState(() {
      level = 0.0;
    });
  }

  void resultListener(SpeechRecognitionResult result) {
    setState(() {
      lastWords = "${result.recognizedWords} - ${result.finalResult}";
    });
  }

  void soundLevelListener(double level) {
    minSoundLevel = min(minSoundLevel, level);
    maxSoundLevel = max(maxSoundLevel, level);
    //print("sound level $level: $minSoundLevel - $maxSoundLevel ");
    setState(() {
      this.level = level;
    });
  }

  void errorListener(SpeechRecognitionError error) {
    print("Received error status: $error, listening: ${speech.isListening}");
    setState(() {
      lastError = "${error.errorMsg} - ${error.permanent}";
    });
  }

  void statusListener(String status) {
    print(
        "Received listener status: $status, listening: ${speech.isListening}");
    setState(() {
      lastStatus = "$status";
    });
  }

  _switchLang(selectedVal) {
    setState(() {
      _currentLocaleId = selectedVal;
    });
    print(selectedVal);
  }
}

I have imported the package by adding a dependency to yaml and importing the pub, and have run out of any further ideas. Please help.
Thank you.


来源: stackexchange

问:
Push Notification for android in wcf data service
is there any sample code or project available for implementing android push notification service in c#.
i want to develope a data service to send notification to android phones is there any API or Helper class available for implementing android push notification in c#.</p>

答: I'm almost sure that WCF and especially WCF data services are not technologies designed for PUSH notifications - WCF services are designed for PULL scenarios (= pooling). The only exception are duplex WCF services which introduce large complexity and are not interoperable. WCF Data Services are based on REST / OData and doesn't support PUSH.</p>

ContentLicense: CC BY-SA 3.0


问:
How to send messages between a web client and a JADE multi-agent system?
I am working on a JADE project and I want to build a React app to interact with my agents.

I would like to send messages to specific agents from my web client using REST. I know that it is possible to send POST requests, but what the body should look like ?

答:
if you create an agent programmatically you can sent message to the agent by means of AgentController.putO2AObject, but you need server code that processes your rest message and delegate it to the agent.

Otherwise you can just create java.net.ServerSocket in agent code and sent any message you want from your client

ContentLicense: CC BY-SA 4.0


问:
Bash check element in array for elements in another array
I came over this cool Bash function for checking if an array contains an element:

```<code>CONTAINS_ELEMENT(){
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}
</code>```

Here is an example of it's usage:

```<code>if CONTAINS_ELEMENT $element "${array[@]}"; then
...
fi
</code>```

My question is this:
Is there a way to rewrite this function so that it can check if any value within an
array is equal to any value withing the other array, and not just check for one single
value as it corrently does?

答:
Loop inside loop:

```<code>#!/bin/bash
clear

arrA=("a" "b" "c" "d" "e" "f")
arrZERO=("c" "e") # must be turned to "0"

echo "arrA:"
echo ${arrA[@]}
echo ""
echo "arrZERO:"
echo ${arrZERO[@]}

for (( i=0; i < ${#arrA[@]}; i++ ))
do
    for (( j=0; j < ${#arrZERO[@]}; j++ ))
    do
        if [[ ${arrA[$i]} = ${arrZERO[$j]} ]]; then
            arrA[$i]="0"
        fi
    done
done

echo ""
echo "FINAL"
echo ${arrA[@]}
</code>```

Terminal will show:

```<code>arrA:
a b c d e f

arrZERO:
c e

FINAL
a b 0 d 0 f
</code>```

Body:
I came over this cool Bash function for checking if an array contains an element:

CONTAINS_ELEMENT(){
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}

Here is an example of it's usage:

if CONTAINS_ELEMENT $element "${array[@]}"; then
...
fi

My question is this:
Is there a way to rewrite this function so that it can check if any value within an
array is equal to any value withing the other array, and not just check for one single
value as it corrently does?

Body:
Loop inside loop:

#!/bin/bash
clear

arrA=("a" "b" "c" "d" "e" "f")
arrZERO=("c" "e") # must be turned to "0"

echo "arrA:"
echo ${arrA[@]}
echo ""
echo "arrZERO:"
echo ${arrZERO[@]}

for (( i=0; i < ${#arrA[@]}; i++ ))
do
    for (( j=0; j < ${#arrZERO[@]}; j++ ))
    do
        if [[ ${arrA[$i]} = ${arrZERO[$j]} ]]; then
            arrA[$i]="0"
        fi
    done
done

echo ""
echo "FINAL"
echo ${arrA[@]}

Terminal will show:

arrA:
a b c d e f

arrZERO:
c e

FINAL
a b 0 d 0 f


问:
Rendered newlines in key causing improper format
I have a ssh key that I am storing in AWS Parameter store. As part of some process I retrieve the key from the paramstore. However, when I use it in ssh I get a invalid format error. When I inspect the file, instead of the normal key file like:

```<code>-----BEGIN OPENSSH PRIVATE KEY-----
<line of chars>
<line of chars>
...
<line of chars>
-----END OPENSSH PRIVATE KEY-----
</code>```

What I find is that the file instead looks like:

```<code>-----BEGIN OPENSSH PRIVATE KEY-----\n<line of chars>\n<line of chars>\n...<line of chars>\n-----END OPENSSH PRIVATE KEY-----
</code>```

AFAIK, these two files should render in the same way, but they don't, and I suspect thats why the ssh command is failing.

1) How do I fix the key file such that it will now be in the correct format? I cant replace the newlines with other newlines. Ideally I would use sed or some other *nix command, but I don't know what to to the file.

2) Why is it that sometimes newlines get represented as actual newlines, and sometimes get represented as string characters?

EDIT:
Basically I want to do this but in reverse.

答: Found the answer by adapting this: cat ~/.ssh/weirdpemkey | sed 's/\\n/\'$'\n/g'

Body:
I have a ssh key that I am storing in AWS Parameter store. As part of some process I retrieve the key from the paramstore. However, when I use it in ssh I get a invalid format error. When I inspect the file, instead of the normal key file like:

-----BEGIN OPENSSH PRIVATE KEY-----
<line of chars>
<line of chars>
...
<line of chars>
-----END OPENSSH PRIVATE KEY-----

What I find is that the file instead looks like:

-----BEGIN OPENSSH PRIVATE KEY-----\n<line of chars>\n<line of chars>\n...<line of chars>\n-----END OPENSSH PRIVATE KEY-----

AFAIK, these two files should render in the same way, but they don't, and I suspect thats why the ssh command is failing.

1) How do I fix the key file such that it will now be in the correct format? I cant replace the newlines with other newlines. Ideally I would use sed or some other *nix command, but I don't know what to to the file.

2) Why is it that sometimes newlines get represented as actual newlines, and sometimes get represented as string characters?

EDIT:
Basically I want to do this but in reverse.


问:
How to create a unique string/key form JavaScript object?
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

```<code>let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}
</code>```

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.

答:
You could create a sorted array of all keys (to make sure that values with the same key are compared), then map those keys to the related values and use JSON.stringify on the array of values:

```<code>  JSON.stringify(
    Object.keys(obj)
    .sort()
    .map(k => obj[k])
 )
</code>```

Body:
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.

Body:
You could create a sorted array of all keys (to make sure that values with the same key are compared), then map those keys to the related values and use JSON.stringify on the array of values:

  JSON.stringify(
    Object.keys(obj)
    .sort()
    .map(k => obj[k])
 )


问:
Getting junk values within response from firebase APIs while calling getIdToken

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}```

I was doing a firebase authentication through google , while calling an api from service
getting values like below format,
  const token =(await this.afAuth.currentUser).getIdToken();

console.log(token);
==> "D {a: 0, i: undefined, c: D, b: null, f: null, …}  " getting an extra D , So not able to extract the token alone from this structure, Attaching the service calls above. Thanks in advance,

Please let me know anything more needed :)

答:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}```

< router >

Body:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}

I was doing a firebase authentication through google , while calling an api from service
getting values like below format,
  const token =(await this.afAuth.currentUser).getIdToken();

console.log(token);
==> "D {a: 0, i: undefined, c: D, b: null, f: null, …}  " getting an extra D , So not able to extract the token alone from this structure, Attaching the service calls above. Thanks in advance,

Please let me know anything more needed :)

Body:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}

< router >


问:
What's the Android's Renderscript equivalent for iOS and Windows Phone?
Renderscript is an Android computation engine that lets you use CPU/GPU native hardware acceleration in order to boost applications, for example in image processing and computer vision algorithms.

Is there a similar thing in iOS and Windows Phone 7/8?

答: I can't speak for Windows Phone but on iOS it would be Apple Metal, its language specification being almost same as renderscript c99.</p>


问:
grails and AJAX dynamic search
I want to organize search by users usernames.
When I write some letters, I want to see list of users,
which usernames start  with that letters.
After clicking one of values I have to update users data.

Is there any easy plugin or other way to do it?

I use grail-1.3.2.

答:
You may want to catch the keypress event at the text box: after the user has type, says, 2 letters, use ajax/jQuery to send a request to the server. Then the server perform searching the database and return a list of approriate user.

I once used jquery-ui plugin, and the result is satisfactory.

Title: grails and AJAX dynamic search


问:
Checking if a message is a DM. (Discord.js and discord.js-commando)
How can I check if a message is a DM in Discord.js? I have tried several ways on how to test against this, I have tried these methods:

```<code>if (msg.channel.isDM) ... Produced undefined
if (msg.isDM) ... Produced undefined
if (msg.channel.DMChannel.isDM) ... produced undefined
if (msg.DMChannel) ... produced undefined
if (msg.channel.DMChannel.dm) ... produced undefined
if (msg.channel.dm) ... produced undefined
</code>```

I have tried everything after producing msg in a console, and trying to decipher where the heck I do this at. Even the documentation isn't very clear on WHERE to check for this at. I have looked at multiple "solutions" who just spout <message>.channel.dm. Well... that doesn't work.

EDIT:
So it does seem it is <message>.isDM. However, in my commands this does not work. I can find isDM in the array and when I console.log(msg) it produced true which is expected. However, doing console.log(msg.isDM) is printing out undefined. It seems weird because it obviously is defined.

答:
client.GetDMChannelAsync(msg.Channel.Id).Result != null

This is how you check that in the latest version

Body:
How can I check if a message is a DM in Discord.js? I have tried several ways on how to test against this, I have tried these methods:

if (msg.channel.isDM) ... Produced undefined
if (msg.isDM) ... Produced undefined
if (msg.channel.DMChannel.isDM) ... produced undefined
if (msg.DMChannel) ... produced undefined
if (msg.channel.DMChannel.dm) ... produced undefined
if (msg.channel.dm) ... produced undefined

I have tried everything after producing msg in a console, and trying to decipher where the heck I do this at. Even the documentation isn't very clear on WHERE to check for this at. I have looked at multiple "solutions" who just spout <message>.channel.dm. Well... that doesn't work.

EDIT:
So it does seem it is <message>.isDM. However, in my commands this does not work. I can find isDM in the array and when I console.log(msg) it produced true which is expected. However, doing console.log(msg.isDM) is printing out undefined. It seems weird because it obviously is defined.


问:
Class 'App\Http\Controllers\Excel' not found in Laravel
In my controller I have the code as below:

```<code>Excel::create('Laravel Excel', function($excel) {

        $excel->sheet('Excel sheet', function($sheet) {

            $sheet->setOrientation('landscape');

        });

    })->export('xls');
</code>```

In config/app.php in aliases array i have defined this:

```<code>'Excel'     => 'Maatwebsite\Excel\ExcelServiceProvider',
</code>```

I dont know why i cant make it work this library...
Any idea?

答:
In laravel 5.4, First install the composer using following command

```<code>composer require maatwebsite/excel:~2.1
</code>```

then, add the following in config/app.php file providers

```<code>Maatwebsite\Excel\ExcelServiceProvider::class,
</code>```

then, add the following in config/app.php file aliases

```<code>'Excel' => Maatwebsite\Excel\Facades\Excel::class,
</code>```

then, add this in your controller file

```<code>use Excel;
</code>```

Body:
In my controller I have the code as below:

Excel::create('Laravel Excel', function($excel) {

        $excel->sheet('Excel sheet', function($sheet) {

            $sheet->setOrientation('landscape');

        });

    })->export('xls');

In config/app.php in aliases array i have defined this:

'Excel'     => 'Maatwebsite\Excel\ExcelServiceProvider',

I dont know why i cant make it work this library...
Any idea?

Body:
In laravel 5.4, First install the composer using following command

composer require maatwebsite/excel:~2.1

then, add the following in config/app.php file providers

Maatwebsite\Excel\ExcelServiceProvider::class,

then, add the following in config/app.php file aliases

'Excel' => Maatwebsite\Excel\Facades\Excel::class,

then, add this in your controller file

use Excel;


问:
Unknown error has occurred in Cloud Functions
First, it looks like this thread but it is not: An unknown error has occurred in Cloud Function: GCP Python

I deployed a couple of times Cloud Functions and they are still working fine. Nevertheless, since last week, following the same procedure I can deploy correctly, but testing them I get the error "An unknown error has occurred in Cloud Functions. The attempted action failed. Please try again, send feedback".

In remote the script works perfectly and writes in Cloud Storage.

My Cloud Function is a zip with a python script, loading a csv in Cloud Storage.

The csv weights 160kB, the python script 5kB. So I used 128MiB of memory allocated.

The execution time is 38 secs, almost half of the default timeout.

It is configured to allow just traffic within the project.

Env variables are not the problem

It's triggered by pub/sub and what I want is to schedule it when I can make it work.

I'm quite puzzled. I have such a lack of ideas right now that I started to think everything works fine but the Google testing method is what is fails... Nevertheless when I run the pub/sub topic in Cloud Scheduler it launches the error log without much info 1. By any chance anyone had the same problem?

Thanks

答:
Answer of myself from the past:

Finally "solved". I'm a processing a csv in the CF of 160kB, in my computer the execution time lasts 38 seconds. For some reason in the CF I need 512MB of Allocated Memory and a timeout larger than 60 secs.

Answer of myself from a closest past:

Don't test a CF using the test button, because sometimes it takes more than the max available timeout to finish, hence you'll get errors.

If you want to test it easily

Write prints after milestones in your code to check how the script is evolving.

Use the logs interface. The prints will be displayed there ;)

Also, logs show valuable info (sometimes even readable).

Also, if you're sending for example, to buckets, check them after the CF is finished, maybe you get a surprise.

To sum up, don't believe blindly in the testing button.

Answer of myself from the present (already regretting the prints thing):

There are nice python libraries to check logs, don't print stuff for that (if you have time).


问:
Duplicate data when working with multiple tables. Clarification needed
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

```<code>DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'
</code>```

答:
You are getting 0 because of the below case statement. If your value is null and statementitem is not 'Revenues' and periodtype is not 'Annual',  you are a making it as 0

```<code>case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual'
then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0
</code>```

You can get rid of these if you don't want 0's in your result.

This will give you without 0's but with nulls,

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,
a.value as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
</code>```

This query will give you no nulls,

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,
 a.value  as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
and (a.value is null or a.value = '')
</code>```

Without Inner join,

```<code>SELECT distinct a.yearmonth, a.symbol, periodtype,
a.value  as Revenue
from Income a
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
and (a.value is null or a.value = '')
and a.symbol in ('AAPL');
</code>```

Body:
I have a very simple table as shown when query returning clean data select * from Income where symbol = 'AAPL' and statementitem = 'Revenues' and periodtype="Annual";

--

When I attempt to put together a report, I get 0 from someplace. How can I remove the 0 to get a clean output? Where do these 0s come from?

DROP TABLE IF EXISTS _vars;
CREATE TABLE _vars(symbol);
INSERT INTO  _vars(symbol) VALUES ('AAPL');

SELECT distinct a.yearmonth, a.symbol, periodtype,

      case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end Revenue,
      case when a.statementitem = 'Gross Profit' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit,
      case when a.statementitem = 'Selling General & Admin Expenses' AND a.periodtype = 'Annual' then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0 end GrossProfit

FROM _vars
INNER JOIN Income a ON a.symbol = _vars.symbol and a.periodtype = 'Annual'

Body:
You are getting 0 because of the below case statement. If your value is null and statementitem is not 'Revenues' and periodtype is not 'Annual',  you are a making it as 0

case when a.statementitem = 'Revenues' AND a.periodtype = 'Annual'
then (CASE WHEN (a.value is null or a.value = '') then 0 ELSE a.value  END) else 0

You can get rid of these if you don't want 0's in your result.

This will give you without 0's but with nulls,

SELECT distinct a.yearmonth, a.symbol, periodtype,
a.value as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'

This query will give you no nulls,

SELECT distinct a.yearmonth, a.symbol, periodtype,
 a.value  as Revenue
FROM _vars
inner JOIN Income a ON a.symbol = _vars.symbol
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
and (a.value is null or a.value = '')

Without Inner join,

SELECT distinct a.yearmonth, a.symbol, periodtype,
a.value  as Revenue
from Income a
where  a.statementitem = 'Revenues' and a.periodtype = 'Annual'
and (a.value is null or a.value = '')
and a.symbol in ('AAPL');


问:
Unable to add Firebase Dynamic Links to a project using a custom domain
I've created Firebase Dynamic Links in other projects before using the page.link URL prefix (the only option at the time). However that no longer appears to be an option when enabling Dynamic Links for a new project today. It looks like the docs for custom domains were updated today. Unfortunately, while they provide some helpful examples, they don't explain how to resolve my issue in a way that I can understand.

So this message seems to indicate that I need to "Put links under a subpath". It seems to me that adding the /link path prefix here should accomplish that? But after making that change, I get the same error message.

It looks like you already have content served on this Hosting site. Put links under a subpath to avoid conflicts with existing content.

I order to try to work around this, I went to my project and added the suggested Hosting configuration and deployed it.

firebase.json:

```<code>{
  "hosting": {
    "public": "dist",
    "ignore": [
      "**/.*"
    ],
    "appAssociation": "AUTO",
    "rewrites": [
      {
        "source": "/link/**",
        "dynamicLinks": true
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
</code>```

Even after waiting an hour, I keep getting the same error and I don't understand what to do.

Note that I have the rewrite to /index.html because I have an Angular Single Page Application hosted at www.devintent.com.

No matter what I do, I keep getting this error and the Continue button stays disabled. I tried using my naked domain devintent.com instead of www.devintent.com, but that didn't help. I tried using links.devintent.com, but got the same error.

If I manually remove disabled from the Continue button, then I get this error message:

This links to the docs for manually configuring hosting for dynamic links which has some steps that I've already completed. Clicking the Check Again button just takes me back to the same error in the first image above.

Workaround to not use Custom Domains

I'm happy at this time to use a page.link link, I just need to create a Dynamic Link and get unblocked on this task, but I can't figure out any way in the console to allow me to do that either.

Update on this: I figured out that I needed to add the subdomain to the page.link URL. The tooltip says "or a free Google-provided domain (for example, yourapp.page.link)" at the end. This is a little less prominent that I would have liked (as I didn't find it for quite a long time). Using devintent.page.link works for me as a workaround for now.

However, I'm not sure why the Custom Domain configuration didn't work and why it would be the default if there are such complications with projects with existing Hosting configurations and custom domains.

答:
```<code>"appAssociation": "AUTO",
"rewrites": [
  {
    "source": "/page/**",
    "destination": "/index.html"
  },
  {
    "source": "/link/**",
    "dynamicLinks": true
  }
]
</code>```

<p>It works! I guess the error caused by the original config of "source":"**". May be the range is too large? Though doc say "/__/*" have high priority. (https://firebase.google.com/docs/hosting/full-config?authuser=0#hosting_priority_order) </p>

Body:
I've created Firebase Dynamic Links in other projects before using the page.link URL prefix (the only option at the time). However that no longer appears to be an option when enabling Dynamic Links for a new project today. It looks like the docs for custom domains were updated today. Unfortunately, while they provide some helpful examples, they don't explain how to resolve my issue in a way that I can understand.

So this message seems to indicate that I need to "Put links under a subpath". It seems to me that adding the /link path prefix here should accomplish that? But after making that change, I get the same error message.

It looks like you already have content served on this Hosting site. Put links under a subpath to avoid conflicts with existing content.

I order to try to work around this, I went to my project and added the suggested Hosting configuration and deployed it.

firebase.json:

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "**/.*"
    ],
    "appAssociation": "AUTO",
    "rewrites": [
      {
        "source": "/link/**",
        "dynamicLinks": true
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Even after waiting an hour, I keep getting the same error and I don't understand what to do.

Note that I have the rewrite to /index.html because I have an Angular Single Page Application hosted at www.devintent.com.

No matter what I do, I keep getting this error and the Continue button stays disabled. I tried using my naked domain devintent.com instead of www.devintent.com, but that didn't help. I tried using links.devintent.com, but got the same error.

If I manually remove disabled from the Continue button, then I get this error message:

This links to the docs for manually configuring hosting for dynamic links which has some steps that I've already completed. Clicking the Check Again button just takes me back to the same error in the first image above.

Workaround to not use Custom Domains

I'm happy at this time to use a page.link link, I just need to create a Dynamic Link and get unblocked on this task, but I can't figure out any way in the console to allow me to do that either.

Update on this: I figured out that I needed to add the subdomain to the page.link URL. The tooltip says "or a free Google-provided domain (for example, yourapp.page.link)" at the end. This is a little less prominent that I would have liked (as I didn't find it for quite a long time). Using devintent.page.link works for me as a workaround for now.

However, I'm not sure why the Custom Domain configuration didn't work and why it would be the default if there are such complications with projects with existing Hosting configurations and custom domains.

Body:
"appAssociation": "AUTO",
"rewrites": [
  {
    "source": "/page/**",
    "destination": "/index.html"
  },
  {
    "source": "/link/**",
    "dynamicLinks": true
  }
]

It works! I guess the error caused by the original config of "source":"**". May be the range is too large? Though doc say "/__/*" have high priority. (https://firebase.google.com/docs/hosting/full-config?authuser=0#hosting_priority_order)


问:
HTML5 DIV flashes on tap
When receving an onclick event from a DIV as a result of a tap on the iPad, The DIV automatically flashes to a dark color to give the user feedback for the tap. Is there any way to prevent this flash from occurring? </p>

答: Maybe try adding a class for div.stylename:active ? give the background the same colour as the div.

Title: HTML5 DIV flashes on tap


问:
Continuing a Project using Pycharm instead of Visual Studio
I am currently in the middle of a Django project and considering switching from Visual Studio Code to Pycharm but after activating the Virtual Env it is not showing any Project Interpreter.

Also when I type in the terminal python manage.py runserver it is saying bash: python: command not found

Is there a way to continue the project using pycharm or do I have to install everything from start?

答: if your using linux then install django to your project,  pip install django</p>


问:
Adding environment variables to Spring's application.properties
I want to run two Amazon S3's SDK information from the application.properties, but instead of putting it in the file, I want to add them when running ./mvnw spring-boot:run. I saw something like this could be done:

```<code>./mvnw spring-boot:run -Dspring-boot.run.arguments="--srp.storage.s3.access-key=FOOBARFOOBAR,--srp.storage.s3.secret-key=foobarfoobarfoobarfoobarfoobar"
</code>```

I tried running the command above with quotes around the arguments and with/without whitespace between them. Also, I tried leaving blank values in the properties files as well as removing them at all.

```<code># srp.storage.s3.access-key=
# srp.storage.s3.secret-key=
</code>```

```<code>srp.storage.s3.access-key=
srp.storage.s3.secret-key=
</code>```

I have a class annotated with @ConfigurationProperties("srp.storage"). The results of these attempts varied from application failing to start because no property was found by the class, to actually running but taking no effect. The variations of the command that caused the server not to start was not specifying any property in application.properties and attempting to run the command with and without quotes and no whitespace. The scenario that it ran but did not take effect was putting whitespace.

I know about running it using the built JAR file, but I want to be able, if possible, to run it like that just to prevent building every time I change something.

Also attempted to specify placeholder as shown here, but again no success. Can I even do what I want using ./mvnw? Or must it be with a JAR file?

```<code>srp.storage.s3.access-key=${access-key}
srp.storage.s3.secret-key=${secret-key}
</code>```

```<code>./mvnw spring-boot:run -Dspring-boot.run.arguments="--access-key=FOOBARFOOBAR,--secret-key=foobarfoobarfoobarfoobarfoobar"
</code>```

答:
Solved using environment variables. That's good enough for me.
It goes without saying you can choose any name you want for the property in Spring's file and variable, just remember that in Linux environments you must set the variable names all capital letters and use underscore.

In .bashrc or .zshrc or similar, add:

```<code>export AWS_S3_ACCESS_KEY=FOOBARFOOBAR
export AWS_S3_SECRET_KEY=foobarfoobarfoobarfoobarfoobar
</code>```

And as shown before, in the application.properties file, add;

```<code>srp.storage.s3.access-key=${AWS_S3_ACCESS_KEY}
srp.storage.s3.secret-key=${AWS_S3_SECRET_KEY}
</code>```

And start normally. Much better.

Body:
I want to run two Amazon S3's SDK information from the application.properties, but instead of putting it in the file, I want to add them when running ./mvnw spring-boot:run. I saw something like this could be done:

./mvnw spring-boot:run -Dspring-boot.run.arguments="--srp.storage.s3.access-key=FOOBARFOOBAR,--srp.storage.s3.secret-key=foobarfoobarfoobarfoobarfoobar"

I tried running the command above with quotes around the arguments and with/without whitespace between them. Also, I tried leaving blank values in the properties files as well as removing them at all.

# srp.storage.s3.access-key=
# srp.storage.s3.secret-key=

srp.storage.s3.access-key=
srp.storage.s3.secret-key=

I have a class annotated with @ConfigurationProperties("srp.storage"). The results of these attempts varied from application failing to start because no property was found by the class, to actually running but taking no effect. The variations of the command that caused the server not to start was not specifying any property in application.properties and attempting to run the command with and without quotes and no whitespace. The scenario that it ran but did not take effect was putting whitespace.

I know about running it using the built JAR file, but I want to be able, if possible, to run it like that just to prevent building every time I change something.

Also attempted to specify placeholder as shown here, but again no success. Can I even do what I want using ./mvnw? Or must it be with a JAR file?

srp.storage.s3.access-key=${access-key}
srp.storage.s3.secret-key=${secret-key}

./mvnw spring-boot:run -Dspring-boot.run.arguments="--access-key=FOOBARFOOBAR,--secret-key=foobarfoobarfoobarfoobarfoobar"

Body:
Solved using environment variables. That's good enough for me.
It goes without saying you can choose any name you want for the property in Spring's file and variable, just remember that in Linux environments you must set the variable names all capital letters and use underscore.

In .bashrc or .zshrc or similar, add:

export AWS_S3_ACCESS_KEY=FOOBARFOOBAR
export AWS_S3_SECRET_KEY=foobarfoobarfoobarfoobarfoobar

And as shown before, in the application.properties file, add;

srp.storage.s3.access-key=${AWS_S3_ACCESS_KEY}
srp.storage.s3.secret-key=${AWS_S3_SECRET_KEY}

And start normally. Much better.


问:
problem about connecting to my Postgres with node.js through knex
I am facing this problem with connecting to my Postgres with node.js through knex. I am trying this for the first time and I ask humbly to help me solving the issue. please help me.

My code is the following. Every time I make a request, PostgreSQL doesn't connect so nothing happens.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex')

const db = knex({
    client: 'pg',
    connection: {
        host: '127.0.0.1',
        user: 'postgres',
        password: '',
        database: 'smart-brain'

    }
});

db.select('*').from('users').then(console.log).catch(console.log);

app.use(cors());

app.post('/signin', (req, res) => {
    if (req.body.email === database.users[0].email &&
        req.body.password === database.users[0].password) {
        res.json('success');
    } else {
        res.status(400).json('error logging in');
    }

})
app.post('/register', (req, res) => {
    const {
        name,
        email,
        password
    } = req.body;
    db('users')
        .returning('*')
        .insert({
            email: email,
            name: name,
            joined: new Date()
        })
        .then(respons => {
            res.json(response);
        }).
    catch(err => res.status(400).json('unable to register'))
})

app.listen(3000, () => {
    console.log('app is running on the port 3000');
});
```

<p>and the response is these on <code>npm</code></p>

<pre class="lang-js prettyprint-override"><code>Error: connect ECONNREFUSED 127.0 .0 .1: 5432
at TCPConnectWrap.afterConnect[as oncomplete](net.js: 1141: 16) {
    errno: 'ECONNREFUSED',
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 5432
}
</code>```

答:
If you are in Ubuntu, then go to the following folder.

/etc/postgresql/{your_pg_version}/main

Or If you are in Windows, then go to the following folder,

C:\Program Files\PostgreSQL\{your_pg_version}\data\

Open the file pg_hba.conf to write with SuperUser/Administrative permission,

Go to the bottom, and put trust at the end of following lines.

```<code># Database administrative login by Unix domain socket
local   all             postgres                                trust

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
</code>```

After that, restart your PostgreSQL server and try again with your code.

Body:
I am facing this problem with connecting to my Postgres with node.js through knex. I am trying this for the first time and I ask humbly to help me solving the issue. please help me.

My code is the following. Every time I make a request, PostgreSQL doesn't connect so nothing happens.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex')

const db = knex({
    client: 'pg',
    connection: {
        host: '127.0.0.1',
        user: 'postgres',
        password: '',
        database: 'smart-brain'

    }
});

db.select('*').from('users').then(console.log).catch(console.log);

app.use(cors());

app.post('/signin', (req, res) => {
    if (req.body.email === database.users[0].email &&
        req.body.password === database.users[0].password) {
        res.json('success');
    } else {
        res.status(400).json('error logging in');
    }

})
app.post('/register', (req, res) => {
    const {
        name,
        email,
        password
    } = req.body;
    db('users')
        .returning('*')
        .insert({
            email: email,
            name: name,
            joined: new Date()
        })
        .then(respons => {
            res.json(response);
        }).
    catch(err => res.status(400).json('unable to register'))
})

app.listen(3000, () => {
    console.log('app is running on the port 3000');
});

and the response is these on npm

Error: connect ECONNREFUSED 127.0 .0 .1: 5432
at TCPConnectWrap.afterConnect[as oncomplete](net.js: 1141: 16) {
    errno: 'ECONNREFUSED',
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 5432
}

Body:
If you are in Ubuntu, then go to the following folder.

/etc/postgresql/{your_pg_version}/main

Or If you are in Windows, then go to the following folder,

C:\Program Files\PostgreSQL\{your_pg_version}\data\

Open the file pg_hba.conf to write with SuperUser/Administrative permission,

Go to the bottom, and put trust at the end of following lines.

# Database administrative login by Unix domain socket
local   all             postgres                                trust

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

After that, restart your PostgreSQL server and try again with your code.


问:
How to input and output A Object data in Android Jetpack Workmanger?
In Android Jetpack WorkManger, define a output data in Worker:

```<code>new Data.Builder().putLong(xxx);
</code>```

there are putLong, putString, putBoolean, BUT there are not define a function to put a Object.

How can i output a Entity Object in Worker.

```<code>public class DownloadDB extends Worker {
    private static final String TAG = "DownloadDB";
    private List<ChoiceTestItem> mChoiceTestItems;

    public DownloadDB(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        downChoiceTestItemFromNetwork();
        HashMap<String, Object> map = new HashMap<>();

        //Wrong Code here!!!
        map.put("a", mChoiceTestItems);
        @SuppressLint("RestrictedApi") Data data = new Data.Builder().putAll(map).build();

        return Result.success(data);
    }
...
</code>```

答:
there are not define a function to put a Object.

Correct. You cannot put arbitrary objects into a Data. As the documentation states: "This is a lightweight container, and should not be considered your data store". Not allowing arbitrary data types is one way they are enforcing this.

How can i output a Entity Object in Worker.

If by "Entity Object" you mean a Room @Entity, put the entity in your database. Put the primary key or other identifier into the Data, and use that to retrieve the entity at a later point from the database.

Body:
In Android Jetpack WorkManger, define a output data in Worker:

new Data.Builder().putLong(xxx);

there are putLong, putString, putBoolean, BUT there are not define a function to put a Object.

How can i output a Entity Object in Worker.

public class DownloadDB extends Worker {
    private static final String TAG = "DownloadDB";
    private List<ChoiceTestItem> mChoiceTestItems;

    public DownloadDB(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        downChoiceTestItemFromNetwork();
        HashMap<String, Object> map = new HashMap<>();

        //Wrong Code here!!!
        map.put("a", mChoiceTestItems);
        @SuppressLint("RestrictedApi") Data data = new Data.Builder().putAll(map).build();

        return Result.success(data);
    }
...


问:
How to get data from textview and checkboxes from dialog?
I have create an EditText button which opens a dialog with bunch of checkboxes and one EditText. In the OnCreate method:

```<code>        skillsEditText = findViewById(R.id.edit_skills);
        skillsEditText.setClickable(true);
        skillsEditText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_skills,null);
                mBuilder.setView(mView);
                specialSkillsDialog = mBuilder.create();
                specialSkillsDialog.setCanceledOnTouchOutside(false);
                specialSkillsDialog.show();
            }
        });

</code>```

After the users clicks Done, I execute the onDoneClick method:

```<code>    public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = findViewById(R.id.edit_custom_text);
        // more code
    }
</code>```

When I run it I get the following error:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
</code>```

From previous threads I learn that those checkboxes and edittext are in the dialog so I can't get them from the MainActivity. What is the best way there to change so it will work?

答:
You need to link them to your dialog.

I.e

```<code>skillCheckbox1 = specialSkillsDialog.findViewById(R.id.someId)
</code>```

do this prior to making the call for IsChecked();

Body:
I have create an EditText button which opens a dialog with bunch of checkboxes and one EditText. In the OnCreate method:

        skillsEditText = findViewById(R.id.edit_skills);
        skillsEditText.setClickable(true);
        skillsEditText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_adding_skills,null);
                mBuilder.setView(mView);
                specialSkillsDialog = mBuilder.create();
                specialSkillsDialog.setCanceledOnTouchOutside(false);
                specialSkillsDialog.show();
            }
        });

After the users clicks Done, I execute the onDoneClick method:

    public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = findViewById(R.id.edit_custom_text);
        // more code
    }

When I run it I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference

From previous threads I learn that those checkboxes and edittext are in the dialog so I can't get them from the MainActivity. What is the best way there to change so it will work?

Body:
You need to link them to your dialog.

I.e

skillCheckbox1 = specialSkillsDialog.findViewById(R.id.someId)

do this prior to making the call for IsChecked();


问:
NSOperation and reloading the parser
I have a parser class that is subclass of NSOperation. It is used to parse the xml and table view is reloaded when the parse is completed. I have a refresh UIBarButtonItem that is used to call the parser and parse the new xml from the link again.

```<code>-(void)refresh {
   [self.queue cancelAllOperations]; //cancel all the current operations
   [self.queue release];
   self.queue=nil;
   self.arrayOfAllPhotos = nil; // The array to load table view
   [self performSelectorOnMainThread:@selector(doItAgain) withObject:nil waitUntilDone:NO];
</code>```

}

```<code>-(void)doItAgain {
   [tableView reloadData];
   NSURL *url = [NSURL URLWithString:@"some url"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLConnection *aconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   self.myConnection = aconnection;
   [aconnection release];
</code>```

}

But, as press refresh button, the app crashes with no message. How do I release the NSOperationQueue and start a new parsing again to load data ?

答:
Your memory management is broken. And you are violating encapsulation. You are calling [self.queue release]. That is reaching into self and breaking it by releasing something self owns.

If I were to reach into your abdomen and release your liver, it might be all for the good of the country, but it probably would be bad for you. This concept is known as encapsulation. The concept is explained here.

Violating encapsulation is bad for any number of reasons and it's bad for self here.

Instead just call self.queue = nil and the setQueue: method will release queue for you when it's the right time (just like it does for arrayOfPhotos).

```<code>[self.queue cancelAllOperations];
self.queue = nil;
self.arrayOfAllPhotos = nil;
</code>```

Taking a step back from the particulars of this issue it appears that you could also spend some time getting a deeper understanding of the MVC paradigm. The WWDC 2010 talk (Session Title: Model-View-Controller for iPhone OS) about it was fantastic and can be found here (you have to log in).

Generally it is a bad idea to conflate networking with your table view controller.

Good luck!

Title: NSOperation and reloading the parser

Body:
I have a parser class that is subclass of NSOperation. It is used to parse the xml and table view is reloaded when the parse is completed. I have a refresh UIBarButtonItem that is used to call the parser and parse the new xml from the link again.

-(void)refresh {
   [self.queue cancelAllOperations]; //cancel all the current operations
   [self.queue release];
   self.queue=nil;
   self.arrayOfAllPhotos = nil; // The array to load table view
   [self performSelectorOnMainThread:@selector(doItAgain) withObject:nil waitUntilDone:NO];

}

-(void)doItAgain {
   [tableView reloadData];
   NSURL *url = [NSURL URLWithString:@"some url"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLConnection *aconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   self.myConnection = aconnection;
   [aconnection release];

}

But, as press refresh button, the app crashes with no message. How do I release the NSOperationQueue and start a new parsing again to load data ?

Body:
Your memory management is broken. And you are violating encapsulation. You are calling [self.queue release]. That is reaching into self and breaking it by releasing something self owns.

If I were to reach into your abdomen and release your liver, it might be all for the good of the country, but it probably would be bad for you. This concept is known as encapsulation. The concept is explained here.

Violating encapsulation is bad for any number of reasons and it's bad for self here.

Instead just call self.queue = nil and the setQueue: method will release queue for you when it's the right time (just like it does for arrayOfPhotos).

[self.queue cancelAllOperations];
self.queue = nil;
self.arrayOfAllPhotos = nil;

Taking a step back from the particulars of this issue it appears that you could also spend some time getting a deeper understanding of the MVC paradigm. The WWDC 2010 talk (Session Title: Model-View-Controller for iPhone OS) about it was fantastic and can be found here (you have to log in).

Generally it is a bad idea to conflate networking with your table view controller.

Good luck!


问:
Remove ArrayOf From asp.net 【core】Web Api xml response
I create default Asp.net core web API solution with Visualstudio 2019.

Change services.AddControllers(); to
services.AddControllers().AddXmlSerializerFormatters();

Send Get Request to https://localhost:xxxxx/weatherforecast.
and I get following response

```<code><ArrayOfWeatherForecast xmlns:xsi="http://www.w3.org.....>
  <WeatherForecast>
  ...
  </WeatherForecast>
......
</ArrayOfWeatherForecast>
</code>```

But I really want to get response like

```<code><WeatherForecasts>
  <WeatherForecast>
  ...
  </WeatherForecast>
......
</WeatherForecasts>
</code>```

I found somes answers about remove arrayof frome asp.net.
Please help me. How to do this in asp.net core.

答:
Have you checked the documentation on Microsoft: https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes

```<code>public class Group {
    [XmlArray("TeamMembers")]
    public Employee[] Employees;
}
</code>```

The attribute gives the name in the serialization like this

```<code><Group>
<TeamMembers>
    <Employee>
        <Name>Haley</Name>
    </Employee>
</TeamMembers>
</Group>
</code>```

Body:
I create default Asp.net core web API solution with Visualstudio 2019.

Change services.AddControllers(); to
services.AddControllers().AddXmlSerializerFormatters();

Send Get Request to https://localhost:xxxxx/weatherforecast.
and I get following response

<ArrayOfWeatherForecast xmlns:xsi="http://www.w3.org.....>
  <WeatherForecast>
  ...
  </WeatherForecast>
......
</ArrayOfWeatherForecast>

But I really want to get response like

<WeatherForecasts>
  <WeatherForecast>
  ...
  </WeatherForecast>
......
</WeatherForecasts>

I found somes answers about remove arrayof frome asp.net.
Please help me. How to do this in asp.net core.

Body:
Have you checked the documentation on Microsoft: https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes

public class Group {
    [XmlArray("TeamMembers")]
    public Employee[] Employees;
}

The attribute gives the name in the serialization like this

<Group>
<TeamMembers>
    <Employee>
        <Name>Haley</Name>
    </Employee>
</TeamMembers>
</Group>


答:
Attempt to invoke virtual method 'boolean
  android.widget.CheckBox.isChecked()' on a null object reference

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

If onProfessionsDoneClick(View view) view coming from Dialog section then pass View's object.

```<code> public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = view.findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = view.findViewById(R.id.edit_custom_text);
        // more code
    }
</code>```

Title: How to get data from textview and checkboxes from dialog?

Body:
Attempt to invoke virtual method 'boolean
  android.widget.CheckBox.isChecked()' on a null object reference

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

If onProfessionsDoneClick(View view) view coming from Dialog section then pass View's object.

 public void onProfessionsDoneClick(View view) {
        CheckBox skillCheckBox1 = view.findViewById(R.id.checkbox_skill1);
        if (skillCheckBox1.isChecked()) {
            allSkills.add(skillCheckBox1.getText().toString());
        }

        // Other checkboxes
        // ...
        TextView textInDialog = view.findViewById(R.id.edit_custom_text);
        // more code
    }