问:
Adding the SVG icon in the custom slider using the custom painter
I am implementing the custom slider, where I have completed the gesture detection on the slider , now I want to add the SVG icon on the knob to drag, cannot find any resource. I just want to add the SVG to any idea of how to implement it. I have put my code and let me know any suggestion if you people have.

Main ui file

```<code>import 'package:animations_sample/custom_slider.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            child: LeftSlider(),
          ),
        ),
      ),
    );
  }
}

</code>```

Custom Slider file

```<code>import 'dart:io';

import 'package:animations_sample/base_painter.dart';
import 'package:animations_sample/customleftPainter.dart';
import 'package:animations_sample/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as UI;

import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';

import 'package:flutter/services.dart';

class LeftSlider extends StatefulWidget {
  LeftSlider({Key key}) : super(key: key);

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

class _LeftSliderState extends State<LeftSlider> {
  //intial Values coming
  int leftEnd = 12;
  String rawLeftSvg =
      '''<svg xmlns="http://www.w3.org/2000/svg" height="512px" viewBox="0 0 32 32" width="512px"><g><path d="m8 0c-4.41113 0-8 3.58887-8 8s3.58887 8 8 8 8-3.58887 8-8-3.58887-8-8-8zm0 15c-3.85986 0-7-3.14014-7-7s3.14014-7 7-7 7 3.14014 7 7-3.14014 7-7 7z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#2184C4"/><path d="m9 3c-1.04364 0-1.9624.536926-2.5 1.34772v-3.84772c0-.276367-.223633-.5-.5-.5-1.6543 0-3 1.3457-3 3 0 1.04364.536926 1.9624 1.34772 2.5h-3.84772c-.276367 0-.5.223633-.5.5 0 1.6543 1.3457 3 3 3 1.04364 0 1.9624-.536926 2.5-1.34772v3.84772c0 .276367.223633.5.5.5 1.6543 0 3-1.3457 3-3 0-1.04364-.536926-1.9624-1.34772-2.5h3.84772c.276367 0 .5-.223633.5-.5 0-1.6543-1.3457-3-3-3zm-6 5c-.930176 0-1.71436-.638184-1.93652-1.5h3.87305c-.222168.861816-1.00635 1.5-1.93652 1.5zm1-5c0-.930176.638184-1.71436 1.5-1.93652v3.87305c-.861816-.222168-1.5-1.00635-1.5-1.93652zm2 3.5c-.276123 0-.5-.223877-.5-.5 0-.276184.223877-.5.5-.5s.5.223816.5.5c0 .276123-.223877.5-.5.5zm2 2.5c0 .930176-.638184 1.71436-1.5 1.93652v-3.87305c.861816.222168 1.5 1.00635 1.5 1.93652zm-.936523-3.5c.222168-.861816 1.00635-1.5 1.93652-1.5.930176 0 1.71436.638184 1.93652 1.5h-3.87305z" transform="translate(2 2)" data-original="#000000" class="active-path" data-old_color="#000000" fill="#2184C4"/></g> </svg>''';
  DrawableRoot svgRoot;
  UI.Image image;
  @override
  void initState() {
    super.initState();
    getLeftIcon();
  }
    // this is for the Ui.Image
  Future<UI.Image> loadUiImage(String imageAssetPath) async {
    final ByteData data = await rootBundle.load(imageAssetPath);

    final Completer<UI.Image> completer = Completer();
    UI.decodeImageFromList(Uint8List.view(data.buffer), (UI.Image img) {
      return completer.complete(img);
    });
    return completer.future;
  }
   //Please Ignore
  /* Future<File> getImageFileFromAssets(String path) async {
    final byteData = await rootBundle.load('assets/$path');

    final file = File('${(await getTemporaryDirectory()).path}/$path');
    await file.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    return file;
  } */

  getLeftIcon() async {
    /*  svgRoot= await svg.fromSvgString(rawLeftSvg, rawLeftSvg); */
    //File file = await getImageFileFromAssets('icon.png');

    image = await loadUiImage('assets/snowflake.png');
    svgRoot = await svg.fromSvgString(rawLeftSvg, rawLeftSvg);
    print('sucess');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SliderLeftPaint(
        leftsvgIcon: svgRoot,
        leftIcon: image,
        leftInitial: 0,
        leftEnd: leftEnd,
        onSelectionChange: (int left) {
          setState(() {
            leftEnd = left;
          });
        },
        child: Center(
            child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 10),
              child: Text(
                '$leftEnd\u00B0',
              ),
            ),
          ],
        )),
      ),
    );
  }
}

class SliderLeftPaint extends StatefulWidget {
  final DrawableRoot leftsvgIcon;
  final UI.Image leftIcon;
  final int leftInitial;
  final int leftEnd;

  final Function onSelectionChange;
  final Widget child;

  const SliderLeftPaint(
      {Key key,
      this.leftsvgIcon,
      @required this.leftIcon,
      @required this.leftInitial,
      @required this.leftEnd,
      @required this.onSelectionChange,
      this.child})
      : super(key: key);

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

class _SliderLeftPaintState extends State<SliderLeftPaint> {
  bool _isInitLeftHandlerSelected = false;

  CustomLeftPainter customLeftPainter;

  /// start angle in radians where we need to locate the initial left handler
  double _leftStartAngle;

  /// end angle in radians where we need to locate the end left  handler
  double _leftEndAngle;

  /// the absolute angle in radians representing the selection
  double _leftSweepAngle;

// we need to update this widget both with gesture detector but
  // also when the parent widget rebuilds itself
  @override
  void didUpdateWidget(SliderLeftPaint oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.leftInitial != widget.leftInitial ||
        oldWidget.leftEnd != widget.leftEnd) {
      _calculatePercentage();
    }
  }

  void _calculatePercentage() {
    if (_isInitLeftHandlerSelected) {
      // This is for left inti and end percentage and the sweep Angle
      // TODO That it should be in a limit of half circle

      double initLeftPercentage = valueToPercentage(widget.leftInitial, 100);
      print('This is initial Left Percentge $initLeftPercentage');
      double endLeftPercentage = valueToPercentage(widget.leftEnd, 100);
      print('This is  End  Left Percentage $endLeftPercentage');

      double sweepLeftAngle =
          getSweepAngle(initLeftPercentage, endLeftPercentage);
      print('This is the sweep angle for the left hand side $sweepLeftAngle');
      _leftStartAngle = percentageToRadians(initLeftPercentage);
      print('This is the Left Start Angle $_leftStartAngle');
      _leftEndAngle = percentageToRadians(endLeftPercentage);
      print('This is the Left End Angle $_leftEndAngle');

      _leftSweepAngle = percentageToRadians(sweepLeftAngle.abs());
      print('This is the Left Sweep Angle $_leftSweepAngle');
    }

    customLeftPainter = CustomLeftPainter(
      leftdrawablesvgIcon: widget.leftsvgIcon,
      leftSvgIcon: widget.leftIcon,
      startLeftAngle: _leftStartAngle,
      endLeftAngle: _leftEndAngle,
      leftSweepAngle: _leftSweepAngle,
      selectionLeftColor: Colors.blueAccent,
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _calculatePaintData();
  }

  void _calculatePaintData() {
    // This is for the right init and end percentage and the sweepangle

    // This is for left inti and end percentage and the sweep Angle
    double initLeftPercentage = valueToPercentage(widget.leftInitial, 100);
    print('This is initial Left Percentge $initLeftPercentage');
    double endLeftPercentage = valueToPercentage(widget.leftEnd, 100);
    print('This is  End  Left Percentage $endLeftPercentage');

    double sweepLeftAngle =
        getSweepAngle(initLeftPercentage, endLeftPercentage);
    print('This is the sweep angle for the left hand side $sweepLeftAngle');
    _leftStartAngle = percentageToRadians(initLeftPercentage);
    print('This is the Left Start Angle $_leftStartAngle');
    _leftEndAngle = percentageToRadians(endLeftPercentage);
    print('This is the Left End Angle $_leftEndAngle');

    _leftSweepAngle = percentageToRadians(sweepLeftAngle.abs());
    print('This is the Left Sweep Angle $_leftSweepAngle');

    customLeftPainter = CustomLeftPainter(
      leftdrawablesvgIcon: widget.leftsvgIcon,
      leftSvgIcon: widget.leftIcon,
      startLeftAngle: _leftStartAngle,
      endLeftAngle: _leftEndAngle,
      leftSweepAngle: _leftSweepAngle,
      selectionLeftColor: Colors.blue,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: _onPanUpdate,
      onPanEnd: _onPanEnd,
      onPanDown: _onPanDown,
      child: CustomPaint(
        painter: BasePainter(
          baseColor: Color(0XFF5E5C5D),
        ),
        foregroundPainter: customLeftPainter,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: widget.child,
        ),
      ),
    );
  }

  _onPanUpdate(DragUpdateDetails details) {
    if (!_isInitLeftHandlerSelected) {
      return;
    }
    if (customLeftPainter.leftcenter == null) {
      return;
    }

    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);
    var leftAngle;

    var leftPercent;

    var newLeftValue;

    if (_leftSweepAngle >= 0) {
      leftAngle = coordinatesToRadians(customLeftPainter.leftcenter, position);
      leftPercent = radianstoPercentageLeft(leftAngle);
      newLeftValue = percentageToValue(leftPercent, 100);
      if (_isInitLeftHandlerSelected) {
        widget.onSelectionChange(newLeftValue);
      }
    }
  }

  _onPanDown(DragDownDetails details) {
    if (customLeftPainter == null) {
      return;
    }
    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);
    if (position != null) {
      _isInitLeftHandlerSelected = isPointInsideCircle(
          position, customLeftPainter.leftInitHandler, 12.0);
    }
  }

  _onPanEnd(_) {
    _isInitLeftHandlerSelected = false;
  }
}

</code>```

Left Painter

