问:
Is there a resource that lists all the symbols HTML supports?
I'm simply trying to find a 'heavy downwards arrow' symbol. It seems that all the resources I've checked so far has iterations of this heavy arrow that point to the right and left, but not down. So I was wondering if there was some 'official' resource out there that has a full list of symbols supported in HTML? I would imagine something like this exists, just can't seem to find it.</p>

答:
Simply using a Search Engine gives the results you seek. The below resources were found in under 30 seconds. It is quicker for you to use a Search Engine than to actually write your Stack Overflow question!

W3 Developer Listing (The canon):

https://dev.w3.org/html5/html-author/charref

Wikipedia:

https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

w3Schools:

https://www.w3schools.com/html/html_symbols.asp

https://www.w3schools.com/charsets/ref_utf_currency.asp

https://www.w3schools.com/charsets/ref_utf_arrows.asp

https://www.w3schools.com/charsets/ref_utf_symbols.asp

And others:

https://www.toptal.com/designers/htmlarrows/symbols/

https://www.freeformatter.com/html-entities.html

http://www.amp-what.com/


来源: stackexchange

问:
Firebase Google Sign In "Unhandled Exception: PlatformException sign_in_failed..."
I know there's a lot of information around the web and I've read all the posts and articles I found on the web and still can't figure it out and google documentation about the errors is very bad. Many people complains about it but I don't see any obvious fix and most people are using debug and development mode to avoid this setup.

I've created a flutter app that needs to make Google Sign In and of course, it don't work.

1) I've created the firebase project, activated the android app project, placed the SHA1 release and the .json on the project.

2) I've followed the flutter docs to release the app (key.properties, changing the signingConfigs and that stuff. App it's not on the Play Store, I'm testing on my phone.

2.1) keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

3) Flutter dependencies:

```<code>firebase_auth: 0.7.0
  google_sign_in: 3.2.4
  cloud_firestore: 0.8.2+3
  fluttertoast: ^2.0.7
  image_picker: 0.4.12+1
  shared_preferences: 0.4.3
  firebase_storage: 1.0.4
  cached_network_image: ^0.7.0
  intl: ^0.15.7
  firebase_core: ^0.2.5
</code>```

4) I'm using the new GoogleAuthProvider.getCredential and not the old SignInWithGoogle

```<code>final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
</code>```

4.1) Built build\app\outputs\apk\debug\app-debug.apk.

5) When I press login I get this errors:

```<code>E/flutter (23045): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter (23045): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
E/flutter (23045): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:217:58)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:256:20)
E/flutter (23045): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:324:48)
E/flutter (23045): #5      _LoginScreenState._handleSignIn (package:flikmechat/login_signup.dart:69:57)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #6      _LoginScreenState._loginPage.<anonymous closure> (package:flikmechat/login_signup.dart:566:52)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #7      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14)
E/flutter (23045): #8      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30)
E/flutter (23045): #9      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
E/flutter (23045): #10     TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9)
E/flutter (23045): #11     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7)
E/flutter (23045): #12     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (23045): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20)
E/flutter (23045): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
E/flutter (23045): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (23045): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (23045): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (23045): #18     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter (23045): #19     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (23045): #20     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (23045): #21     _invoke1 (dart:ui/hooks.dart:233:10)
E/flutter (23045): #22     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
</code>```

Please advise, I really don't know what to do. Thank you so much.

答:
Plenty can go wrong, as I explained in my answer to this question: Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

Make sure to have your  set in your firebase project settings:

ContentLicense: CC BY-SA 4.0

Body:
I know there's a lot of information around the web and I've read all the posts and articles I found on the web and still can't figure it out and google documentation about the errors is very bad. Many people complains about it but I don't see any obvious fix and most people are using debug and development mode to avoid this setup.

I've created a flutter app that needs to make Google Sign In and of course, it don't work.

1) I've created the firebase project, activated the android app project, placed the SHA1 release and the .json on the project.

2) I've followed the flutter docs to release the app (key.properties, changing the signingConfigs and that stuff. App it's not on the Play Store, I'm testing on my phone.

2.1) keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

3) Flutter dependencies:

firebase_auth: 0.7.0
  google_sign_in: 3.2.4
  cloud_firestore: 0.8.2+3
  fluttertoast: ^2.0.7
  image_picker: 0.4.12+1
  shared_preferences: 0.4.3
  firebase_storage: 1.0.4
  cached_network_image: ^0.7.0
  intl: ^0.15.7
  firebase_core: ^0.2.5

4) I'm using the new GoogleAuthProvider.getCredential and not the old SignInWithGoogle

final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

4.1) Built build\app\outputs\apk\debug\app-debug.apk.

5) When I press login I get this errors:

E/flutter (23045): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter (23045): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
E/flutter (23045): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:217:58)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:256:20)
E/flutter (23045): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:324:48)
E/flutter (23045): #5      _LoginScreenState._handleSignIn (package:flikmechat/login_signup.dart:69:57)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #6      _LoginScreenState._loginPage.<anonymous closure> (package:flikmechat/login_signup.dart:566:52)
E/flutter (23045): <asynchronous suspension>
E/flutter (23045): #7      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14)
E/flutter (23045): #8      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30)
E/flutter (23045): #9      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
E/flutter (23045): #10     TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9)
E/flutter (23045): #11     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7)
E/flutter (23045): #12     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (23045): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20)
E/flutter (23045): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
E/flutter (23045): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (23045): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (23045): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (23045): #18     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter (23045): #19     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (23045): #20     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (23045): #21     _invoke1 (dart:ui/hooks.dart:233:10)
E/flutter (23045): #22     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)

Please advise, I really don't know what to do. Thank you so much.


问:
How to cast string to ascii value in java?
I have new assignment and since I am new to JAVA I don't know how to make it work, I have searched this website frequently but all the solutions which were suggested didn't work out for me or I didn't use them properly, I would be grateful if someone helps me...
the code below is the most simple solution I could find but still doesn't work...

I want to get inputs like names from people and change them to numbers (int)...it says it is not possible to cast from string to int ... !!

```<code> package loveindex;
import java.util.Scanner;
//import java.math.BigInteger;

public class LoveIndex {

private static Scanner scan;

public static void main(String[] args) {
    scan = new Scanner(System.in);

    System.out.println("Testing Scanner, write something: ");
    String testi = scan.nextLine();
    System.out.println(testi);
    System.out.println("Testing Scanner, write something: ");
    String testi2 = scan.nextLine();
    System.out.println(testi2);

    int ascii = (int) testi;
    int ascii = (int) testi2;
  }

}
</code>```

答:
Achieve the same in a concise way by employing Java 8's lambda function.
From your comment (at the accepted answer) you need the sum of the characters at the end?</p>

```<code>String str = "name";
int sum = str.chars().reduce(0, Integer::sum);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have new assignment and since I am new to JAVA I don't know how to make it work, I have searched this website frequently but all the solutions which were suggested didn't work out for me or I didn't use them properly, I would be grateful if someone helps me...
the code below is the most simple solution I could find but still doesn't work...

I want to get inputs like names from people and change them to numbers (int)...it says it is not possible to cast from string to int ... !!

 package loveindex;
import java.util.Scanner;
//import java.math.BigInteger;

public class LoveIndex {

private static Scanner scan;

public static void main(String[] args) {
    scan = new Scanner(System.in);

    System.out.println("Testing Scanner, write something: ");
    String testi = scan.nextLine();
    System.out.println(testi);
    System.out.println("Testing Scanner, write something: ");
    String testi2 = scan.nextLine();
    System.out.println(testi2);

    int ascii = (int) testi;
    int ascii = (int) testi2;
  }

}

Body:
Achieve the same in a concise way by employing Java 8's lambda function.
From your comment (at the accepted answer) you need the sum of the characters at the end?

String str = "name";
int sum = str.chars().reduce(0, Integer::sum);


问:
Trying to convert string to datetime using ParseExact
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

```<code>$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)
</code>```

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.

答:
postanote's answer contains effective solutions, but it's worth analyzing the problem.

Firstly, simply casting your string to [datetime] is enough, because your input string is directly recognized according to the rules of the invariant culture that PowerShell applies in this case, irrespective of the current culture (the invariant culture is meant to be culture-neutral and is based on the US-English culture):

```<code>PS> [datetime] "5/29/2019 8:46:47 PM"

