问:
I am trying to load a jsp using spring boot with gradle but I am only getting internal server error
I am new to spring boot and trying to load a jsp page but even after trying a lot and searching on internet I couldn't find any solution of it. I am unable to get  the error causing part in this complete process.

To build this all I used command 'gradle build' on command prompt.

To start the server I used command :- java -jar build\libs\one-0.0.1-SNAPSHOT.war

then I on browser I typed :- http://localhost:8080/helloWorld

Here is my build.gradle

plugins {
 id 'org.springframework.boot' version '2.2.2.RELEASE'
 id 'io.spring.dependency-management' version '1.0.8.RELEASE'
 id 'java'
 id 'war'
}

group = 'com.tm'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
 developmentOnly
 runtimeClasspath {
  extendsFrom developmentOnly
 }
}

repositories {
 mavenCentral()
}

dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-actuator'
 implementation 'org.springframework.boot:spring-boot-starter-web'
  providedRuntime 'javax.servlet:jstl'
  providedRuntime 'org.apache.tomcat.embed:tomcat-embed-jasper'
 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
 developmentOnly 'org.springframework.boot:spring-boot-devtools'

 testImplementation('org.springframework.boot:spring-boot-starter-test') {
  exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
 }
}

test {
 useJUnitPlatform()
}```
</div>
</div>
</p>

<p>This is my java code of controller HelloJSPController.java, it is in this folder structure: \src\main\java\com\tm\one </p>

```package com.tm.one;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloJSPController
{
 @GetMapping("/helloWorld")
 public String helloWorld()
  {
    return "helloWorld";
  }
}
```

<p>This is WebMvcConfig.java configuration file</p>

```package com.tm.one.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
 @Bean
 public InternalResourceViewResolver viewResolver()
  {
     InternalResourceViewResolver resolver = new InternalResourceViewResolver();
     resolver.setPrefix("/WEB-INF/jsp/");
     resolver.setSuffix(".jsp");
     return resolver;
  }

 }
```

<p>OR I tried this two lines in application.propertes also instead of above configuration file </p>

<blockquote>
  <p>spring.mvc.view.prefix=/WEB-INF/jsp/<br>
    spring.mvc.view.suffix=.jsp</p>
</blockquote>

<p>This is JSP file helloWorld.jsp in folder structure :--  \one\src\main\webapp\WEB-INF\jsp</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    <h2>Hello everyone I am AD</h2>
</body>
</html></code>```

This is error I am getting on browser

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jan 13 16:53:14 IST 2020
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template [helloWorld], template might not exist or might not be accessible by any of the configured Template Resolvers```
</div>
</div>
</p>

<p>This is OneApplication.java</p>

```package com.tm.one;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication

    public class OneApplication extends SpringBootServletInitializer {

        public static void main(String[] args) {
            SpringApplication.run(OneApplication.class, args);
        }

    @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(OneApplication.class);
        }

    }
```

答: Had the same issue as you, and I believe it's not due to the java code. The only solution I found was switching to maven. Absolutely no other change in the java code, only build.gradle -> pom.xml.

Body:
I am new to spring boot and trying to load a jsp page but even after trying a lot and searching on internet I couldn't find any solution of it. I am unable to get  the error causing part in this complete process.

To build this all I used command 'gradle build' on command prompt.

To start the server I used command :- java -jar build\libs\one-0.0.1-SNAPSHOT.war

then I on browser I typed :- http://localhost:8080/helloWorld

Here is my build.gradle

plugins {
 id 'org.springframework.boot' version '2.2.2.RELEASE'
 id 'io.spring.dependency-management' version '1.0.8.RELEASE'
 id 'java'
 id 'war'
}

group = 'com.tm'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
 developmentOnly
 runtimeClasspath {
  extendsFrom developmentOnly
 }
}

repositories {
 mavenCentral()
}

dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-actuator'
 implementation 'org.springframework.boot:spring-boot-starter-web'
  providedRuntime 'javax.servlet:jstl'
  providedRuntime 'org.apache.tomcat.embed:tomcat-embed-jasper'
 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
 developmentOnly 'org.springframework.boot:spring-boot-devtools'

 testImplementation('org.springframework.boot:spring-boot-starter-test') {
  exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
 }
}

test {
 useJUnitPlatform()
}

This is my java code of controller HelloJSPController.java, it is in this folder structure: \src\main\java\com\tm\one

package com.tm.one;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloJSPController
{
 @GetMapping("/helloWorld")
 public String helloWorld()
  {
    return "helloWorld";
  }
}

This is WebMvcConfig.java configuration file

package com.tm.one.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
 @Bean
 public InternalResourceViewResolver viewResolver()
  {
     InternalResourceViewResolver resolver = new InternalResourceViewResolver();
     resolver.setPrefix("/WEB-INF/jsp/");
     resolver.setSuffix(".jsp");
     return resolver;
  }

 }

OR I tried this two lines in application.propertes also instead of above configuration file

spring.mvc.view.prefix=/WEB-INF/jsp/

    spring.mvc.view.suffix=.jsp

This is JSP file helloWorld.jsp in folder structure :--  \one\src\main\webapp\WEB-INF\jsp

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello</title>

Hello everyone I am AD

This is error I am getting on browser

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jan 13 16:53:14 IST 2020
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template [helloWorld], template might not exist or might not be accessible by any of the configured Template Resolvers

This is OneApplication.java

package com.tm.one;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication

    public class OneApplication extends SpringBootServletInitializer {

        public static void main(String[] args) {
            SpringApplication.run(OneApplication.class, args);
        }

    @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(OneApplication.class);
        }

    }


来源: stackexchange

问:
Subscribe is deprecated: Use an observer instead of an error callback
When I run the linter it says:

```<code>subscribe is deprecated: Use an observer instead of an error callback
</code>```

Code from this angular app:

    this.userService.updateUser(data).pipe(
       tap(() => {bla bla bla})
    ).subscribe(
       this.handleUpdateResponse.bind(this),
       this.handleError.bind(this)
    );
```

Don't know exactly what should I use and how...

Thanks!

答:
Find the details at official website
https://rxjs.dev/deprecations/subscribe-arguments

Notice the {} braces in second subscribe code below.

```<code>import { of } from 'rxjs';

// recommended
of([1,2,3]).subscribe((v) => console.info(v));
// also recommended
of([1,2,3]).subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete')
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I run the linter it says:

subscribe is deprecated: Use an observer instead of an error callback

Code from this angular app:

    this.userService.updateUser(data).pipe(
       tap(() => {bla bla bla})
    ).subscribe(
       this.handleUpdateResponse.bind(this),
       this.handleError.bind(this)
    );

Don't know exactly what should I use and how...

Thanks!

Body:
Find the details at official website
https://rxjs.dev/deprecations/subscribe-arguments

Notice the {} braces in second subscribe code below.

import { of } from 'rxjs';

// recommended
of([1,2,3]).subscribe((v) => console.info(v));
// also recommended
of([1,2,3]).subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete')
})


问:
I have a problem with <button>. I don't know what I'm doing wrong
I'm just a beginner and I'm trying to add a button with url to website.

It works in browser, but for some reason Dreamweaver keeps giving me error that special characters need to be escaped. Please help, what am I doing wrong?

Here's the button code I've written (of course button class has definition in style)

<button class="button button2", onclick="location.href=url.html">url_text</button>

答:
Try this instead:</p>
```<code><button class="button button2" onclick="location.href='url.html'">url_text</button>
</code>```

Body:
Try this instead:

<button class="button button2" onclick="location.href='url.html'">url_text</button>


问:
Use Ajax Json Data to Chart
I have ajax response like this

```<code>{
  "status": "success",
  "data": [
    {
      "DAY": "11",
      "SIGNUPS": 0,
      "VISITS": "0"
    },
    {
      "DAY": "12",
      "SIGNUPS": 3,
      "VISITS": "13"
    }
  ]
}
</code>```

I want use this data to my chart which have static data like this

```<code>var chartDom1 = document.getElementById('traffic_chart');
            var myChart1 = echarts.init(chartDom1);
            var option1;

            option1 = {
              title: {
                text: 'Stacked Line',
                show: false
              },
              tooltip: {
                trigger: 'axis'
              },
              legend: {
                data: ['Visits', 'Signups'],
                show:false
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              xAxis: {
                type: 'Day',
                boundaryGap: false,
                data: [1,2]
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  name: 'Visits',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                },
                {
                  name: 'Signups',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                }
              ]
            };

            option1 && myChart1.setOption(option1);