```<code>import 'dart:math';
import 'dart:ui' as UI;

import 'package:animations_sample/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class CustomLeftPainter extends CustomPainter {
  DrawableRoot leftdrawablesvgIcon;
  UI.Image leftSvgIcon;
  double startLeftAngle;
  double endLeftAngle;
  double leftSweepAngle;
  Color selectionLeftColor;
  Size actuallsize = Size(30, 30);

  Offset leftcenter;

  double leftradius;

  Offset leftInitHandler;

  CustomLeftPainter({
    @required this.leftdrawablesvgIcon,
    @required this.leftSvgIcon,
    @required this.startLeftAngle,
    @required this.endLeftAngle,
    @required this.leftSweepAngle,
    @required this.selectionLeftColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    //This was the problem when all the both left and right angles are 0 then it will return with no points
    /* if (startLeftAngle == 0.0 &&
        endLeftAngle == 0.0 &&
        startRightAngle == 0.0 &&
        endRightAngle == 0.0) return;
 */

    Paint leftprogress = _getPaint(color: selectionLeftColor, width: 20);

    leftcenter = Offset(size.width / 2, size.height / 2);

    leftradius = min(size.width / 2, size.height / 2);

    canvas.drawArc(Rect.fromCircle(center: leftcenter, radius: leftradius),
        pi / 2 + startLeftAngle, leftSweepAngle, false, leftprogress);

    Paint lefthandler =
        _getPaint(color: Colors.white, style: PaintingStyle.fill);
    Paint lefthandlerOutter = _getPaint(color: selectionLeftColor);

    leftInitHandler =
        radiansToCoordinates(leftcenter, pi / 2 + endLeftAngle, leftradius);
    canvas.drawCircle(leftInitHandler, 8.0, lefthandler);
    canvas.drawCircle(leftInitHandler, 12.0, lefthandlerOutter);

    // To draw image but problem is it has scalling problem

    /* canvas.drawImage(
        leftSvgIcon,
        Offset(leftInitHandler.dx - 12, leftInitHandler.dy - 12),
        lefthandlerOutter); */
    //

    leftdrawablesvgIcon.scaleCanvasToViewBox(canvas, size);

    leftdrawablesvgIcon.clipCanvasToViewBox(canvas);

       //This is the add part for the edit
    Rect myRect = Offset(leftInitHandler.dx,leftInitHandler.dy) & const Size(50.0, 50.0);

    leftdrawablesvgIcon.draw(
        canvas,myRect);
  }

  Paint _getPaint({@required Color color, double width, PaintingStyle style}) =>
      Paint()
        ..color = color
        ..strokeCap = StrokeCap.square
        ..style = style ?? PaintingStyle.stroke
        ..strokeWidth = width ?? 8.0;

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

</code>```

utils file for conversions.

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

double percentageToRadians(double percentage) => ((pi * percentage) / 100);

double radiansToPercentage(double radians) {
  var normalized = radians < 0 ? -radians : pi - radians;
  var percentage = ((100 * normalized) / (pi));
  // TODO we have an inconsistency of pi/2 in terms of percentage and radians
  return (percentage + 50) % 100;
}

double radianstoPercentageLeft(double radians) {
  var normalized = radians < 0 ? -radians : pi - radians;
  print('************This is left normalized $normalized');
  var percentage = ((100 * normalized) / (pi));
  return (percentage - 50) % 100;
}

double coordinatesToRadians(Offset center, Offset coords) {
  var a = coords.dx - center.dx;
  var b = center.dy - coords.dy;
  return atan2(b, a);
}

Offset radiansToCoordinates(Offset center, double radians, double radius) {
  var dx = center.dx + radius * cos(radians);
  var dy = center.dy + radius * sin(radians);
  return Offset(dx, dy);
}

double valueToPercentage(int time, int intervals) => (time / intervals) * 100;

int percentageToValue(double percentage, int intervals) =>
    ((percentage * intervals) / 100).round();

bool isPointInsideCircle(Offset point, Offset center, double rradius) {
  if(center ==Offset(0,0))
  {
    return false;
  }
  var radius = rradius * 1.2;
  return point.dx < (center.dx + radius) &&
      point.dx > (center.dx - radius) &&
      point.dy < (center.dy + radius) &&
      point.dy > (center.dy - radius);
}

bool isPointAlongCircle(Offset point, Offset center, double radius) {
  // distance is root(sqr(x2 - x1) + sqr(y2 - y1))
  // i.e., (7,8) and (3,2) -> 7.21
  var d1 = pow(point.dx - center.dx, 2);
  var d2 = pow(point.dy - center.dy, 2);
  var distance = sqrt(d1 + d2);
  return (distance - radius).abs() < 10;
}

double getSweepAngle(double init, double end) {
  if (end > init) {
    return end - init;
  }
  if(end == init)
  {
    return 0;
  }
  return (100 - init + end).abs();
}

List<Offset> getSectionsCoordinatesInCircle(
    Offset center, double radius, int sections) {
  var intervalAngle = (pi * 2) / sections;
  return List<int>.generate(sections, (int index) => index).map((i) {
    var radians = (pi / 2) + (intervalAngle * i);
    return radiansToCoordinates(center, radians, radius);
  }).toList();
}

bool isAngleInsideRadiansSelection(double angle, double start, double sweep) {
  var normalized = angle > pi / 2 ? 5 * pi / 2 - angle : pi / 2 - angle;
  var end = (start + sweep) % (2 * pi);
  return end > start
      ? normalized > start && normalized < end
      : normalized > start || normalized < end;
}

// this is not 100% accurate but it works
// we just want to see if a value changed drastically its value
bool radiansWasModuloed(double current, double previous) {
  return (previous - current).abs() > (3 * pi / 2);
}

</code>```

Would like to add this small svg icon on the knob

```<code>  List<String> rightPath = <String>[
    "m256 512c-30.879 0-56-25.122-56-56v-16.298c-11.863-3.606-23.331-8.359-34.292-14.212l-11.534 11.534c-10.574 10.573-24.635 16.396-39.594 16.396-14.966 0-29.031-5.823-39.604-16.396-21.829-21.843-21.827-57.37.001-79.197l11.534-11.534c-5.853-10.961-10.605-22.43-14.212-34.292h-16.299c-14.953 0-29.014-5.827-39.594-16.407s-16.406-24.642-16.406-39.594c0-30.878 25.121-56 56-56h16.299c3.606-11.863 8.359-23.331 14.212-34.292l-11.534-11.534c-10.574-10.574-16.397-24.635-16.397-39.594 0-14.965 5.823-29.03 16.396-39.604 21.844-21.831 57.37-21.828 79.198 0l11.534 11.534c10.961-5.853 22.429-10.605 34.292-14.212v-16.298c0-14.952 5.826-29.013 16.405-39.593 10.581-10.58 24.642-16.407 39.595-16.407 3.721 0 7.472.375 11.149 1.113 26.004 5.283 44.851 28.364 44.851 54.887v16.298c11.863 3.606 23.331 8.359 34.292 14.212l11.534-11.534c10.574-10.573 24.635-16.396 39.594-16.396 14.966 0 29.031 5.823 39.604 16.396 21.829 21.843 21.827 57.37-.001 79.197l-11.534 11.534c5.853 10.961 10.605 22.43 14.212 34.292h16.299c14.953 0 29.014 5.827 39.594 16.407s16.406 24.642 16.406 39.594c0 30.878-25.121 56-56 56h-16.299c-3.606 11.863-8.359 23.331-14.212 34.292l11.534 11.534c10.573 10.574 16.396 24.635 16.396 39.594 0 14.965-5.823 29.03-16.396 39.604-10.921 10.914-25.266 16.371-39.604 16.372-14.343.001-28.679-5.456-39.594-16.371l-11.534-11.534c-10.961 5.853-22.429 10.605-34.292 14.212v16.297c0 14.952-5.826 29.013-16.405 39.593-7.813 7.813-17.637 13.099-28.41 15.287-.012.002-.023.005-.035.007-3.677.738-7.428 1.113-11.149 1.113zm8-16.8h.01zm-100.925-105.7c2.913 0 5.843.793 8.453 2.419 14.892 9.274 31.071 15.978 48.088 19.926 7.251 1.682 12.384 8.143 12.384 15.586v28.569c0 13.233 10.767 24 24 24 1.601 0 3.222-.162 4.821-.481 4.592-.934 8.792-3.2 12.146-6.553 4.535-4.536 7.033-10.561 7.033-16.966v-28.57c0-7.443 5.133-13.904 12.384-15.586 17.017-3.948 33.196-10.652 48.088-19.926 6.314-3.933 14.511-2.994 19.771 2.268l20.21 20.21c9.355 9.354 24.583 9.354 33.946-.004 4.526-4.526 7.021-10.555 7.021-16.973 0-6.411-2.494-12.437-7.024-16.966l-20.209-20.209c-5.262-5.262-6.201-13.456-2.269-19.771 9.274-14.893 15.979-31.072 19.926-48.088 1.682-7.251 8.143-12.384 15.586-12.384h28.57c13.233 0 24-10.767 24-24 0-6.405-2.498-12.43-7.034-16.966-4.535-4.537-10.561-7.035-16.966-7.035h-28.57c-7.443 0-13.904-5.133-15.586-12.384-3.947-17.016-10.651-33.195-19.926-48.088-3.933-6.316-2.993-14.51 2.269-19.771l20.21-20.209c9.355-9.355 9.354-24.583-.004-33.946-4.525-4.526-10.555-7.02-16.973-7.02-6.411 0-12.438 2.495-16.967 7.024l-20.21 20.209c-5.262 5.263-13.456 6.201-19.771 2.268-14.892-9.274-31.071-15.978-48.088-19.926-7.251-1.683-12.384-8.144-12.384-15.587v-28.57c0-11.37-8.068-21.262-19.186-23.521-1.572-.315-3.204-.479-4.814-.479-6.405 0-12.431 2.498-16.967 7.034-4.535 4.536-7.033 10.561-7.033 16.966v28.57c0 7.443-5.133 13.904-12.384 15.586-17.017 3.948-33.196 10.652-48.088 19.926-6.313 3.934-14.51 2.994-19.771-2.268l-20.21-20.21c-9.355-9.355-24.583-9.353-33.946.004-4.526 4.526-7.021 10.555-7.021 16.973 0 6.411 2.494 12.437 7.024 16.966l20.209 20.209c5.262 5.262 6.201 13.456 2.269 19.771-9.274 14.893-15.979 31.072-19.926 48.088-1.681 7.252-8.142 12.385-15.586 12.385h-28.57c-13.233 0-24 10.767-24 24 0 6.405 2.498 12.43 7.034 16.966 4.535 4.536 10.561 7.034 16.966 7.034h28.57c7.443 0 13.904 5.133 15.586 12.384 3.947 17.016 10.651 33.195 19.926 48.088 3.933 6.316 2.993 14.51-2.269 19.771l-20.21 20.209c-9.355 9.355-9.354 24.583.004 33.946 4.525 4.526 10.555 7.02 16.973 7.02 6.411 0 12.438-2.495 16.967-7.024l20.21-20.209c3.087-3.086 7.184-4.685 11.318-4.685z"
  ];