Wednesday, May 29, 2019 8:46:47 PM

</code>```

Behind the scenes, PowerShell translates this into the following call:

```<code>[datetime]::Parse("5/29/2019 8:46:47 PM", [cultureinfo]::InvariantCulture)
</code>```

By contrast, Get-Date is sensitive to the current culture:

```<code># Works, but only in cultures that use AM / PM and place the month *first* in
# dates, notably, US-English.
PS> Get-Date -Date "5/29/2019 8:46:47 PM"

Wednesday, May 29, 2019 8:46:47 PM
</code>```

The above would fail in cultures such as fr-FR (French (France)), where it is the day that comes first.

This unfortunate discrepancy in data-type-conversion behavior between casts and cmdlet parameters is a longstanding bug documented in this GitHub issue; for backward-compatibility reasons, however, it won't be fixed.

As for what you tried:

As Lee_Daily points out, your problem is that that your format string, 'MM dd yyyy HH:mm:ss' doesn't match the input date string, "5/29/2019 8:46:47 PM":

HH represents the hour of the day in 24-hour format, whereas your input uses 12-hour format.

The PM in your input is not represented in the format string; use tt to generically represent the AM / PM specifier.

You're using spaces to separate the date components, whereas the input string uses /

Your format string specifies a double-digit month component (MM; e.g., 05), whereas the input has only a single digit (5).

Therefore, you should have used the following:

```<code>PS> [datetime]::ParseExact('5/29/2019 8:46:47 PM','M/d/yyyy h:mm:ss tt', [cultureinfo]::InvariantCulture)

Wednesday, May 29, 2019 8:46:47 PM
</code>```

Note the use of [cultureinfo]::InvariantCulture instead of $null, as the latter would default to the current culture, which means that call may fail in cultures that use localized AM / PM designators (for instance, in the Vietnamese culture (vi-VN), the designators are SA / CH).

Of course, you could have used an appropriate specific culture such as en-US (English (United States)) as well (or assume that your code will never run with any other culture active).

As an aside, note that even / and : in format strings aren't literals: they represent the culture-specific date and time separators, respectively.

To treat them as literals, you'd have to use embedded quoting; e.g., / would be quoted as '/', '"/" or \/

To demonstrate the non-literal interpretation:

```<code>PS> [datetime]::ParseExact('6.2019','M/yyyy', [cultureinfo] 'de-DE')

Saturday, June 1, 2019 12:00:00 AM
</code>```

Note how / matched the culture-appropriate date separator, ..

While the culture-appropriate separators are always used on output formatting, during parsing - as a courtesy -  the literal interpretation of / and : is used as a fallback mechanism:

```<code># Works too - "/" is also recognized as a literal.
PS> [datetime]::ParseExact('6/2019','M/yyyy', [cultureinfo] 'de-DE')

Saturday, June 1, 2019 12:00:00 AM
</code>```

Body:
I am trying to convert a string like this '5/29/2019 8:46:47 PM' to a datetime for use as a PowerShell object but I am getting an error

I am trying to use the [datetime]::ParseExact method

$Date = "5/29/2019 8:46:47 PM"

[datetime]::ParseExact($Date,'MM dd yyyy HH:mm:ss', $null)

Instead of getting a datetime object, I just get this error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Any help will be greatly appreciated.

Body:
postanote's answer contains effective solutions, but it's worth analyzing the problem.

Firstly, simply casting your string to [datetime] is enough, because your input string is directly recognized according to the rules of the invariant culture that PowerShell applies in this case, irrespective of the current culture (the invariant culture is meant to be culture-neutral and is based on the US-English culture):

PS> [datetime] "5/29/2019 8:46:47 PM"

Wednesday, May 29, 2019 8:46:47 PM

Behind the scenes, PowerShell translates this into the following call:

[datetime]::Parse("5/29/2019 8:46:47 PM", [cultureinfo]::InvariantCulture)

By contrast, Get-Date is sensitive to the current culture:

# Works, but only in cultures that use AM / PM and place the month *first* in
# dates, notably, US-English.
PS> Get-Date -Date "5/29/2019 8:46:47 PM"

Wednesday, May 29, 2019 8:46:47 PM

The above would fail in cultures such as fr-FR (French (France)), where it is the day that comes first.

This unfortunate discrepancy in data-type-conversion behavior between casts and cmdlet parameters is a longstanding bug documented in this GitHub issue; for backward-compatibility reasons, however, it won't be fixed.

As for what you tried:

As Lee_Daily points out, your problem is that that your format string, 'MM dd yyyy HH:mm:ss' doesn't match the input date string, "5/29/2019 8:46:47 PM":

HH represents the hour of the day in 24-hour format, whereas your input uses 12-hour format.

The PM in your input is not represented in the format string; use tt to generically represent the AM / PM specifier.

You're using spaces to separate the date components, whereas the input string uses /

Your format string specifies a double-digit month component (MM; e.g., 05), whereas the input has only a single digit (5).

Therefore, you should have used the following:

PS> [datetime]::ParseExact('5/29/2019 8:46:47 PM','M/d/yyyy h:mm:ss tt', [cultureinfo]::InvariantCulture)

Wednesday, May 29, 2019 8:46:47 PM

Note the use of [cultureinfo]::InvariantCulture instead of $null, as the latter would default to the current culture, which means that call may fail in cultures that use localized AM / PM designators (for instance, in the Vietnamese culture (vi-VN), the designators are SA / CH).

Of course, you could have used an appropriate specific culture such as en-US (English (United States)) as well (or assume that your code will never run with any other culture active).

As an aside, note that even / and : in format strings aren't literals: they represent the culture-specific date and time separators, respectively.

To treat them as literals, you'd have to use embedded quoting; e.g., / would be quoted as '/', '"/" or \/

To demonstrate the non-literal interpretation:

PS> [datetime]::ParseExact('6.2019','M/yyyy', [cultureinfo] 'de-DE')

Saturday, June 1, 2019 12:00:00 AM

Note how / matched the culture-appropriate date separator, ..

While the culture-appropriate separators are always used on output formatting, during parsing - as a courtesy -  the literal interpretation of / and : is used as a fallback mechanism:

# Works too - "/" is also recognized as a literal.
PS> [datetime]::ParseExact('6/2019','M/yyyy', [cultureinfo] 'de-DE')

Saturday, June 1, 2019 12:00:00 AM


答: I'm not sure about "official" per se, but I like to use this site to search for codes. For example, one such arrow might be the "downwards black arrow": ⬇ (⬇). There are other arrows you can search for if this one isn't the one you're looking for.

Title: Is there a resource that lists all the symbols HTML supports?

Body: I'm simply trying to find a 'heavy downwards arrow' symbol. It seems that all the resources I've checked so far has iterations of this heavy arrow that point to the right and left, but not down. So I was wondering if there was some 'official' resource out there that has a full list of symbols supported in HTML? I would imagine something like this exists, just can't seem to find it.

Body: I'm not sure about "official" per se, but I like to use this site to search for codes. For example, one such arrow might be the "downwards black arrow": &#11015; (⬇). There are other arrows you can search for if this one isn't the one you're looking for.


问:
Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
The dialog (Google form) for the credentials is opened successfully, but after I fill my credentials I'm getting this error. I followed the instructions from here. Created a Firebase project, enabled the Google Drive API (that's what I need for now) from the Google APIs Console.

The code throwing the exception:

```<code>final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'https://www.googleapis.com/auth/drive',
  ],
);

