问:
Error: Type 'ui.TextHeightBehavior' not found in flutter
I got a problem when I flutter build appbundle in terminal command

Compiler message:

```<code>    ../../flutter/packages/flutter/lib/src/widgets/basic.dart:5149:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:149:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:432:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:78:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:281:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior get textHeightBehavior => _textPainter.textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:282:26: Error: Type 'ui.TextHeightBehavior' not found.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                             ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:145:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:346:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior get textHeightBehavior => _textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:347:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior _textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:348:26: Error: Type 'ui.TextHeightBehavior' not found.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                             ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1070:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/basic.dart:5149:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:149:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:200:43: Error: 'TextHeightBehavior' isn't a type.
        properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
                                              ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:432:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:487:43: Error: 'TextHeightBehavior' isn't a type.
        properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
                                              ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:78:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:282:29: Error: 'TextHeightBehavior' isn't a type.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                                ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:145:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:347:6: Error: 'TextHeightBehavior' isn't a type.
      ui.TextHeightBehavior _textHeightBehavior;
         ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:348:29: Error: 'TextHeightBehavior' isn't a type.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                                ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:422:7: Error: No named parameter with the name 'textHeightBehavior'.
          textHeightBehavior: _textHeightBehavior,
          ^^^^^^^^^^^^^^^^^^
    org-dartlang-sdk:///flutter/lib/ui/text.dart:865:3: Context: Found this candidate, but the arguments don't match.
      ParagraphStyle({
      ^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1070:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1091:7: Error: No named parameter with the name 'textHeightBehavior'.
          textHeightBehavior: textHeightBehavior,

      ^^^^^^^^^^^^^^^^^^
org-dartlang-sdk:///flutter/lib/ui/text.dart:865:3: Context: Found this candidate, but the arguments don't match.
  ParagraphStyle({
  ^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

</code>```

Where:                                                                 Script
'/Users/mac/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle'
line: 801

```<code>* What went wrong:
Execution failed for task ':app:compileFlutterBuildRelease'.
> Process 'command '/Users/mac/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1
</code>```

**this is my flutter doctor: **

[✓] Flutter (Channel master, v1.14.7-pre.83, on Mac OS X 10.15.2
19C57, locale en-ID)
• Flutter version 1.14.7-pre.83 at /Users/mac/flutter
• Framework revision e10df3c1a6 (2 days ago), 2020-02-01 11:23:01 +0800
• Engine revision e625e174c5
• Dart version 2.8.0 (build 2.8.0-dev.6.0 5ae5aff640)

[✓] Android toolchain - develop for Android devices (Android SDK
version 29.0.2)
• Android SDK at /Users/mac/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3.1, Build version 11C504
• CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 43.0.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] IntelliJ IDEA Community Edition (version 2018.2.2)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 29.1.3
• Dart plugin version 182.4129.13

Previously I success upload my app to Google Playstore. But when I want to update my app, I face this problem. thank you before

答:
change your flutter master
at terminal of your project  write
flutter channel stable</p>

Body:
I got a problem when I flutter build appbundle in terminal command