trying too add the above list<String> but it is not scaling

This the svg :
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" enable-background="new 0 0 512 512" height="512px" viewBox="0 0 512 512" width="512px" class=""><g><g>
<path d="m256 512c-30.879 0-56-25.122-56-56v-16.298c-11.863-3.606-23.331-8.359-34.292-14.212l-11.534 11.534c-10.574 10.573-24.635 16.396-39.594 16.396-14.966 0-29.031-5.823-39.604-16.396-21.829-21.843-21.827-57.37.001-79.197l11.534-11.534c-5.853-10.961-10.605-22.43-14.212-34.292h-16.299c-14.953 0-29.014-5.827-39.594-16.407s-16.406-24.642-16.406-39.594c0-30.878 25.121-56 56-56h16.299c3.606-11.863 8.359-23.331 14.212-34.292l-11.534-11.534c-10.574-10.574-16.397-24.635-16.397-39.594 0-14.965 5.823-29.03 16.396-39.604 21.844-21.831 57.37-21.828 79.198 0l11.534 11.534c10.961-5.853 22.429-10.605 34.292-14.212v-16.298c0-14.952 5.826-29.013 16.405-39.593 10.581-10.58 24.642-16.407 39.595-16.407 3.721 0 7.472.375 11.149 1.113 26.004 5.283 44.851 28.364 44.851 54.887v16.298c11.863 3.606 23.331 8.359 34.292 14.212l11.534-11.534c10.574-10.573 24.635-16.396 39.594-16.396 14.966 0 29.031 5.823 39.604 16.396 21.829 21.843 21.827 57.37-.001 79.197l-11.534 11.534c5.853 10.961 10.605 22.43 14.212 34.292h16.299c14.953 0 29.014 5.827 39.594 16.407s16.406 24.642 16.406 39.594c0 30.878-25.121 56-56 56h-16.299c-3.606 11.863-8.359 23.331-14.212 34.292l11.534 11.534c10.573 10.574 16.396 24.635 16.396 39.594 0 14.965-5.823 29.03-16.396 39.604-10.921 10.914-25.266 16.371-39.604 16.372-14.343.001-28.679-5.456-39.594-16.371l-11.534-11.534c-10.961 5.853-22.429 10.605-34.292 14.212v16.297c0 14.952-5.826 29.013-16.405 39.593-7.813 7.813-17.637 13.099-28.41 15.287-.012.002-.023.005-.035.007-3.677.738-7.428 1.113-11.149 1.113zm8-16.8h.01zm-100.925-105.7c2.913 0 5.843.793 8.453 2.419 14.892 9.274 31.071 15.978 48.088 19.926 7.251 1.682 12.384 8.143 12.384 15.586v28.569c0 13.233 10.767 24 24 24 1.601 0 3.222-.162 4.821-.481 4.592-.934 8.792-3.2 12.146-6.553 4.535-4.536 7.033-10.561 7.033-16.966v-28.57c0-7.443 5.133-13.904 12.384-15.586 17.017-3.948 33.196-10.652 48.088-19.926 6.314-3.933 14.511-2.994 19.771 2.268l20.21 20.21c9.355 9.354 24.583 9.354 33.946-.004 4.526-4.526 7.021-10.555 7.021-16.973 0-6.411-2.494-12.437-7.024-16.966l-20.209-20.209c-5.262-5.262-6.201-13.456-2.269-19.771 9.274-14.893 15.979-31.072 19.926-48.088 1.682-7.251 8.143-12.384 15.586-12.384h28.57c13.233 0 24-10.767 24-24 0-6.405-2.498-12.43-7.034-16.966-4.535-4.537-10.561-7.035-16.966-7.035h-28.57c-7.443 0-13.904-5.133-15.586-12.384-3.947-17.016-10.651-33.195-19.926-48.088-3.933-6.316-2.993-14.51 2.269-19.771l20.21-20.209c9.355-9.355 9.354-24.583-.004-33.946-4.525-4.526-10.555-7.02-16.973-7.02-6.411 0-12.438 2.495-16.967 7.024l-20.21 20.209c-5.262 5.263-13.456 6.201-19.771 2.268-14.892-9.274-31.071-15.978-48.088-19.926-7.251-1.683-12.384-8.144-12.384-15.587v-28.57c0-11.37-8.068-21.262-19.186-23.521-1.572-.315-3.204-.479-4.814-.479-6.405 0-12.431 2.498-16.967 7.034-4.535 4.536-7.033 10.561-7.033 16.966v28.57c0 7.443-5.133 13.904-12.384 15.586-17.017 3.948-33.196 10.652-48.088 19.926-6.313 3.934-14.51 2.994-19.771-2.268l-20.21-20.21c-9.355-9.355-24.583-9.353-33.946.004-4.526 4.526-7.021 10.555-7.021 16.973 0 6.411 2.494 12.437 7.024 16.966l20.209 20.209c5.262 5.262 6.201 13.456 2.269 19.771-9.274 14.893-15.979 31.072-19.926 48.088-1.681 7.252-8.142 12.385-15.586 12.385h-28.57c-13.233 0-24 10.767-24 24 0 6.405 2.498 12.43 7.034 16.966 4.535 4.536 10.561 7.034 16.966 7.034h28.57c7.443 0 13.904 5.133 15.586 12.384 3.947 17.016 10.651 33.195 19.926 48.088 3.933 6.316 2.993 14.51-2.269 19.771l-20.21 20.209c-9.355 9.355-9.354 24.583.004 33.946 4.525 4.526 10.555 7.02 16.973 7.02 6.411 0 12.438-2.495 16.967-7.024l20.21-20.209c3.087-3.086 7.184-4.685 11.318-4.685z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#EE2C5E"/><path d="m256 368c-61.757 0-112-50.243-112-112s50.243-112 112-112c3.181 0 6.339.135 9.389.4 27.848 2.289 53.742 14.915 72.835 35.548 19.201 20.75 29.776 47.76 29.776 76.052s-10.575 55.302-29.776 76.052c-19.093 20.633-44.987 33.259-72.913 35.555-2.972.258-6.13.393-9.311.393zm0-192c-44.112 0-80 35.888-80 80s35.888 80 80 80c2.258 0 4.482-.094 6.611-.279 41.187-3.386 73.389-38.4 73.389-79.721s-32.202-76.335-73.311-79.714c-2.207-.192-4.431-.286-6.689-.286z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#EE2C5E"/></g></g> </svg>

</code>```

答:
Use the flutter_svg package, it has an example on how to draw an SVG to a canvas, which is basically what you want to achieve:

import 'package:flutter_svg/flutter_svg.dart';
final String rawSvg = '''<svg viewBox="...">...</svg>''';
final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

// If you only want the final Picture output, just use
final Picture picture = svgRoot.toPicture();

// Otherwise, if you want to draw it to a canvas:
// Optional, but probably normally desirable: scale the canvas dimensions to
// the SVG's viewbox
svgRoot.scaleCanvasToViewBox(canvas);

// Optional, but probably normally desireable: ensure the SVG isn't rendered
// outside of the viewbox bounds
svgRoot.clipCanvasToViewBox(canvas);
svgRoot.draw(canvas, size); // <---------- I think this is the one that you actually want
```

You can also load the SVG as an Asset from your files. Bear in mind that a simpler example on your question could lead to better answers.

Body:
I am implementing the custom slider, where I have completed the gesture detection on the slider , now I want to add the SVG icon on the knob to drag, cannot find any resource. I just want to add the SVG to any idea of how to implement it. I have put my code and let me know any suggestion if you people have.

Main ui file

import 'package:animations_sample/custom_slider.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            child: LeftSlider(),
          ),
        ),
      ),
    );
  }
}

Custom Slider file

import 'dart:io';

import 'package:animations_sample/base_painter.dart';
import 'package:animations_sample/customleftPainter.dart';
import 'package:animations_sample/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as UI;

import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';

import 'package:flutter/services.dart';