await _googleSignIn.signIn();
</code>```

That's the stack trace:

```<code>E/flutter ( 5068): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 5068): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter ( 5068): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:551:7)
E/flutter ( 5068): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:292:18)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:226:58)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:268:20)
E/flutter ( 5068): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:339:48)
E/flutter ( 5068): #5      ThatsMyComponentState.theSignInFuction.<anonymous closure> (package:my_app/widgets/my_file.dart:666:45)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter ( 5068): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter ( 5068): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter ( 5068): #9      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter ( 5068): #10     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
E/flutter ( 5068): #11     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter ( 5068): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:184:20)
E/flutter ( 5068): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter ( 5068): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter ( 5068): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter ( 5068): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter ( 5068): #17     _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter ( 5068): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
</code>```

The version of the google_sign_in plugin is 4.0.0.

That's the output of flutter doctot -v:

```<code>[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
• Flutter version 1.0.0 at C:\src\flutter-0.7.3\flutter
• Framework revision 5391447fae (10 weeks ago), 2018-11-29 19:41:26 -0800
• Engine revision 7375a0f414
• Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
• Android SDK at C:\Users\myuser\AppData\Local\Android\Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = C:\Users\myuser\AppData\Local\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
• All Android licenses accepted.

[√] Android Studio (version 3.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 32.0.1
• Dart plugin version 182.5124
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] IntelliJ IDEA Community Edition (version 2018.1)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.6
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
  https://flutter.io/intellij-setup/#installing-the-plugins

[!] VS Code, 64-bit edition (version 1.30.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension not installed; install from
  https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 8.1.0 (API 27) (emulator)

! Doctor found issues in 2 categories.
</code>```

Any help will be much appreciated. Thanks!

答: When I came across this problem, I tried all other solutions described in this post. None of these worked. Eventually I figured it out: In my situation I had to make sure to have my "support email" set.

Body:
The dialog (Google form) for the credentials is opened successfully, but after I fill my credentials I'm getting this error. I followed the instructions from here. Created a Firebase project, enabled the Google Drive API (that's what I need for now) from the Google APIs Console.

The code throwing the exception:

final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'https://www.googleapis.com/auth/drive',
  ],
);

await _googleSignIn.signIn();

That's the stack trace:

E/flutter ( 5068): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 5068): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter ( 5068): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:551:7)
E/flutter ( 5068): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:292:18)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:226:58)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:268:20)
E/flutter ( 5068): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:339:48)
E/flutter ( 5068): #5      ThatsMyComponentState.theSignInFuction.<anonymous closure> (package:my_app/widgets/my_file.dart:666:45)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter ( 5068): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter ( 5068): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter ( 5068): #9      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter ( 5068): #10     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
E/flutter ( 5068): #11     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter ( 5068): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:184:20)
E/flutter ( 5068): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter ( 5068): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter ( 5068): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter ( 5068): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter ( 5068): #17     _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter ( 5068): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)

The version of the google_sign_in plugin is 4.0.0.

That's the output of flutter doctot -v:

[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
• Flutter version 1.0.0 at C:\src\flutter-0.7.3\flutter
• Framework revision 5391447fae (10 weeks ago), 2018-11-29 19:41:26 -0800
• Engine revision 7375a0f414
• Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
• Android SDK at C:\Users\myuser\AppData\Local\Android\Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = C:\Users\myuser\AppData\Local\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
• All Android licenses accepted.

[√] Android Studio (version 3.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 32.0.1
• Dart plugin version 182.5124
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] IntelliJ IDEA Community Edition (version 2018.1)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.6
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
  https://flutter.io/intellij-setup/#installing-the-plugins

[!] VS Code, 64-bit edition (version 1.30.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension not installed; install from
  https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 8.1.0 (API 27) (emulator)

! Doctor found issues in 2 categories.

Any help will be much appreciated. Thanks!


问:
unable to find links in laravel for pagination
i get a json response like this  note i am using GuzzleHttp to call my API

```<code>$response =  $response->getBody()->getContents();
$output = (json_decode($response));
dd(output)
</code>```

```<code>{#232 ▼
  +"current_page": 1
  +"data": array:2 [▼
    0 => {#230 ▼
      +"id": 1
      +"test_col": "Test one"
    }
    1 => {#237 ▼
      +"id": 3
      +"test_col": "Test three"
    }
  ]
  +"first_page_url": "http://api/api/test?page=1"
  +"from": 1
  +"last_page": 8
  +"last_page_url": "http://api/api/test?page=8"
  +"next_page_url": "http://api/api/test?page=2"
  +"path": "http://api/api/test"
  +"per_page": 2
  +"prev_page_url": null
  +"to": 2
  +"total": 15
}
</code>```

and now when i go to my front end and do this

```<code> {{$outputs->links()}}
</code>```

to get the pagination links it shows me an error

ErrorException (E_ERROR) Call to undefined method stdClass::links()

and on my API side i am doing this

```<code>      $results = DB::table('test_table')->paginate(2);
        return ($results);
</code>```

答:
The object from the response ($output) can not have any methods. The response already has links (first_page_url, last_page_url, next_page_url). If you need to HTML rendered links then you can try to create instance of LengthAwarePaginator

```<code>$pagination = new LengthAwarePaginator($outputs->data, $outputs->total, $outputs->per_page, $outputs->current_page);
echo $pagination->links();
</code>```

(not tested)

Body:
i get a json response like this  note i am using GuzzleHttp to call my API

$response =  $response->getBody()->getContents();
$output = (json_decode($response));
dd(output)

{#232 ▼
  +"current_page": 1
  +"data": array:2 [▼
    0 => {#230 ▼
      +"id": 1
      +"test_col": "Test one"
    }
    1 => {#237 ▼
      +"id": 3
      +"test_col": "Test three"
    }
  ]
  +"first_page_url": "http://api/api/test?page=1"
  +"from": 1
  +"last_page": 8
  +"last_page_url": "http://api/api/test?page=8"
  +"next_page_url": "http://api/api/test?page=2"
  +"path": "http://api/api/test"
  +"per_page": 2
  +"prev_page_url": null
  +"to": 2
  +"total": 15
}

and now when i go to my front end and do this

 {{$outputs->links()}}

to get the pagination links it shows me an error

ErrorException (E_ERROR) Call to undefined method stdClass::links()

and on my API side i am doing this

      $results = DB::table('test_table')->paginate(2);
        return ($results);

Body:
The object from the response ($output) can not have any methods. The response already has links (first_page_url, last_page_url, next_page_url). If you need to HTML rendered links then you can try to create instance of LengthAwarePaginator

$pagination = new LengthAwarePaginator($outputs->data, $outputs->total, $outputs->per_page, $outputs->current_page);
echo $pagination->links();

(not tested)


问:
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:

```<code>def nearlyequal(a, b, sigfig=5):
</code>```

The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.

Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:

```<code>assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal(1e4, 1e4 + 1, 5)
assert nearlyequal(0.0, 1e-15, 5)
assert not nearlyequal(0.0, 1e-4, 6)
</code>```

Additional notes:

Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.

Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.

Speed... I've got to compare a lot of numbers so the faster the better.

I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.

答:
There are already plenty of great answers, but here's a think:</p>
```<code>def closeness(a, b):
  """Returns measure of equality (for two floats), in unit
     of decimal significant figures."""
  if a == b:
    return float("infinity")
  difference = abs(a - b)
  avg = (a + b) / 2
  return math.log10(avg / difference)

if closeness(1000, 1000.1) > 3:
  print("Joy!")
</code>```

OwnerDisplayName: Salim Fadhley

Body:
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:

def nearlyequal(a, b, sigfig=5):

The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.

Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:

assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal(1e4, 1e4 + 1, 5)
assert nearlyequal(0.0, 1e-15, 5)
assert not nearlyequal(0.0, 1e-4, 6)

Additional notes:

Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.

Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.

Speed... I've got to compare a lot of numbers so the faster the better.

I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.

LastEditorDisplayName: starblue

Body:
There are already plenty of great answers, but here's a think:

def closeness(a, b):
  """Returns measure of equality (for two floats), in unit
     of decimal significant figures."""
  if a == b:
    return float("infinity")
  difference = abs(a - b)
  avg = (a + b) / 2
  return math.log10(avg / difference)

if closeness(1000, 1000.1) > 3:
  print("Joy!")


问:
Split words and capitalize first character
I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

```<code>String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}
</code>```

答:
tokenize the string and split by space " " and then take each iteration and capitalize it and then put it back together again

read all about string tokenization here

Body:
I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}


问:
Reading a huge .csv file
I'm currently trying to read data from .csv files in Python 2.7 with up to 1 million rows, and 200 columns (files range from 100mb to 1.6gb). I can do this (very slowly) for the files with under 300,000 rows, but once I go above that I get memory errors. My code looks like this:

```<code>def getdata(filename, criteria):
    data=[]
    for criterion in criteria:
        data.append(getstuff(filename, criteron))
    return data

def getstuff(filename, criterion):
    import csv
    data=[]
    with open(filename, "rb") as csvfile:
        datareader=csv.reader(csvfile)
        for row in datareader:
            if row[3]=="column header":
                data.append(row)
            elif len(data)<2 and row[3]!=criterion:
                pass
            elif row[3]==criterion:
                data.append(row)
            else:
                return data
</code>```

The reason for the else clause in the getstuff function is that all the elements which fit the criterion will be listed together in the csv file, so I leave the loop when I get past them to save time.

My questions are:

How can I manage to get this to work with the bigger files?

Is there any way I can make it faster?

My computer has 8gb RAM, running 64bit Windows 7, and the processor is 3.40 GHz (not certain what information you need).

答:
For someone who lands to this question. Using pandas with ‘chunksize’ and ‘usecols’ helped me to read a huge zip file faster than the other proposed options.

```<code>import pandas as pd

sample_cols_to_keep =['col_1', 'col_2', 'col_3', 'col_4','col_5']

# First setup dataframe iterator, ‘usecols’ parameter filters the columns, and 'chunksize' sets the number of rows per chunk in the csv. (you can change these parameters as you wish)
df_iter = pd.read_csv('../data/huge_csv_file.csv.gz', compression='gzip', chunksize=20000, usecols=sample_cols_to_keep)

# this list will store the filtered dataframes for later concatenation
df_lst = []

# Iterate over the file based on the criteria and append to the list
for df_ in df_iter:
        tmp_df = (df_.rename(columns={col: col.lower() for col in df_.columns}) # filter eg. rows where 'col_1' value grater than one
                                  .pipe(lambda x:  x[x.col_1 > 0] ))
        df_lst += [tmp_df.copy()]

# And finally combine filtered df_lst into the final lareger output say 'df_final' dataframe
df_final = pd.concat(df_lst)
</code>```

Title: Reading a huge .csv file

Body:
I'm currently trying to read data from .csv files in Python 2.7 with up to 1 million rows, and 200 columns (files range from 100mb to 1.6gb). I can do this (very slowly) for the files with under 300,000 rows, but once I go above that I get memory errors. My code looks like this:

def getdata(filename, criteria):
    data=[]
    for criterion in criteria:
        data.append(getstuff(filename, criteron))
    return data

def getstuff(filename, criterion):
    import csv
    data=[]
    with open(filename, "rb") as csvfile:
        datareader=csv.reader(csvfile)
        for row in datareader:
            if row[3]=="column header":
                data.append(row)
            elif len(data)<2 and row[3]!=criterion:
                pass
            elif row[3]==criterion:
                data.append(row)
            else:
                return data

The reason for the else clause in the getstuff function is that all the elements which fit the criterion will be listed together in the csv file, so I leave the loop when I get past them to save time.

My questions are:

How can I manage to get this to work with the bigger files?

Is there any way I can make it faster?

My computer has 8gb RAM, running 64bit Windows 7, and the processor is 3.40 GHz (not certain what information you need).

Body:
For someone who lands to this question. Using pandas with ‘chunksize’ and ‘usecols’ helped me to read a huge zip file faster than the other proposed options.

import pandas as pd

sample_cols_to_keep =['col_1', 'col_2', 'col_3', 'col_4','col_5']

# First setup dataframe iterator, ‘usecols’ parameter filters the columns, and 'chunksize' sets the number of rows per chunk in the csv. (you can change these parameters as you wish)
df_iter = pd.read_csv('../data/huge_csv_file.csv.gz', compression='gzip', chunksize=20000, usecols=sample_cols_to_keep)

# this list will store the filtered dataframes for later concatenation
df_lst = []

# Iterate over the file based on the criteria and append to the list
for df_ in df_iter:
        tmp_df = (df_.rename(columns={col: col.lower() for col in df_.columns}) # filter eg. rows where 'col_1' value grater than one
                                  .pipe(lambda x:  x[x.col_1 > 0] ))
        df_lst += [tmp_df.copy()]

# And finally combine filtered df_lst into the final lareger output say 'df_final' dataframe
df_final = pd.concat(df_lst)


问:
How to wait for the promise when using get in Firestore
I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?

Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response.  I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out.  I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response.  Can anyone point me in the right direction?

```<code>      'use strict';

const functions = require('firebase-functions'); //don't forget this one

// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');

const Firestore = require('@google-cloud/firestore');

var doc;

var question1;

const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');

const config = functions.config();

const WELCOME_INTENT = 'Default Welcome Intent';

const app = dialogflow({debug: true});

async function dbaccess(rando) {

console.log("dbaseaccess started")

var currentquestion2 = 'question-' + rando.toString();

var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff

question1 = cityRef.data().n111

} catch(e) {

//error!
}
console.log("one line above return something");

return rando;

}