Compiler message:

    ../../flutter/packages/flutter/lib/src/widgets/basic.dart:5149:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:149:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:432:9: Error: Type 'ui.TextHeightBehavior' not found.
      final ui.TextHeightBehavior textHeightBehavior;
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:78:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:281:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior get textHeightBehavior => _textPainter.textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:282:26: Error: Type 'ui.TextHeightBehavior' not found.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                             ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:145:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:346:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior get textHeightBehavior => _textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:347:3: Error: Type 'ui.TextHeightBehavior' not found.
      ui.TextHeightBehavior _textHeightBehavior;
      ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:348:26: Error: Type 'ui.TextHeightBehavior' not found.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                             ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1070:5: Error: Type 'ui.TextHeightBehavior' not found.
        ui.TextHeightBehavior textHeightBehavior,
        ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/basic.dart:5149:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:149:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:200:43: Error: 'TextHeightBehavior' isn't a type.
        properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
                                              ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:432:12: Error: 'TextHeightBehavior' isn't a type.
      final ui.TextHeightBehavior textHeightBehavior;
               ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/widgets/text.dart:487:43: Error: 'TextHeightBehavior' isn't a type.
        properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
                                              ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:78:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/rendering/paragraph.dart:282:29: Error: 'TextHeightBehavior' isn't a type.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                                ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:145:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:347:6: Error: 'TextHeightBehavior' isn't a type.
      ui.TextHeightBehavior _textHeightBehavior;
         ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:348:29: Error: 'TextHeightBehavior' isn't a type.
      set textHeightBehavior(ui.TextHeightBehavior value) {
                                ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_painter.dart:422:7: Error: No named parameter with the name 'textHeightBehavior'.
          textHeightBehavior: _textHeightBehavior,
          ^^^^^^^^^^^^^^^^^^
    org-dartlang-sdk:///flutter/lib/ui/text.dart:865:3: Context: Found this candidate, but the arguments don't match.
      ParagraphStyle({
      ^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1070:8: Error: 'TextHeightBehavior' isn't a type.
        ui.TextHeightBehavior textHeightBehavior,
           ^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/painting/text_style.dart:1091:7: Error: No named parameter with the name 'textHeightBehavior'.
          textHeightBehavior: textHeightBehavior,

      ^^^^^^^^^^^^^^^^^^
org-dartlang-sdk:///flutter/lib/ui/text.dart:865:3: Context: Found this candidate, but the arguments don't match.
  ParagraphStyle({
  ^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

Where:                                                                 Script
'/Users/mac/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle'
line: 801

* What went wrong:
Execution failed for task ':app:compileFlutterBuildRelease'.
> Process 'command '/Users/mac/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1

**this is my flutter doctor: **

[✓] Flutter (Channel master, v1.14.7-pre.83, on Mac OS X 10.15.2
19C57, locale en-ID)
• Flutter version 1.14.7-pre.83 at /Users/mac/flutter
• Framework revision e10df3c1a6 (2 days ago), 2020-02-01 11:23:01 +0800
• Engine revision e625e174c5
• Dart version 2.8.0 (build 2.8.0-dev.6.0 5ae5aff640)

[✓] Android toolchain - develop for Android devices (Android SDK
version 29.0.2)
• Android SDK at /Users/mac/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3.1, Build version 11C504
• CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 43.0.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] IntelliJ IDEA Community Edition (version 2018.2.2)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 29.1.3
• Dart plugin version 182.4129.13

Previously I success upload my app to Google Playstore. But when I want to update my app, I face this problem. thank you before


来源: stackexchange

问:
Convert html block to image in laravel
I am creating a html code by sending an ajax request.

Ajax script

```<code>$.ajax({
    url: "{{url('/')}}/phpScript", //Server script to process data
    type: 'POST',
    dataType: 'json',
    data: data, //this is an object with all my required variables
    success: function (html) {
        if (html) {
            $('#someTag').html(html); //change the html of #someTag with new html
        }
    }

});
</code>```

PHP Script:

```<code>static function createHtml() {
    ob_start(); ?>
        <div class="large-12 medium-12 columns" id="certificate-holder">
            <div class="middle-wrappe">
               <?php //some other code here to create the html ?>
            </div>
            <style>/** some style here**/</style>
        </div>

    <?php return ob_get_clean();
}
</code>```

This is working fine and I am able to create html and change the html with new html.

Is there any way to create the image of that html block, so that I can return the image back and show the image in that #someTag instead of the html.

I have used anam/phantommagick to create image from html, but in this I need to pass the url of page to create image.

Thanks

答:
There are two ways two generate image from HTML block are:-

1.Using Jquery:-

```<code>html2canvas(document.getElementById('frame')).then(function(canvas) {
       // to view the generated image on the same page
        document.body.appendChild(canvas);

        // to save the image as png file
        Canvas2Image.saveAsPNG(canvas);

        // Get base64URL
    canvas.toDataURL('image/jpeg').replace('image/jpeg','image/octet-stream');
});
</code>```

https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js

2. Using spatie/browsershot package:-

This package can be installed through Composer.

```<code>composer require spatie/browsershot
</code>```

In all examples it is assumed that you imported this namespace at the top of your file

```<code>use Spatie\Browsershot\Browsershot;
</code>```

Here's the easiest way to create an image of a webpage:

```<code>Browsershot::url('https://example.com')->save($pathToImage);
</code>```

By default the screenshot's type will be a png. (According to Puppeteer's Config) But you can change it to jpeg with quality option.

```<code>Browsershot::url('https://example.com')
    ->setScreenshotType('jpeg', 100)
    ->save($pathToImage);
</code>```

By default the screenshot's size will match the resolution you use for your desktop. Want another size of screenshot? No problem!

```<code>Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->save($pathToImage);
</code>```

You can take a screenshot of an element matching a selector using select.

```<code>Browsershot::url('https://example.com')
    ->select('.some-selector')
    ->save($pathToImage);
</code>```

You can take a screenshot of the full length of the page by using fullPage().

```<code>Browsershot::url('https://example.com')
    ->fullPage()
    ->save($pathToImage);
</code>```

For more options you can use the official documentation:-
https://github.com/spatie/browsershot

ContentLicense: CC BY-SA 4.0

Title: Convert html block to image in laravel

Body:
I am creating a html code by sending an ajax request.

Ajax script

$.ajax({
    url: "{{url('/')}}/phpScript", //Server script to process data
    type: 'POST',
    dataType: 'json',
    data: data, //this is an object with all my required variables
    success: function (html) {
        if (html) {
            $('#someTag').html(html); //change the html of #someTag with new html
        }
    }

});

PHP Script:

static function createHtml() {
    ob_start(); ?>

               <?php //some other code here to create the html ?>

    <?php return ob_get_clean();
}

This is working fine and I am able to create html and change the html with new html.

Is there any way to create the image of that html block, so that I can return the image back and show the image in that #someTag instead of the html.

I have used anam/phantommagick to create image from html, but in this I need to pass the url of page to create image.

Thanks

Body:
There are two ways two generate image from HTML block are:-

1.Using Jquery:-

html2canvas(document.getElementById('frame')).then(function(canvas) {
       // to view the generated image on the same page
        document.body.appendChild(canvas);

        // to save the image as png file
        Canvas2Image.saveAsPNG(canvas);

        // Get base64URL
    canvas.toDataURL('image/jpeg').replace('image/jpeg','image/octet-stream');
});

https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js

2. Using spatie/browsershot package:-

This package can be installed through Composer.

composer require spatie/browsershot

In all examples it is assumed that you imported this namespace at the top of your file

use Spatie\Browsershot\Browsershot;

Here's the easiest way to create an image of a webpage:

Browsershot::url('https://example.com')->save($pathToImage);

By default the screenshot's type will be a png. (According to Puppeteer's Config) But you can change it to jpeg with quality option.

Browsershot::url('https://example.com')
    ->setScreenshotType('jpeg', 100)
    ->save($pathToImage);

By default the screenshot's size will match the resolution you use for your desktop. Want another size of screenshot? No problem!

Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->save($pathToImage);

You can take a screenshot of an element matching a selector using select.

Browsershot::url('https://example.com')
    ->select('.some-selector')
    ->save($pathToImage);

You can take a screenshot of the full length of the page by using fullPage().

Browsershot::url('https://example.com')
    ->fullPage()
    ->save($pathToImage);

For more options you can use the official documentation:-
https://github.com/spatie/browsershot


问:
JSOUP .attr() method don't extract data from working html
I have an issue with a .attr method which is not working for all attributes besides "class".
I've tried to extract the "alt" attribute to get the name of the shop but it just doesn't work. Tried same for an "src" and "data-original" and nothing has been printed out.

Here is the entire method that I've used to extract data.

public List<String> getShops() {
        Elements elements = document.select(".store-logo");
        System.out.println(elements.html());
       for(Element image : elements){
           System.out.println(image.attr("alt"));
       }
        return null;
    }

```

<p>To make sure that I'm not using the empty document I've printed out entire HTML for all the elements which look like that:</p>

<pre class="lang-html prettyprint-override"><code><img src="//image.ceneostatic.pl/imageschain/data/shops_s/20853/logo.jpg;data/custom_images/590/custom_image.png" alt="nalepsze.pl">
<img src="/content/img/icons/pix-empty.png" alt="allegro.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/20136/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="avans.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/18601/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="proshop.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/29068/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="g2a.com" data-original="//image.ceneostatic.pl/imageschain/data/shops/23040/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="fotosoft.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/3914/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="techsat24.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/5666/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="imperiumpc.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/12579/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="domsary.eu" data-original="//image.ceneostatic.pl/imageschain/data/shops/4725/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="net-s.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/3653/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="sferis.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/4614/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="morele.net" data-original="//image.ceneostatic.pl/imageschain/data/shops/379/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="zakupy.vip" data-original="//image.ceneostatic.pl/imageschain/data/shops/29402/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="fotoelektro.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/1671/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="3kropki.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/357/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="electro.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/16202/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="allegro.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/20136/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="avans.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/18601/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">
<img src="/content/img/icons/pix-empty.png" alt="proshop.pl" data-original="//image.ceneostatic.pl/imageschain/data/shops/29068/logo.jpg;data/custom_images/585/custom_image.png" class="js_lazy">

</code>```

Data in this extraction is correct but the next step in for each loop isn't working I get an empty string for every single one of the elements which are quite strange because I can extract a "class" attribute.

I would really appreciate any tips according that topic.

PS. jsoup ver is 1.11.3

答: In your example you use class "store-logo", but in html document attached none of the img elements has this class. When replacing class name to "js_lazy", your code extracts alt attributes.</p>

Body:
I have an issue with a .attr method which is not working for all attributes besides "class".
I've tried to extract the "alt" attribute to get the name of the shop but it just doesn't work. Tried same for an "src" and "data-original" and nothing has been printed out.

Here is the entire method that I've used to extract data.

public List<String> getShops() {
        Elements elements = document.select(".store-logo");
        System.out.println(elements.html());
       for(Element image : elements){
           System.out.println(image.attr("alt"));
       }
        return null;
    }

To make sure that I'm not using the empty document I've printed out entire HTML for all the elements which look like that:

Data in this extraction is correct but the next step in for each loop isn't working I get an empty string for every single one of the elements which are quite strange because I can extract a "class" attribute.

I would really appreciate any tips according that topic.

PS. jsoup ver is 1.11.3


问:
Easy way to see saved NSUserDefaults?
Is there a way to see what's been saved to NSUserDefaults directly?  I'd like to see if my data saved correctly.

答:
Swift 5 Xcode 11.2 Solution

This is the whole path where your UserDefaults key values will be in a plist file. Follow and find your app bundle identifier .plist file.

/Users/'Your User Name'/Library/Developer/CoreSimulator/Devices/4176EED3-B9FC-4C77-A25E-ASD201B9FDFG2/data/Containers/Data/Application/56D7CE31-9A8B-4371-9B0F-9604E239423B0/Library/Preferences

Here "4176EED3-B9FC-4C77-A25E-ASD201B9FDFG2" is your Device ID

and "56D7CE31-9A8B-4371-9B0F-9604E239423B0" is your Application ID

I normally get them by sorting folders by last Date Modified in Finder. And most recent edited folder is my device ID and App ID.

Enjoy!

ContentLicense: CC BY-SA 3.0

Title: Easy way to see saved NSUserDefaults?


问:
Why am I receiving IntegrityError (1062, "Duplicate entry '' for key 'username'")?
I am receiving the following error (1062, "Duplicate entry '' for key 'username'")
even though I haven't provided a username field at all.

I am trying to save the updated info of the user in its existing Account table.

Can you please help me understand the problem?
The following are the details and code snippets. Thank you for your time in advance.

Error:

```<code>Request URL:    http://127.0.0.1:8000/profile/profileUpdate/
Django Version: 3.0.2
Exception Type: IntegrityError
Exception Value:
(1062, "Duplicate entry '' for key 'username'")
Exception Location: C:\Users\hp\Envs\test\lib\site-packages\MySQLdb\connections.py in query, line 239
Python Executable:  C:\Users\hp\Envs\test\Scripts\python.exe
Python Version: 3.7.3
</code>```

froms.py:

```<code>class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Account
        fields = ('image', 'phone', 'guardianPhone', 'parrentPhone', 'emergencyPhone', 'address1', 'address2')
</code>```

models.py:

```<code>class Account(AbstractBaseUser):
    username     = models.CharField(max_length = 50, unique= True)
    email        = models.EmailField(verbose_name = "email", max_length = 50, unique=True)
    image        = models.ImageField(upload_to = "pics/", default = "user/noimg")
    dateTime_joined  = models.DateTimeField(verbose_name="date joined", auto_now_add = True)
    is_admin     = models.BooleanField(default=False)
    is_staff     = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active    = models.BooleanField(default=True)

    first_login  =  models.BooleanField(default=True)
    room         = models.CharField(max_length = 10 , default = "unAssigned")
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone        = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
    #phone        = PhoneNumberField(null=False, unique = True)
    guardianPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)
    parrentPhone = models.CharField(validators=[phone_regex], max_length=17, blank=True)
    emergencyPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)

    address1 = models.CharField(max_length = 200, blank=True)
    address2 = models.CharField(max_length = 200, blank=True)

</code>```

views.py :

```<code>def profileUpdate(request):
    context = {}
    if request.POST:
        form = ProfileUpdateForm(request.POST)
        if form.is_valid():
            form.save()
            user = request.user

            return redirect('../../dashboard/')
        else:
            context['profile_form'] = form
    else:
        form = ProfileUpdateForm()
        context['profile_form'] = form
    return render(request, 'profileUpdate.html', context)

</code>```

答:
This happens because you set unique constraint on username field:

```<code>models.CharField(max_length = 50, unique= True)
</code>```

Error is saying that you already have a record in DB with the username of zero length.
You should or provide really unique name with your logic or generate a default unique name by adding default argument to this field:

```<code>models.CharField(max_length = 50, unique= True, default=some_callable)
</code>```

, where callable is a method that provides unique names by default if non was provided during object creation with form. This may be a callable with some randome names generation.

Another option is to use pre_save signal with setting username by default to something like user.username = f'user_{hash_of_something}

Body:
I am receiving the following error (1062, "Duplicate entry '' for key 'username'")
even though I haven't provided a username field at all.

I am trying to save the updated info of the user in its existing Account table.

Can you please help me understand the problem?
The following are the details and code snippets. Thank you for your time in advance.

Error:

Request URL:    http://127.0.0.1:8000/profile/profileUpdate/
Django Version: 3.0.2
Exception Type: IntegrityError
Exception Value:
(1062, "Duplicate entry '' for key 'username'")
Exception Location: C:\Users\hp\Envs\test\lib\site-packages\MySQLdb\connections.py in query, line 239
Python Executable:  C:\Users\hp\Envs\test\Scripts\python.exe
Python Version: 3.7.3

froms.py:

class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Account
        fields = ('image', 'phone', 'guardianPhone', 'parrentPhone', 'emergencyPhone', 'address1', 'address2')

models.py:

class Account(AbstractBaseUser):
    username     = models.CharField(max_length = 50, unique= True)
    email        = models.EmailField(verbose_name = "email", max_length = 50, unique=True)
    image        = models.ImageField(upload_to = "pics/", default = "user/noimg")
    dateTime_joined  = models.DateTimeField(verbose_name="date joined", auto_now_add = True)
    is_admin     = models.BooleanField(default=False)
    is_staff     = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active    = models.BooleanField(default=True)

    first_login  =  models.BooleanField(default=True)
    room         = models.CharField(max_length = 10 , default = "unAssigned")
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone        = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
    #phone        = PhoneNumberField(null=False, unique = True)
    guardianPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)
    parrentPhone = models.CharField(validators=[phone_regex], max_length=17, blank=True)
    emergencyPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)

    address1 = models.CharField(max_length = 200, blank=True)
    address2 = models.CharField(max_length = 200, blank=True)