class LeftSlider extends StatefulWidget {
  LeftSlider({Key key}) : super(key: key);

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

class _LeftSliderState extends State<LeftSlider> {
  //intial Values coming
  int leftEnd = 12;
  String rawLeftSvg =
      '''<svg xmlns="http://www.w3.org/2000/svg" height="512px" viewBox="0 0 32 32" width="512px"><g><path d="m8 0c-4.41113 0-8 3.58887-8 8s3.58887 8 8 8 8-3.58887 8-8-3.58887-8-8-8zm0 15c-3.85986 0-7-3.14014-7-7s3.14014-7 7-7 7 3.14014 7 7-3.14014 7-7 7z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#2184C4"/><path d="m9 3c-1.04364 0-1.9624.536926-2.5 1.34772v-3.84772c0-.276367-.223633-.5-.5-.5-1.6543 0-3 1.3457-3 3 0 1.04364.536926 1.9624 1.34772 2.5h-3.84772c-.276367 0-.5.223633-.5.5 0 1.6543 1.3457 3 3 3 1.04364 0 1.9624-.536926 2.5-1.34772v3.84772c0 .276367.223633.5.5.5 1.6543 0 3-1.3457 3-3 0-1.04364-.536926-1.9624-1.34772-2.5h3.84772c.276367 0 .5-.223633.5-.5 0-1.6543-1.3457-3-3-3zm-6 5c-.930176 0-1.71436-.638184-1.93652-1.5h3.87305c-.222168.861816-1.00635 1.5-1.93652 1.5zm1-5c0-.930176.638184-1.71436 1.5-1.93652v3.87305c-.861816-.222168-1.5-1.00635-1.5-1.93652zm2 3.5c-.276123 0-.5-.223877-.5-.5 0-.276184.223877-.5.5-.5s.5.223816.5.5c0 .276123-.223877.5-.5.5zm2 2.5c0 .930176-.638184 1.71436-1.5 1.93652v-3.87305c.861816.222168 1.5 1.00635 1.5 1.93652zm-.936523-3.5c.222168-.861816 1.00635-1.5 1.93652-1.5.930176 0 1.71436.638184 1.93652 1.5h-3.87305z" transform="translate(2 2)" data-original="#000000" class="active-path" data-old_color="#000000" fill="#2184C4"/></g> </svg>''';
  DrawableRoot svgRoot;
  UI.Image image;
  @override
  void initState() {
    super.initState();
    getLeftIcon();
  }
    // this is for the Ui.Image
  Future<UI.Image> loadUiImage(String imageAssetPath) async {
    final ByteData data = await rootBundle.load(imageAssetPath);

    final Completer<UI.Image> completer = Completer();
    UI.decodeImageFromList(Uint8List.view(data.buffer), (UI.Image img) {
      return completer.complete(img);
    });
    return completer.future;
  }
   //Please Ignore
  /* Future<File> getImageFileFromAssets(String path) async {
    final byteData = await rootBundle.load('assets/$path');

    final file = File('${(await getTemporaryDirectory()).path}/$path');
    await file.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    return file;
  } */

  getLeftIcon() async {
    /*  svgRoot= await svg.fromSvgString(rawLeftSvg, rawLeftSvg); */
    //File file = await getImageFileFromAssets('icon.png');

    image = await loadUiImage('assets/snowflake.png');
    svgRoot = await svg.fromSvgString(rawLeftSvg, rawLeftSvg);
    print('sucess');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SliderLeftPaint(
        leftsvgIcon: svgRoot,
        leftIcon: image,
        leftInitial: 0,
        leftEnd: leftEnd,
        onSelectionChange: (int left) {
          setState(() {
            leftEnd = left;
          });
        },
        child: Center(
            child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 10),
              child: Text(
                '$leftEnd\u00B0',
              ),
            ),
          ],
        )),
      ),
    );
  }
}

class SliderLeftPaint extends StatefulWidget {
  final DrawableRoot leftsvgIcon;
  final UI.Image leftIcon;
  final int leftInitial;
  final int leftEnd;

  final Function onSelectionChange;
  final Widget child;

  const SliderLeftPaint(
      {Key key,
      this.leftsvgIcon,
      @required this.leftIcon,
      @required this.leftInitial,
      @required this.leftEnd,
      @required this.onSelectionChange,
      this.child})
      : super(key: key);

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

class _SliderLeftPaintState extends State<SliderLeftPaint> {
  bool _isInitLeftHandlerSelected = false;

  CustomLeftPainter customLeftPainter;

  /// start angle in radians where we need to locate the initial left handler
  double _leftStartAngle;

  /// end angle in radians where we need to locate the end left  handler
  double _leftEndAngle;

  /// the absolute angle in radians representing the selection
  double _leftSweepAngle;

// we need to update this widget both with gesture detector but
  // also when the parent widget rebuilds itself
  @override
  void didUpdateWidget(SliderLeftPaint oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.leftInitial != widget.leftInitial ||
        oldWidget.leftEnd != widget.leftEnd) {
      _calculatePercentage();
    }
  }

  void _calculatePercentage() {
    if (_isInitLeftHandlerSelected) {
      // This is for left inti and end percentage and the sweep Angle
      // TODO That it should be in a limit of half circle

      double initLeftPercentage = valueToPercentage(widget.leftInitial, 100);
      print('This is initial Left Percentge $initLeftPercentage');
      double endLeftPercentage = valueToPercentage(widget.leftEnd, 100);
      print('This is  End  Left Percentage $endLeftPercentage');

      double sweepLeftAngle =
          getSweepAngle(initLeftPercentage, endLeftPercentage);
      print('This is the sweep angle for the left hand side $sweepLeftAngle');
      _leftStartAngle = percentageToRadians(initLeftPercentage);
      print('This is the Left Start Angle $_leftStartAngle');
      _leftEndAngle = percentageToRadians(endLeftPercentage);
      print('This is the Left End Angle $_leftEndAngle');

      _leftSweepAngle = percentageToRadians(sweepLeftAngle.abs());
      print('This is the Left Sweep Angle $_leftSweepAngle');
    }

    customLeftPainter = CustomLeftPainter(
      leftdrawablesvgIcon: widget.leftsvgIcon,
      leftSvgIcon: widget.leftIcon,
      startLeftAngle: _leftStartAngle,
      endLeftAngle: _leftEndAngle,
      leftSweepAngle: _leftSweepAngle,
      selectionLeftColor: Colors.blueAccent,
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _calculatePaintData();
  }

  void _calculatePaintData() {
    // This is for the right init and end percentage and the sweepangle

    // This is for left inti and end percentage and the sweep Angle
    double initLeftPercentage = valueToPercentage(widget.leftInitial, 100);
    print('This is initial Left Percentge $initLeftPercentage');
    double endLeftPercentage = valueToPercentage(widget.leftEnd, 100);
    print('This is  End  Left Percentage $endLeftPercentage');

    double sweepLeftAngle =
        getSweepAngle(initLeftPercentage, endLeftPercentage);
    print('This is the sweep angle for the left hand side $sweepLeftAngle');
    _leftStartAngle = percentageToRadians(initLeftPercentage);
    print('This is the Left Start Angle $_leftStartAngle');
    _leftEndAngle = percentageToRadians(endLeftPercentage);
    print('This is the Left End Angle $_leftEndAngle');

    _leftSweepAngle = percentageToRadians(sweepLeftAngle.abs());
    print('This is the Left Sweep Angle $_leftSweepAngle');

    customLeftPainter = CustomLeftPainter(
      leftdrawablesvgIcon: widget.leftsvgIcon,
      leftSvgIcon: widget.leftIcon,
      startLeftAngle: _leftStartAngle,
      endLeftAngle: _leftEndAngle,
      leftSweepAngle: _leftSweepAngle,
      selectionLeftColor: Colors.blue,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: _onPanUpdate,
      onPanEnd: _onPanEnd,
      onPanDown: _onPanDown,
      child: CustomPaint(
        painter: BasePainter(
          baseColor: Color(0XFF5E5C5D),
        ),
        foregroundPainter: customLeftPainter,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: widget.child,
        ),
      ),
    );
  }

  _onPanUpdate(DragUpdateDetails details) {
    if (!_isInitLeftHandlerSelected) {
      return;
    }
    if (customLeftPainter.leftcenter == null) {
      return;
    }

    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);
    var leftAngle;

    var leftPercent;

    var newLeftValue;

    if (_leftSweepAngle >= 0) {
      leftAngle = coordinatesToRadians(customLeftPainter.leftcenter, position);
      leftPercent = radianstoPercentageLeft(leftAngle);
      newLeftValue = percentageToValue(leftPercent, 100);
      if (_isInitLeftHandlerSelected) {
        widget.onSelectionChange(newLeftValue);
      }
    }
  }

  _onPanDown(DragDownDetails details) {
    if (customLeftPainter == null) {
      return;
    }
    RenderBox renderBox = context.findRenderObject();
    var position = renderBox.globalToLocal(details.globalPosition);
    if (position != null) {
      _isInitLeftHandlerSelected = isPointInsideCircle(
          position, customLeftPainter.leftInitHandler, 12.0);
    }
  }

  _onPanEnd(_) {
    _isInitLeftHandlerSelected = false;
  }
}

Left Painter

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