app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;

switch (intent) {
 case WELCOME_INTENT:

var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);

const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);

break;

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
</code>```

答:
You have 2 options: you can use async/await or you can use Promise.then() depending on how you want the code to execute.

Async/await:

```<code>async function databasetest {
  var cityRef;
  try{
    cityRef = await db.collection('cities').doc('SF');
    // do stuff
  } catch(e) {
    // error!
  }
</code>```

Promise.then():

```<code>db.collection('cities').doc('SF').then((cityRef) => {
  cityRef.get()
    .then(doc => { /* do stuff */ })
    .catch(err => { /* error! */ });
});
</code>```

Body:
I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?

Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response.  I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out.  I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response.  Can anyone point me in the right direction?

      'use strict';

const functions = require('firebase-functions'); //don't forget this one

// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');

const Firestore = require('@google-cloud/firestore');

var doc;

var question1;

const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');

const config = functions.config();

const WELCOME_INTENT = 'Default Welcome Intent';

const app = dialogflow({debug: true});

async function dbaccess(rando) {

console.log("dbaseaccess started")

var currentquestion2 = 'question-' + rando.toString();

var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff

question1 = cityRef.data().n111

} catch(e) {

//error!
}
console.log("one line above return something");

return rando;

}

app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;

switch (intent) {
 case WELCOME_INTENT:

var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);

const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);

break;

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);

Body:
You have 2 options: you can use async/await or you can use Promise.then() depending on how you want the code to execute.

Async/await:

async function databasetest {
  var cityRef;
  try{
    cityRef = await db.collection('cities').doc('SF');
    // do stuff
  } catch(e) {
    // error!
  }

Promise.then():

db.collection('cities').doc('SF').then((cityRef) => {
  cityRef.get()
    .then(doc => { /* do stuff */ })
    .catch(err => { /* error! */ });
});


问:
How to destroy a frame by clicking on a button?
I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.

```<code>public class LoginWindow {

    public void CreateLoginWindow () {

        /** Set Style to Main Frame **/
        JFrame main_window = new JFrame();
        main_window.setUndecorated(true);
        main_window.setLocationRelativeTo(null);
        main_window.setLayout(new BorderLayout());
        main_window.setLayout(new FlowLayout());
        main_window.setVisible(false);
        main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
        main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
        main_window.setSize(1920,1080);
        main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /** Some Codes **/

        JButton login_button = new JButton("Click to Exit");
        login_button.setBounds(920,480,120,45);

        /** Login Button Action **/
        login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            ValidateLogin validateLogin = new ValidateLogin();
            Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
            main_window.dispose();
            }
        });

        main_window.add(login_button);
        main_window.setVisible(true);

    }

}
</code>```

It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.

And this is my ValidateLogin Class :

```<code>public class ValidateLogin {

    public Boolean ValidateLoginAction (String username, String password){

        ConnectToDB validate_login = new ConnectToDB();
        String right_password = validate_login.GetPassOfAnUsername(username);
        if ( right_password.equals(password) ){
            return true;
        } else {
            return false;
        }

    }

}
</code>```

And this is my ConnectToDB Class :

```<code>public class ConnectToDB {

    /** Connect to Database **/
    private Connection connect() {

        String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }

    /** Get Password of an Username **/
    public String GetPassOfAnUsername(String username){

        String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";

        try (Connection connection = this.connect();
             PreparedStatement statement= connection.prepareStatement(password);
             ResultSet results = statement.executeQuery()) {

            return results.getString("Password");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}
</code>```

And this is my MainWindow Class :

```<code>public class MainWindow {

    public static void main(String[] args) {
        LoginWindow loginWindow = new LoginWindow();
        loginWindow.CreateLoginWindow();
    }

}
</code>```

答:
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.</p>

```<code>login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    ValidateLogin validateLogin = new ValidateLogin();
                    Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
                }
                catch(Exception ex) {
                    //handle exception
                }
                finally {
                    main_window.dispose();
                }
            }
        });