views.py :

def profileUpdate(request):
    context = {}
    if request.POST:
        form = ProfileUpdateForm(request.POST)
        if form.is_valid():
            form.save()
            user = request.user

            return redirect('../../dashboard/')
        else:
            context['profile_form'] = form
    else:
        form = ProfileUpdateForm()
        context['profile_form'] = form
    return render(request, 'profileUpdate.html', context)

Body:
This happens because you set unique constraint on username field:

models.CharField(max_length = 50, unique= True)

Error is saying that you already have a record in DB with the username of zero length.
You should or provide really unique name with your logic or generate a default unique name by adding default argument to this field:

models.CharField(max_length = 50, unique= True, default=some_callable)

, where callable is a method that provides unique names by default if non was provided during object creation with form. This may be a callable with some randome names generation.

Another option is to use pre_save signal with setting username by default to something like user.username = f'user_{hash_of_something}


问:
How to detect if my app's vpn is connected in iOS?
I want to know if my VPN is connected. If so, I wouldn't connect again and would shown a message "it's connected".

But if it's not my VPN, I should connect it.

Can I do this?

```<code>settings ["__SCOPED__": {
    en0 =     {
        ExceptionsList = (
            "*.local",
            "169.254/16"
        );
        FTPPassive = 1;
    };
}, "ExceptionsList": <__NSCFArray 0x282a58740>(
*.local,
169.254/16
)
, "FTPPassive": 1]
</code>```

答:
You can Check vpn connection with this code :

var isConnectedToVpn: Bool {
        if let settings = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? Dictionary<String, Any>,
            let scopes = settings["__SCOPED__"] as? [String:Any] {
            for (key, _) in scopes {
                    if key.contains("tap") || key.contains("tun") || key.contains("ppp") || key.contains("ipsec") || key.contains("ipsec0") {
                    return true
                }
            }
        }
        return false
    }
```

Body:
I want to know if my VPN is connected. If so, I wouldn't connect again and would shown a message "it's connected".

But if it's not my VPN, I should connect it.

Can I do this?

settings ["__SCOPED__": {
    en0 =     {
        ExceptionsList = (
            "*.local",
            "169.254/16"
        );
        FTPPassive = 1;
    };
}, "ExceptionsList": <__NSCFArray 0x282a58740>(
*.local,
169.254/16
)
, "FTPPassive": 1]


问:
What is happening in this numpy problem where a numpy array is multiplied with different array?
```<code>import numpy as np

x = np.array([[1, 2], [3, 4], [5, 6]])

y = x [[0,1,2], [0,1,0]]   #:i did not understand this step,what is happening here?

print y

OUTPUT: [1 4 5]
</code>```

答:
When you're doing

```<code>x[a, b]
</code>```

With a and b being arrays, you're specifying a series of indices to use. For instance, here you are saying "pick the 0th row, then the 1st, then the 2nd" and "pick the 0th column, the 1st and the 0th".

So, your resulting array is [x[0,0], x[1,1], x[2,0]]

Body:
When you're doing

x[a, b]

With a and b being arrays, you're specifying a series of indices to use. For instance, here you are saying "pick the 0th row, then the 1st, then the 2nd" and "pick the 0th column, the 1st and the 0th".

So, your resulting array is [x[0,0], x[1,1], x[2,0]]


问:
Pivot Table MySQL?
I Have A Query :

```<code>SELECT item_id,
       MAX(CASE WHEN `vendor_id` = 2
                THEN price
                END) AS "Bandung",
       MAX(CASE WHEN `vendor_id` = 3
                THEN price
                END) AS "Vendor Bandung",
       MAX(CASE WHEN `vendor_id` = 4
                THEN price
                END) AS "Jakarta",
       MIN(price)
FROM transactions
GROUP BY item_id
</code>```

Output:

I Want to get detail information about price from where,.. like below

```<code>|ItemID|Bandung|Vendor Bandung|Jakarta |Price Min|*Area*
|10001 |12000  |11000         |9000    |9000     |*Jakarta|*
|10002 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10004 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10005 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
</code>```

答:
```<code>WITH cte AS (
SELECT item_id,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MIN(price) MinPrice
FROM transactions
GROUP BY item_id
)
SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     ELSE 'unknown'
                     END Area
FROM cte
</code>```

For ancient versions:

```<code>SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     ELSE 'unknown'
                     END Area