import 'package:animations_sample/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class CustomLeftPainter extends CustomPainter {
  DrawableRoot leftdrawablesvgIcon;
  UI.Image leftSvgIcon;
  double startLeftAngle;
  double endLeftAngle;
  double leftSweepAngle;
  Color selectionLeftColor;
  Size actuallsize = Size(30, 30);

  Offset leftcenter;

  double leftradius;

  Offset leftInitHandler;

  CustomLeftPainter({
    @required this.leftdrawablesvgIcon,
    @required this.leftSvgIcon,
    @required this.startLeftAngle,
    @required this.endLeftAngle,
    @required this.leftSweepAngle,
    @required this.selectionLeftColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    //This was the problem when all the both left and right angles are 0 then it will return with no points
    /* if (startLeftAngle == 0.0 &&
        endLeftAngle == 0.0 &&
        startRightAngle == 0.0 &&
        endRightAngle == 0.0) return;
 */

    Paint leftprogress = _getPaint(color: selectionLeftColor, width: 20);

    leftcenter = Offset(size.width / 2, size.height / 2);

    leftradius = min(size.width / 2, size.height / 2);

    canvas.drawArc(Rect.fromCircle(center: leftcenter, radius: leftradius),
        pi / 2 + startLeftAngle, leftSweepAngle, false, leftprogress);

    Paint lefthandler =
        _getPaint(color: Colors.white, style: PaintingStyle.fill);
    Paint lefthandlerOutter = _getPaint(color: selectionLeftColor);

    leftInitHandler =
        radiansToCoordinates(leftcenter, pi / 2 + endLeftAngle, leftradius);
    canvas.drawCircle(leftInitHandler, 8.0, lefthandler);
    canvas.drawCircle(leftInitHandler, 12.0, lefthandlerOutter);

    // To draw image but problem is it has scalling problem

    /* canvas.drawImage(
        leftSvgIcon,
        Offset(leftInitHandler.dx - 12, leftInitHandler.dy - 12),
        lefthandlerOutter); */
    //

    leftdrawablesvgIcon.scaleCanvasToViewBox(canvas, size);

    leftdrawablesvgIcon.clipCanvasToViewBox(canvas);

       //This is the add part for the edit
    Rect myRect = Offset(leftInitHandler.dx,leftInitHandler.dy) & const Size(50.0, 50.0);

    leftdrawablesvgIcon.draw(
        canvas,myRect);
  }

  Paint _getPaint({@required Color color, double width, PaintingStyle style}) =>
      Paint()
        ..color = color
        ..strokeCap = StrokeCap.square
        ..style = style ?? PaintingStyle.stroke
        ..strokeWidth = width ?? 8.0;

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

utils file for conversions.

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

double percentageToRadians(double percentage) => ((pi * percentage) / 100);

double radiansToPercentage(double radians) {
  var normalized = radians < 0 ? -radians : pi - radians;
  var percentage = ((100 * normalized) / (pi));
  // TODO we have an inconsistency of pi/2 in terms of percentage and radians
  return (percentage + 50) % 100;
}

double radianstoPercentageLeft(double radians) {
  var normalized = radians < 0 ? -radians : pi - radians;
  print('************This is left normalized $normalized');
  var percentage = ((100 * normalized) / (pi));
  return (percentage - 50) % 100;
}

double coordinatesToRadians(Offset center, Offset coords) {
  var a = coords.dx - center.dx;
  var b = center.dy - coords.dy;
  return atan2(b, a);
}

Offset radiansToCoordinates(Offset center, double radians, double radius) {
  var dx = center.dx + radius * cos(radians);
  var dy = center.dy + radius * sin(radians);
  return Offset(dx, dy);
}

double valueToPercentage(int time, int intervals) => (time / intervals) * 100;

int percentageToValue(double percentage, int intervals) =>
    ((percentage * intervals) / 100).round();

bool isPointInsideCircle(Offset point, Offset center, double rradius) {
  if(center ==Offset(0,0))
  {
    return false;
  }
  var radius = rradius * 1.2;
  return point.dx < (center.dx + radius) &&
      point.dx > (center.dx - radius) &&
      point.dy < (center.dy + radius) &&
      point.dy > (center.dy - radius);
}

bool isPointAlongCircle(Offset point, Offset center, double radius) {
  // distance is root(sqr(x2 - x1) + sqr(y2 - y1))
  // i.e., (7,8) and (3,2) -> 7.21
  var d1 = pow(point.dx - center.dx, 2);
  var d2 = pow(point.dy - center.dy, 2);
  var distance = sqrt(d1 + d2);
  return (distance - radius).abs() < 10;
}

double getSweepAngle(double init, double end) {
  if (end > init) {
    return end - init;
  }
  if(end == init)
  {
    return 0;
  }
  return (100 - init + end).abs();
}

List<Offset> getSectionsCoordinatesInCircle(
    Offset center, double radius, int sections) {
  var intervalAngle = (pi * 2) / sections;
  return List<int>.generate(sections, (int index) => index).map((i) {
    var radians = (pi / 2) + (intervalAngle * i);
    return radiansToCoordinates(center, radians, radius);
  }).toList();
}

bool isAngleInsideRadiansSelection(double angle, double start, double sweep) {
  var normalized = angle > pi / 2 ? 5 * pi / 2 - angle : pi / 2 - angle;
  var end = (start + sweep) % (2 * pi);
  return end > start
      ? normalized > start && normalized < end
      : normalized > start || normalized < end;
}

// this is not 100% accurate but it works
// we just want to see if a value changed drastically its value
bool radiansWasModuloed(double current, double previous) {
  return (previous - current).abs() > (3 * pi / 2);
}

Would like to add this small svg icon on the knob

  List<String> rightPath = <String>[
    "m256 512c-30.879 0-56-25.122-56-56v-16.298c-11.863-3.606-23.331-8.359-34.292-14.212l-11.534 11.534c-10.574 10.573-24.635 16.396-39.594 16.396-14.966 0-29.031-5.823-39.604-16.396-21.829-21.843-21.827-57.37.001-79.197l11.534-11.534c-5.853-10.961-10.605-22.43-14.212-34.292h-16.299c-14.953 0-29.014-5.827-39.594-16.407s-16.406-24.642-16.406-39.594c0-30.878 25.121-56 56-56h16.299c3.606-11.863 8.359-23.331 14.212-34.292l-11.534-11.534c-10.574-10.574-16.397-24.635-16.397-39.594 0-14.965 5.823-29.03 16.396-39.604 21.844-21.831 57.37-21.828 79.198 0l11.534 11.534c10.961-5.853 22.429-10.605 34.292-14.212v-16.298c0-14.952 5.826-29.013 16.405-39.593 10.581-10.58 24.642-16.407 39.595-16.407 3.721 0 7.472.375 11.149 1.113 26.004 5.283 44.851 28.364 44.851 54.887v16.298c11.863 3.606 23.331 8.359 34.292 14.212l11.534-11.534c10.574-10.573 24.635-16.396 39.594-16.396 14.966 0 29.031 5.823 39.604 16.396 21.829 21.843 21.827 57.37-.001 79.197l-11.534 11.534c5.853 10.961 10.605 22.43 14.212 34.292h16.299c14.953 0 29.014 5.827 39.594 16.407s16.406 24.642 16.406 39.594c0 30.878-25.121 56-56 56h-16.299c-3.606 11.863-8.359 23.331-14.212 34.292l11.534 11.534c10.573 10.574 16.396 24.635 16.396 39.594 0 14.965-5.823 29.03-16.396 39.604-10.921 10.914-25.266 16.371-39.604 16.372-14.343.001-28.679-5.456-39.594-16.371l-11.534-11.534c-10.961 5.853-22.429 10.605-34.292 14.212v16.297c0 14.952-5.826 29.013-16.405 39.593-7.813 7.813-17.637 13.099-28.41 15.287-.012.002-.023.005-.035.007-3.677.738-7.428 1.113-11.149 1.113zm8-16.8h.01zm-100.925-105.7c2.913 0 5.843.793 8.453 2.419 14.892 9.274 31.071 15.978 48.088 19.926 7.251 1.682 12.384 8.143 12.384 15.586v28.569c0 13.233 10.767 24 24 24 1.601 0 3.222-.162 4.821-.481 4.592-.934 8.792-3.2 12.146-6.553 4.535-4.536 7.033-10.561 7.033-16.966v-28.57c0-7.443 5.133-13.904 12.384-15.586 17.017-3.948 33.196-10.652 48.088-19.926 6.314-3.933 14.511-2.994 19.771 2.268l20.21 20.21c9.355 9.354 24.583 9.354 33.946-.004 4.526-4.526 7.021-10.555 7.021-16.973 0-6.411-2.494-12.437-7.024-16.966l-20.209-20.209c-5.262-5.262-6.201-13.456-2.269-19.771 9.274-14.893 15.979-31.072 19.926-48.088 1.682-7.251 8.143-12.384 15.586-12.384h28.57c13.233 0 24-10.767 24-24 0-6.405-2.498-12.43-7.034-16.966-4.535-4.537-10.561-7.035-16.966-7.035h-28.57c-7.443 0-13.904-5.133-15.586-12.384-3.947-17.016-10.651-33.195-19.926-48.088-3.933-6.316-2.993-14.51 2.269-19.771l20.21-20.209c9.355-9.355 9.354-24.583-.004-33.946-4.525-4.526-10.555-7.02-16.973-7.02-6.411 0-12.438 2.495-16.967 7.024l-20.21 20.209c-5.262 5.263-13.456 6.201-19.771 2.268-14.892-9.274-31.071-15.978-48.088-19.926-7.251-1.683-12.384-8.144-12.384-15.587v-28.57c0-11.37-8.068-21.262-19.186-23.521-1.572-.315-3.204-.479-4.814-.479-6.405 0-12.431 2.498-16.967 7.034-4.535 4.536-7.033 10.561-7.033 16.966v28.57c0 7.443-5.133 13.904-12.384 15.586-17.017 3.948-33.196 10.652-48.088 19.926-6.313 3.934-14.51 2.994-19.771-2.268l-20.21-20.21c-9.355-9.355-24.583-9.353-33.946.004-4.526 4.526-7.021 10.555-7.021 16.973 0 6.411 2.494 12.437 7.024 16.966l20.209 20.209c5.262 5.262 6.201 13.456 2.269 19.771-9.274 14.893-15.979 31.072-19.926 48.088-1.681 7.252-8.142 12.385-15.586 12.385h-28.57c-13.233 0-24 10.767-24 24 0 6.405 2.498 12.43 7.034 16.966 4.535 4.536 10.561 7.034 16.966 7.034h28.57c7.443 0 13.904 5.133 15.586 12.384 3.947 17.016 10.651 33.195 19.926 48.088 3.933 6.316 2.993 14.51-2.269 19.771l-20.21 20.209c-9.355 9.355-9.354 24.583.004 33.946 4.525 4.526 10.555 7.02 16.973 7.02 6.411 0 12.438-2.495 16.967-7.024l20.21-20.209c3.087-3.086 7.184-4.685 11.318-4.685z"
  ];

trying too add the above list<String> but it is not scaling

This the svg :
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" enable-background="new 0 0 512 512" height="512px" viewBox="0 0 512 512" width="512px" class=""><g><g>
<path d="m256 512c-30.879 0-56-25.122-56-56v-16.298c-11.863-3.606-23.331-8.359-34.292-14.212l-11.534 11.534c-10.574 10.573-24.635 16.396-39.594 16.396-14.966 0-29.031-5.823-39.604-16.396-21.829-21.843-21.827-57.37.001-79.197l11.534-11.534c-5.853-10.961-10.605-22.43-14.212-34.292h-16.299c-14.953 0-29.014-5.827-39.594-16.407s-16.406-24.642-16.406-39.594c0-30.878 25.121-56 56-56h16.299c3.606-11.863 8.359-23.331 14.212-34.292l-11.534-11.534c-10.574-10.574-16.397-24.635-16.397-39.594 0-14.965 5.823-29.03 16.396-39.604 21.844-21.831 57.37-21.828 79.198 0l11.534 11.534c10.961-5.853 22.429-10.605 34.292-14.212v-16.298c0-14.952 5.826-29.013 16.405-39.593 10.581-10.58 24.642-16.407 39.595-16.407 3.721 0 7.472.375 11.149 1.113 26.004 5.283 44.851 28.364 44.851 54.887v16.298c11.863 3.606 23.331 8.359 34.292 14.212l11.534-11.534c10.574-10.573 24.635-16.396 39.594-16.396 14.966 0 29.031 5.823 39.604 16.396 21.829 21.843 21.827 57.37-.001 79.197l-11.534 11.534c5.853 10.961 10.605 22.43 14.212 34.292h16.299c14.953 0 29.014 5.827 39.594 16.407s16.406 24.642 16.406 39.594c0 30.878-25.121 56-56 56h-16.299c-3.606 11.863-8.359 23.331-14.212 34.292l11.534 11.534c10.573 10.574 16.396 24.635 16.396 39.594 0 14.965-5.823 29.03-16.396 39.604-10.921 10.914-25.266 16.371-39.604 16.372-14.343.001-28.679-5.456-39.594-16.371l-11.534-11.534c-10.961 5.853-22.429 10.605-34.292 14.212v16.297c0 14.952-5.826 29.013-16.405 39.593-7.813 7.813-17.637 13.099-28.41 15.287-.012.002-.023.005-.035.007-3.677.738-7.428 1.113-11.149 1.113zm8-16.8h.01zm-100.925-105.7c2.913 0 5.843.793 8.453 2.419 14.892 9.274 31.071 15.978 48.088 19.926 7.251 1.682 12.384 8.143 12.384 15.586v28.569c0 13.233 10.767 24 24 24 1.601 0 3.222-.162 4.821-.481 4.592-.934 8.792-3.2 12.146-6.553 4.535-4.536 7.033-10.561 7.033-16.966v-28.57c0-7.443 5.133-13.904 12.384-15.586 17.017-3.948 33.196-10.652 48.088-19.926 6.314-3.933 14.511-2.994 19.771 2.268l20.21 20.21c9.355 9.354 24.583 9.354 33.946-.004 4.526-4.526 7.021-10.555 7.021-16.973 0-6.411-2.494-12.437-7.024-16.966l-20.209-20.209c-5.262-5.262-6.201-13.456-2.269-19.771 9.274-14.893 15.979-31.072 19.926-48.088 1.682-7.251 8.143-12.384 15.586-12.384h28.57c13.233 0 24-10.767 24-24 0-6.405-2.498-12.43-7.034-16.966-4.535-4.537-10.561-7.035-16.966-7.035h-28.57c-7.443 0-13.904-5.133-15.586-12.384-3.947-17.016-10.651-33.195-19.926-48.088-3.933-6.316-2.993-14.51 2.269-19.771l20.21-20.209c9.355-9.355 9.354-24.583-.004-33.946-4.525-4.526-10.555-7.02-16.973-7.02-6.411 0-12.438 2.495-16.967 7.024l-20.21 20.209c-5.262 5.263-13.456 6.201-19.771 2.268-14.892-9.274-31.071-15.978-48.088-19.926-7.251-1.683-12.384-8.144-12.384-15.587v-28.57c0-11.37-8.068-21.262-19.186-23.521-1.572-.315-3.204-.479-4.814-.479-6.405 0-12.431 2.498-16.967 7.034-4.535 4.536-7.033 10.561-7.033 16.966v28.57c0 7.443-5.133 13.904-12.384 15.586-17.017 3.948-33.196 10.652-48.088 19.926-6.313 3.934-14.51 2.994-19.771-2.268l-20.21-20.21c-9.355-9.355-24.583-9.353-33.946.004-4.526 4.526-7.021 10.555-7.021 16.973 0 6.411 2.494 12.437 7.024 16.966l20.209 20.209c5.262 5.262 6.201 13.456 2.269 19.771-9.274 14.893-15.979 31.072-19.926 48.088-1.681 7.252-8.142 12.385-15.586 12.385h-28.57c-13.233 0-24 10.767-24 24 0 6.405 2.498 12.43 7.034 16.966 4.535 4.536 10.561 7.034 16.966 7.034h28.57c7.443 0 13.904 5.133 15.586 12.384 3.947 17.016 10.651 33.195 19.926 48.088 3.933 6.316 2.993 14.51-2.269 19.771l-20.21 20.209c-9.355 9.355-9.354 24.583.004 33.946 4.525 4.526 10.555 7.02 16.973 7.02 6.411 0 12.438-2.495 16.967-7.024l20.21-20.209c3.087-3.086 7.184-4.685 11.318-4.685z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#EE2C5E"/><path d="m256 368c-61.757 0-112-50.243-112-112s50.243-112 112-112c3.181 0 6.339.135 9.389.4 27.848 2.289 53.742 14.915 72.835 35.548 19.201 20.75 29.776 47.76 29.776 76.052s-10.575 55.302-29.776 76.052c-19.093 20.633-44.987 33.259-72.913 35.555-2.972.258-6.13.393-9.311.393zm0-192c-44.112 0-80 35.888-80 80s35.888 80 80 80c2.258 0 4.482-.094 6.611-.279 41.187-3.386 73.389-38.4 73.389-79.721s-32.202-76.335-73.311-79.714c-2.207-.192-4.431-.286-6.689-.286z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#EE2C5E"/></g></g> </svg>

Body:
Use the flutter_svg package, it has an example on how to draw an SVG to a canvas, which is basically what you want to achieve:

import 'package:flutter_svg/flutter_svg.dart';
final String rawSvg = '''<svg viewBox="...">...</svg>''';
final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

// If you only want the final Picture output, just use
final Picture picture = svgRoot.toPicture();

// Otherwise, if you want to draw it to a canvas:
// Optional, but probably normally desirable: scale the canvas dimensions to
// the SVG's viewbox
svgRoot.scaleCanvasToViewBox(canvas);

// Optional, but probably normally desireable: ensure the SVG isn't rendered
// outside of the viewbox bounds
svgRoot.clipCanvasToViewBox(canvas);
svgRoot.draw(canvas, size); // <---------- I think this is the one that you actually want

You can also load the SVG as an Asset from your files. Bear in mind that a simpler example on your question could lead to better answers.


来源: stackexchange

问:
String confusion in Javascript with regard to dynamically loading a path
I've encountered something very peculiar in Javascript, which I can't explain.  Simply put, I'm building a dynamic Button component in React in which one can optionally pass in the path of an icon file.

This approach works perfectly:

```<code>const image = require('../styling/assets/images/search-icon.svg');

<button className='button' onClick={props.handleButtonClick}>
  <img className='button-icon' src={image} />
  <p>{props.label}</p>
</button>
</code>```

But it fails if I change the first line to these two:

```<code>const path = '../styling/assets/images/search-icon.svg';
const image = require(path);
</code>```

In this second case I get this error: Error: Cannot find module '../styling/assets/images/search-icon.svg'

Fundamentally the two approaches seem equivalent to me but apparently not.

Why does the 2nd approach fail?

答:
According with MDN docs:

The import statement cannot be used in embedded scripts unless such
  script has a type="module". Bindings imported are called live bindings
  because they are updated by the module that exported the binding.

More information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

ContentLicense: CC BY-SA 4.0

Body:
I've encountered something very peculiar in Javascript, which I can't explain.  Simply put, I'm building a dynamic Button component in React in which one can optionally pass in the path of an icon file.

This approach works perfectly:

const image = require('../styling/assets/images/search-icon.svg');

<button className='button' onClick={props.handleButtonClick}>

{props.label}

</button>

But it fails if I change the first line to these two:

const path = '../styling/assets/images/search-icon.svg';
const image = require(path);

In this second case I get this error: Error: Cannot find module '../styling/assets/images/search-icon.svg'

Fundamentally the two approaches seem equivalent to me but apparently not.

Why does the 2nd approach fail?


问:
Constant validation accuracy in binary classification using ResNet50
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:</p>

```<code>callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043
</code>```

答:
For binary classification, you should change output dense layer to 1 unit and loss to binary_crossentropy.

```<code>model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
</code>```

Also make sure your target arrays (y_train,y_valid) have correct shape and data. They should contain binary labels, 0 or 1

Body:
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:

callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043

Body:
For binary classification, you should change output dense layer to 1 unit and loss to binary_crossentropy.

model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])