</code>```

Body:
I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.

public class LoginWindow {

    public void CreateLoginWindow () {

        /** Set Style to Main Frame **/
        JFrame main_window = new JFrame();
        main_window.setUndecorated(true);
        main_window.setLocationRelativeTo(null);
        main_window.setLayout(new BorderLayout());
        main_window.setLayout(new FlowLayout());
        main_window.setVisible(false);
        main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
        main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
        main_window.setSize(1920,1080);
        main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /** Some Codes **/

        JButton login_button = new JButton("Click to Exit");
        login_button.setBounds(920,480,120,45);

        /** Login Button Action **/
        login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            ValidateLogin validateLogin = new ValidateLogin();
            Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
            main_window.dispose();
            }
        });

        main_window.add(login_button);
        main_window.setVisible(true);

    }

}

It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.

And this is my ValidateLogin Class :

public class ValidateLogin {

    public Boolean ValidateLoginAction (String username, String password){

        ConnectToDB validate_login = new ConnectToDB();
        String right_password = validate_login.GetPassOfAnUsername(username);
        if ( right_password.equals(password) ){
            return true;
        } else {
            return false;
        }

    }

}

And this is my ConnectToDB Class :

public class ConnectToDB {

    /** Connect to Database **/
    private Connection connect() {

        String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }

    /** Get Password of an Username **/
    public String GetPassOfAnUsername(String username){

        String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";

        try (Connection connection = this.connect();
             PreparedStatement statement= connection.prepareStatement(password);
             ResultSet results = statement.executeQuery()) {

            return results.getString("Password");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}

And this is my MainWindow Class :

public class MainWindow {

    public static void main(String[] args) {
        LoginWindow loginWindow = new LoginWindow();
        loginWindow.CreateLoginWindow();
    }

}

Body:
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.

login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    ValidateLogin validateLogin = new ValidateLogin();
                    Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
                }
                catch(Exception ex) {
                    //handle exception
                }
                finally {
                    main_window.dispose();
                }
            }
        });


问:
How to create and populate two dimentional array inside ES6 class constructor
I want to initialize and populate a two-dimensional array, but my solution doesn't seem to work. It only returns a function, not a value.

class Board{
    constructor(width,height,cols,rows)
    {
        this.width=width;
        this.height=height;
        this.cols=cols;
        this.rows=rows;
        this.array= function(){
            let array=[];
            for(let i=0;i<this.cols;i++)
            {
                array[i]=[];
                for(let j=0;j<this.rows;j++){
                    array[i][j]=0;
                }
            }
            return array;
        }
    }
```

答:
There's no need for the inner function, just populate the array and assign it to the property.

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    let array = [];
    for (let i = 0; i < this.cols; i++) {
      array[i] = [];
      for (let j = 0; j < this.rows; j++) {
        array[i][j] = 0;
      }
    }
    this.array = array;
  }
}

const b = new Board(2, 3, 4, 5);
console.log(b.array);```


问:
Collection View inside Table View Cell not being called
I am trying to implement a collection view inside a table view cell.

My table view cell is a xib, and I've dragged a collection view into it.

Then, I created a class and xib for the collection view cell:

```<code>class MyCollectionViewCell: UICollectionViewCell {

    var media: Image?

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func initialize(media: PostImage) {
        self.media = media

        if let url = media.url {
            imageView.kf.setImage(with: URL(string: url))
        }
    }

}
</code>```

And I've given the xib the class "MyCollectionViewCell" and also given it the identifier "MyCollectionViewCell".

Then, in my table view cell class, I have done the following:

```<code>class MyTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    var post: Post!

    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var mediaCollectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()

        mediaCollectionView.delegate = self
        mediaCollectionView.dataSource = self

        let mediaCollectionViewCell = UINib(nibName: "MyCollectionViewCell", bundle: nil)
        mediaCollectionView.register(mediaCollectionViewCell, forCellWithReuseIdentifier: "MyCollectionViewCell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath as IndexPath) as? MyCollectionViewCell else {
            fatalError("The dequeued cell is not an instance of MyCollectionViewCell.")
        }

        let media = post.images[indexPath.row]

        cell.initialize(media: media)

        return cell
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func initialize(post: Post) {
        self.post = post

        title.text = post.title

        self.mediaCollectionView.reloadData()
    }
}
</code>```

The problem is, the collection view never shows when I run this. The title  label text shows fine, but the collection view does not show, and I don't know what I'm doing wrong.

cellForItemAt doesn't even seem to get called, because when I add print("hello") at the top of the function, it never shows up in the console.

What am I doing wrong?

答:
I think the problem is the height of the collection view is very small that it isn't shown.
Try to set the height for the table view cell:

```<code>func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
     return 100
}
</code>```

where the 100 should be bigger than the collection view

Body:
I am trying to implement a collection view inside a table view cell.

My table view cell is a xib, and I've dragged a collection view into it.

Then, I created a class and xib for the collection view cell:

class MyCollectionViewCell: UICollectionViewCell {

    var media: Image?

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func initialize(media: PostImage) {
        self.media = media

        if let url = media.url {
            imageView.kf.setImage(with: URL(string: url))
        }
    }

}

And I've given the xib the class "MyCollectionViewCell" and also given it the identifier "MyCollectionViewCell".

Then, in my table view cell class, I have done the following:

class MyTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    var post: Post!

    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var mediaCollectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()

        mediaCollectionView.delegate = self
        mediaCollectionView.dataSource = self

        let mediaCollectionViewCell = UINib(nibName: "MyCollectionViewCell", bundle: nil)
        mediaCollectionView.register(mediaCollectionViewCell, forCellWithReuseIdentifier: "MyCollectionViewCell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath as IndexPath) as? MyCollectionViewCell else {
            fatalError("The dequeued cell is not an instance of MyCollectionViewCell.")
        }

        let media = post.images[indexPath.row]

        cell.initialize(media: media)

        return cell
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func initialize(post: Post) {
        self.post = post

        title.text = post.title

        self.mediaCollectionView.reloadData()
    }
}

The problem is, the collection view never shows when I run this. The title  label text shows fine, but the collection view does not show, and I don't know what I'm doing wrong.

cellForItemAt doesn't even seem to get called, because when I add print("hello") at the top of the function, it never shows up in the console.

What am I doing wrong?

Body:
I think the problem is the height of the collection view is very small that it isn't shown.
Try to set the height for the table view cell:

func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
     return 100
}

where the 100 should be bigger than the collection view


问:
How to change a boolean value in JavaScript?
I want when my site first loads for a value to be false but when a button is clicked I want it to update the value to make it true.

What I've tried so far:

For the HTML

```<code><button onclick="button1()"></button>
</code>```

For the JavaScript

```<code>let button1pressed = false;