FROM
(
SELECT item_id,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MIN(price) MinPrice
FROM transactions
GROUP BY item_id
) cte
</code>```

Title: Pivot Table MySQL?

Body:
I Have A Query :

SELECT item_id,
       MAX(CASE WHEN `vendor_id` = 2
                THEN price
                END) AS "Bandung",
       MAX(CASE WHEN `vendor_id` = 3
                THEN price
                END) AS "Vendor Bandung",
       MAX(CASE WHEN `vendor_id` = 4
                THEN price
                END) AS "Jakarta",
       MIN(price)
FROM transactions
GROUP BY item_id

Output:

I Want to get detail information about price from where,.. like below

|ItemID|Bandung|Vendor Bandung|Jakarta |Price Min|*Area*
|10001 |12000  |11000         |9000    |9000     |*Jakarta|*
|10002 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10004 |12000  |11000         |12400   |11000    |*Vendor Bandung|*
|10005 |12000  |11000         |12400   |11000    |*Vendor Bandung|*

Body:
WITH cte AS (
SELECT item_id,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MIN(price) MinPrice
FROM transactions
GROUP BY item_id
)
SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     ELSE 'unknown'
                     END Area
FROM cte

For ancient versions:

SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     ELSE 'unknown'
                     END Area
FROM
(
SELECT item_id,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MIN(price) MinPrice
FROM transactions
GROUP BY item_id
) cte


问:
no single-int-arg constructor/factory method
I have this code:

```<code>final Person p = new Person(1L);
final ObjectMapper mapper = JacksonUtil.INSTANCE.getMapper();
final TypeReference<HashMap<String, Object>> typeMap = new TypeReference<HashMap<String, Object>>() {};
final String personJson= mapper.writeValueAsString(p);
mapper.readValue(personJson, typeMap);
</code>```

personJson is like:

```<code>"id" : 1
</code>```

Whenever I have a Long type in my Json, it doesn't work when I try to read it. I have this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not
  instantiate value of type [simple type, class
  org.codehaus.jackson.generated.java.lang.Number] from Integral number;
  no single-int-arg constructor/factory method

How can I make it accept the type Long? Is there any feature to enable in the mapper?

答:
Create a constructor in Person that accepts an integer (and not a long as you do). If you definitely want to accept a long then try to create a constructor that accepts a Number.
Suppose you have a bean/model class like this

```<code>public class Person{
    private Long id;
    private String name;

    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Person(Long id) {
        super();
        this.id = id;
    }

    //getter and setter
}
</code>```

Here second constructor accept an Long value

I hope that your

no single-int-arg constructor/factory method

error will be gone

Body:
I have this code:

final Person p = new Person(1L);
final ObjectMapper mapper = JacksonUtil.INSTANCE.getMapper();
final TypeReference<HashMap<String, Object>> typeMap = new TypeReference<HashMap<String, Object>>() {};
final String personJson= mapper.writeValueAsString(p);
mapper.readValue(personJson, typeMap);

personJson is like:

"id" : 1

Whenever I have a Long type in my Json, it doesn't work when I try to read it. I have this error:

com.fasterxml.jackson.databind.JsonMappingException: Can not
  instantiate value of type [simple type, class
  org.codehaus.jackson.generated.java.lang.Number] from Integral number;
  no single-int-arg constructor/factory method

How can I make it accept the type Long? Is there any feature to enable in the mapper?

Body:
Create a constructor in Person that accepts an integer (and not a long as you do). If you definitely want to accept a long then try to create a constructor that accepts a Number.
Suppose you have a bean/model class like this

public class Person{
    private Long id;
    private String name;

    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Person(Long id) {
        super();
        this.id = id;
    }

    //getter and setter
}

Here second constructor accept an Long value

I hope that your

no single-int-arg constructor/factory method

error will be gone


答: This operation provides the sequence of the values with indexes taken from [0,1,2], [0,1,0]. First list relates to the first dimension, second one to the second one. So the coordinates will be (0, 0), (1, 1), (2, 0) and its values are 1, 4, 5 in the array x.

Title: What is happening in this numpy problem where a numpy array is multiplied with different array?

Body:
import numpy as np

x = np.array([[1, 2], [3, 4], [5, 6]])

y = x [[0,1,2], [0,1,0]]   #:i did not understand this step,what is happening here?

print y

OUTPUT: [1 4 5]


问:
Calculation loop in python new values
I would like to do the calculation loop using my function.

```<code>b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)
</code>```

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

```<code>[17183, 11,521, 5,826, 99]
</code>```

答:
Perhaps something like this</p>

```<code>x = b[8]
output = []
output.append(x)
while x > 0:
    x = balance(b[9], b[11], X)
    output.append(x)
</code>```

Title: Calculation loop in python new values

Body:
I would like to do the calculation loop using my function.

b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

[17183, 11,521, 5,826, 99]

Body:
Perhaps something like this

x = b[8]
output = []
output.append(x)
while x > 0:
    x = balance(b[9], b[11], X)
    output.append(x)


问:
SCNetworkReachabilityGetFlags returns 0 even when wireless available
I have an app that uses Apples reachability code. When I tab out of the app, turn on airplane mode, go back into the app, I correctly get a message that says no connection is available. If I go back out turn OFF airplane mode and go back into the app, I STILL get the message that no connection is available. The specific problem code is this:

```<code>NetworkStatus status = kNotReachable;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
    status = [self networkStatusForFlags: flags];
    return status;
}
</code>```

I get inside the if statement and flags ends up being 0 (kSCNetworkReachabilityFlagsTransientConnection). What does that mean exactly? Has anyone experienced this and does anyone know a work-around or fix? Been playing with it for hours...

答: If the flags were received and they end up being 0, as you've seen, this indicates Airplane Mode is on.  However, the results of this check seem to be cached, at least for a short time.  Try this: leave your app, turn Airplane Mode off, hit a site in Mobile Safari, then return to your app.  This may invalidate the cache.</p>

Body:
I have an app that uses Apples reachability code. When I tab out of the app, turn on airplane mode, go back into the app, I correctly get a message that says no connection is available. If I go back out turn OFF airplane mode and go back into the app, I STILL get the message that no connection is available. The specific problem code is this:

NetworkStatus status = kNotReachable;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
    status = [self networkStatusForFlags: flags];
    return status;
}

I get inside the if statement and flags ends up being 0 (kSCNetworkReachabilityFlagsTransientConnection). What does that mean exactly? Has anyone experienced this and does anyone know a work-around or fix? Been playing with it for hours...


问:
Apaches Ignite doesn't serialize/deserialize Guavas LoadingCache
I'm using Java7 and I'm configuring Apaches Ignite (version 2.7.5) where the servers/clients are up and running. However, clients are unable to retrieve Guavas LoadingCache variable from the object (however ConcurrentHashMap is retrieved without issues). It seems that somehow on Ignites proxy calls the object is not serialized/deserialized correctly and I'm having trouble as Guavas docs says that LoadingCache/Cache implement Serializable.

In the following sample, MyContainer class and _foo1 are ok and were correctly serialized and deserialized but _foo (LoadingCache) was not.

```<code>public class MyContainer {

private final ConcurrentHashMap<Object, Object> _foo1 = new ConcurrentHashMap<>();

private final LoadingCache<Object, Test> _foo = CacheBuilder.newBuilder().weakValues()
               .build(new CacheLoader<Object, Test>() {
                @Override public Test load(Object key) throws Exception {
                     return new Test(key);
                }});

}
</code>```

Please let me know if you need more details and any help is greatly appreciated.
Best Regards, Hélder

UPDATE

Hello everyone, with Denis response I did more digging and found some mentions about cfg.setMarshaller(new OptimizedMarshaller().setRequireSerializable(false)); and it worked. However, setMarshaller is deprecated and I'm not sure about this approach implications mainly at performance level.

Any read/explanation on what was the big deal behind the deprecation of this method?

Best Regards, Hélder

答:
The CacheBuilder constructs an instance of LocalCache.LocalLoadingCache. It has a writeReplace method that messes up the serialization.

This issue has been fixed in Ignite 2.3: https://issues.apache.org/jira/browse/IGNITE-6485

Which version of Ignite do you use? I would recommend upgrading to a fresh version of Ignite and switching to Java 8 or 11, since Java 7 is not supported by Ignite anymore.

Body:
I'm using Java7 and I'm configuring Apaches Ignite (version 2.7.5) where the servers/clients are up and running. However, clients are unable to retrieve Guavas LoadingCache variable from the object (however ConcurrentHashMap is retrieved without issues). It seems that somehow on Ignites proxy calls the object is not serialized/deserialized correctly and I'm having trouble as Guavas docs says that LoadingCache/Cache implement Serializable.

In the following sample, MyContainer class and _foo1 are ok and were correctly serialized and deserialized but _foo (LoadingCache) was not.

public class MyContainer {

private final ConcurrentHashMap<Object, Object> _foo1 = new ConcurrentHashMap<>();

private final LoadingCache<Object, Test> _foo = CacheBuilder.newBuilder().weakValues()
               .build(new CacheLoader<Object, Test>() {
                @Override public Test load(Object key) throws Exception {
                     return new Test(key);
                }});

}

Please let me know if you need more details and any help is greatly appreciated.
Best Regards, Hélder

UPDATE

Hello everyone, with Denis response I did more digging and found some mentions about cfg.setMarshaller(new OptimizedMarshaller().setRequireSerializable(false)); and it worked. However, setMarshaller is deprecated and I'm not sure about this approach implications mainly at performance level.

Any read/explanation on what was the big deal behind the deprecation of this method?

Best Regards, Hélder


问:
How to validate multiple flask forms in a single method?
I am validating three forms in the same method, I was able to validate two out of three forms, but third form is not validating.

```<code>views.py
......
@main.route('/tournament/<tid>', methods=["GET", "POST"])
def tournament(tid):
    ......
    form1 = AddTeamForm()
    form2 = CreateTeamForm()
    form3 = CreateMatchForm()

    # Dynamic allocation of team choices
    team_choices = [(team.id, team.name) for team in tournament.teams]
    form3.team1.choices = team_choices
    form3.team2.choices = team_choices

    if form1.validate_on_submit():
        .....
        return redirect(url_for('main.tournament', tid=tid))

    if form2.validate_on_submit():
        .....
        return redirect(url_for('main.tournament', tid=tid))

    if form3.validate_on_submit():
        print('Passed the validation')
        team1 = Team.query.get(int(form3.team1.data))
        team2 = Team.query.get(int(form3.team2.data))
        match = Match(
            tournment_id=tid,
            name=team1.name+' Vs '+team2.name,
            match_date=form3.match_date.data)
        match.teams.append(team1)
        match.teams.append(team2)
        db.session.add(match)
        db.session.commit()
        return redirect(url_for('main.tournament', tid=tid))

    return render_template(
        'main/tournment.html',
        form1=form1,
        form2=form2,
        form3=form3)

forms.py
....
class CreateMatchForm(FlaskForm):
    team1 = SelectField('Team1',  coerce=int, validators=[DataRequired()])
    team2 = SelectField('Team2',  coerce=int, validators=[DataRequired()])
    match_date = DateField('Match Date', validators=[DataRequired()],
        render_kw={'type': 'date'},
        default=date.today()+timedelta(days=1))
    submit = SubmitField('Create New Match')