</code>```

I want use DAY Column in xAxis data and SIGNUPS and VISITS Column in Series, I have tried lot but not able to find proper way to do it. Sorry I am beginner and have not proper knowledge of JavaScript.

Thanks!

答:
If you want to pass the Day data as an array to xAxis data you should make an  array like this:

```<code>let array = [];
for (const i in response.data) {
   array.push(response.data[i].DAY);
}
</code>```

after this your array is like this:

```<code>[11, 12]
</code>```

and now you can pass it to your xAxis object ...

and also you can use this method for SIGNUPS and VISITS too.

Title: Use Ajax Json Data to Chart

Body:
I have ajax response like this

{
  "status": "success",
  "data": [
    {
      "DAY": "11",
      "SIGNUPS": 0,
      "VISITS": "0"
    },
    {
      "DAY": "12",
      "SIGNUPS": 3,
      "VISITS": "13"
    }
  ]
}

I want use this data to my chart which have static data like this

var chartDom1 = document.getElementById('traffic_chart');
            var myChart1 = echarts.init(chartDom1);
            var option1;

            option1 = {
              title: {
                text: 'Stacked Line',
                show: false
              },
              tooltip: {
                trigger: 'axis'
              },
              legend: {
                data: ['Visits', 'Signups'],
                show:false
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              toolbox: {
                feature: {
                  saveAsImage: {}
                }
              },
              xAxis: {
                type: 'Day',
                boundaryGap: false,
                data: [1,2]
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  name: 'Visits',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                },
                {
                  name: 'Signups',
                  type: 'line',
                  stack: 'Total',
                  data: [150, 232]
                }
              ]
            };

            option1 && myChart1.setOption(option1);

I want use DAY Column in xAxis data and SIGNUPS and VISITS Column in Series, I have tried lot but not able to find proper way to do it. Sorry I am beginner and have not proper knowledge of JavaScript.

Thanks!

Body:
If you want to pass the Day data as an array to xAxis data you should make an  array like this:

let array = [];
for (const i in response.data) {
   array.push(response.data[i].DAY);
}

after this your array is like this:

[11, 12]

and now you can pass it to your xAxis object ...

and also you can use this method for SIGNUPS and VISITS too.


问:
how to postback part of a page in ASP.NET
I know that update panels help rendering part of a page, but what I'm asking is how to postback part of a page to server not all. I have a page that has several inside each a form that postsback some info to server. I want each submit button to postback only it's own form information not all others too.

The actual problem is that when I submit one of the forms required field of other forms won't let me do the postback. So a rephrased question might be, how do I disable validation for a button and enable it for others?

答:
You need to use validation groups.  For example:

```<code><asp:requiredfieldvalidator
   ValidationGroup=“val_grp_1”
   ErrorText=“Missing Value”
   ControlToValidate=“txt_firstname”
   runat=“server”/>
</code>```

And then on your submit button, you reference the group you want to have validated:

```<code><asp:button
   text=“Group1”
   ValidationGroup=“val_grp_1”
   runat=“server”/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You need to use validation groups.  For example:

<asp:requiredfieldvalidator
   ValidationGroup=“val_grp_1”
   ErrorText=“Missing Value”
   ControlToValidate=“txt_firstname”
   runat=“server”/>

And then on your submit button, you reference the group you want to have validated:

<asp:button
   text=“Group1”
   ValidationGroup=“val_grp_1”
   runat=“server”/>


问:
How to push a docker image to a private repository
I have a docker image tagged as me/my-image, and I have a private repo on the dockerhub named me-private.

When I push my me/my-image, I end up always hitting the public repo.

What is the exact syntax to specifically push my image to my private repo?

答:
If somebody looking for a quick way to push all images to a private repository,
you can use my bash script - it will push all the Docker images to the new private registry:</p>
```<code>#!/bin/bash

repo="<change_to_your_new_repo>"
remote_repo="<the_new_repo_name>"

for img in $(docker images --format "{{.Repository}}:{{.Tag}}")
do
        image=$(echo $img | cut -d ":" -f 1)
        image_tag=$(echo $img | cut -d ":" -f 2)

        docker image tag $image:$image_tag $repo/$remote_repo/$image:$image_tag
        docker image push $repo/$remote_repo/$image:$image_tag

        docker rmi $repo/$remote_repo/$image:$image_tag
done
</code>```

Body:
If somebody looking for a quick way to push all images to a private repository,
you can use my bash script - it will push all the Docker images to the new private registry:

#!/bin/bash

repo="<change_to_your_new_repo>"
remote_repo="<the_new_repo_name>"

for img in $(docker images --format "{{.Repository}}:{{.Tag}}")
do
        image=$(echo $img | cut -d ":" -f 1)
        image_tag=$(echo $img | cut -d ":" -f 2)

        docker image tag $image:$image_tag $repo/$remote_repo/$image:$image_tag
        docker image push $repo/$remote_repo/$image:$image_tag

        docker rmi $repo/$remote_repo/$image:$image_tag
done


问:
HTML/CSS What is the name of the effect, video link pops on same page and background darkens?
First of all, im lurking for the last week and it very much helped me build the page with basically zero no none prior knowledge, thank you so much!

But now i want to build an effect and i cant search for it because i dont know what to search for. Can you help me get a name for that, im almost certain i can figure it out myself from there.

I want it so that when im clicking a picture which leads to a video it does not link me to a new page but playes the video with some custom text beneath on the same page and blacks out the environment, like a cinema mode? Like a popup on the same page which darkens the page behind.