function button1(){
  button1pressed = true;
}
</code>```

But the problem with this is that afterwards I have an if statement

```<code>if(button1pressed === true) {
console.log('The value is now true');
}
</code>```

However the message doesn't log to the console.

How do I solve this problem?

答:
You need to move the condition inside of the event function, because the code is later evaluated and at start the value is false.

function button1(){
    if (!button1pressed) {
        button1pressed = true;
        console.log('The value is now true');
    }
}

let button1pressed = false;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="button1()">click</button></code>```

An other approach is to use an interval with a check and get the message only once.

function button1(){
    button1pressed = true;
}

let button1pressed = false,
    interval = setInterval(function () {
        if (button1pressed) {
            console.log('The value is now true');
            clearInterval(interval);
        }
    }, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="button1()">click</button></code>```

Body:
I want when my site first loads for a value to be false but when a button is clicked I want it to update the value to make it true.

What I've tried so far:

For the HTML

<button onclick="button1()"></button>

For the JavaScript

let button1pressed = false;

function button1(){
  button1pressed = true;
}

But the problem with this is that afterwards I have an if statement

if(button1pressed === true) {
console.log('The value is now true');
}

However the message doesn't log to the console.

How do I solve this problem?

Body:
You need to move the condition inside of the event function, because the code is later evaluated and at start the value is false.

function button1(){
    if (!button1pressed) {
        button1pressed = true;
        console.log('The value is now true');
    }
}

let button1pressed = false;

<button onclick="button1()">click</button>

An other approach is to use an interval with a check and get the message only once.

function button1(){
    button1pressed = true;
}

let button1pressed = false,
    interval = setInterval(function () {
        if (button1pressed) {
            console.log('The value is now true');
            clearInterval(interval);
        }
    }, 1000);

<button onclick="button1()">click</button>


答:
Can be easier

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    this.array = [];
    for (let i = 0; i < this.cols; i++) {
      this.array.push(new Array(this.rows).fill(0));
    }
  }```

Title: How to create and populate two dimentional array inside ES6 class constructor

Body:
I want to initialize and populate a two-dimensional array, but my solution doesn't seem to work. It only returns a function, not a value.

class Board{
    constructor(width,height,cols,rows)
    {
        this.width=width;
        this.height=height;
        this.cols=cols;
        this.rows=rows;
        this.array= function(){
            let array=[];
            for(let i=0;i<this.cols;i++)
            {
                array[i]=[];
                for(let j=0;j<this.rows;j++){
                    array[i][j]=0;
                }
            }
            return array;
        }
    }


问:
How to programmatically enable Autostart option for my app in MI 4i security APP?
For check screenshot and detail, click here

Please give related suggession or code for how to add automatic enable auto start for my app , please check here attached screen shot thanks in advance.

答:
Few OEMs including (RedMi) customizes the stack ROM for battery/memory optimization and have blocked the "onDestroy()" and "onTaskRemoved" callbacks. As an user you can prevent the App's service from killing by locking the App. Or, White listing the app by enabling "Autostart" setting for the App. Programmatically you can prompt the user to enable the Autostart for the App Please find details here

Please note: I have tested the Autostart enabling programatically on few devices but found that it does not works always. Please check above link to see the possible options.


答:
You can directly put values on property no need to function

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    let array = new Array(this.cols).fill(0).map(val=> new Array(this.rows).fill(0))
    this.array = array;
  }
}

const b = new Board(2, 3, 4, 5);
console.log(b.array);```


问:
sass-loader Can't resolve @import url
I am using nuxt.js with fastify.js ( fastify-vue-plugin ) and I am setting up my styling.

The scss compiles and works, but throws an error on build when I am trying to import a font from googlefonts as so:

```<code>// _variables.scss
@import url('https://fonts.googleapis.com/css?family=Crimson+Text&display=swap');
@import url('https://fonts.googleapis.com/css?family=Montserrat&display=swap');
</code>```

```<code>// styles.scss
@import 'variables'; // i've tested this import, it works flawlessly.
</code>```

The error I'm getting with npm run dev is this:

```<code>ERROR  Failed to compile with 1 errors                                                                           friendly-errors 04:00:16

 ERROR  in ./assets/scss/styles.scss                                                                              friendly-errors 04:00:16

Module build failed (from ./node_modules/postcss-loader/src/index.js):                                            friendly-errors 04:00:16
Error: Can't resolve 'https:/fonts.googleapis.com/css?family=Crimson+Text&display=swap' in '/Users/home/Projects/voxicard-app/assets/scss'
    at onError (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:61:15)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at runAfter (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
    at innerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:252:11)
    at innerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:144:11)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:249:35)
    at resolver.doResolve.createInnerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:44:6)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at afterInnerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:166:11)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:249:35)
    at /Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js:23:4
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
                                                                                friendly-errors 04:00:16
 @ ./assets/scss/styles.scss 4:14-301 14:3-18:5 15:22-309
 @ ./.nuxt/App.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js
</code>```

```<code>// nuxt.config.js
...
css: [
    './assets/scss/styles.scss'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    '@nuxtjs/style-resources'
  ],
  bootstrapVue: {
    bootstrapCSS: false,
    bootstrapVueCSS: false
  },
  styleResources:{
    scss:[
        './assets/scss/*.scss',
    ]
  },
...
</code>```

I have another project where I've used sass-loader with the same font import and that worked, though it wasn't a Nuxtjs project.

What is not working here?

答:
From Aldarund's comment, I managed to fix this error by removing this line from my nuxt.config.js

```<code>// nuxt.config.js
styleResources : {
    scss: [
        './assets/scss/*.scss' // <<<< I Removed this line and kept this array empty.
    ]
}
</code>```

Title: sass-loader Can't resolve @import url

Body:
I am using nuxt.js with fastify.js ( fastify-vue-plugin ) and I am setting up my styling.

The scss compiles and works, but throws an error on build when I am trying to import a font from googlefonts as so:

// _variables.scss
@import url('https://fonts.googleapis.com/css?family=Crimson+Text&display=swap');
@import url('https://fonts.googleapis.com/css?family=Montserrat&display=swap');

// styles.scss
@import 'variables'; // i've tested this import, it works flawlessly.

The error I'm getting with npm run dev is this:

ERROR  Failed to compile with 1 errors                                                                           friendly-errors 04:00:16

 ERROR  in ./assets/scss/styles.scss                                                                              friendly-errors 04:00:16

Module build failed (from ./node_modules/postcss-loader/src/index.js):                                            friendly-errors 04:00:16
Error: Can't resolve 'https:/fonts.googleapis.com/css?family=Crimson+Text&display=swap' in '/Users/home/Projects/voxicard-app/assets/scss'
    at onError (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:61:15)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at runAfter (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:158:4)
    at innerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:146:3)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:252:11)
    at innerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:144:11)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:249:35)
    at resolver.doResolve.createInnerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:44:6)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at afterInnerCallback (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/Resolver.js:166:11)
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
    at next (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/node_modules/tapable/lib/Tapable.js:249:35)
    at /Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js:23:4
    at loggingCallbackWrapper (/Users/home/Projects/voxicard-app/node_modules/enhanced-resolve/lib/createInnerCallback.js:31:19)
                                                                                friendly-errors 04:00:16
 @ ./assets/scss/styles.scss 4:14-301 14:3-18:5 15:22-309
 @ ./.nuxt/App.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js

// nuxt.config.js
...
css: [
    './assets/scss/styles.scss'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    '@nuxtjs/style-resources'
  ],
  bootstrapVue: {
    bootstrapCSS: false,
    bootstrapVueCSS: false
  },
  styleResources:{
    scss:[
        './assets/scss/*.scss',
    ]
  },
...

I have another project where I've used sass-loader with the same font import and that worked, though it wasn't a Nuxtjs project.

What is not working here?

Body:
From Aldarund's comment, I managed to fix this error by removing this line from my nuxt.config.js

// nuxt.config.js
styleResources : {
    scss: [
        './assets/scss/*.scss' // <<<< I Removed this line and kept this array empty.
    ]
}


问:
Calculate time span in MVC Model using C#
I have a Model in my MVC project that stores Activities. I need to display the difference between start time and end time.
Here is my model class:

```<code>[Table("DailyCrewActivity")]
public partial class DailyCrewActivity
{
    [Key]
    public int id { get; set; }