tournment.html
....
<form class="form-inline" method="POST" action="{{ url_for('main.tournament', tid=tid) }}">
    {{ form3.hidden_tag() }}
    {{ form3.team1(class="form-control m-2")}}
    {{ form3.team1(class="form-control m-2")}}
    {{ form3.match_date(class="form-control m-2")}}
    {{ form3.submit(class="form-control m-2 btn btn-success btn-sm")}}
</form>
</code>```

This is how the UI looks:

After Post Request:

It's not even printing the print/error message.

The third form is not validating for any value, so the matches are not creating. I tried to create matches using the same script in flask shell, its perfectly working and the matches are creating, but I was unable to create using this form. How do I get through it?

答:
I figured out a temporary solution. Instead of using flask forms I used raw html forms and it worked.

Replaced form3 with request object in views.py:

```<code>if request.method == "POST":
        print('Passed the validation')
        team1 = Team.query.get(int(request.form['team1']))
        team2 = Team.query.get(int(request.form['team2']))
        match = Match(
            tournament_id=tid,
            name=team1.name+' Vs '+team2.name,
            match_date=request.form['match_date'])
        match.teams.append(team1)
        match.teams.append(team2)
        db.session.add(match)
        db.session.commit()
        return redirect(url_for('main.tournament', tid=tid))
</code>```

Replaced flask forms with raw html forms:

```<code><form class="form-inline" method="POST" action="{{ url_for('main.tournment', tid=tid) }}">
    <select class="form-control m-2" id="team1" name="team1" required="">
        {% for team in tournament.teams %}
            <option value={{team.id}}>{{team.name}}</option>
        {% endfor %}
    </select>
    <select class="form-control m-2" id="team2" name="team2" required="">
        {% for team in tournament.teams %}
            <option value={{team.id}}>{{team.name}}</option>
        {% endfor %}
    </select>
    <input class="form-control m-2" type="date" name="match_date" required="">
    <input class="form-control m-2 btn btn-success btn-sm" type="submit" value="Create Match">
</form>
</code>```

Now it is working as expected:

Still, I am clueless. Why it's not working using flask forms?

Body:
I am validating three forms in the same method, I was able to validate two out of three forms, but third form is not validating.

views.py
......
@main.route('/tournament/<tid>', methods=["GET", "POST"])
def tournament(tid):
    ......
    form1 = AddTeamForm()
    form2 = CreateTeamForm()
    form3 = CreateMatchForm()

    # Dynamic allocation of team choices
    team_choices = [(team.id, team.name) for team in tournament.teams]
    form3.team1.choices = team_choices
    form3.team2.choices = team_choices

    if form1.validate_on_submit():
        .....
        return redirect(url_for('main.tournament', tid=tid))

    if form2.validate_on_submit():
        .....
        return redirect(url_for('main.tournament', tid=tid))

    if form3.validate_on_submit():
        print('Passed the validation')
        team1 = Team.query.get(int(form3.team1.data))
        team2 = Team.query.get(int(form3.team2.data))
        match = Match(
            tournment_id=tid,
            name=team1.name+' Vs '+team2.name,
            match_date=form3.match_date.data)
        match.teams.append(team1)
        match.teams.append(team2)
        db.session.add(match)
        db.session.commit()
        return redirect(url_for('main.tournament', tid=tid))

    return render_template(
        'main/tournment.html',
        form1=form1,
        form2=form2,
        form3=form3)

forms.py
....
class CreateMatchForm(FlaskForm):
    team1 = SelectField('Team1',  coerce=int, validators=[DataRequired()])
    team2 = SelectField('Team2',  coerce=int, validators=[DataRequired()])
    match_date = DateField('Match Date', validators=[DataRequired()],
        render_kw={'type': 'date'},
        default=date.today()+timedelta(days=1))
    submit = SubmitField('Create New Match')

tournment.html
....
<form class="form-inline" method="POST" action="{{ url_for('main.tournament', tid=tid) }}">
    {{ form3.hidden_tag() }}
    {{ form3.team1(class="form-control m-2")}}
    {{ form3.team1(class="form-control m-2")}}
    {{ form3.match_date(class="form-control m-2")}}
    {{ form3.submit(class="form-control m-2 btn btn-success btn-sm")}}
</form>

This is how the UI looks:

After Post Request:

It's not even printing the print/error message.

The third form is not validating for any value, so the matches are not creating. I tried to create matches using the same script in flask shell, its perfectly working and the matches are creating, but I was unable to create using this form. How do I get through it?

Body:
I figured out a temporary solution. Instead of using flask forms I used raw html forms and it worked.

Replaced form3 with request object in views.py:

if request.method == "POST":
        print('Passed the validation')
        team1 = Team.query.get(int(request.form['team1']))
        team2 = Team.query.get(int(request.form['team2']))
        match = Match(
            tournament_id=tid,
            name=team1.name+' Vs '+team2.name,
            match_date=request.form['match_date'])
        match.teams.append(team1)
        match.teams.append(team2)
        db.session.add(match)
        db.session.commit()
        return redirect(url_for('main.tournament', tid=tid))

Replaced flask forms with raw html forms:

<form class="form-inline" method="POST" action="{{ url_for('main.tournment', tid=tid) }}">
    <select class="form-control m-2" id="team1" name="team1" required="">
        {% for team in tournament.teams %}
            <option value={{team.id}}>{{team.name}}</option>
        {% endfor %}
    </select>
    <select class="form-control m-2" id="team2" name="team2" required="">
        {% for team in tournament.teams %}
            <option value={{team.id}}>{{team.name}}</option>
        {% endfor %}
    </select>
    <input class="form-control m-2" type="date" name="match_date" required="">
    <input class="form-control m-2 btn btn-success btn-sm" type="submit" value="Create Match">
</form>

Now it is working as expected:

Still, I am clueless. Why it's not working using flask forms?


问:
How can I check if value is object or array of objects via Joi
My request body can be a single JSON object or array of JSON objects:

Single JSON Object

```<code>{
   "name" : "item 1",
   "description" : "item 1 description"
}
</code>```

Array of JSON Object

```<code>[{
   "name" : "item 1",
   "description" : "item 1 description"
}, {
   "name" : "item 2",
   "description" : "item 2 description"
}
]
</code>```

I want to validate these cases via celebrate/Joi

```<code>export const Create = celebrate({
    [ Segments.BODY ]: Joi.any() // how can I handle them here
});
</code>```

答:
How to tell if item is array or object, using vanilla JavaScript:

    const arrayOrObject = (item) => {
      if (item instanceof Array) return ‘array’;
      else if (item instanceof Object) return ‘object’;
      return null;
    }
```

<p>A similar "array or object" test using <code>Joi</code>:</p>

<pre class="lang-js prettyprint-override"><code>    const Joi = require('@hapi/joi');

    const isArray = (item) => !Joi.array().validate(item).error;
    const isObject = (item) => !Joi.object().validate(item).error;

    let arr = [1,2,3];
    console.log(isArray(arr));  // true
    console.log(isObject(arr)); // false

    obj = {foo: "bar"};
    console.log(isArray(obj));  // false
    console.log(isObject(obj)); // true
</code>```

Body:
My request body can be a single JSON object or array of JSON objects:

Single JSON Object

{
   "name" : "item 1",
   "description" : "item 1 description"
}

Array of JSON Object

[{
   "name" : "item 1",
   "description" : "item 1 description"
}, {
   "name" : "item 2",
   "description" : "item 2 description"
}
]

I want to validate these cases via celebrate/Joi

export const Create = celebrate({
    [ Segments.BODY ]: Joi.any() // how can I handle them here
});

Body:
How to tell if item is array or object, using vanilla JavaScript:

    const arrayOrObject = (item) => {
      if (item instanceof Array) return ‘array’;
      else if (item instanceof Object) return ‘object’;
      return null;
    }

A similar "array or object" test using Joi:

    const Joi = require('@hapi/joi');

    const isArray = (item) => !Joi.array().validate(item).error;
    const isObject = (item) => !Joi.object().validate(item).error;

    let arr = [1,2,3];
    console.log(isArray(arr));  // true
    console.log(isObject(arr)); // false

    obj = {foo: "bar"};
    console.log(isArray(obj));  // false
    console.log(isObject(obj)); // true


问:
Intl.NumberFormat to format price in Norwegian Krone
I'm trying to format a price using Intl.NumberFormat(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) in Norwegian Krone.

The instruction I'm using is:

console.log(new Intl.NumberFormat('no-NO', { style: 'currency', currency: 'NOK' }).format(123));```

But as you can see, the output is "123,00 NOK" while I was expecting "123,00 kr".
Have anyone encountered the same problem ?

Thanks for your help

答:
One workaround could be if you only wanna get kr:

console.log(new Intl.NumberFormat('sv', { style: 'currency', currency: 'SEK'}).format(number));

Body:
I'm trying to format a price using Intl.NumberFormat(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) in Norwegian Krone.

The instruction I'm using is:

console.log(new Intl.NumberFormat('no-NO', { style: 'currency', currency: 'NOK' }).format(123));

But as you can see, the output is "123,00 NOK" while I was expecting "123,00 kr".
Have anyone encountered the same problem ?

Thanks for your help


问:
How to use NSTask with pbcopy?
I am a beginner and I have a problem. I would like to use NSTask with the command "pbcopy". I tried this but it seems that it doesn't work :

```<code>NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/echo"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"my-text-to-copy", @"| pbcopy", nil];
[task setArguments: arguments];

[task launch];
</code>```

Any ideas ? Thanks.

It works fine :

```<code>NSTask *task = [[NSTask alloc] init];

NSPipe *pipe;
pipe = [NSPipe pipe];

task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/echo"];
[task setStandardOutput:pipe]; // write to pipe
[task setArguments: [NSArray arrayWithObjects: @"tmp", nil]];
[task launch];
[task waitUntilExit];

task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/pbcopy"];
[task setStandardInput:pipe]; // read from pipe
[task launch];
[task waitUntilExit];
</code>```

答:
The pipe ("|") is a feature of the shell, not an argument to the command you're using. You have to use two NSTasks, one for echo and one for pbcopy and set up an NSPipe between them.

Btw, I'm assuming that you're just using this as an example. Otherwise it would be much simpler to use NSPasteboard for this.

Title: How to use NSTask with pbcopy?

Body:
I am a beginner and I have a problem. I would like to use NSTask with the command "pbcopy". I tried this but it seems that it doesn't work :

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/echo"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"my-text-to-copy", @"| pbcopy", nil];
[task setArguments: arguments];

[task launch];

Any ideas ? Thanks.

It works fine :

NSTask *task = [[NSTask alloc] init];

NSPipe *pipe;
pipe = [NSPipe pipe];

task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/echo"];
[task setStandardOutput:pipe]; // write to pipe
[task setArguments: [NSArray arrayWithObjects: @"tmp", nil]];
[task launch];
[task waitUntilExit];

task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/pbcopy"];
[task setStandardInput:pipe]; // read from pipe
[task launch];
[task waitUntilExit];


问:
GroupBy unique aggregation and with specific condition in pandas
I have a dataframe as shown below

```<code>UnitID    Sector    Start_Date      Status
1         SE1       2018-02-26      Closed
1         SE1       2019-03-27      Active
2         SE1       2017-02-26      Closed
2         SE1       2018-02-26      Closed
2         SE1       2019-02-26      Active
3         SE1       NaT             Not_in_contract
4         SE1       NaT             Not_in_contract
5         SE2       2017-02-26      Closed
5         SE2       2018-02-26      Closed
5         SE2       2019-02-26      Active
6         SE2       2018-02-26      Closed
6         SE2       2019-02-26      Active
7         SE2       2018-02-26      Closed
7         SE2       2018-07-15      Closed
8         SE2       NaT             Not_in_contract
9         SE2       NaT             Not_in_contract
10        SE2       2019-05-22      Active
11        SE2       2019-06-24      Active
</code>```

From the above I would like to prepare below data frame

```<code>Sector      Number_of_unique_units     Number_of_Active_units
SE1         4                          2
SE2         7                          4
</code>```

答:
Use GroupBy.agg with DataFrameGroupBy.nunique and custom lambda function with count number of Active by sum of boolean mask:

```<code>df1=(df.groupby('Sector').agg(Number_of_unique_units=('UnitID','nunique'),
                              Number_of_Active_units=('Status',lambda x:x.eq('Active').sum()))
                         .reset_index())
print (df1)
  Sector  Number_of_unique_units  Number_of_Active_units
0    SE1                       4                       2
1    SE2                       7                       4
</code>```

Body:
I have a dataframe as shown below

UnitID    Sector    Start_Date      Status
1         SE1       2018-02-26      Closed
1         SE1       2019-03-27      Active
2         SE1       2017-02-26      Closed
2         SE1       2018-02-26      Closed
2         SE1       2019-02-26      Active
3         SE1       NaT             Not_in_contract
4         SE1       NaT             Not_in_contract
5         SE2       2017-02-26      Closed
5         SE2       2018-02-26      Closed
5         SE2       2019-02-26      Active
6         SE2       2018-02-26      Closed
6         SE2       2019-02-26      Active
7         SE2       2018-02-26      Closed
7         SE2       2018-07-15      Closed
8         SE2       NaT             Not_in_contract
9         SE2       NaT             Not_in_contract
10        SE2       2019-05-22      Active
11        SE2       2019-06-24      Active

From the above I would like to prepare below data frame

Sector      Number_of_unique_units     Number_of_Active_units
SE1         4                          2
SE2         7                          4

Body:
Use GroupBy.agg with DataFrameGroupBy.nunique and custom lambda function with count number of Active by sum of boolean mask:

df1=(df.groupby('Sector').agg(Number_of_unique_units=('UnitID','nunique'),
                              Number_of_Active_units=('Status',lambda x:x.eq('Active').sum()))
                         .reset_index())
print (df1)
  Sector  Number_of_unique_units  Number_of_Active_units
0    SE1                       4                       2
1    SE2                       7                       4


问:
Is there a better way to join query in laravel eloquent.?
I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error

```<code>Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)
</code>```

my code for the query is following.

```<code> public function bride(){

    $query = app(UserDetail::class)->newQuery();
    $query= $query->where('gender','LIKE','female');
    $query= $query->where('matrimonial','LIKE','1');
    $query = $query->rightJoin('users','users_details.user_id','=','users.id');
    $request = request();
      if(request()->exists('sort')){
        $sorts = explode(',',request()->sort);
        foreach ($sorts as $sort){
            list($sortCol, $sortDir) = explode('|',$sort);
            $query = $query->orderBy($sortCol,$sortDir);
         }
    }
     else {
            $query = $query->orderBy('id','asc');
        }
  if($request->exists('filter')) {
      $query->where(function($q) use($request){
        $value = "%{$request->filter}%";
        $q->where('name','like',$value)
              ->orWhere('father_name','like',$value)
              ->orWhere('city','like',$value)
              ->orWhere('mother_name','like',$value);
      });
  }
  $per_page = request()->has('per_page')?(int) request()->per_page : null;
  $pagination = $query->paginate($per_page);
  $pagination->appends([
      'sort'=>request()->sort,
      'filter'=>request()->filter,
      'per_page'=>request()->per_page
  ]);

    return response()->json(
        $pagination
    )
    ->header('Access-Control-Allow-Origin','*')
    ->header('Access-Control-Allow-Methods','GET');
}
</code>```

What should I do to get the result. Thanks

答:
Because there are same column name in your tables(gender in user_details and users), you need to specify the table name with the column, so that mysql can find the true column for you,

like this:

    $query= $query->where('user_details.gender','LIKE','female');