Also make sure your target arrays (y_train,y_valid) have correct shape and data. They should contain binary labels, 0 or 1


问:
Chek if an element is x times in some array of a 2D array
I want something that returns True if 0 appears x times in some array of a 2D array withou using for loop

```<code>a= [[1,2,0,4],[1,0,0,4],[0,2,3,4]]
b= [[1,2,0,4],[1,0,3,4],[0,2,3,4]]
x= 2
</code>```

for a the function will return True and for b the function will return False
Or at least i need to find the max number of zeroes, for a it is 2 and for b it is 1
I dont want to use for loop because i have arrays with million elements and i have to do it many times

答:
You can use numpy library for that. just import numpy and do like this.

```<code>import numpy as np
np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)
</code>```

output is,

```<code>array([2, 3])
</code>```

Now if you know your shape of axis it's easy to find.

Body:
I want something that returns True if 0 appears x times in some array of a 2D array withou using for loop

a= [[1,2,0,4],[1,0,0,4],[0,2,3,4]]
b= [[1,2,0,4],[1,0,3,4],[0,2,3,4]]
x= 2

for a the function will return True and for b the function will return False
Or at least i need to find the max number of zeroes, for a it is 2 and for b it is 1
I dont want to use for loop because i have arrays with million elements and i have to do it many times

Body:
You can use numpy library for that. just import numpy and do like this.

import numpy as np
np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)

output is,

array([2, 3])

Now if you know your shape of axis it's easy to find.


问:
How can I get my function to run the Custom Object for the computer Names?
I'm a newcomer to Powershell, and I want to run everything in my Custom Object which $info for all of the computers in $computerName in order to get their information. In this code, I've named them A, B, C for general reference. I tried implementing a foreach loop to write-host of $info so that it would accomplish the task but it's not working. I also tried just just running $info.OSInfo for the CustomObjects, but nothing happens when I run the file in VS Code. Would appreciate your help.</p>