    [Display(Name = "Crew Name")]
    [ForeignKey("DailyCrew")]
    public int daily_crew_id { get; set; }

    [Display(Name = "Task Number")]
    [ForeignKey("ContractTask")]
    public int contract_task_id { get; set; }

    [Display(Name = "Activity Date")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime activity_date { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Activity Code")]
    public string activity_code { get; set; }

    [Display(Name = "Start Time")]
    [DisplayFormat(DataFormatString = "{0:hh:mm}")]
    public string activity_start { get; set; }

    [Display(Name = "End Time")]
    [DisplayFormat(DataFormatString = "{0:hh:mm}")]
    public string activity_end { get; set; }

    [NotMapped]
    [Display(Name = "Hours")]
    [DisplayFormat(DataFormatString = "{0:#.##}")]
    public decimal ElapsedTime
    {
        get
        {
            decimal duration = 0;
            if (String.IsNullOrEmpty(activity_start) && String.IsNullOrEmpty(activity_end))
            {

                TimeSpan spanStart;
                TimeSpan spanEnd;
                if (TimeSpan.TryParse(activity_start, out spanStart) && TimeSpan.TryParse(activity_end, out spanEnd))
                {
                    duration = Convert.ToDecimal(spanEnd - spanStart);
                }

            }
            return duration;
        }
    }

    public DailyCrew DailyCrew { get; set; }
    public ContractTask ContractTask { get; set; }

}
</code>```

I am not getting a calculation returned to ElapsedTime. Is it because I am storing time in a string and then parsing it to TimeSpan?
I am not sure what it going on.

Thanks

Ryan

答:
You are checking for both values to be null, which won't give you anything. You need to instead check for not empty/nulls on both:</p>

```<code>if (!String.IsNullOrEmpty(activity_start) && !String.IsNullOrEmpty(activity_end))
{
    ...
}
</code>```

Body:
I have a Model in my MVC project that stores Activities. I need to display the difference between start time and end time.
Here is my model class:

[Table("DailyCrewActivity")]
public partial class DailyCrewActivity
{
    [Key]
    public int id { get; set; }

    [Display(Name = "Crew Name")]
    [ForeignKey("DailyCrew")]
    public int daily_crew_id { get; set; }

    [Display(Name = "Task Number")]
    [ForeignKey("ContractTask")]
    public int contract_task_id { get; set; }

    [Display(Name = "Activity Date")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime activity_date { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Activity Code")]
    public string activity_code { get; set; }

    [Display(Name = "Start Time")]
    [DisplayFormat(DataFormatString = "{0:hh:mm}")]
    public string activity_start { get; set; }

    [Display(Name = "End Time")]
    [DisplayFormat(DataFormatString = "{0:hh:mm}")]
    public string activity_end { get; set; }

    [NotMapped]
    [Display(Name = "Hours")]
    [DisplayFormat(DataFormatString = "{0:#.##}")]
    public decimal ElapsedTime
    {
        get
        {
            decimal duration = 0;
            if (String.IsNullOrEmpty(activity_start) && String.IsNullOrEmpty(activity_end))
            {

                TimeSpan spanStart;
                TimeSpan spanEnd;
                if (TimeSpan.TryParse(activity_start, out spanStart) && TimeSpan.TryParse(activity_end, out spanEnd))
                {
                    duration = Convert.ToDecimal(spanEnd - spanStart);
                }

            }
            return duration;
        }
    }

    public DailyCrew DailyCrew { get; set; }
    public ContractTask ContractTask { get; set; }

}

I am not getting a calculation returned to ElapsedTime. Is it because I am storing time in a string and then parsing it to TimeSpan?
I am not sure what it going on.

Thanks

Ryan

Body:
You are checking for both values to be null, which won't give you anything. You need to instead check for not empty/nulls on both:

if (!String.IsNullOrEmpty(activity_start) && !String.IsNullOrEmpty(activity_end))
{
    ...
}


问:
Javascript delete object property not working
I'm running some project on MEAN.js and I've got a following problem. I want to make some user's profile calculation and the save it to database. But there's a problem with method in users model:

```<code>UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }
    next();
});
</code>```

If I will send a password with my changes, it will change credentials, so user is unable to login next time. I want to delete password from user object before save, but I'm not able to do it (let's look at the comments in my code below):

```<code>exports.signin = function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err || !user) {
            res.status(400).send(info);
        } else {
            /* Some calculations and user's object changes */
            req.login(user, function(err) {
                if(err) {
                    res.status(400).send(err);
                } else {
                    console.log(delete user.password); // returns true
                    console.log(user.password); // still returns password :(
                    //user.save();
                    //res.json(user);
                }
            });
        }
    })(req, res, next);
};
</code>```

What's wrong? Why the delete method returns true, but nothing happens? Thanks for your help :)

答:
Just do:

```<code>user.password = undefined;
</code>```

instead of:

```<code>delete user.password;
</code>```

and the password property will not appear at the output.

Body:
I'm running some project on MEAN.js and I've got a following problem. I want to make some user's profile calculation and the save it to database. But there's a problem with method in users model:

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }
    next();
});

If I will send a password with my changes, it will change credentials, so user is unable to login next time. I want to delete password from user object before save, but I'm not able to do it (let's look at the comments in my code below):

exports.signin = function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err || !user) {
            res.status(400).send(info);
        } else {
            /* Some calculations and user's object changes */
            req.login(user, function(err) {
                if(err) {
                    res.status(400).send(err);
                } else {
                    console.log(delete user.password); // returns true
                    console.log(user.password); // still returns password :(
                    //user.save();
                    //res.json(user);
                }
            });
        }
    })(req, res, next);
};

What's wrong? Why the delete method returns true, but nothing happens? Thanks for your help :)

Body:
Just do:

user.password = undefined;

instead of:

delete user.password;

and the password property will not appear at the output.


问:
Why am I unable to request a certain webpage using python requests
I can't get inside this webpage.
When I try using requests.get(url) it doesn't progress at all and I get no HTTP errors just hangs like it's trying over and over.

I have tried using session and headers but none of them worked for me.

```<code>import bs4
from bs4 import BeautifulSoup as bs
import requests

url="https://www.gogoanime1.com/watch/hangyakusei-million-arthur-2nd-season/episode/episode-1"
epn=int(input("enter which episode link is it?: "))
newses=requests.Session()
newses.headers.update({'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'})
ssn=newses.get(url)
page=ssn.text
print()

soup=bs(page,'html.parser')
a=soup.find('div',{'class':'vmn-buttons'})
links=a.find_all('a')

for link in links:
    print(link)
    if link.text=="Download":
        print("found")
        dl=link['href']
        break
print(dl)