答:
When the user click the image and the video starts you can set the background color with the rgba function (https://www.w3schools.com/cssref/func_rgba.asp).

With the alpha parameter you can set the opacity for your background, for example:

```<code>body {
    background-color: rgba(0,0,0,0.4); /* Black with opacity */
}
</code>```

Look to exclude the video element from this behaviour.

Body:
When the user click the image and the video starts you can set the background color with the rgba function (https://www.w3schools.com/cssref/func_rgba.asp).

With the alpha parameter you can set the opacity for your background, for example:

body {
    background-color: rgba(0,0,0,0.4); /* Black with opacity */
}

Look to exclude the video element from this behaviour.


问:
How to add line dash in Flutter
How to make a line dash in Flutter like this?

答:
The following code creates a dashed path not only for lines, but for any path you want dashed.

Demo:

The idea is to take the originalPath and move along it, alternately adding dashes and gaps until the entire path has been extracted:

Path _getDashedPath(
  Path originalPath,
  double dashLength,
  double dashGapLength,
) {
  final metricsIterator = originalPath.computeMetrics().iterator;
  while (metricsIterator.moveNext()) {
    final metric = metricsIterator.current;
    _dashedPathProperties.extractedPathLength = 0.0;
    while (_dashedPathProperties.extractedPathLength < metric.length) {
      if (_dashedPathProperties.addDashNext) {
        _dashedPathProperties.addDash(metric, dashLength);
      } else {
        _dashedPathProperties.addDashGap(metric, dashGapLength);
      }
    }
  }
  return _dashedPathProperties.path;
}
```
<p>I created a class <code>DashedPathProperties</code> to track things like the currently <code>extractedPathLength</code> or the <code>_remainingDashLength</code>, which becomes relevant if the <code>originalPath</code> consists of several sub-paths and a dash (or dash gap) must be continued on the next sub-path:</p>
<pre class="lang-dart prettyprint-override"><code>class DashedPathProperties {
  double extractedPathLength;
  Path path;

  final double _dashLength;
  double _remainingDashLength;
  double _remainingDashGapLength;
  bool _previousWasDash;

  DashedPathProperties({
    required this.path,
    required double dashLength,
    required double dashGapLength,
  })  : assert(dashLength > 0.0, 'dashLength must be > 0.0'),
        assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'),
        _dashLength = dashLength,
        _remainingDashLength = dashLength,
        _remainingDashGapLength = dashGapLength,
        _previousWasDash = false,
        extractedPathLength = 0.0;

  //...
}
</code>```

You can use like this (you could wrap your CustomPaint in a ClipRect if you want to make sure that the painter cannot paint outside of the bounds):

CustomPaint(
  painter: DashedPathPainter(
    originalPath: Path()
      ..addOval(
        const Rect.fromLTWH(0, 0, 100, 100),
      ),
    pathColor: Colors.white,
  ),
  size: const Size(100.0, 100.0),
)
```
<p>Full example code you can run in DartPad:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:ui' as ui;
import 'dart:math' as math;

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: ExampleDashedPath(),
        ),
      ),
    );
  }
}

class ExampleDashedPath extends StatelessWidget {
  const ExampleDashedPath({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()..lineTo(100, 0),
            pathColor: Colors.red,
            strokeWidth: 5.0,
            dashGapLength: 10.0,
            dashLength: 10.0,
          ),
          size: const Size(100.0, 2.0),
        ),
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()
              ..addOval(
                const Rect.fromLTWH(0, 0, 100, 100),
              ),
            pathColor: Colors.white,
          ),
          size: const Size(100.0, 100.0),
        ),
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()
              ..addRect(
                const Rect.fromLTWH(0, 0, 100, 100),
              )
              ..lineTo(100, 100),
            pathColor: Colors.grey,
            strokeWidth: 2.0,
            dashLength: 25.0,
          ),
          size: const Size(100.0, 100.0),
        ),
      ],
    );
  }
}

class DashedPathPainter extends CustomPainter {
  final Path originalPath;
  final Color pathColor;
  final double strokeWidth;
  final double dashGapLength;
  final double dashLength;
  late DashedPathProperties _dashedPathProperties;

  DashedPathPainter({
    required this.originalPath,
    required this.pathColor,
    this.strokeWidth = 3.0,
    this.dashGapLength = 5.0,
    this.dashLength = 10.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    _dashedPathProperties = DashedPathProperties(
      path: Path(),
      dashLength: dashLength,
      dashGapLength: dashGapLength,
    );
    final dashedPath = _getDashedPath(originalPath, dashLength, dashGapLength);
    canvas.drawPath(
      dashedPath,
      Paint()
        ..style = PaintingStyle.stroke
        ..color = pathColor
        ..strokeWidth = strokeWidth,
    );
  }

  @override
  bool shouldRepaint(DashedPathPainter oldDelegate) =>
      oldDelegate.originalPath != originalPath ||
      oldDelegate.pathColor != pathColor ||
      oldDelegate.strokeWidth != strokeWidth ||
      oldDelegate.dashGapLength != dashGapLength ||
      oldDelegate.dashLength != dashLength;

  Path _getDashedPath(
    Path originalPath,
    double dashLength,
    double dashGapLength,
  ) {
    final metricsIterator = originalPath.computeMetrics().iterator;
    while (metricsIterator.moveNext()) {
      final metric = metricsIterator.current;
      _dashedPathProperties.extractedPathLength = 0.0;
      while (_dashedPathProperties.extractedPathLength < metric.length) {
        if (_dashedPathProperties.addDashNext) {
          _dashedPathProperties.addDash(metric, dashLength);
        } else {
          _dashedPathProperties.addDashGap(metric, dashGapLength);
        }
      }
    }
    return _dashedPathProperties.path;
  }
}

class DashedPathProperties {
  double extractedPathLength;
  Path path;

  final double _dashLength;
  double _remainingDashLength;
  double _remainingDashGapLength;
  bool _previousWasDash;

  DashedPathProperties({
    required this.path,
    required double dashLength,
    required double dashGapLength,
  })  : assert(dashLength > 0.0, 'dashLength must be > 0.0'),
        assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'),
        _dashLength = dashLength,
        _remainingDashLength = dashLength,
        _remainingDashGapLength = dashGapLength,
        _previousWasDash = false,
        extractedPathLength = 0.0;

  bool get addDashNext {
    if (!_previousWasDash || _remainingDashLength != _dashLength) {
      return true;
    }
    return false;
  }

  void addDash(ui.PathMetric metric, double dashLength) {
    // Calculate lengths (actual + available)
    final end = _calculateLength(metric, _remainingDashLength);
    final availableEnd = _calculateLength(metric, dashLength);
    // Add path
    final pathSegment = metric.extractPath(extractedPathLength, end);
    path.addPath(pathSegment, Offset.zero);
    // Update
    final delta = _remainingDashLength - (end - extractedPathLength);
    _remainingDashLength = _updateRemainingLength(
      delta: delta,
      end: end,
      availableEnd: availableEnd,
      initialLength: dashLength,
    );
    extractedPathLength = end;
    _previousWasDash = true;
  }

  void addDashGap(ui.PathMetric metric, double dashGapLength) {
    // Calculate lengths (actual + available)
    final end = _calculateLength(metric, _remainingDashGapLength);
    final availableEnd = _calculateLength(metric, dashGapLength);
    // Move path's end point
    ui.Tangent tangent = metric.getTangentForOffset(end)!;
    path.moveTo(tangent.position.dx, tangent.position.dy);
    // Update
    final delta = end - extractedPathLength;
    _remainingDashGapLength = _updateRemainingLength(
      delta: delta,
      end: end,
      availableEnd: availableEnd,
      initialLength: dashGapLength,
    );
    extractedPathLength = end;
    _previousWasDash = false;
  }

  double _calculateLength(ui.PathMetric metric, double addedLength) {
    return math.min(extractedPathLength + addedLength, metric.length);
  }

  double _updateRemainingLength({
    required double delta,
    required double end,
    required double availableEnd,
    required double initialLength,
  }) {
    return (delta > 0 && availableEnd == end) ? delta : initialLength;
  }
}
</code>```

Title: How to add line dash in Flutter

Body:
The following code creates a dashed path not only for lines, but for any path you want dashed.

Demo:

The idea is to take the originalPath and move along it, alternately adding dashes and gaps until the entire path has been extracted:

Path _getDashedPath(
  Path originalPath,
  double dashLength,
  double dashGapLength,
) {
  final metricsIterator = originalPath.computeMetrics().iterator;
  while (metricsIterator.moveNext()) {
    final metric = metricsIterator.current;
    _dashedPathProperties.extractedPathLength = 0.0;
    while (_dashedPathProperties.extractedPathLength < metric.length) {
      if (_dashedPathProperties.addDashNext) {
        _dashedPathProperties.addDash(metric, dashLength);
      } else {
        _dashedPathProperties.addDashGap(metric, dashGapLength);
      }
    }
  }
  return _dashedPathProperties.path;
}

I created a class DashedPathProperties to track things like the currently extractedPathLength or the _remainingDashLength, which becomes relevant if the originalPath consists of several sub-paths and a dash (or dash gap) must be continued on the next sub-path:

class DashedPathProperties {
  double extractedPathLength;
  Path path;

  final double _dashLength;
  double _remainingDashLength;
  double _remainingDashGapLength;
  bool _previousWasDash;

  DashedPathProperties({
    required this.path,
    required double dashLength,
    required double dashGapLength,
  })  : assert(dashLength > 0.0, 'dashLength must be > 0.0'),
        assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'),
        _dashLength = dashLength,
        _remainingDashLength = dashLength,
        _remainingDashGapLength = dashGapLength,
        _previousWasDash = false,
        extractedPathLength = 0.0;

  //...
}

You can use like this (you could wrap your CustomPaint in a ClipRect if you want to make sure that the painter cannot paint outside of the bounds):

CustomPaint(
  painter: DashedPathPainter(
    originalPath: Path()
      ..addOval(
        const Rect.fromLTWH(0, 0, 100, 100),
      ),
    pathColor: Colors.white,
  ),
  size: const Size(100.0, 100.0),
)

Full example code you can run in DartPad:

import 'dart:ui' as ui;
import 'dart:math' as math;

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: ExampleDashedPath(),
        ),
      ),
    );
  }
}