```<code>Function Get-SystemInfo {

    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $computerName
    )
    $compSysProps = @{ Property = @('Name','Model','NumberOfProcessors','Manufacturer','Domain','NumberOfLogicalProcessors','TotalPhysicalMemory'); }
    $OsInfoProps = @{ Property = @('Property', 'InstallDate', 'Caption', 'Version');}
    $BiosProps = @{ Property = @('SerialNumber'); }
    $ProcessorProps = @{ Property = @('Name', 'NumberofCores','NumberofLogicalProcessors', 'SocketDesignation');}
    $DiskProps = @{ Property = @('Caption', 'Size', 'FreeSpace'); }

    $computerName = @('A','B','C')

    foreach ($computer in $computerName)
    {
        Write-Host $info
    }

    $info = [PSCustomObject]@{
        OSInfo  = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computerName | Select-Object  @OsInfoProps
        BIOSInfo = Get-CimInstance -ClassName Win32_bios -ComputerName $computerName | Select-Object @BiosProps
        ComputerSystemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $computerName | Select-Object @compSysProps
        ProcessorInfo = Get-CimInstance -Class Win32_processor -ComputerName $computerName| Select-Object @ProcessorProps
        DiskInfo = Get-CimInstance -Class Win32_LogicalDisk -ComputerName $computerName | Select-Object @DiskProps
    }
}
</code>```

答:
You're calling printing before you set the value for $info, which means that it will be printing nothing. There was also an issue where it was $computerName instead of $computer when getting info. Restructured code in StackOverflow below:

```<code>Function Get-SystemInfo {

    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $computerName
    )
    $compSysProps = @{ Property = @('Name','Model','NumberOfProcessors','Manufacturer','Domain','NumberOfLogicalProcessors','TotalPhysicalMemory'); }
    $OsInfoProps = @{ Property = @('Property', 'InstallDate', 'Caption', 'Version');}
    $BiosProps = @{ Property = @('SerialNumber'); }
    $ProcessorProps = @{ Property = @('Name', 'NumberofCores','NumberofLogicalProcessors', 'SocketDesignation');}
    $DiskProps = @{ Property = @('Caption', 'Size', 'FreeSpace'); }

    $computerName = @('A','B','C')

    foreach ($computer in $computerName)
    {
        $info = [PSCustomObject]@{
            OSInfo  = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer | Select-Object  @OsInfoProps
            BIOSInfo = Get-CimInstance -ClassName Win32_bios -ComputerName $computer | Select-Object @BiosProps
            ComputerSystemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $computer | Select-Object @compSysProps
            ProcessorInfo = Get-CimInstance -Class Win32_processor -ComputerName $computer | Select-Object @ProcessorProps
            DiskInfo = Get-CimInstance -Class Win32_LogicalDisk -ComputerName $computer | Select-Object @DiskProps
        }
        Write-Host $info
    }
}
</code>```

Body:
I'm a newcomer to Powershell, and I want to run everything in my Custom Object which $info for all of the computers in $computerName in order to get their information. In this code, I've named them A, B, C for general reference. I tried implementing a foreach loop to write-host of $info so that it would accomplish the task but it's not working. I also tried just just running $info.OSInfo for the CustomObjects, but nothing happens when I run the file in VS Code. Would appreciate your help.

Function Get-SystemInfo {

    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $computerName
    )
    $compSysProps = @{ Property = @('Name','Model','NumberOfProcessors','Manufacturer','Domain','NumberOfLogicalProcessors','TotalPhysicalMemory'); }
    $OsInfoProps = @{ Property = @('Property', 'InstallDate', 'Caption', 'Version');}
    $BiosProps = @{ Property = @('SerialNumber'); }
    $ProcessorProps = @{ Property = @('Name', 'NumberofCores','NumberofLogicalProcessors', 'SocketDesignation');}
    $DiskProps = @{ Property = @('Caption', 'Size', 'FreeSpace'); }

    $computerName = @('A','B','C')

    foreach ($computer in $computerName)
    {
        Write-Host $info
    }

    $info = [PSCustomObject]@{
        OSInfo  = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computerName | Select-Object  @OsInfoProps
        BIOSInfo = Get-CimInstance -ClassName Win32_bios -ComputerName $computerName | Select-Object @BiosProps
        ComputerSystemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $computerName | Select-Object @compSysProps
        ProcessorInfo = Get-CimInstance -Class Win32_processor -ComputerName $computerName| Select-Object @ProcessorProps
        DiskInfo = Get-CimInstance -Class Win32_LogicalDisk -ComputerName $computerName | Select-Object @DiskProps
    }
}

Body:
You're calling printing before you set the value for $info, which means that it will be printing nothing. There was also an issue where it was $computerName instead of $computer when getting info. Restructured code in StackOverflow below:

Function Get-SystemInfo {

    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $computerName
    )
    $compSysProps = @{ Property = @('Name','Model','NumberOfProcessors','Manufacturer','Domain','NumberOfLogicalProcessors','TotalPhysicalMemory'); }
    $OsInfoProps = @{ Property = @('Property', 'InstallDate', 'Caption', 'Version');}
    $BiosProps = @{ Property = @('SerialNumber'); }
    $ProcessorProps = @{ Property = @('Name', 'NumberofCores','NumberofLogicalProcessors', 'SocketDesignation');}
    $DiskProps = @{ Property = @('Caption', 'Size', 'FreeSpace'); }

    $computerName = @('A','B','C')

    foreach ($computer in $computerName)
    {
        $info = [PSCustomObject]@{
            OSInfo  = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer | Select-Object  @OsInfoProps
            BIOSInfo = Get-CimInstance -ClassName Win32_bios -ComputerName $computer | Select-Object @BiosProps
            ComputerSystemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $computer | Select-Object @compSysProps
            ProcessorInfo = Get-CimInstance -Class Win32_processor -ComputerName $computer | Select-Object @ProcessorProps
            DiskInfo = Get-CimInstance -Class Win32_LogicalDisk -ComputerName $computer | Select-Object @DiskProps
        }
        Write-Host $info
    }
}


问:
How can I host my own SQL Server database with my computer?
I was creating a Log in system based on a simple key with C# and SQL Server.

Here is my code:

```<code>private void Checker_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Joze\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");

    string query = "Select * from First Where [Key] = '" + KeyBox.Text.Trim() + "'";

    SqlDataAdapter sda = new SqlDataAdapter(query, con);

    DataTable dt = new DataTable();
    sda.Fill(dt);

    if (dt.Rows.Count ==- 1)
    {
        CorrectKey(); //external method
    }
    else
    {
        MessageBox.Show("Invalid Lisence Key");
    }
}
</code>```

It works perfectly fine but obviously it does not work on someones pc since the connection is made through my database which is located on my Documents folder.

My question is, how would it be possible to make the SQL connection in order to make it to work for everyone else?

Thanks in advance.

答:
You want to have your SQL database hosted somewhere that the intended users can access.

Signing up for Azure is free, and you recieve credit when you sign up.  This credit can be used to develop for free, and estimate the monthly costs of hosting a database in Azure.  These costs are based on the amount of throughput. If you only have a handful of users, it is quite inexpensive.

Create an Azure account

In Azure Portal, you create a resource group and add the Azure SQL Database resource to it.

Create a resource group
Create an Azure SQL Database resource

After the Azure database is created, you are assigned a connection string that you can use to replace:

```<code>SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Joze\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");
</code>```

Note: Connection strings should reside in your configuration file, and you should parameterize any values you pass to the WHERE clause of your SQL query.  Also, if you plan on having this project access and query multiple tables, consider using an ORM such as Entity Framework for data access.

Getting Started with Entity Framework

Body:
I was creating a Log in system based on a simple key with C# and SQL Server.

Here is my code:

private void Checker_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Joze\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");

    string query = "Select * from First Where [Key] = '" + KeyBox.Text.Trim() + "'";

    SqlDataAdapter sda = new SqlDataAdapter(query, con);

    DataTable dt = new DataTable();
    sda.Fill(dt);

    if (dt.Rows.Count ==- 1)
    {
        CorrectKey(); //external method
    }
    else
    {
        MessageBox.Show("Invalid Lisence Key");
    }
}

It works perfectly fine but obviously it does not work on someones pc since the connection is made through my database which is located on my Documents folder.

My question is, how would it be possible to make the SQL connection in order to make it to work for everyone else?

Thanks in advance.

Body:
You want to have your SQL database hosted somewhere that the intended users can access.

Signing up for Azure is free, and you recieve credit when you sign up.  This credit can be used to develop for free, and estimate the monthly costs of hosting a database in Azure.  These costs are based on the amount of throughput. If you only have a handful of users, it is quite inexpensive.

Create an Azure account

In Azure Portal, you create a resource group and add the Azure SQL Database resource to it.

Create a resource group
Create an Azure SQL Database resource

After the Azure database is created, you are assigned a connection string that you can use to replace:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Joze\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");

Note: Connection strings should reside in your configuration file, and you should parameterize any values you pass to the WHERE clause of your SQL query.  Also, if you plan on having this project access and query multiple tables, consider using an ORM such as Entity Framework for data access.

Getting Started with Entity Framework


问:
Create route in Spring Cloud Gateway with OAuth2 Resource Owner Password grant type
How to configure a route in Spring Cloud Gateway to use an OAuth2 client with authorization-grant-type: password? In other words, how to add the Authorization header with the token in the requests to an API? Because I'm integrating with a legacy application, I must use the grant type password.

I have this application:

```<code>@SpringBootApplication
public class DemoApplication {

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

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
           .route("route_path", r -> r.path("/**")
                   .filters(f -> f.addRequestHeader("Authorization", "bearer <token>"))
                   .uri("http://localhost:8092/messages"))
           .build();
    }
}
</code>```

Replacing the <token> with an actual token, everything just works fine.

I found this project that does something similar: https://github.com/jgrandja/spring-security-oauth-5-2-migrate. It has a client (messaging-client-password) that is used to configure the WebClient to add OAuth2 support to make requests (i.e. by adding the Authorization header).

We can't use this sample project right away because Spring Cloud Gateway is reactive and the way we configure things changes significantly. I think to solve this problem is mostly about converting the WebClientConfig class.

UPDATE

I kinda make it work, but it is in very bad shape.

First, I found how to convert WebClientConfig to be reactive:

```<code>@Configuration
public class WebClientConfig {

    @Bean
    WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth.setDefaultOAuth2AuthorizedClient(true);
        oauth.setDefaultClientRegistrationId("messaging-client-password");
        return WebClient.builder()
                .filter(oauth)
                .build();
    }

    @Bean
    ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
            ReactiveClientRegistrationRepository clientRegistrationRepository,
            ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

        ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
                ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
                        .refreshToken()
                        .password()
                        .build();
        DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
                new DefaultReactiveOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        // For the `password` grant, the `username` and `password` are supplied via request parameters,
        // so map it to `OAuth2AuthorizationContext.getAttributes()`.
        authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

        return authorizedClientManager;
    }

    private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
        return authorizeRequest -> {
            Map<String, Object> contextAttributes = Collections.emptyMap();
            ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
            String username = serverWebExchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
            String password = serverWebExchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
            if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
                contextAttributes = new HashMap<>();

                // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
                contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
                contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
            }
            return Mono.just(contextAttributes);
        };
    }
}
</code>```

With this configuration, we can use the WebClient to make a request. This somehow initializes the OAuth2 client after calling the endpoint:

```<code>@GetMapping("/explicit")
public Mono<String[]> explicit() {
    return this.webClient
        .get()
        .uri("http://localhost:8092/messages")
        .attributes(clientRegistrationId("messaging-client-password"))
        .retrieve()
        .bodyToMono(String[].class);
}
</code>```

Then, by calling this one we are able to get the reference to the authorized client:

```<code>private OAuth2AuthorizedClient authorizedClient;
@GetMapping("/token")
public String token(@RegisteredOAuth2AuthorizedClient("messaging-client-password") OAuth2AuthorizedClient authorizedClient) {
    this.authorizedClient = authorizedClient;
    return authorizedClient.getAccessToken().getTokenValue();
}
</code>```

And finally, by configuring a global filter, we can modify the request to include the Authorization header:

```<code>@Bean
public GlobalFilter customGlobalFilter() {
    return (exchange, chain) -> {
        //adds header to proxied request
        exchange.getRequest().mutate().header("Authorization", authorizedClient.getAccessToken().getTokenType().getValue() + " " + authorizedClient.getAccessToken().getTokenValue()).build();
        return chain.filter(exchange);
    };
}
</code>```

After running this three requests in order, we can use the password grant with Spring Cloud Gateway.

Of course, this process is very messy. What still needs to be done:

Get the reference for the authorized client inside the filter

Initialize the authorized client with the credentials using contextAttributesMapper

Write all of this in a filter, not in a global filter. TokenRelayGatewayFilterFactory implementation can provide a good help to do this.

答:
I implemented authorization-grant-type: password using WebClientHttpRoutingFilter.

By default, spring cloud gateway use Netty Routing Filter but there is an alternative that not requires Netty (https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-netty-routing-filter)

WebClientHttpRoutingFilter uses WebClient for route the requests.

The WebClient can be configured with a ReactiveOAuth2AuthorizedClientManager through of an ExchangeFilterFunction (https://docs.spring.io/spring-security/site/docs/current/reference/html5/#webclient). The ReactiveOAuth2AuthorizedClientManager will be responsible of management the access/refresh tokens and will do all the hard work for you

Here you can review this implementation. In addition, I implemented the client-credentials grant with this approach

Body:
How to configure a route in Spring Cloud Gateway to use an OAuth2 client with authorization-grant-type: password? In other words, how to add the Authorization header with the token in the requests to an API? Because I'm integrating with a legacy application, I must use the grant type password.

I have this application:

@SpringBootApplication
public class DemoApplication {

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

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
           .route("route_path", r -> r.path("/**")
                   .filters(f -> f.addRequestHeader("Authorization", "bearer <token>"))
                   .uri("http://localhost:8092/messages"))
           .build();
    }
}

Replacing the <token> with an actual token, everything just works fine.

I found this project that does something similar: https://github.com/jgrandja/spring-security-oauth-5-2-migrate. It has a client (messaging-client-password) that is used to configure the WebClient to add OAuth2 support to make requests (i.e. by adding the Authorization header).

We can't use this sample project right away because Spring Cloud Gateway is reactive and the way we configure things changes significantly. I think to solve this problem is mostly about converting the WebClientConfig class.

UPDATE

I kinda make it work, but it is in very bad shape.

First, I found how to convert WebClientConfig to be reactive:

@Configuration
public class WebClientConfig {

    @Bean
    WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth.setDefaultOAuth2AuthorizedClient(true);
        oauth.setDefaultClientRegistrationId("messaging-client-password");
        return WebClient.builder()
                .filter(oauth)
                .build();
    }

    @Bean
    ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
            ReactiveClientRegistrationRepository clientRegistrationRepository,
            ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

        ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
                ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
                        .refreshToken()
                        .password()
                        .build();
        DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
                new DefaultReactiveOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        // For the `password` grant, the `username` and `password` are supplied via request parameters,
        // so map it to `OAuth2AuthorizationContext.getAttributes()`.
        authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());

        return authorizedClientManager;
    }

    private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper() {
        return authorizeRequest -> {
            Map<String, Object> contextAttributes = Collections.emptyMap();
            ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
            String username = serverWebExchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.USERNAME);
            String password = serverWebExchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.PASSWORD);
            if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
                contextAttributes = new HashMap<>();

                // `PasswordOAuth2AuthorizedClientProvider` requires both attributes
                contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
                contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
            }
            return Mono.just(contextAttributes);
        };
    }
}

With this configuration, we can use the WebClient to make a request. This somehow initializes the OAuth2 client after calling the endpoint:

@GetMapping("/explicit")
public Mono<String[]> explicit() {
    return this.webClient
        .get()
        .uri("http://localhost:8092/messages")
        .attributes(clientRegistrationId("messaging-client-password"))
        .retrieve()
        .bodyToMono(String[].class);
}

Then, by calling this one we are able to get the reference to the authorized client:

private OAuth2AuthorizedClient authorizedClient;
@GetMapping("/token")
public String token(@RegisteredOAuth2AuthorizedClient("messaging-client-password") OAuth2AuthorizedClient authorizedClient) {
    this.authorizedClient = authorizedClient;
    return authorizedClient.getAccessToken().getTokenValue();
}

And finally, by configuring a global filter, we can modify the request to include the Authorization header:

@Bean
public GlobalFilter customGlobalFilter() {
    return (exchange, chain) -> {
        //adds header to proxied request
        exchange.getRequest().mutate().header("Authorization", authorizedClient.getAccessToken().getTokenType().getValue() + " " + authorizedClient.getAccessToken().getTokenValue()).build();
        return chain.filter(exchange);
    };
}

After running this three requests in order, we can use the password grant with Spring Cloud Gateway.

Of course, this process is very messy. What still needs to be done:

Get the reference for the authorized client inside the filter

Initialize the authorized client with the credentials using contextAttributesMapper

Write all of this in a filter, not in a global filter. TokenRelayGatewayFilterFactory implementation can provide a good help to do this.


问:
How do you write or replace a url in a function using onClick?
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

```<code>   <script type="text/javascript">

    function addurl(){
    "server": [
                 {
                    "position": "center",
                    "url": "New_Url"
                 }
              ]
                     }
    </script>

    <div id="urlbutton"></div>
    <input type="button" onclick="????" value="url123">
</code>```

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

答:
The contents of your function should be a series of statements; your sample is more like (almost) an object literal. So that won't run.

Intially I'll ignore your almost object literal because I don't understand what you're trying to do. Instead, here are two ways that a button can call a function to set the url of the page, i.e., cause the browser to navigate away from the current page to that URL. The first you pass the URL to the function. The second you pass a reference to the button to the function and then from that reference access the button's 'value' attribute. Plus I've given a way to set the URL without a function.

Note: I'm not sure that any of these is necessarily a sensible thing to do on a webpage. If you want to navigate to another URL use an  tag so that it will work for users with no JavaScript. But anyway...

```<code>function addUrl(newUrl) {
   window.location.href = newUrl;
}
function addUrl2(btn) {
   window.location.href = btn.value;
}

<input type="button" value="My URL" onclick="addUrl('someURL');">
<input type="button" value="www.google.com" onclick="addUrl2(this);">
<input type="button" value="Something" onclick="window.location.href='www.google.com';">
</code>```

If what you're really trying to do is update some data structure then maybe something more like this (assumes your data object has a "server" property that is an array of url objects, like you seemed to be trying to do in your original function):

```<code>var myData = {
   "server": [ {"position": "center",
                "url": "New_Url"   } ]
};

function addUrl(newUrl) {
   myData["server"].push{"position":"center",
                         "url" : newUrl});
}
function updateUrl(index,newUrl) {
   myData["server"][index]["url"] = newUrl;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

    <input type="button" onclick="????" value="url123">

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

Body:
The contents of your function should be a series of statements; your sample is more like (almost) an object literal. So that won't run.

Intially I'll ignore your almost object literal because I don't understand what you're trying to do. Instead, here are two ways that a button can call a function to set the url of the page, i.e., cause the browser to navigate away from the current page to that URL. The first you pass the URL to the function. The second you pass a reference to the button to the function and then from that reference access the button's 'value' attribute. Plus I've given a way to set the URL without a function.

Note: I'm not sure that any of these is necessarily a sensible thing to do on a webpage. If you want to navigate to another URL use an <a> tag so that it will work for users with no JavaScript. But anyway...

function addUrl(newUrl) {
   window.location.href = newUrl;
}
function addUrl2(btn) {
   window.location.href = btn.value;
}

<input type="button" value="My URL" onclick="addUrl('someURL');">
<input type="button" value="www.google.com" onclick="addUrl2(this);">
<input type="button" value="Something" onclick="window.location.href='www.google.com';">

If what you're really trying to do is update some data structure then maybe something more like this (assumes your data object has a "server" property that is an array of url objects, like you seemed to be trying to do in your original function):

var myData = {
   "server": [ {"position": "center",
                "url": "New_Url"   } ]
};

function addUrl(newUrl) {
   myData["server"].push{"position":"center",
                         "url" : newUrl});
}
function updateUrl(index,newUrl) {
   myData["server"][index]["url"] = newUrl;
}