```

Body:
I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error

Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)

my code for the query is following.

 public function bride(){

    $query = app(UserDetail::class)->newQuery();
    $query= $query->where('gender','LIKE','female');
    $query= $query->where('matrimonial','LIKE','1');
    $query = $query->rightJoin('users','users_details.user_id','=','users.id');
    $request = request();
      if(request()->exists('sort')){
        $sorts = explode(',',request()->sort);
        foreach ($sorts as $sort){
            list($sortCol, $sortDir) = explode('|',$sort);
            $query = $query->orderBy($sortCol,$sortDir);
         }
    }
     else {
            $query = $query->orderBy('id','asc');
        }
  if($request->exists('filter')) {
      $query->where(function($q) use($request){
        $value = "%{$request->filter}%";
        $q->where('name','like',$value)
              ->orWhere('father_name','like',$value)
              ->orWhere('city','like',$value)
              ->orWhere('mother_name','like',$value);
      });
  }
  $per_page = request()->has('per_page')?(int) request()->per_page : null;
  $pagination = $query->paginate($per_page);
  $pagination->appends([
      'sort'=>request()->sort,
      'filter'=>request()->filter,
      'per_page'=>request()->per_page
  ]);

    return response()->json(
        $pagination
    )
    ->header('Access-Control-Allow-Origin','*')
    ->header('Access-Control-Allow-Methods','GET');
}

What should I do to get the result. Thanks


问:
Library build fails with Angular 9
I am trying to migrate this library https://github.com/flauc/angular2-notifications from Angular 2+ to Angular 9.

The original error was about the ModuleWithProviders that has become a generic type, so I fixed it. I also had an error described here https://github.com/angular/angular/issues/32352 which i fixed with require('@angular/compiler-cli'); and now I'm facing another error:

../node_modules/@angular/common/common.d.ts:115:22 - error NG6002:
  Appears in the NgModule.imports of SimpleNotificationsModule, but
  could not be resolved to an NgModule class

It's pretty hard for me to understand what's going on since I've never built a library before, and the build with gulp appears to be kinda hacky, since this line ngc = require('@angular/compiler-cli/src/main').main refers to a function that does not belong to the public API.

Edit:

Following the idea in the comments (and my own feeling), I tried to build without gulp:

Created a angular.json file

Separated index.ts into public_api.ts and simple-notifications.module.ts

Did some changes in the files and folders structure

But I still have the same exact error...

My attempt: https://github.com/youkouleley/angular2-notifications
I try to build this with ng build, the scripts in package.json have not been updated

答:
I figured out what going wrong, I had a Angular 8 project (containing a library project) that I have upgraded to Angular 9 (with a lib also: ng generate library core, I created at first a new angular 9 project to compare the differences with my project made with ng 8, i figure out that there is some things missing, here is the steps I followed:
- Delete node_modules
- Delete dist folder
- In the Angular 9 project lib there is a new file called: tsconfig.lib.prod.json

```<code>{
  "extends": "./tsconfig.lib.json",
  "angularCompilerOptions": {
    "enableIvy": false
  }
}
</code>```

In your angular.json add the following:

```<code>{
  ...
  "projects": {
     ...
     "configurations": {
            "production": {
              "tsConfig": "projects/core/tsconfig.lib.prod.json"
             }
      }
  ...
  }
}
</code>```

run ng build --prod, and everything will work :D

PS: in this case the library is called "core"

Title: Library build fails with Angular 9

Body:
I figured out what going wrong, I had a Angular 8 project (containing a library project) that I have upgraded to Angular 9 (with a lib also: ng generate library core, I created at first a new angular 9 project to compare the differences with my project made with ng 8, i figure out that there is some things missing, here is the steps I followed:
- Delete node_modules
- Delete dist folder
- In the Angular 9 project lib there is a new file called: tsconfig.lib.prod.json

{
  "extends": "./tsconfig.lib.json",
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

In your angular.json add the following:

{
  ...
  "projects": {
     ...
     "configurations": {
            "production": {
              "tsConfig": "projects/core/tsconfig.lib.prod.json"
             }
      }
  ...
  }
}

run ng build --prod, and everything will work :D

PS: in this case the library is called "core"


问:
Copying one file to another: scanf keeps looping
I am creating a program that takes two command-line arguments: the first line argument is the name of the file to be copied and the second is the new file. If the second argument is missing, copy the file to stdout. If both arguments are missing, the program should read from stdin and print to stdout ie. ./a.out input.txt output.txt

I did the following but I'm facing a problem where scanf keeps looping and does not quit:

```<code>int main(int argc, char *argv[]) `
{
    char text[10];
    FILE *input;
    FILE *output;
    char ch;

    printf("%s", argv[0]);
    if (argc == 3)
    {
        input = fopen(argv[1], "r");
        output = fopen(argv[2], "w");

        while ((ch = fgetc(input)) != EOF)
        {
            fputc(ch, output);
            ch = fgetc(output);
        }
    }

    if (argc == 2)
    {
        input = fopen(argv[1], "r");

        while ((ch = fgetc(input)) != EOF)
        {
            printf("%c", ch);
        }

        printf("\n");
    }

    if (argc == 1)
    {
        scanf("%c", text);
        // here it keeps looping
    }
    fclose(input);

    return 0;
}
</code>```

Screen shot with cursor at end of line after some input before return is hit

答:
There are multiple problems in your code:

You output argv[0] to stdout: if argc < 3, you are supposed to copy to stdout, this extra output is corrupting the output. You might instead output to stderr or remove this line completely.

you do not check for fopen failure, causing undefined behavior if either file cannot be opened.

ch has type char which is too small to accommodate for all return values of fgetc(). On machines with 8-bit bytes, fgetc() has 257 possible return values, you must make ch an int to reliably distinguish EOF from all other return values.

in the fgetc() / fputc() loop, you read 2 bytes in each iteration of the loop but only write one byte.

the scanf() on the last case is simply waiting for input as you are supposed to copy from stdin to stdout, but the program will stop as soon as you hit the Enter key. You should just use the same fgetc()/fputc() loop for all copying loops.

you should include <stdio.h>

Here is a modified version:

int main(int argc, char *argv[]) {
    FILE *input = stdin;
    FILE *output = stdout;
    int ch;

    if (argc > 1) {
        input = fopen(argv[1], "r");
        if (input == NULL) {
            fprintf("cannot open input file %s\n", argv[1]);
            return 1;
        }
    }
    if (argc > 2) {
        output = fopen(argv[2], "w");
        if (output == NULL) {
            fprintf("cannot open output file %s\n", argv[2]);
            return 1;
        }
    }
    while ((ch = fgetc(input)) != EOF) {
        fputc(ch, output);
    }
    if (argc > 2) {
        fclose(output);
    }
    if (argc > 1) {
        fclose(input);
    }
    return 0;
}
```

Body:
I am creating a program that takes two command-line arguments: the first line argument is the name of the file to be copied and the second is the new file. If the second argument is missing, copy the file to stdout. If both arguments are missing, the program should read from stdin and print to stdout ie. ./a.out input.txt output.txt

I did the following but I'm facing a problem where scanf keeps looping and does not quit:

int main(int argc, char *argv[]) `
{
    char text[10];
    FILE *input;
    FILE *output;
    char ch;

    printf("%s", argv[0]);
    if (argc == 3)
    {
        input = fopen(argv[1], "r");
        output = fopen(argv[2], "w");

        while ((ch = fgetc(input)) != EOF)
        {
            fputc(ch, output);
            ch = fgetc(output);
        }
    }

    if (argc == 2)
    {
        input = fopen(argv[1], "r");

        while ((ch = fgetc(input)) != EOF)
        {
            printf("%c", ch);
        }

        printf("\n");
    }

    if (argc == 1)
    {
        scanf("%c", text);
        // here it keeps looping
    }
    fclose(input);

    return 0;
}

Screen shot with cursor at end of line after some input before return is hit


问:
Accept 'DD MM YYYY' or 'DD MMM YYYY' at same time in ngx-Bootstrap datepicker
In ngx-Bootstrap datepicker

Currently the input only accepts 'DD MMM YYY' or 'MM DD YYYY' at same time.

If I give input like 30 10 1995 the it gives an error. Invalid format

how to achieve the 'DD/MM/YYYY' or 'DD MMM YYYY' accept input format at same time

ngx-Bootstrap: 1.9.3

Angular version: 4

答:
Looking at the source code, the config value dateInputFormat looks like it only handles a string.

https://github.com/valor-software/ngx-bootstrap/blob/development/src/datepicker/bs-datepicker.config.ts

The dateInputFormat is used in two places: 1. to parse and 2. to format.

For just parsing, you can get away with setting the dateInputFormat to an array, because the parser accepts either a string or an array.

```<code>**NOT A SOLUTION**
[bsConfig]="{ dateInputFormat: [ 'YYYY-MM-DD', 'DD-MM-YYYY' ] }"
</code>```

But then this causes errors when it comes to formatting the date for display in the input, as the formatter only accepts a string. This makes sense when you think about it, as the formatter would have to guess at which formatter you wanted to use, and there is potential for ambiguity between formats.

So as far as I can tell, it's not possible through the config.

Handling events via the (bsValueChange) event is also not possible, as it only fires when a "valid" date is found.

I think the requirement for multiple formats is a valid feature request. The spec would be something like

dateInputFormat accepts either a string or a string array. If a string, that format is used for both parsing and formatting. If an array, the first successful match is used for parsing. The first string is used for formatting.

Body:
Looking at the source code, the config value dateInputFormat looks like it only handles a string.

https://github.com/valor-software/ngx-bootstrap/blob/development/src/datepicker/bs-datepicker.config.ts

The dateInputFormat is used in two places: 1. to parse and 2. to format.

For just parsing, you can get away with setting the dateInputFormat to an array, because the parser accepts either a string or an array.

**NOT A SOLUTION**
[bsConfig]="{ dateInputFormat: [ 'YYYY-MM-DD', 'DD-MM-YYYY' ] }"

But then this causes errors when it comes to formatting the date for display in the input, as the formatter only accepts a string. This makes sense when you think about it, as the formatter would have to guess at which formatter you wanted to use, and there is potential for ambiguity between formats.

So as far as I can tell, it's not possible through the config.

Handling events via the (bsValueChange) event is also not possible, as it only fires when a "valid" date is found.

I think the requirement for multiple formats is a valid feature request. The spec would be something like

dateInputFormat accepts either a string or a string array. If a string, that format is used for both parsing and formatting. If an array, the first successful match is used for parsing. The first string is used for formatting.


问:
Invalid argument supplied for foreach() in Form and Multi Image upload in Laravel
The Form upload and the product image as featured image and other other images using the store function of laravel     </p>