class ExampleDashedPath extends StatelessWidget {
  const ExampleDashedPath({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()..lineTo(100, 0),
            pathColor: Colors.red,
            strokeWidth: 5.0,
            dashGapLength: 10.0,
            dashLength: 10.0,
          ),
          size: const Size(100.0, 2.0),
        ),
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()
              ..addOval(
                const Rect.fromLTWH(0, 0, 100, 100),
              ),
            pathColor: Colors.white,
          ),
          size: const Size(100.0, 100.0),
        ),
        const SizedBox(height: 50),
        CustomPaint(
          painter: DashedPathPainter(
            originalPath: Path()
              ..addRect(
                const Rect.fromLTWH(0, 0, 100, 100),
              )
              ..lineTo(100, 100),
            pathColor: Colors.grey,
            strokeWidth: 2.0,
            dashLength: 25.0,
          ),
          size: const Size(100.0, 100.0),
        ),
      ],
    );
  }
}

class DashedPathPainter extends CustomPainter {
  final Path originalPath;
  final Color pathColor;
  final double strokeWidth;
  final double dashGapLength;
  final double dashLength;
  late DashedPathProperties _dashedPathProperties;

  DashedPathPainter({
    required this.originalPath,
    required this.pathColor,
    this.strokeWidth = 3.0,
    this.dashGapLength = 5.0,
    this.dashLength = 10.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    _dashedPathProperties = DashedPathProperties(
      path: Path(),
      dashLength: dashLength,
      dashGapLength: dashGapLength,
    );
    final dashedPath = _getDashedPath(originalPath, dashLength, dashGapLength);
    canvas.drawPath(
      dashedPath,
      Paint()
        ..style = PaintingStyle.stroke
        ..color = pathColor
        ..strokeWidth = strokeWidth,
    );
  }

  @override
  bool shouldRepaint(DashedPathPainter oldDelegate) =>
      oldDelegate.originalPath != originalPath ||
      oldDelegate.pathColor != pathColor ||
      oldDelegate.strokeWidth != strokeWidth ||
      oldDelegate.dashGapLength != dashGapLength ||
      oldDelegate.dashLength != dashLength;

  Path _getDashedPath(
    Path originalPath,
    double dashLength,
    double dashGapLength,
  ) {
    final metricsIterator = originalPath.computeMetrics().iterator;
    while (metricsIterator.moveNext()) {
      final metric = metricsIterator.current;
      _dashedPathProperties.extractedPathLength = 0.0;
      while (_dashedPathProperties.extractedPathLength < metric.length) {
        if (_dashedPathProperties.addDashNext) {
          _dashedPathProperties.addDash(metric, dashLength);
        } else {
          _dashedPathProperties.addDashGap(metric, dashGapLength);
        }
      }
    }
    return _dashedPathProperties.path;
  }
}

class DashedPathProperties {
  double extractedPathLength;
  Path path;

  final double _dashLength;
  double _remainingDashLength;
  double _remainingDashGapLength;
  bool _previousWasDash;

  DashedPathProperties({
    required this.path,
    required double dashLength,
    required double dashGapLength,
  })  : assert(dashLength > 0.0, 'dashLength must be > 0.0'),
        assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'),
        _dashLength = dashLength,
        _remainingDashLength = dashLength,
        _remainingDashGapLength = dashGapLength,
        _previousWasDash = false,
        extractedPathLength = 0.0;

  bool get addDashNext {
    if (!_previousWasDash || _remainingDashLength != _dashLength) {
      return true;
    }
    return false;
  }

  void addDash(ui.PathMetric metric, double dashLength) {
    // Calculate lengths (actual + available)
    final end = _calculateLength(metric, _remainingDashLength);
    final availableEnd = _calculateLength(metric, dashLength);
    // Add path
    final pathSegment = metric.extractPath(extractedPathLength, end);
    path.addPath(pathSegment, Offset.zero);
    // Update
    final delta = _remainingDashLength - (end - extractedPathLength);
    _remainingDashLength = _updateRemainingLength(
      delta: delta,
      end: end,
      availableEnd: availableEnd,
      initialLength: dashLength,
    );
    extractedPathLength = end;
    _previousWasDash = true;
  }

  void addDashGap(ui.PathMetric metric, double dashGapLength) {
    // Calculate lengths (actual + available)
    final end = _calculateLength(metric, _remainingDashGapLength);
    final availableEnd = _calculateLength(metric, dashGapLength);
    // Move path's end point
    ui.Tangent tangent = metric.getTangentForOffset(end)!;
    path.moveTo(tangent.position.dx, tangent.position.dy);
    // Update
    final delta = end - extractedPathLength;
    _remainingDashGapLength = _updateRemainingLength(
      delta: delta,
      end: end,
      availableEnd: availableEnd,
      initialLength: dashGapLength,
    );
    extractedPathLength = end;
    _previousWasDash = false;
  }

  double _calculateLength(ui.PathMetric metric, double addedLength) {
    return math.min(extractedPathLength + addedLength, metric.length);
  }

  double _updateRemainingLength({
    required double delta,
    required double end,
    required double availableEnd,
    required double initialLength,
  }) {
    return (delta > 0 && availableEnd == end) ? delta : initialLength;
  }
}


问:
Finding if there is a space in a list(return boolean value)
Looking for some help on a tick tac toe exercise:

I have the bellow:

test_board = ['#','X','O','X','O','X','O','','O','X']

```<code>def space_check(board,position):
    free_space = ""
    if free_space in board[position]:
        return True
    else:
        return False
</code>```

When running the function I cannot see the False return, only True:

```<code>space_check(test_board,7)
Output: True
space_check(test_board,9)
Output: True
</code>```

答:
If free_space in board[position]

You are search a "" in a string not in a list of string,so the results always true because "" always exist in any string.

You just Use equal operation == instead of in.

Body:
Looking for some help on a tick tac toe exercise:

I have the bellow:

test_board = ['#','X','O','X','O','X','O','','O','X']

def space_check(board,position):
    free_space = ""
    if free_space in board[position]:
        return True
    else:
        return False

When running the function I cannot see the False return, only True:

space_check(test_board,7)
Output: True
space_check(test_board,9)
Output: True


问:
Reduce boolean Iterator
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);
```

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

答:
I think the cleanest is below. Using this reference pattern; you can also destructure
the tuple inline, whereas fold is a bit like reduce, except that you won't get constrained to Option<Self::Item> as return type, and have to provide an initial value, etc.

```<code>let result = row
    .iter()
    .map(|(_, marked)| marked)
    .fold(true, |acc, &mk| acc && mk);
</code>```

result will be of type bool.

Title: Reduce boolean Iterator

Body:
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

Body:
I think the cleanest is below. Using this reference pattern; you can also destructure
the tuple inline, whereas fold is a bit like reduce, except that you won't get constrained to Option<Self::Item> as return type, and have to provide an initial value, etc.

let result = row
    .iter()
    .map(|(_, marked)| marked)
    .fold(true, |acc, &mk| acc && mk);

result will be of type bool.


问:
Can't play wav or mp3 files with Javafx MediaPlayer. Also can't play wav files with the native java library
I have a java project where I have to make a music player that plays either wav or mp3 files. However I can't get my wav or mp3 files to play using the Javafx libraries or with native java libraries. I've checked and made sure the wav and mp3 files I'm using to test aren't corrupted. I'm using Javafx 17.0.2 and JDK 11.

Mini Reproducible Example With Javafx

JavaFxMp3WavPlayer

```<code>package mediaplayerjavafx;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class JavaFxMp3WavPlayer extends Application {

    public static void main(String[] args) throws MalformedURLException, IOException {
        launch(args);

    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("My");
        Button button = new Button("My Button");
        Scene scene = new Scene(button, 200, 100);
        stage.setScene(scene);
        stage.show();
        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
        String path = file.toURI().toASCIIString();
        Media media = new Media(path);
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        button.setOnAction(new EventHandler() {
            @Override
            public void handle(Event arg0) {
                runMusicPlayer(mediaPlayer);
            }
        });
    }

    public void runMusicPlayer(MediaPlayer mediaPlayer) {
        mediaPlayer.play();
    }
}
</code>```

module-info

```<code>module MotisHarmony {
    requires javafx.swt;
    requires javafx.base;
    requires javafx.controls;
    requires javafx.fxml;
    requires javafx.graphics;
    requires javafx.media;
    requires javafx.swing;
    requires javafx.web;
    exports mediaplayerjavafx;
    opens mediaplayerjavafx to javafx.graphics;
}
</code>```

Error Produced

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
    at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:519)
    at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:422)
    at MotisHarmony/mediaplayerjavafx.JavaFxMp3WavPlayer.start(JavaFxMp3WavPlayer.java:37)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    ... 1 more
Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
    at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:297)
    at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:475)
    ... 11 more
Exception running application mediaplayerjavafx.JavaFxMp3WavPlayer
</code>```