bom=newses.get(dl)
print(bom.text)
</code>```

I want at least a response, but it hangs in there all day long, how can I access the page like a real user and scrape its content?

答: I didn't notice that it was actually a file and not a webpage to parse. Which took more time as it downloads the file.</p>

Body:
I can't get inside this webpage.
When I try using requests.get(url) it doesn't progress at all and I get no HTTP errors just hangs like it's trying over and over.

I have tried using session and headers but none of them worked for me.

import bs4
from bs4 import BeautifulSoup as bs
import requests

url="https://www.gogoanime1.com/watch/hangyakusei-million-arthur-2nd-season/episode/episode-1"
epn=int(input("enter which episode link is it?: "))
newses=requests.Session()
newses.headers.update({'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'})
ssn=newses.get(url)
page=ssn.text
print()

soup=bs(page,'html.parser')
a=soup.find('div',{'class':'vmn-buttons'})
links=a.find_all('a')

for link in links:
    print(link)
    if link.text=="Download":
        print("found")
        dl=link['href']
        break
print(dl)

bom=newses.get(dl)
print(bom.text)

I want at least a response, but it hangs in there all day long, how can I access the page like a real user and scrape its content?


问:
Simple jQuery page not working
```<code>  …
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id ="iAmNew">id="iAmNew"</div>
  <script>
    $(#iAmNew).style("border", "4px dotted blue");
  </script>
  …
</code>```

答:
```<code>$("#iAmNew").css("border", "4px dotted blue");
</code>```

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …


问:
ElasticSearch : IN equivalent operator in ElasticSearch
I am trying to find ElasticSearch query equivalent to IN \ NOT in SQL.

I know we can use QueryString query with multiple OR to get the same answer, but that ends up with lot of OR's.

Can anyone share the example?

答:
1  terms

you can use terms term query in ElasticSearch that will act as IN

terms query is used to check if the value matches any of the provided values from Array.

2  must_not

must_not can be used as NOT in ElasticSearch.

ex.

```<code>GET my_index/my_type/_search
{
    "query" : {
         "bool" : {
              "must":[
                {
                   "terms": {
                        "id" : ["1234","12345","123456"]
                    }
                },
                {
                   "bool" : {
                        "must_not" : [
                            {
                              "match":{
                                  "id" : "123"
                               }
                            }
                        ]
                    }
                }
              ]
         }
    }
}
</code>```

exists

Also if it helps you can also use "exists" query to check if the field exists or not.
for ex,
check if the field exists

```<code>"exists" : {
      "field" : "mobileNumber"
   }
</code>```

check if a field does not exist

```<code>"bool":{
    "must_not" : [
        {
           "exists" : {
               "field" : "mobileNumber"
           }
        }
     ]
}
</code>```

Body:
1  terms

you can use terms term query in ElasticSearch that will act as IN

terms query is used to check if the value matches any of the provided values from Array.

2  must_not

must_not can be used as NOT in ElasticSearch.

ex.

GET my_index/my_type/_search
{
    "query" : {
         "bool" : {
              "must":[
                {
                   "terms": {
                        "id" : ["1234","12345","123456"]
                    }
                },
                {
                   "bool" : {
                        "must_not" : [
                            {
                              "match":{
                                  "id" : "123"
                               }
                            }
                        ]
                    }
                }
              ]
         }
    }
}

exists

Also if it helps you can also use "exists" query to check if the field exists or not.
for ex,
check if the field exists

"exists" : {
      "field" : "mobileNumber"
   }

check if a field does not exist

"bool":{
    "must_not" : [
        {
           "exists" : {
               "field" : "mobileNumber"
           }
        }
     ]
}


问:
Altering standard MSSqlServerSink table from appsettings
In my ASP.NET Core 2.1 web API, I use Serilog with MSSqlServerSink. How can I alter the default table structure and add data to those columns by configuring it using appsettings?

I've tried settings the values as per the documentation examples but there are no errors. It is just as if the settings are ignored. I know the settings are being read because some of them are being picked up such as the table name. I've posted questions on other ASP.NET forums and the suggestions don't have any effect. I posted questions on the Serilog Gitter feed but I didn't get an answer. I did post on the github issues and someone suggested upgrading from the latest version to the dev version but this is a live environment. This is the section in the appsettings.json file that configures serilog.

```<code>"Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning"
        }
    },
    "WriteTo": [
        {
            "Name": "MSSqlServer",
            "Args": {
                "connectionString": "Server=(local);Database=ACLWebAPILogs;trusted_connection=true",
                "tableName": "ACLWebAPILog",
                "restrictedToMinimumLevel": "Information",
                "autoCreateSqlTable": true
                "columnOptionsSection": {
                    "disableTriggers": true,
                "removeStandardColumns": [ "MessageTemplate", "Properties" ],
                    "additionalColumns": [
                        {
                            "ColumnName": "ControllerName",
                            "DataType": "nvarchar",
                            "AllowNull": true,
                            "DataLength": 50
                        },
                        {
                            "ColumnName": "MessageType",
                            "DataType": "nvarchar",
                            "AllowNull": true,
                            "DataLength": 50
                        }
                    ]
                }
            }
        }
    ]
}
</code>```

The code that is in the Startup constructor in Startup.cs has the following line to add the logging system:

```<code>            // Init Serilog configuration
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.ConfigurationSection(configuration.GetSection("Serilog"))
            .CreateLogger();
</code>```

In the Configure function I do have:

```<code>loggerFactory.AddSerilog();
</code>```

I would have expected this to have removed the MessageTemplate and Properties columns and added the two referenced below. It's as if everything passed autoCreateSqlTable is ignored. I've looked at Enrichers and they don't do what I want.

答:
Update Serilog.Sinks.MSSqlServer to version 5.1.3

```<code>Install-Package Serilog.Sinks.MSSqlServer -Version 5.1.3
</code>```

Check this answer for more details https://stackoverflow.com/a/55264488/3134112

Body:
In my ASP.NET Core 2.1 web API, I use Serilog with MSSqlServerSink. How can I alter the default table structure and add data to those columns by configuring it using appsettings?

I've tried settings the values as per the documentation examples but there are no errors. It is just as if the settings are ignored. I know the settings are being read because some of them are being picked up such as the table name. I've posted questions on other ASP.NET forums and the suggestions don't have any effect. I posted questions on the Serilog Gitter feed but I didn't get an answer. I did post on the github issues and someone suggested upgrading from the latest version to the dev version but this is a live environment. This is the section in the appsettings.json file that configures serilog.

"Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning"
        }
    },
    "WriteTo": [
        {
            "Name": "MSSqlServer",
            "Args": {
                "connectionString": "Server=(local);Database=ACLWebAPILogs;trusted_connection=true",
                "tableName": "ACLWebAPILog",
                "restrictedToMinimumLevel": "Information",
                "autoCreateSqlTable": true
                "columnOptionsSection": {
                    "disableTriggers": true,
                "removeStandardColumns": [ "MessageTemplate", "Properties" ],
                    "additionalColumns": [
                        {
                            "ColumnName": "ControllerName",
                            "DataType": "nvarchar",
                            "AllowNull": true,
                            "DataLength": 50
                        },
                        {
                            "ColumnName": "MessageType",
                            "DataType": "nvarchar",
                            "AllowNull": true,
                            "DataLength": 50
                        }
                    ]
                }
            }
        }
    ]
}

The code that is in the Startup constructor in Startup.cs has the following line to add the logging system:

            // Init Serilog configuration
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.ConfigurationSection(configuration.GetSection("Serilog"))
            .CreateLogger();

In the Configure function I do have:

loggerFactory.AddSerilog();

I would have expected this to have removed the MessageTemplate and Properties columns and added the two referenced below. It's as if everything passed autoCreateSqlTable is ignored. I've looked at Enrichers and they don't do what I want.

Body:
Update Serilog.Sinks.MSSqlServer to version 5.1.3

Install-Package Serilog.Sinks.MSSqlServer -Version 5.1.3

Check this answer for more details https://stackoverflow.com/a/55264488/3134112