```<code>use App\Productimage;
use App\Products;
public function store(Request $request)
{
    $featured = $request->featured_image->store('products_featured');
    $product = Products::create([       //uploading successfully
    'name'=>$request->name,
    'featured_image' => $featured,
    ]);
             foreach ($request->photos as $photo) {   //error
        $filename = $photo->store('product_images');
        Productimage::create([
            'product_id' => $product->id,
            'image_name' => $filename,
        ]);
    }
    return back();
}
</code>```

答:
you form should have enctype="multipart/form-data" and input type file is array

   foreach ($request->file('photos') as $photo) {   //error
            $filename = $photo->store('product_images');
            Productimage::create([
                'product_id' => $product->id,
                'image_name' => $filename,
            ]);
        }
```

<pre class="lang-html prettyprint-override"><code><form action="" method="post" enctype="multipart/form-data">
<input type="file" name="photos[]"/>

</code>```

Body:
The Form upload and the product image as featured image and other other images using the store function of laravel

use App\Productimage;
use App\Products;
public function store(Request $request)
{
    $featured = $request->featured_image->store('products_featured');
    $product = Products::create([       //uploading successfully
    'name'=>$request->name,
    'featured_image' => $featured,
    ]);
             foreach ($request->photos as $photo) {   //error
        $filename = $photo->store('product_images');
        Productimage::create([
            'product_id' => $product->id,
            'image_name' => $filename,
        ]);
    }
    return back();
}

Body:
you form should have enctype="multipart/form-data" and input type file is array

   foreach ($request->file('photos') as $photo) {   //error
            $filename = $photo->store('product_images');
            Productimage::create([
                'product_id' => $product->id,
                'image_name' => $filename,
            ]);
        }

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="photos[]"/>


问:
WSO2 ESB: How to handle internal error returned by an endpoint
I am using CALL mediator to invoke a Get method on an endpoint. The endpoint returns 500 internal server error as pasted below. But instead of control going to the fault sequence, the mediation flow continues as usual. How to route to fault sequence? How to handle internal error in wso2?</p>

```<code>[2020-02-14 17:51:21,175] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << HTTP/1.1 500 Internal Server Error
[2020-02-14 17:51:21,175] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << HTTP/1.1 500 Internal Server Error
[2020-02-14 17:51:21,176] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Strict-Transport-Security: max-age=15638400; includeSubDomains
[2020-02-14 17:51:21,176] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Strict-Transport-Security: max-age=15638400; includeSubDomains
[2020-02-14 17:51:21,177] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Access-Control-Allow-Methods: POST, GET
[2020-02-14 17:51:21,177] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Access-Control-Allow-Methods: POST, GET
</code>```

答:
WSO2 ESB does not hit fault sequence when the endpoint returns 500 because, irrespective of the response code, the mediation flow should proceed. We can retrieve the status code of the response and then trigger the fault sequence. A sample insequence is given below.</p>

```<code><inSequence>
     <call>
        <endpoint>
           <http uri-template="http://www.mocky.io/v2/5e465018330000520002605f"/>
        </endpoint>
     </call>
     <filter source="$axis2:HTTP_SC" regex="500">
        <then>
           <sequence key="fault"/>
        </then>
        <else/>
     </filter>
     <respond/>
  </inSequence>
</code>```

Body:
I am using CALL mediator to invoke a Get method on an endpoint. The endpoint returns 500 internal server error as pasted below. But instead of control going to the fault sequence, the mediation flow continues as usual. How to route to fault sequence? How to handle internal error in wso2?

[2020-02-14 17:51:21,175] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << HTTP/1.1 500 Internal Server Error
[2020-02-14 17:51:21,175] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << HTTP/1.1 500 Internal Server Error
[2020-02-14 17:51:21,176] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Strict-Transport-Security: max-age=15638400; includeSubDomains
[2020-02-14 17:51:21,176] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Strict-Transport-Security: max-age=15638400; includeSubDomains
[2020-02-14 17:51:21,177] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Access-Control-Allow-Methods: POST, GET
[2020-02-14 17:51:21,177] DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 << Access-Control-Allow-Methods: POST, GET

Body:
WSO2 ESB does not hit fault sequence when the endpoint returns 500 because, irrespective of the response code, the mediation flow should proceed. We can retrieve the status code of the response and then trigger the fault sequence. A sample insequence is given below.

<inSequence>
     <call>
        <endpoint>
           <http uri-template="http://www.mocky.io/v2/5e465018330000520002605f"/>
        </endpoint>
     </call>
     <filter source="$axis2:HTTP_SC" regex="500">
        <then>
           <sequence key="fault"/>
        </then>
        <else/>
     </filter>
     <respond/>
  </inSequence>


问:
XML style information
I am trying to learn XML with some simple code. When the code is opened in a web browser, there's a message saying:

This XML file does not appear to have any style information associated with it. The document tree is shown below.

After the above message, the XML is displayed

What does this warning message mean, and how can I solve it?

答:
xml & svg namespace bug

The reason is that the SVG file was not set the right namespace, so the browser can not render it rightly for preview, only show XML tree.

my solution

you just need manually add an SVG namespace before preview it, it's so easy!

   const svgAutoConvert = (svgStr = ``) => {
      // set svg namespace
      const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
      const xml = /<\?xml[\s\S]*\?>/i;
      let result = ``;
      result = svgStr.replace(xml,``);
      let index = result.indexOf(`>`);
      // get the svg string, after remove error part
      result = result.substr(index + 1);
      result = viewport + result;
      // add xml namespace(not add below line, it's also OK)
      result = `<?xml version="1.0" encoding="UTF-8"?>\n` + result;
      return result;
    };

```

<h2>demo</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const log = console.log;

const box = document.querySelector(`[id="svg-box"]`);

const svgStr = box.innerHTML;

log(`svgStr \n`, svgStr);

const svgAutoConvert = (svgStr = ``) => {
  // set svg namespace
  const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
  const xml = /<\?xml[\s\S]*\?>/i;
  let result = ``;
  result = svgStr.replace(xml,``);
  let index = result.indexOf(`>`);
  // get the svg string, after remove error part
  result = result.substr(index + 1);
  result = viewport + result;
  // add xml namespace(not add below line, it's also OK)
  result = `<?xml version="1.0" encoding="UTF-8"?>\n` + result;
  return result;
};

const svgStrWithNamespace = svgAutoConvert(svgStr);
log(`svgStrWithNamespace \n`, svgStrWithNamespace);</code>```

  <svg width="187px" height="141px" viewBox="0 0 187 141" version="1.1">
      <polygon points="93.5 2 182.423784 52.4417594 148.457921 134.058241 38.5420789 134.058241 4.57621573 52.4417594"></polygon>
  </svg>

```

compare

https://cdn.xgqfrms.xyz/svg/namespace/poly.svg

https://cdn.xgqfrms.xyz/svg/namespace/poly-bug.svg

Title: XML style information

Body:
xml & svg namespace bug

The reason is that the SVG file was not set the right namespace, so the browser can not render it rightly for preview, only show XML tree.

my solution

you just need manually add an SVG namespace before preview it, it's so easy!

   const svgAutoConvert = (svgStr = ``) => {
      // set svg namespace
      const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
      const xml = /<\?xml[\s\S]*\?>/i;
      let result = ``;
      result = svgStr.replace(xml,``);
      let index = result.indexOf(`>`);
      // get the svg string, after remove error part
      result = result.substr(index + 1);
      result = viewport + result;
      // add xml namespace(not add below line, it's also OK)
      result = `<?xml version="1.0" encoding="UTF-8"?>\n` + result;
      return result;
    };

demo

const log = console.log;

const box = document.querySelector(`[id="svg-box"]`);

const svgStr = box.innerHTML;

log(`svgStr \n`, svgStr);

const svgAutoConvert = (svgStr = ``) => {
  // set svg namespace
  const viewport = `<svg width="100%" height="100%" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
  const xml = /<\?xml[\s\S]*\?>/i;
  let result = ``;
  result = svgStr.replace(xml,``);
  let index = result.indexOf(`>`);
  // get the svg string, after remove error part
  result = result.substr(index + 1);
  result = viewport + result;
  // add xml namespace(not add below line, it's also OK)
  result = `<?xml version="1.0" encoding="UTF-8"?>\n` + result;
  return result;
};

const svgStrWithNamespace = svgAutoConvert(svgStr);
log(`svgStrWithNamespace \n`, svgStrWithNamespace);

<div id="svg-box">
  <svg width="187px" height="141px" viewBox="0 0 187 141" version="1.1">
      <polygon points="93.5 2 182.423784 52.4417594 148.457921 134.058241 38.5420789 134.058241 4.57621573 52.4417594"></polygon>
  </svg>
</div>

compare

https://cdn.xgqfrms.xyz/svg/namespace/poly.svg

https://cdn.xgqfrms.xyz/svg/namespace/poly-bug.svg