So after this didn't work, I tried it with native Java libraries.

Mini Reproducible Example With Native Java Libraries

JavaWavPlayer

```<code>import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class JavaWavPlayer {

    /**
     * @param args the command line arguments
     */
    public static Clip clip;

    public static void main(String[] args) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
        File yourFile = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\WavTest.wav");
        AudioInputStream stream;
        AudioFormat format;
        DataLine.Info info;
        stream = AudioSystem.getAudioInputStream(yourFile);
        format = stream.getFormat();
        info = new DataLine.Info(Clip.class, format);
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(stream);
        clip.start();
    }

}
</code>```

Error Produced

```<code>Exception in thread "main" java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported.
    at java.desktop/javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:425)
    at javawavplayer.JavaWavPlayer.main(JavaWavPlayer.java:33)
C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:1330: The following error occurred while executing this line:
C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:936: Java returned: 1
</code>```

Extra Information

Link to the Mp3 file I used to test.
https://drive.google.com/file/d/1CvAafbMviQ7nvKyojnem9GK73LJsD6MJ/view?usp=sharing

Link to the Wav file I used to text.
https://drive.google.com/file/d/1k7a93pZIGY65sGs8BrFMDgeRrgYc0C5k/view?usp=sharing

I am using JDK 11 and Javafx 17.0.2

System Type: 64-bit operating system, x64-based processor

Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz   2.81 GHz

Windows Edition: Windows 10 Home

答:
I could not reproduce your issue.

Your issue is environmental, exactly what it is I could not say.

I advise creating a new project in idea and following the same steps I did and it should work as long as you have the file path correct.

These are the steps I followed to get allow the media to play with your sample app:

Created a new JavaFX project in Idea with OpenJDK 17.0.2 and JavaFX 17.0.2 on Windows 11.

Copy-and-pasted your JavaFX sample code into the new project.

Followed the instructions to add media handling to the project:

Can not work with MediaPlayer class, javafx.media is not found

Downloaded your mp3 and wav files.

Set the file path to each in turn.

Ran the app and hit the play button for each file.

Both the MP3 and WAV files played without problem.

Your lie in april is nice, I will try to learn it.

Body:
I have a java project where I have to make a music player that plays either wav or mp3 files. However I can't get my wav or mp3 files to play using the Javafx libraries or with native java libraries. I've checked and made sure the wav and mp3 files I'm using to test aren't corrupted. I'm using Javafx 17.0.2 and JDK 11.

Mini Reproducible Example With Javafx

JavaFxMp3WavPlayer

package mediaplayerjavafx;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class JavaFxMp3WavPlayer extends Application {

    public static void main(String[] args) throws MalformedURLException, IOException {
        launch(args);

    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("My");
        Button button = new Button("My Button");
        Scene scene = new Scene(button, 200, 100);
        stage.setScene(scene);
        stage.show();
        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
        String path = file.toURI().toASCIIString();
        Media media = new Media(path);
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        button.setOnAction(new EventHandler() {
            @Override
            public void handle(Event arg0) {
                runMusicPlayer(mediaPlayer);
            }
        });
    }

    public void runMusicPlayer(MediaPlayer mediaPlayer) {
        mediaPlayer.play();
    }
}

module-info

module MotisHarmony {
    requires javafx.swt;
    requires javafx.base;
    requires javafx.controls;
    requires javafx.fxml;
    requires javafx.graphics;
    requires javafx.media;
    requires javafx.swing;
    requires javafx.web;
    exports mediaplayerjavafx;
    opens mediaplayerjavafx to javafx.graphics;
}

Error Produced

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
    at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:519)
    at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:422)
    at MotisHarmony/mediaplayerjavafx.JavaFxMp3WavPlayer.start(JavaFxMp3WavPlayer.java:37)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    ... 1 more
Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
    at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:297)
    at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:475)
    ... 11 more
Exception running application mediaplayerjavafx.JavaFxMp3WavPlayer

So after this didn't work, I tried it with native Java libraries.

Mini Reproducible Example With Native Java Libraries

JavaWavPlayer

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class JavaWavPlayer {

    /**
     * @param args the command line arguments
     */
    public static Clip clip;

    public static void main(String[] args) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
        File yourFile = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\WavTest.wav");
        AudioInputStream stream;
        AudioFormat format;
        DataLine.Info info;
        stream = AudioSystem.getAudioInputStream(yourFile);
        format = stream.getFormat();
        info = new DataLine.Info(Clip.class, format);
        clip = (Clip) AudioSystem.getLine(info);
        clip.open(stream);
        clip.start();
    }

}

Error Produced

Exception in thread "main" java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported.
    at java.desktop/javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:425)
    at javawavplayer.JavaWavPlayer.main(JavaWavPlayer.java:33)
C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:1330: The following error occurred while executing this line:
C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:936: Java returned: 1

Extra Information

Link to the Mp3 file I used to test.
https://drive.google.com/file/d/1CvAafbMviQ7nvKyojnem9GK73LJsD6MJ/view?usp=sharing

Link to the Wav file I used to text.
https://drive.google.com/file/d/1k7a93pZIGY65sGs8BrFMDgeRrgYc0C5k/view?usp=sharing

I am using JDK 11 and Javafx 17.0.2

System Type: 64-bit operating system, x64-based processor

Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz   2.81 GHz

Windows Edition: Windows 10 Home


问:
GameplayKit: Enemy agent overshoots destination point during seek behavior
I'm trying to incorporate GameplayKit into a SpriteKit project.

Specifically, I'm trying to use GameplayKit's seek-and-avoid behavior wherein an "enemy" character chases a moving "player" character while avoiding obstacles.

I have managed to make the enemy seek the player, but the enemy's movement is weird/undesirable: The enemy's speed should adjust so that it comes to a halt at the desired end point, however its speed does not change, which makes it overshoot its target considerably.

Think of a fast-moving train: Once it gets up to speed, it's hard to stop; it wants to just keep on moving. It's the same phenomenon with the enemy character sprite. It moves like a heavy, lumbering object that can't stop quickly enough.

Here's what I'm doing (please assume that properties such as node are defined):

Configure the player character's GameplayKit stuff:

```<code>let entity1 = GKEntity()
heroAgent = GKAgent2D()
heroComponent = GKSKNodeComponent(node: node)
heroAgent.delegate = self
node.entity = entity1
heroEntity = entity1
if let comp = heroComponent {
    entity1.addComponent(comp)
    entity1.addComponent(heroAgent)
}
</code>```

Configure the enemy character's GameplayKit stuff:

```<code>let entity = GKEntity()
let agent = GKAgent2D()
let avoid = GKGoal(toAvoid: obstaclesForThisLevel!, maxPredictionTime: 1000.0)
let pursue = GKGoal(toInterceptAgent: heroAgent, maxPredictionTime: 0.0)
nodeComponent = GKSKNodeComponent(node: node)
agent.maxSpeed = 100.0
agent.maxAcceleration = 50.0
agent.position = vector_float2(x: Float(levelData.enemies[i].x), y: Float(levelData.enemies[i].y))
agent.radius = Float(node.size.width*0.5)
agent.behavior = GKBehavior(goals: [avoid, pursue], andWeights: [100.0, 100.0])
agent.delegate = self
node.entity = entity
enemyAgent = agent
if let comp = nodeComponent {
    entity.addComponent(comp)
    entity.addComponent(agent)
}
nodeEntity = entity
</code>```

In the SKScene's update(_:) method, set the player agent's position and call the enemy character's update(deltaTime:) method:

```<code>//Coordinate the hero agent's position with the hero's actual position. Without this, the values in agentDidUpdate() are nan.
heroAgent.position = vector_float2(x: Float(mainCharacter?.position.x ?? 0.0), y: Float(mainCharacter?.position.y ?? 0.0))
nodeComponent?.node.entity?.update(deltaTime: currentTime-lastFrameTime)
</code>```

Set the enemy character's position in agentDidUpdate(_:):

```<code>func agentDidUpdate(_ agent: GKAgent) {
   if let a = agent as? GKAgent2D {
      nodeComponent?.node.position = CGPoint(x: CGFloat(a.position.x), y: CGFloat(a.position.y))
   }
}
</code>```

Question: Why is the enemy character overshooting its designated target point instead of managing its speed correctly, and how do I fix the issue?

Thank you!

答:
I decided to only use GameplayKit for the purpose of generating a path around the obstacles (findPath(from:to:) is very helpful), and to simply move the enemy character along that path via SKAction.follow(_:asOffset:orientToPath:speed:) when I want to send the enemy back to its starting position.

So, to accomplish the "seeking" behavior, I'm just doing the following from inside my SKScene's update(_:) method:

```<code>let dx = mainCharacter.position.x - enemy.position.x
let dy = mainCharacter.position.y - enemy.position.y
let angle = atan2(dy, dx)
let vx = cos(angle) * enemySpeed
let vy = sin(angle) * enemySpeed

enemy.physicsBody?.velocity.dx = vx
enemy.physicsBody?.velocity.dy = vy
</code>```

This seeking behavior does not consider obstacles, so the enemy can get kind of stuck behind an obstacle that's located between the enemy and the player. So, it's not ideal, but I think it's going to work for me because of other factors in my game.

To generate a path that does consider obstacles, for use with SKAction, I'm doing the following:

```<code>let graph = GKObstacleGraph(obstacles: obstaclesForThisLevel, bufferRadius: 0.0)
let startingPoint = GKGraphNode2D(point: vector_float2(x: Float(enemy.position.x), y: Float(enemy.position.y)))
let endPoint = GKGraphNode2D(point: vector_float2(x: Float(enemy.enemyOriginalPosition.x), y: Float(enemy.enemyOriginalPosition.y)))
graph.connectUsingObstacles(node: startingPoint)
graph.connectUsingObstacles(node: endPoint)
let path = (graph as GKGraph).findPath(from: startingPoint, to: endPoint)

if path.count >= 2 {
    let realPath = GKPath(graphNodes: path, radius: 100.0)
    let myPath: UIBezierPath = UIBezierPath()

     for j in 1..<realPath.numPoints {
          let previousPoint = realPath.float2(at: j-1)
          let nextPoint = realPath.float2(at: j)
          if j == 1 {
              myPath.move(to: CGPoint(x: CGFloat(previousPoint.x), y: CGFloat(previousPoint.y)))
          }
          myPath.addLine(to: CGPoint(x: CGFloat(nextPoint.x), y: CGFloat(nextPoint.y)))
      }
}
</code>```

And finally:

```<code>let followPath = SKAction.follow(myPath.cgPath, asOffset: false, orientToPath: false, speed: enemySpeed)

enemy.run(followPath)
</code>```

Body:
I'm trying to incorporate GameplayKit into a SpriteKit project.

Specifically, I'm trying to use GameplayKit's seek-and-avoid behavior wherein an "enemy" character chases a moving "player" character while avoiding obstacles.

I have managed to make the enemy seek the player, but the enemy's movement is weird/undesirable: The enemy's speed should adjust so that it comes to a halt at the desired end point, however its speed does not change, which makes it overshoot its target considerably.

Think of a fast-moving train: Once it gets up to speed, it's hard to stop; it wants to just keep on moving. It's the same phenomenon with the enemy character sprite. It moves like a heavy, lumbering object that can't stop quickly enough.

Here's what I'm doing (please assume that properties such as node are defined):

Configure the player character's GameplayKit stuff:

let entity1 = GKEntity()
heroAgent = GKAgent2D()
heroComponent = GKSKNodeComponent(node: node)
heroAgent.delegate = self
node.entity = entity1
heroEntity = entity1
if let comp = heroComponent {
    entity1.addComponent(comp)
    entity1.addComponent(heroAgent)
}

Configure the enemy character's GameplayKit stuff:

let entity = GKEntity()
let agent = GKAgent2D()
let avoid = GKGoal(toAvoid: obstaclesForThisLevel!, maxPredictionTime: 1000.0)
let pursue = GKGoal(toInterceptAgent: heroAgent, maxPredictionTime: 0.0)
nodeComponent = GKSKNodeComponent(node: node)
agent.maxSpeed = 100.0
agent.maxAcceleration = 50.0
agent.position = vector_float2(x: Float(levelData.enemies[i].x), y: Float(levelData.enemies[i].y))
agent.radius = Float(node.size.width*0.5)
agent.behavior = GKBehavior(goals: [avoid, pursue], andWeights: [100.0, 100.0])
agent.delegate = self
node.entity = entity
enemyAgent = agent
if let comp = nodeComponent {
    entity.addComponent(comp)
    entity.addComponent(agent)
}
nodeEntity = entity

In the SKScene's update(_:) method, set the player agent's position and call the enemy character's update(deltaTime:) method:

//Coordinate the hero agent's position with the hero's actual position. Without this, the values in agentDidUpdate() are nan.
heroAgent.position = vector_float2(x: Float(mainCharacter?.position.x ?? 0.0), y: Float(mainCharacter?.position.y ?? 0.0))
nodeComponent?.node.entity?.update(deltaTime: currentTime-lastFrameTime)

Set the enemy character's position in agentDidUpdate(_:):

func agentDidUpdate(_ agent: GKAgent) {
   if let a = agent as? GKAgent2D {
      nodeComponent?.node.position = CGPoint(x: CGFloat(a.position.x), y: CGFloat(a.position.y))
   }
}

Question: Why is the enemy character overshooting its designated target point instead of managing its speed correctly, and how do I fix the issue?

Thank you!

Body:
I decided to only use GameplayKit for the purpose of generating a path around the obstacles (findPath(from:to:) is very helpful), and to simply move the enemy character along that path via SKAction.follow(_:asOffset:orientToPath:speed:) when I want to send the enemy back to its starting position.

So, to accomplish the "seeking" behavior, I'm just doing the following from inside my SKScene's update(_:) method:

let dx = mainCharacter.position.x - enemy.position.x
let dy = mainCharacter.position.y - enemy.position.y
let angle = atan2(dy, dx)
let vx = cos(angle) * enemySpeed
let vy = sin(angle) * enemySpeed

enemy.physicsBody?.velocity.dx = vx
enemy.physicsBody?.velocity.dy = vy

This seeking behavior does not consider obstacles, so the enemy can get kind of stuck behind an obstacle that's located between the enemy and the player. So, it's not ideal, but I think it's going to work for me because of other factors in my game.

To generate a path that does consider obstacles, for use with SKAction, I'm doing the following:

let graph = GKObstacleGraph(obstacles: obstaclesForThisLevel, bufferRadius: 0.0)
let startingPoint = GKGraphNode2D(point: vector_float2(x: Float(enemy.position.x), y: Float(enemy.position.y)))
let endPoint = GKGraphNode2D(point: vector_float2(x: Float(enemy.enemyOriginalPosition.x), y: Float(enemy.enemyOriginalPosition.y)))
graph.connectUsingObstacles(node: startingPoint)
graph.connectUsingObstacles(node: endPoint)
let path = (graph as GKGraph).findPath(from: startingPoint, to: endPoint)

if path.count >= 2 {
    let realPath = GKPath(graphNodes: path, radius: 100.0)
    let myPath: UIBezierPath = UIBezierPath()

     for j in 1..<realPath.numPoints {
          let previousPoint = realPath.float2(at: j-1)
          let nextPoint = realPath.float2(at: j)
          if j == 1 {
              myPath.move(to: CGPoint(x: CGFloat(previousPoint.x), y: CGFloat(previousPoint.y)))
          }
          myPath.addLine(to: CGPoint(x: CGFloat(nextPoint.x), y: CGFloat(nextPoint.y)))
      }
}

And finally:

let followPath = SKAction.follow(myPath.cgPath, asOffset: false, orientToPath: false, speed: enemySpeed)

enemy.run(followPath)


问:
Recursive Function to Create DOM Tree String from DOM Object
I'm currently struggling with trying to build out a function that should take an input object from parsing HTML5 (node-html5-parser) and I need to process all tags and children tags, with their content to output a string of xml. The issue I'm running into is how to get a recursive function (or any function) to properly maintain the HTML5 tag order and outputting the content.

Example:

My Content

With the node-html5-parser, I get the following when it parses that:

```<code>rootElem {
    childNodes: [
        {
            tagName: 'div',
            childNodes: [
                {
                    tagName: 'span',
                    childNodes: [
                        {
                             rawText: 'My Content'
                        }
                    ],
                }
            ]
        }
    ]
}
</code>```

I thought a simple DFS recursive algorithm could be used to build up a string, but I can't get it to work correctly.

```<code>const DOMRootObj = parse(this.htmlStr);

const processedData = this.processContent(DOMRootObj);
</code>```

```<code> processContent(root: any): string {
    if (root && !root.childNodes.length) {
      return root.rawText;
    } else {
      for (const childNode of root.childNodes) {

        const str = this.processContent(childNode);

        const { tagName } = childNode;

        if (tagName) {
          this.outputStr += `<${tagName}>${str}</${tagName}>`;
        }

      }
    }

  }
</code>```

from this HTML that's parsed by the parse() function: (object is as above)

```<code><div><span>My Content</span></div>
</code>```

This ends up outputting:

```<code><span>undefined</span><div>undefined</div>
</code>```

but It should output:

```<code><div><span>My Content</span></div>
</code>```

答:
Unpolished code, but you can get the ideia. You can add more attributes like onclick and tabindex simply by repeating the pattern. Although I don't think putting everything on the generator a good idea (you can lose track of what's being generated).</p>
```<code>fillHeaderCurrenciesList = () => {
    // Generated structure example
    // <div
    //     id='currency-1'
    //     class='currency currency--hoverable'
    //     onclick='selectMainCurrency(this.id)'
    // >
    //     <div class='currency__name'>Bitcoin</div>

    //     <div class='currency__icon'>
    //         <img src='assets/img/icon-coin.svg' alt='LG Bank' />

    //         <img src='assets/img/icon-btc.svg' alt='LG Bank' />
    //     </div>

    //     <div class='currency__balance'>
    //         <span class='currency__title'>Balance</span>

    //         <div class='currency__value'>
    //             <span>Exemplo1 | R$ 234.342.367,90</span>
    //         </div>
    //     </div>
    // </div>;

    let currenciesList = document.getElementById('currencies-list');

    for (let i = 0; i < currencyData.length; i++) {
        const currency = currencyData[i];

        let currencyTree = {
            tagName: 'div',

            id: `currency-${i}`,
            class: ['currency', 'currency--hoverable'],
            onClick: function () {
                selectMainCurrency(this, 'currencies-main-currency');
            },

            onKeyDown: function () {
                keyDownEnter(
                    selectMainCurrency(this, 'currencies-main-currency')
                );
            },

            tabIndex: '0',

            children: [
                {
                    tagName: 'div',
                    class: ['currency__name'],
                    text: currency.name,
                },

                {
                    tagName: 'div',
                    class: ['currency__icon'],

                    children: [
                        {
                            tagName: 'img',
                            src: currency.icon.src,
                            alt: currency.icon.alt,
                        },

                        {
                            tagName: 'img',
                            src: currency.iconName.src,
                            alt: currency.iconName.alt,
                        },
                    ],
                },

                {
                    tagName: 'div',
                    class: ['currency__balance'],

                    children: [
                        {
                            tagName: 'span',
                            class: ['currency__title'],
                            text: 'Balance',
                        },

                        {
                            tagName: 'div',
                            class: ['currency__value'],

                            children: [
                                {
                                    tagName: 'span',
                                    text: currency.balance,
                                },
                            ],
                        },
                    ],
                },
            ],
        };

        currenciesList.appendChild(DOMListItemGenerator(currencyTree));
    }
};

const currencyData = [
    {
        name: 'bitcoin',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo1bitcoin | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'teste',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo3teste | R$ 234.342.367,90',
    },
];

fillHeaderCurrenciesList();

DOMListItemGenerator = (inputTree) => {
    let tree = Object.entries(inputTree);
    let item;
    let output;

    for (let i = 0; i < tree.length; i++) {
        const branch = tree[i];

        if (branch[0] === 'tagName') {
            output = document.createElement(branch[1]);
        }

        if (branch[0] === 'id') {
            output.setAttribute('id', branch[1]);
        }

        if (branch[0] === 'tabIndex') {
            output.setAttribute('tabindex', branch[1]);
        }

        if (branch[0] === 'class') {
            for (const classItem of branch[1]) {
                output.classList.add(classItem);
            }
        }

        if (branch[0] === 'src') {
            output.src = branch[1];
        }

        if (branch[0] === 'alt') {
            output.alt = branch[1];
        }

        if (branch[0] === 'text') {
            output.textContent = branch[1];
        }

        if (branch[0] === 'onClick') {
            output.onclick = branch[1];
        }

        if (branch[0] === 'onKeyDown') {
            output.onkeydown = branch[1];
        }

        if (branch[0] === 'children' && branch[1].length > 0) {
            for (let j = 0; j < branch[1].length; j++) {
                const children = branch[1][j];
                item = DOMListItemGenerator(children);
                output.appendChild(item);
            }
        }
    }

    return output;
};
</code>```

Body:
I'm currently struggling with trying to build out a function that should take an input object from parsing HTML5 (node-html5-parser) and I need to process all tags and children tags, with their content to output a string of xml. The issue I'm running into is how to get a recursive function (or any function) to properly maintain the HTML5 tag order and outputting the content.

Example:

My Content

With the node-html5-parser, I get the following when it parses that:

rootElem {
    childNodes: [
        {
            tagName: 'div',
            childNodes: [
                {
                    tagName: 'span',
                    childNodes: [
                        {
                             rawText: 'My Content'
                        }
                    ],
                }
            ]
        }
    ]
}

I thought a simple DFS recursive algorithm could be used to build up a string, but I can't get it to work correctly.

const DOMRootObj = parse(this.htmlStr);

const processedData = this.processContent(DOMRootObj);

 processContent(root: any): string {
    if (root && !root.childNodes.length) {
      return root.rawText;
    } else {
      for (const childNode of root.childNodes) {

        const str = this.processContent(childNode);

        const { tagName } = childNode;

        if (tagName) {
          this.outputStr += `<${tagName}>${str}</${tagName}>`;
        }

      }
    }

  }

from this HTML that's parsed by the parse() function: (object is as above)

My Content

This ends up outputting:

undefined
undefined

but It should output:

My Content

Body:
Unpolished code, but you can get the ideia. You can add more attributes like onclick and tabindex simply by repeating the pattern. Although I don't think putting everything on the generator a good idea (you can lose track of what's being generated).

fillHeaderCurrenciesList = () => {
    // Generated structure example
    // <div
    //     id='currency-1'
    //     class='currency currency--hoverable'
    //     onclick='selectMainCurrency(this.id)'
    // >
    //     <div class='currency__name'>Bitcoin</div>

    //     <div class='currency__icon'>
    //         <img src='assets/img/icon-coin.svg' alt='LG Bank' />

    //         <img src='assets/img/icon-btc.svg' alt='LG Bank' />
    //     </div>

    //     <div class='currency__balance'>
    //         <span class='currency__title'>Balance</span>

    //         <div class='currency__value'>
    //             <span>Exemplo1 | R$ 234.342.367,90</span>
    //         </div>
    //     </div>
    // </div>;

    let currenciesList = document.getElementById('currencies-list');

    for (let i = 0; i < currencyData.length; i++) {
        const currency = currencyData[i];

        let currencyTree = {
            tagName: 'div',

            id: `currency-${i}`,
            class: ['currency', 'currency--hoverable'],
            onClick: function () {
                selectMainCurrency(this, 'currencies-main-currency');
            },

            onKeyDown: function () {
                keyDownEnter(
                    selectMainCurrency(this, 'currencies-main-currency')
                );
            },

            tabIndex: '0',

            children: [
                {
                    tagName: 'div',
                    class: ['currency__name'],
                    text: currency.name,
                },

                {
                    tagName: 'div',
                    class: ['currency__icon'],

                    children: [
                        {
                            tagName: 'img',
                            src: currency.icon.src,
                            alt: currency.icon.alt,
                        },

                        {
                            tagName: 'img',
                            src: currency.iconName.src,
                            alt: currency.iconName.alt,
                        },
                    ],
                },

                {
                    tagName: 'div',
                    class: ['currency__balance'],

                    children: [
                        {
                            tagName: 'span',
                            class: ['currency__title'],
                            text: 'Balance',
                        },

                        {
                            tagName: 'div',
                            class: ['currency__value'],

                            children: [
                                {
                                    tagName: 'span',
                                    text: currency.balance,
                                },
                            ],
                        },
                    ],
                },
            ],
        };

        currenciesList.appendChild(DOMListItemGenerator(currencyTree));
    }
};

const currencyData = [
    {
        name: 'bitcoin',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo1bitcoin | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'ethereum',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo2ethereum | R$ 234.342.367,90',
    },
    {
        name: 'teste',
        icon: {
            src: 'assets/img/icon-coin.svg',
            alt: 'LG Bank',
        },
        iconName: {
            src: 'assets/img/icon-btc.svg',
            alt: 'LG Bank',
        },
        quotation: '',
        balance: 'Exemplo3teste | R$ 234.342.367,90',
    },
];

fillHeaderCurrenciesList();

DOMListItemGenerator = (inputTree) => {
    let tree = Object.entries(inputTree);
    let item;
    let output;

    for (let i = 0; i < tree.length; i++) {
        const branch = tree[i];

        if (branch[0] === 'tagName') {
            output = document.createElement(branch[1]);
        }

        if (branch[0] === 'id') {
            output.setAttribute('id', branch[1]);
        }

        if (branch[0] === 'tabIndex') {
            output.setAttribute('tabindex', branch[1]);
        }

        if (branch[0] === 'class') {
            for (const classItem of branch[1]) {
                output.classList.add(classItem);
            }
        }

        if (branch[0] === 'src') {
            output.src = branch[1];
        }

        if (branch[0] === 'alt') {
            output.alt = branch[1];
        }

        if (branch[0] === 'text') {
            output.textContent = branch[1];
        }

        if (branch[0] === 'onClick') {
            output.onclick = branch[1];
        }

        if (branch[0] === 'onKeyDown') {
            output.onkeydown = branch[1];
        }

        if (branch[0] === 'children' && branch[1].length > 0) {
            for (let j = 0; j < branch[1].length; j++) {
                const children = branch[1][j];
                item = DOMListItemGenerator(children);
                output.appendChild(item);
            }
        }
    }

    return output;
};


问:
dotnet ef core HttpContext.User.Claims doesn't match with JWT

here is my JWT.
My HttpContext.User doesn't match with JWT.

here my httpcontext:

Plese help me...

Program.cs:

答:
Usually,setting the MapInboundClaims=false should stop the library from renaming your claims.

But you could try to add the following to your startup class:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // By default, Microsoft has some legacy claim mapping that converts
    // standard JWT claims into proprietary ones. This removes those mappings.
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
    ..
</code>```

Body:
Usually,setting the MapInboundClaims=false should stop the library from renaming your claims.

But you could try to add the following to your startup class:

public void ConfigureServices(IServiceCollection services)
{
    // By default, Microsoft has some legacy claim mapping that converts
    // standard JWT claims into proprietary ones. This removes those mappings.
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
    ..


问:
How to convert dataURL to file object in javascript?
I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.</p>

答:
In Latest browsers:

const dataURLtoBlob = (dataURL) => {
        fetch(dataURL)
            .then(res => res.blob())
            .then(blob => console.log(blob))
            .catch(err => console.log(err))
    }```


问:
Is there a way to render files from a MySQL database into a website?
I'm tasked to build a web document management system where files (PDFs, and perhaps images) will be uploaded and viewed later in the website. Currently what I have is the upload goes into MySQl workbench, in a longblob data type field.

I want to render the files on the webpage somewhat like research journal websites that have a PDF viewer of some sort in their pages.

I tried selecting the File value off the database table, and placing it in iframe's src attribute but it does not do anything. Though iframe does render the file if given a file address on my computer.

答:
You should not save file in mysql!
Its better to save the file somewhere on your host then give the files links to the mysql and for rendering it you should load files from their links.
Or You can use other tricks ...
I personally use this trick !</p>


问:
How to get the Screen Coordinates anywhere in the phone Flutter
I'm trying to find the coordinates for the screen while I'm outside of the app. I found a way to get the coordinates inside the app by this way.

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  GlobalKey key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Material(
        child: Listener(
          child: SizedBox.expand(
            key: key,
            child: GestureDetector(

              onPanUpdate: (details) {
                print(details.globalPosition);
              },

            ),
          ),
        ),
      ),
    );
  }
}
</code>```

```<code>I/flutter ( 9587): Offset(149.4, 182.0)
I/flutter ( 9587): Offset(148.6, 182.8)
I/flutter ( 9587): Offset(148.6, 183.4)
</code>```

This obviously works inside the app. Is there a way to know the same positions outside of the app. That means like Even shows the location when dragged in the home screen or any other app

Is the way to do it by creating a background service? if so How do you get the app screen(1st picture) and phone screen meaning working any where on the phone(2nd image) to work together?

Edit: Is there a way to get the pointer location data from settings > Developer options > Input > Pointer location

Any help would be appreciated!

答:
Maybe you can try pyautogui. position but this work only for your desktop screen, but if you have an Android studio you can try it and after this, you can calculate the position of your android screen you need not the screen resolution of your desktop, and if you put an Android emulation to corner you can easily calculate with this math operation 1:x(times2. Or if you have only mobile devices you can try some apps in PlayStore</p>
```<code>import time
import pyautugui as pg
time.sleep(5)
print(pg.position())
</code>```

Body:
I'm trying to find the coordinates for the screen while I'm outside of the app. I found a way to get the coordinates inside the app by this way.

import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  GlobalKey key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Material(
        child: Listener(
          child: SizedBox.expand(
            key: key,
            child: GestureDetector(

              onPanUpdate: (details) {
                print(details.globalPosition);
              },

            ),
          ),
        ),
      ),
    );
  }
}

I/flutter ( 9587): Offset(149.4, 182.0)
I/flutter ( 9587): Offset(148.6, 182.8)
I/flutter ( 9587): Offset(148.6, 183.4)

This obviously works inside the app. Is there a way to know the same positions outside of the app. That means like Even shows the location when dragged in the home screen or any other app

Is the way to do it by creating a background service? if so How do you get the app screen(1st picture) and phone screen meaning working any where on the phone(2nd image) to work together?

Edit: Is there a way to get the pointer location data from settings > Developer options > Input > Pointer location

Any help would be appreciated!

Body:
Maybe you can try pyautogui. position but this work only for your desktop screen, but if you have an Android studio you can try it and after this, you can calculate the position of your android screen you need not the screen resolution of your desktop, and if you put an Android emulation to corner you can easily calculate with this math operation 1:x(times2. Or if you have only mobile devices you can try some apps in PlayStore

import time
import pyautugui as pg
time.sleep(5)
print(pg.position())


问:
Heavy CRON Tasks
I have to run a pretty heavy task on PHP once a week (script that curls to various locations (websites, API's), gathers, sorts data and inserts it into a db). The whole script takes about 10 to 15 mintues to run on my mac (localhost) - guessing it'll run a bit faster on a server. Nevertheless - I'm currently looping through with AJAX, so when each task is finished, next one is launched. Now I need to run it weekly, automatically. So I think I can't do it with AJAX Anymore.

Do I have to just set the php.ini to let a script run for 30 mintues or there is a better way to do it ?

答:
php.ini has nothing to do with scheduling jobs. It's simply definining PHP's startup settings. What you want is a cron job, as your title says.

For OSX cron setup, see http://hintsforums.macworld.com/showthread.php?s=&threadid=39005

Title: Heavy CRON Tasks