问:
I Want to load image from json in my assest as a string and then pass it to an imageview. How to do it?
I Want to load image from json in my assest as a string  and then pass it  to an imageview. How to do it?</p>

答:
You can use Library like Glide and Picasso for load image in imageview as a string
Please check below link
How to load Image into ImageView from Url using Glide v4.0.0RC1</p>


来源: stackexchange

问:
Google map Polygon: Set transparent for circles intersecting
I follow the post Change map opacity outside circle of Google Maps JavaScript API v3, but I have multi circles and sometimes they are intersecting. In the intersecting, they are not transparent. How I can set them transparent?

Code On jsfiddle.net

Thank you.

// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.
const places = [
  {
    center: { "lat": 1.3512492664554796, "lng": 103.85072488875811 },
    radius: 2000
  },
  {
    center: { "lat": 1.3225896205754812, "lng": 103.86600275130694 },
    radius: 2000
  },
  {
    center:{ "lat": 1.3136655910729036, "lng": 103.88866205306475 },
    radius: 2000
  },
  {
    center: { "lat": 1.305427997082587, "lng": 103.83613367171709 },
    radius: 2000
  }
];

let map;

const mapDefault = {

};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), mapDefault);
  const bounds = new google.maps.LatLngBounds();

  let pathsCircle = [];

  places.forEach(place => {
    bounds.extend(place.center);
    pathsCircle.push(drawCircle(place.center, place.radius, 1));
  });

  map.fitBounds(bounds);

  const worldCoords = [
    new google.maps.LatLng(-85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 0)
  ];

  new google.maps.Polygon({
    paths: [worldCoords, ...pathsCircle],
    strokeColor: '#fff',
    strokeOpacity: 0,
    strokeWeight: 0,
    fillColor: '#000',
    fillOpacity: 0.3,
    map,
  });
}

function drawCircle(point, radius, dir) {
}```

That is my code.

答:
To avoid the non-transparent intersections, the circles need to be combined into a single polygon.

One option would be to use the JSTS library to compute the union of the circles.

```<code>var geometryFactory = new jsts.geom.GeometryFactory();

var poly1,poly2,polyunion;
var polys = [];
for (var i=0; i<pathsCircle.length; i++) {
   if (i==0) {
     poly1 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly1.normalize();
     polys[i] = poly1;

   } else {
     poly2 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly2.normalize();
     polys[i] = polys[i-1].union(poly2);
     polys[i].normalize();
   }
}

  polys[i-1].normalize();
  var boundary = polys[i-1].getBoundary();
  var outputPath = jsts2googleMaps(boundary);

var jsts2googleMaps = function (geometry) {
  var coordArray = geometry.getCoordinates();
  GMcoords = [];
  for (var i = 0; i < coordArray.length; i++) {
    GMcoords.push(new google.maps.LatLng(coordArray[i].x, coordArray[i].y));
  }
  return GMcoords;
}
var array2JSTS = function(boundaries) {
  var coordinates = [];
  for (var i = 0; i < boundaries.length; i++) {
    coordinates.push(new jsts.geom.Coordinate(
        boundaries[i].lat, boundaries[i].lng));
  }
  return coordinates;
};
</code>```

proof of concept fiddle

code snippet:

const places = [
  {
    center: { "lat": 1.3512492664554796, "lng": 103.85072488875811 },
    radius: 2000
  },
  {
    center: { "lat": 1.3225896205754812, "lng": 103.86600275130694 },
    radius: 2000
  },
  {
    center:{ "lat": 1.3136655910729036, "lng": 103.88866205306475 },
    radius: 2000
  },
  {
    center: { "lat": 1.305427997082587, "lng": 103.83613367171709 },
    radius: 2000
  }
];

let map;

const mapDefault = {
    center: places[0].center,
    zoom: 10,
    minZoom: 1,
    maxZoom: 19,
    clickableIcons: false
};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), mapDefault);
  const bounds = new google.maps.LatLngBounds();

  let pathsCircle = [];

  places.forEach(place => {
    bounds.extend(place.center);
    pathsCircle.push(drawCircle(place.center, place.radius, 1));
  });

  map.fitBounds(bounds);

  const worldCoords = [
    new google.maps.LatLng(-85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 0)
  ];
var geometryFactory = new jsts.geom.GeometryFactory();

var poly1,poly2,polyunion;
var polys = [];
for (var i=0; i<pathsCircle.length; i++) {
   if (i==0) {
     poly1 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly1.normalize();
     polys[i] = poly1;

   } else {
     poly2 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly2.normalize();
     polys[i] = polys[i-1].union(poly2);
     polys[i].normalize();
   }
}

  polys[i-1].normalize();
  var boundary = polys[i-1].getBoundary();
  var outputPath = jsts2googleMaps(boundary);

new google.maps.Polygon({
    paths: [worldCoords, outputPath],
    strokeColor: '#fff',
    strokeOpacity: 0,
    strokeWeight: 0,
    fillColor: '#000',
    fillOpacity: 0.3,
    map,
  });
}

function drawCircle(point, radius, dir) {
  let d2r = Math.PI / 180;   // degrees to radians
  let r2d = 180 / Math.PI;   // radians to degrees
  let earthsradius = 6378137; // 6378137 is the radius of the earth in metters
  let points = 128; // number of point to draw Circle

  // find the raidus in lat/lon
  let rlat = (radius / earthsradius) * r2d;
  let rlng = rlat / Math.cos(point.lat * d2r);

  let extp = [];

  let start, end;
  if (dir == 1) {  // one extra here makes sure we connect the
    start = 0; end = points + 1
  } else {
    start = points + 1; end = 0
  }
  for (let i = start; (dir == 1 ? i < end : i > end); i = i + dir) {
    let theta = Math.PI * (i / (points / 2));
    const ey = point.lng + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
    const ex = point.lat + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
    extp.push({
      lat: ex,
      lng: ey,
    });
  }
  return extp;
}
var jsts2googleMaps = function (geometry) {
  var coordArray = geometry.getCoordinates();
  GMcoords = [];
  for (var i = 0; i < coordArray.length; i++) {
    GMcoords.push(new google.maps.LatLng(coordArray[i].x, coordArray[i].y));
  }
  return GMcoords;
}
var array2JSTS = function(boundaries) {
  var coordinates = [];
  for (var i = 0; i < boundaries.length; i++) {
    coordinates.push(new jsts.geom.Coordinate(
        boundaries[i].lat, boundaries[i].lng));
  }
  return coordinates;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

<!DOCTYPE html>

    <title>Data Layer: Polygon</title>

 ```

ContentLicense: CC BY-SA 4.0

Body:
I follow the post Change map opacity outside circle of Google Maps JavaScript API v3, but I have multi circles and sometimes they are intersecting. In the intersecting, they are not transparent. How I can set them transparent?

Code On jsfiddle.net

Thank you.

// This example uses the Google Maps JavaScript API's Data layer
// to create a rectangular polygon with 2 holes in it.
const places = [
  {
    center: { "lat": 1.3512492664554796, "lng": 103.85072488875811 },
    radius: 2000
  },
  {
    center: { "lat": 1.3225896205754812, "lng": 103.86600275130694 },
    radius: 2000
  },
  {
    center:{ "lat": 1.3136655910729036, "lng": 103.88866205306475 },
    radius: 2000
  },
  {
    center: { "lat": 1.305427997082587, "lng": 103.83613367171709 },
    radius: 2000
  }
];

let map;

const mapDefault = {

};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), mapDefault);
  const bounds = new google.maps.LatLngBounds();

  let pathsCircle = [];

  places.forEach(place => {
    bounds.extend(place.center);
    pathsCircle.push(drawCircle(place.center, place.radius, 1));
  });

  map.fitBounds(bounds);

  const worldCoords = [
    new google.maps.LatLng(-85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 0)
  ];

  new google.maps.Polygon({
    paths: [worldCoords, ...pathsCircle],
    strokeColor: '#fff',
    strokeOpacity: 0,
    strokeWeight: 0,
    fillColor: '#000',
    fillOpacity: 0.3,
    map,
  });
}

function drawCircle(point, radius, dir) {
}

That is my code.

Body:
To avoid the non-transparent intersections, the circles need to be combined into a single polygon.

One option would be to use the JSTS library to compute the union of the circles.

var geometryFactory = new jsts.geom.GeometryFactory();

var poly1,poly2,polyunion;
var polys = [];
for (var i=0; i<pathsCircle.length; i++) {
   if (i==0) {
     poly1 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly1.normalize();
     polys[i] = poly1;

   } else {
     poly2 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly2.normalize();
     polys[i] = polys[i-1].union(poly2);
     polys[i].normalize();
   }
}

  polys[i-1].normalize();
  var boundary = polys[i-1].getBoundary();
  var outputPath = jsts2googleMaps(boundary);

var jsts2googleMaps = function (geometry) {
  var coordArray = geometry.getCoordinates();
  GMcoords = [];
  for (var i = 0; i < coordArray.length; i++) {
    GMcoords.push(new google.maps.LatLng(coordArray[i].x, coordArray[i].y));
  }
  return GMcoords;
}
var array2JSTS = function(boundaries) {
  var coordinates = [];
  for (var i = 0; i < boundaries.length; i++) {
    coordinates.push(new jsts.geom.Coordinate(
        boundaries[i].lat, boundaries[i].lng));
  }
  return coordinates;
};

proof of concept fiddle

code snippet:

const places = [
  {
    center: { "lat": 1.3512492664554796, "lng": 103.85072488875811 },
    radius: 2000
  },
  {
    center: { "lat": 1.3225896205754812, "lng": 103.86600275130694 },
    radius: 2000
  },
  {
    center:{ "lat": 1.3136655910729036, "lng": 103.88866205306475 },
    radius: 2000
  },
  {
    center: { "lat": 1.305427997082587, "lng": 103.83613367171709 },
    radius: 2000
  }
];

let map;

const mapDefault = {
    center: places[0].center,
    zoom: 10,
    minZoom: 1,
    maxZoom: 19,
    clickableIcons: false
};

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), mapDefault);
  const bounds = new google.maps.LatLngBounds();

  let pathsCircle = [];

  places.forEach(place => {
    bounds.extend(place.center);
    pathsCircle.push(drawCircle(place.center, place.radius, 1));
  });

  map.fitBounds(bounds);

  const worldCoords = [
    new google.maps.LatLng(-85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, -180),
    new google.maps.LatLng(85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 180),
    new google.maps.LatLng(-85.1054596961173, 0)
  ];
var geometryFactory = new jsts.geom.GeometryFactory();

var poly1,poly2,polyunion;
var polys = [];
for (var i=0; i<pathsCircle.length; i++) {
   if (i==0) {
     poly1 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly1.normalize();
     polys[i] = poly1;

   } else {
     poly2 = geometryFactory.createPolygon(geometryFactory.createLinearRing(array2JSTS(pathsCircle[i])));
     poly2.normalize();
     polys[i] = polys[i-1].union(poly2);
     polys[i].normalize();
   }
}

  polys[i-1].normalize();
  var boundary = polys[i-1].getBoundary();
  var outputPath = jsts2googleMaps(boundary);

new google.maps.Polygon({
    paths: [worldCoords, outputPath],
    strokeColor: '#fff',
    strokeOpacity: 0,
    strokeWeight: 0,
    fillColor: '#000',
    fillOpacity: 0.3,
    map,
  });
}

function drawCircle(point, radius, dir) {
  let d2r = Math.PI / 180;   // degrees to radians
  let r2d = 180 / Math.PI;   // radians to degrees
  let earthsradius = 6378137; // 6378137 is the radius of the earth in metters
  let points = 128; // number of point to draw Circle

  // find the raidus in lat/lon
  let rlat = (radius / earthsradius) * r2d;
  let rlng = rlat / Math.cos(point.lat * d2r);

  let extp = [];

  let start, end;
  if (dir == 1) {  // one extra here makes sure we connect the
    start = 0; end = points + 1
  } else {
    start = points + 1; end = 0
  }
  for (let i = start; (dir == 1 ? i < end : i > end); i = i + dir) {
    let theta = Math.PI * (i / (points / 2));
    const ey = point.lng + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
    const ex = point.lat + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
    extp.push({
      lat: ex,
      lng: ey,
    });
  }
  return extp;
}
var jsts2googleMaps = function (geometry) {
  var coordArray = geometry.getCoordinates();
  GMcoords = [];
  for (var i = 0; i < coordArray.length; i++) {
    GMcoords.push(new google.maps.LatLng(coordArray[i].x, coordArray[i].y));
  }
  return GMcoords;
}
var array2JSTS = function(boundaries) {
  var coordinates = [];
  for (var i = 0; i < boundaries.length; i++) {
    coordinates.push(new jsts.geom.Coordinate(
        boundaries[i].lat, boundaries[i].lng));
  }
  return coordinates;
};

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<!DOCTYPE html>
<html>
  <head>
    <title>Data Layer: Polygon</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://cdn.jsdelivr.net/npm/jsts@2.8.1/dist/jsts.js"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map"></div>

    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2"
      async
    ></script>
  </body>
</html>


问:
Test fails due to react-native-permissions
Test fails due to react-native-permissions

Output:

```<code>react-native-permissions: NativeModule.RNPermissions is null. To fix this issue try these steps:
• If you are using CocoaPods on iOS, run pod install in the ios directory and then clean, rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.
• If you are getting this error while unit testing you need to mock the native module. You can use this to get started: https://github.com/react-native-community/react-native-permissions/blob/master/mock.js
If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-permissions

  at Object.<anonymous> (node_modules/react-native-qrcode-scanner/node_modules/react-native-permissions/lib/commonjs/index.ts:6:9)
  at Object.<anonymous> (node_modules/react-native-qrcode-scanner/index.js:19:1)
</code>```

Plateform:
both ios and android

before installation of react-native-qrcode-scanner and react-native-permissions all tests were ok and working perfect

here is my output attached the error I am facing

I have also mocked react-native-permissions in jest.setup.js file in root dir of project as shown below , still its not working

```<code>jest.mock('react-native-permissions', () =>
  require('react-native-permissions/mock'),
);
</code>```

at time of installation i ignored ios configrations required for this pakage because i am working on ubuntu for android only

shall be thankfull for your help

答:
I have found 2 ways to get rid of issue

1.mock react-native-qrcode-scanner inside the test file , this is solution for single file as shown below
write mock of react-native-qrcode-scanner on top of test file after imports

```<code>jest.mock('react-native-qrcode-scanner', () => jest.fn());
</code>```

mock react-native-qrcode-scanner inside the jest.setup.js file in root dir of project, this is solution for all tests files as shown below

write mock of react-native-qrcode-scanner inside jest.setup.js file in root dir as shown below

```<code>jest.mock(
  'react-native-qrcode-scanner/node_modules/react-native-permissions',
  () => require('react-native-permissions/mock'),
);
</code>```

Body:
Test fails due to react-native-permissions

Output:

react-native-permissions: NativeModule.RNPermissions is null. To fix this issue try these steps:
• If you are using CocoaPods on iOS, run pod install in the ios directory and then clean, rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.
• If you are getting this error while unit testing you need to mock the native module. You can use this to get started: https://github.com/react-native-community/react-native-permissions/blob/master/mock.js
If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-permissions

  at Object.<anonymous> (node_modules/react-native-qrcode-scanner/node_modules/react-native-permissions/lib/commonjs/index.ts:6:9)
  at Object.<anonymous> (node_modules/react-native-qrcode-scanner/index.js:19:1)

Plateform:
both ios and android

before installation of react-native-qrcode-scanner and react-native-permissions all tests were ok and working perfect

here is my output attached the error I am facing

I have also mocked react-native-permissions in jest.setup.js file in root dir of project as shown below , still its not working

jest.mock('react-native-permissions', () =>
  require('react-native-permissions/mock'),
);

at time of installation i ignored ios configrations required for this pakage because i am working on ubuntu for android only

shall be thankfull for your help

Body:
I have found 2 ways to get rid of issue

1.mock react-native-qrcode-scanner inside the test file , this is solution for single file as shown below
write mock of react-native-qrcode-scanner on top of test file after imports

jest.mock('react-native-qrcode-scanner', () => jest.fn());

mock react-native-qrcode-scanner inside the jest.setup.js file in root dir of project, this is solution for all tests files as shown below

write mock of react-native-qrcode-scanner inside jest.setup.js file in root dir as shown below

jest.mock(
  'react-native-qrcode-scanner/node_modules/react-native-permissions',
  () => require('react-native-permissions/mock'),
);


问:
Is there a way to temporarily store information between Application.Restart(...) calls in WinForms?
I have a C# application where the user has the option to restart, which is essentially a button tied directly to Application.Restart(...).  This works well.

Unfortunately there is some non-critical data I wish to carry between sessions like window sizes and dropdown selections, and currently I do not have any data store the application is connected to that can be used as scratch.  Is there some .NET (or Windows) provided store for a small amount of non-critical non-security-sensitive data I can use for this purpose?

答:
Well here is a quick and dirty way how I would retain any settings upon application restarts:

```<code>using System;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.Specialized;

namespace RetainSettings
{
    public partial class Form1 : Form
    {
        NameValueCollection EnvironmentSettings = ConfigurationManager.AppSettings;
        private int EnvHeight;
        private int EnvWidth;

        public Form1()
        {
            InitializeComponent();
            LoadAppConfig("Height");
            LoadAppConfig("Width");
        }

        private void UpdateAppConfig(string key, object value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings[key].Value = value.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void LoadAppConfig(string ConfigKey)
        {
            switch (ConfigKey)
            {
                case "Height":
                    EnvHeight = int.Parse(EnvironmentSettings[ConfigKey]);
                    break;
                case "Width":
                    EnvWidth = int.Parse(EnvironmentSettings[ConfigKey]);
                    break;
                default:
                    break;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Height = EnvHeight;
            Width = EnvWidth;
        }

        private void RestartButton_Click(object sender, EventArgs e)
        {
            UpdateAppConfig("Height", Height);
            UpdateAppConfig("Width", Width);

            Application.Restart();
        }
    }
}
</code>```

UpdateAppConfig(string, object)

Note that this method is opening the executable configuration file that is generated inside the bin folder along with the executable. This file will have name as same as the exe file with an extenion .config appended in the end.

The flow is pretty much understandable if you read this method once. First the config file is loaded then any modifications are done and finally saving the config file which obviously flushes the changes to disk.

LoadAppConfig(string)

In this method you can see I've specified the keys that I might want to load from the configuration file. In this example I have used to Height and Width of the form to be retained upon restart.

Important!

If you open the configuration file of a newly created project you'll see that its an XML document and a section <appSettings></appSettings> is missing.

For this project I've added the section and the keys to be retained manually like:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>

<!-- Manually Added -->
<appSettings>
  <add key="Height" value="463" />
  <add key="Width" value="558" />
 </appSettings>

</configuration>
</code>```

Finally

The LoadAppConfig is added in Application's constructor and UpdateAppConfig is called just before the restart to update the configuration.

This isn't a concrete answer and I hope experts here will also shed some light on other methods too.

Body:
Well here is a quick and dirty way how I would retain any settings upon application restarts:

using System;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.Specialized;

namespace RetainSettings
{
    public partial class Form1 : Form
    {
        NameValueCollection EnvironmentSettings = ConfigurationManager.AppSettings;
        private int EnvHeight;
        private int EnvWidth;

        public Form1()
        {
            InitializeComponent();
            LoadAppConfig("Height");
            LoadAppConfig("Width");
        }

        private void UpdateAppConfig(string key, object value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings[key].Value = value.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void LoadAppConfig(string ConfigKey)
        {
            switch (ConfigKey)
            {
                case "Height":
                    EnvHeight = int.Parse(EnvironmentSettings[ConfigKey]);
                    break;
                case "Width":
                    EnvWidth = int.Parse(EnvironmentSettings[ConfigKey]);
                    break;
                default:
                    break;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Height = EnvHeight;
            Width = EnvWidth;
        }

        private void RestartButton_Click(object sender, EventArgs e)
        {
            UpdateAppConfig("Height", Height);
            UpdateAppConfig("Width", Width);

            Application.Restart();
        }
    }
}

UpdateAppConfig(string, object)

Note that this method is opening the executable configuration file that is generated inside the bin folder along with the executable. This file will have name as same as the exe file with an extenion .config appended in the end.

The flow is pretty much understandable if you read this method once. First the config file is loaded then any modifications are done and finally saving the config file which obviously flushes the changes to disk.

LoadAppConfig(string)

In this method you can see I've specified the keys that I might want to load from the configuration file. In this example I have used to Height and Width of the form to be retained upon restart.

Important!

If you open the configuration file of a newly created project you'll see that its an XML document and a section <appSettings></appSettings> is missing.

For this project I've added the section and the keys to be retained manually like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>

<!-- Manually Added -->
<appSettings>
  <add key="Height" value="463" />
  <add key="Width" value="558" />
 </appSettings>

</configuration>

Finally

The LoadAppConfig is added in Application's constructor and UpdateAppConfig is called just before the restart to update the configuration.

This isn't a concrete answer and I hope experts here will also shed some light on other methods too.


问:
Quessing game by Object
I am trying to make simple guessing game by object method.I want to practice object method. Everything is working, except one condition. I want compare input with random num. I don't know why this condition ignore me. How can I fix it?  Thank you</p>
```<code>
let game = {
  quess: () => {
    const input = document.querySelector('.input').value
     return input
  },
  randomNumber: () => {
    //const x = Math.floor(Math.random() * 10) + 1
    const x = 3   // for testing
    return x
  },
  displayQuess: function() {
      const userNum = document.querySelector('.quess')
      return userNum.innerHTML = this.quess()
  },

  clearFields: function() {
    document.querySelector('.input').value = ''
  },
  result: function() {
     const output = document.querySelector('.output')

     const input = this.quess()
     const random = this.randomNumber()

     if(random === input) {         // this condition ignore me , why ?
       output.innerHTML = ' Winner !!'
     }

     if(input != random) {
       output.innerHTML = 'correct num was : ' + random
     }
  }
}

 const btn = document.querySelector('.btn')
 const output = document.querySelector('.output')
 const quesss = document.querySelector('.quesses')

 let quesses = 3

 btn.addEventListener('click', function() {
   //console.log( game.displayQuess())
      game.displayQuess()
      game.clearFields()
      game.result()

      quesses--
      quesss.innerHTML = quesses
      if(quesses < 1 ){
          output.style.color = 'red'
          output.innerHTML = 'game over'
          document.querySelector('.input').disabled = true;
          document.querySelector('.btn').disabled = true;
      }
 })

</code>```

答:
The === is a strict type equality check. It checks that both operands are of the same type and are equal. This is not passing the condition because you are comparing a number with a string. Even though they have the same value, they are of data types (a numeric type, and a text (string) type).

You can use == to do loose equality checks, which allows checking across different types, but it is better practice to use strict equality checks. So if you expect a number, it might be better to convert the string type to a number type

```<code>quess: () => {
    const input = document.querySelector('.input').value
     return parseFloat(input);
  },
</code>```

Further Reading:

parseFloat

Strict Equality (===)

Equality (==)

Title: Quessing game by Object

Body:
I am trying to make simple guessing game by object method.I want to practice object method. Everything is working, except one condition. I want compare input with random num. I don't know why this condition ignore me. How can I fix it?  Thank you

let game = {
  quess: () => {
    const input = document.querySelector('.input').value
     return input
  },
  randomNumber: () => {
    //const x = Math.floor(Math.random() * 10) + 1
    const x = 3   // for testing
    return x
  },
  displayQuess: function() {
      const userNum = document.querySelector('.quess')
      return userNum.innerHTML = this.quess()
  },

  clearFields: function() {
    document.querySelector('.input').value = ''
  },
  result: function() {
     const output = document.querySelector('.output')

     const input = this.quess()
     const random = this.randomNumber()

     if(random === input) {         // this condition ignore me , why ?
       output.innerHTML = ' Winner !!'
     }

     if(input != random) {
       output.innerHTML = 'correct num was : ' + random
     }
  }
}

 const btn = document.querySelector('.btn')
 const output = document.querySelector('.output')
 const quesss = document.querySelector('.quesses')

 let quesses = 3

 btn.addEventListener('click', function() {
   //console.log( game.displayQuess())
      game.displayQuess()
      game.clearFields()
      game.result()

      quesses--
      quesss.innerHTML = quesses
      if(quesses < 1 ){
          output.style.color = 'red'
          output.innerHTML = 'game over'
          document.querySelector('.input').disabled = true;
          document.querySelector('.btn').disabled = true;
      }
 })

Body:
The === is a strict type equality check. It checks that both operands are of the same type and are equal. This is not passing the condition because you are comparing a number with a string. Even though they have the same value, they are of data types (a numeric type, and a text (string) type).

You can use == to do loose equality checks, which allows checking across different types, but it is better practice to use strict equality checks. So if you expect a number, it might be better to convert the string type to a number type

quess: () => {
    const input = document.querySelector('.input').value
     return parseFloat(input);
  },

Further Reading:

parseFloat

Strict Equality (===)

Equality (==)


问:
How to check if Coupon is valid for customer before checkout in stripe api
I have a use case where I need to find that whether applied code is valid for a specific customer or not before making the payment using the Stripe. Assume there is one coupon code as "50%off" created in the Stripe which can only be used once by customers. There will be two scenario:

If customer using it for first time, they discount will be applied which is fine.

If customer using it second time, I dont want to show them discounted price at application level. And at the Stripe level, discount will not be provided as well.

I am not managing coupon code at my application level and using below code to retrieve coupon code data:

```<code>\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon);
</code>```

The above code share with me below details

```<code>[body] => {
  "id": "50%off",
  "object": "coupon",
  "amount_off": 600,
  "created": 1494427220,
  "currency": "usd",
  "duration": "once",
  "duration_in_months": null,
  "livemode": false,
  "max_redemptions": null,
  "metadata": {
  },
  "name": null,
  "percent_off": null,
  "percent_off_precise": null,
  "redeem_by": null,
  "times_redeemed": 4,
  "valid": true
}
</code>```

but I can not figure out if the customer has already used this coupon code earlier or not. I tried to pass customer id as well as below:

```<code>\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon, ['customer' => $stripe_customer_id]);
</code>```

but it shares the same response.

Can anyone please help me in this, thanks!

答: Stripe doesn't tell you whether the Coupon has already been used by a customer before or not. This is something you will need to track on your end in your own database instead every time a customer redeems a Coupon.</p>

Body:
I have a use case where I need to find that whether applied code is valid for a specific customer or not before making the payment using the Stripe. Assume there is one coupon code as "50%off" created in the Stripe which can only be used once by customers. There will be two scenario:

If customer using it for first time, they discount will be applied which is fine.

If customer using it second time, I dont want to show them discounted price at application level. And at the Stripe level, discount will not be provided as well.

I am not managing coupon code at my application level and using below code to retrieve coupon code data:

\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon);

The above code share with me below details

[body] => {
  "id": "50%off",
  "object": "coupon",
  "amount_off": 600,
  "created": 1494427220,
  "currency": "usd",
  "duration": "once",
  "duration_in_months": null,
  "livemode": false,
  "max_redemptions": null,
  "metadata": {
  },
  "name": null,
  "percent_off": null,
  "percent_off_precise": null,
  "redeem_by": null,
  "times_redeemed": 4,
  "valid": true
}

but I can not figure out if the customer has already used this coupon code earlier or not. I tried to pass customer id as well as below:

\Stripe\Stripe::setApiKey($this->config->item('stripe_secret_key'));
$couponData = \Stripe\Coupon::retrieve($coupon, ['customer' => $stripe_customer_id]);

but it shares the same response.

Can anyone please help me in this, thanks!


问:
Flutter Doctor gives Bad Cpu Type in executable
I'm using Mac mini , MacOs monterey and m1 chip. When trying to setup flutter, it is giving error.
command: flutter doctor
o/p: /Users/admin/Desktop/flutter/bin/internal/shared.sh: line 229: /Users/admin/Desktop/flutter/bin/cache/dart-sdk/bin/dart: Bad CPU type in executable

I have tried below command but it is also not working,
Terminal command: sudo softwareupdate --install-rosetta --agree-to-license
Terminal output:
By using the agreetolicense option, you are agreeing that you have run this tool with the license only option and have read and agreed to the terms.
If you do not agree, press CTRL-C and cancel this process immediately.
Rosetta 2 update is not available

答: run "softwareupdate --install-rosetta" in the terminal</p>


答: If you want to store the whole image in your JSON, than you could use base64 to convert from byte[] to String and vice versa. Java has base64 encoders and decoders in it's util packages. Wiki page: https://en.wikipedia.org/wiki/Base64.</p>

Title: I Want to load image from json in my assest as a string and then pass it to an imageview. How to do it?


问:
c# editing sql table data without loosing the existing

Possible Duplicate:

  C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?

I have a sql datatable, and I don't want the users to delete or modify anything, they can only add new rows if they want.

My solution was to use datagridview to show the existing data, but I'm stuck, because I cannot deny editing or deleting without denying adding a new row, so this is not a good way. Otherwise using update method will override all the data the user has changed (later on maybe I can give overriding permissions for that).

I could make a read-only dgw to show the existing data, and allow the user to enter the new data one by one with textboxes, but that's a bigger work and maybe unnecessary.

Is there a simple way to allow adding new row without letting editing the existing data? Maybe manipulating the datatable?

Thank you.

答:
The simpler way i could think of is, while populating the grid, ill see how many existing rows i am adding from DB. Ill keep a count on it. Then when user clicks save, ill update the DB from rows after this count. Once update the DB, ill update the count to new rows count.
The same holds good even if you dont want to allow the user to edit, you can write events where you can check if the editable row is less than tis count, then disallow him to edit.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I return users and roles in the same View?
I'm learning asp.net core MVC and I am trying to just make a simple user management model, but I cant seem to figure out how to make an algorithm that outputs the user and their role. I believe its due to the function outputting the user as a string, and the roles being output as a List. I cant seem to successfully call two model to make  the Model work. Or am I doing this incorrectly?

I can get it to successfully list the user and their info with this

```<code>        [Route("EditUser/{id?}")]
        public async Task<IActionResult> EditUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
                return View("NotFound");
            }

            return View(user);
}
</code>```

However since I have 3 or 4 different roles I cant just use List<>  right?

```<code>        var model = new List<ManageUserRolesViewModel>();

        foreach (var role in _roleManager.Roles)
        {
            var userRolesViewModel = new ManageUserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            if (await _userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.Selected = true;
            }
            else
            {
                userRolesViewModel.Selected = false;
            }
            model.Add(userRolesViewModel);
        }
</code>```

Which I cant output to view due to the string vs list issue.

```<code><div class="card-body">
            @for (int i = 0; i < Model.Count; i++)
            {
                <div class="form-check m-1">
                    <input type="hidden" asp-for="@Model[i].RoleId" />
                    <input type="hidden" asp-for="@Model[i].RoleName" />
                    <input asp-for="@Model[i].Selected" class="form-check-input" />
                    <label class="form-check-label" asp-for="@Model[i].Selected">
                        @Model[i].RoleName
                    </label>
                </div>
            }
            <div asp-validation-summary="All" class="text-danger"></div>
        </div>
</code>```

答:
It's no need to pass the user or role's model to the view directly, You can just  pass their string Names.

In this demo, I will only show that one user corresponds to multiple roles, Other correspondences are basically the same as this.

I create a ViewModel contains user and role's name

ViewModel

```<code>public class UserRoleModel
    {
        public string UserName { get; set; }
        public List<string> RoleName { get; set; }
    }
</code>```

In controller, I will return List<UserRoleModel>

controller

```<code>public IActionResult Show()
        {
            //get the User and Role from database and add them to UserRoleModel.
           //I'm assuming you got the User (jack and mike) and their corresponding roles

            List<UserRoleModel> userRoleModel = new List<UserRoleModel>
            {
                 new UserRoleModel
                 {
                    UserName = "Jack",
                    RoleName = new List<string> {
                        "Admin",
                        "User",
                        "Other"
                    }
                 },

                new UserRoleModel()
                {
                    UserName = "Mike",
                    RoleName = new List<string> {
                        "Admin",
                        "User",
                        "Other"
                    }
                }
            };
            return View(userRoleModel);
        }
</code>```

View

```<code>@model List<CustomIdentity.Models.UserRoleModel>

<h1>User and Roles</h1>

@foreach (var item in @Model)
{
    <div>User: @item.UserName</div>
    @foreach (var role in item.RoleName)
   {
       <div>Role: @role</div>
   }
   <br />
}
</code>```

Then you can get the user and roles in the same view

Body:
I'm learning asp.net core MVC and I am trying to just make a simple user management model, but I cant seem to figure out how to make an algorithm that outputs the user and their role. I believe its due to the function outputting the user as a string, and the roles being output as a List. I cant seem to successfully call two model to make  the Model work. Or am I doing this incorrectly?

I can get it to successfully list the user and their info with this

        [Route("EditUser/{id?}")]
        public async Task<IActionResult> EditUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
                return View("NotFound");
            }

            return View(user);
}

However since I have 3 or 4 different roles I cant just use List<>  right?

        var model = new List<ManageUserRolesViewModel>();

        foreach (var role in _roleManager.Roles)
        {
            var userRolesViewModel = new ManageUserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            if (await _userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.Selected = true;
            }
            else
            {
                userRolesViewModel.Selected = false;
            }
            model.Add(userRolesViewModel);
        }

Which I cant output to view due to the string vs list issue.

            @for (int i = 0; i < Model.Count; i++)
            {

                    <input type="hidden" asp-for="@Model[i].RoleId" />
                    <input type="hidden" asp-for="@Model[i].RoleName" />
                    <input asp-for="@Model[i].Selected" class="form-check-input" />

                        @Model[i].RoleName

            }

Body:
It's no need to pass the user or role's model to the view directly, You can just  pass their string Names.

In this demo, I will only show that one user corresponds to multiple roles, Other correspondences are basically the same as this.

I create a ViewModel contains user and role's name

ViewModel

public class UserRoleModel
    {
        public string UserName { get; set; }
        public List<string> RoleName { get; set; }
    }

In controller, I will return List<UserRoleModel>

controller

public IActionResult Show()
        {
            //get the User and Role from database and add them to UserRoleModel.
           //I'm assuming you got the User (jack and mike) and their corresponding roles

            List<UserRoleModel> userRoleModel = new List<UserRoleModel>
            {
                 new UserRoleModel
                 {
                    UserName = "Jack",
                    RoleName = new List<string> {
                        "Admin",
                        "User",
                        "Other"
                    }
                 },

                new UserRoleModel()
                {
                    UserName = "Mike",
                    RoleName = new List<string> {
                        "Admin",
                        "User",
                        "Other"
                    }
                }
            };
            return View(userRoleModel);
        }

View

@model List<CustomIdentity.Models.UserRoleModel>

<h1>User and Roles</h1>

@foreach (var item in @Model)
{
    <div>User: @item.UserName</div>
    @foreach (var role in item.RoleName)
   {
       <div>Role: @role</div>
   }
   <br />
}

Then you can get the user and roles in the same view


问:
How to fix Illegal instruction (core dumped)
Hi i am trying to fix this issue when i run python3 brain.py below i get this error
Illegal instruction (core dumped)

```<code>from imageai.Prediction import ImagePrediction
import os
execution_path=os.getcwd()

prediction = ImagePrediction()
prediction.setModelTypeAsSqueezeNet()
prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5"))
prediction.loadModel()

predictions, probabilities = prediction.predictImage(os.path.join(execution_path, "giraffe.jpg"), result_count=5 )
for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction , " : " , eachProbability)
</code>```

I have tried to downgrade Tensorflow to 1.5.0 but then after i run that i get these errors

```<code>[ons mar 25 23:11:45] Jonathan@Whats next?:~/ReallySmartBrain$ pip3 install tensorflow==1.5.0
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement tensorflow==1.5.0 (from versions: 1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 1.15.0rc0, 1.15.0rc1, 1.15.0rc2, 1.15.0rc3, 1.15.0, 1.15.2, 2.0.0a0, 2.0.0b0, 2.0.0b1, 2.0.0rc0, 2.0.0rc1, 2.0.0rc2, 2.0.0, 2.0.1, 2.1.0rc0, 2.1.0rc1, 2.1.0rc2, 2.1.0, 2.2.0rc0, 2.2.0rc1)
ERROR: No matching distribution found for tensorflow==1.5.0
</code>```

The other solution is to compile it from source code but i'don't have any idea to compile it from source code.
Can i fix this anyway?

答: I've got a similar problem with an old CPU on a vintage Mac OS now running Linux because no recent Mac OS can run on it. I've tried to compile from sources and got a bunch of problems (Bazel, compiler, flags, dependencies, ...). Finally, I've lost few hours to learn that could be a real nightmare. Good advice, don't even try it!</p>

Body:
Hi i am trying to fix this issue when i run python3 brain.py below i get this error
Illegal instruction (core dumped)

from imageai.Prediction import ImagePrediction
import os
execution_path=os.getcwd()

prediction = ImagePrediction()
prediction.setModelTypeAsSqueezeNet()
prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5"))
prediction.loadModel()

predictions, probabilities = prediction.predictImage(os.path.join(execution_path, "giraffe.jpg"), result_count=5 )
for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction , " : " , eachProbability)

I have tried to downgrade Tensorflow to 1.5.0 but then after i run that i get these errors

[ons mar 25 23:11:45] Jonathan@Whats next?:~/ReallySmartBrain$ pip3 install tensorflow==1.5.0
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement tensorflow==1.5.0 (from versions: 1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 1.15.0rc0, 1.15.0rc1, 1.15.0rc2, 1.15.0rc3, 1.15.0, 1.15.2, 2.0.0a0, 2.0.0b0, 2.0.0b1, 2.0.0rc0, 2.0.0rc1, 2.0.0rc2, 2.0.0, 2.0.1, 2.1.0rc0, 2.1.0rc1, 2.1.0rc2, 2.1.0, 2.2.0rc0, 2.2.0rc1)
ERROR: No matching distribution found for tensorflow==1.5.0

The other solution is to compile it from source code but i'don't have any idea to compile it from source code.
Can i fix this anyway?


问:
Converting "Stream<String>" to "String" in java8 to combine group of strings in a stream
I want to convert Stream<String> to String and print all the string.

```<code>Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);
</code>```

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

答:
In java 8, there is method joining(), Which is the part of Collectors class. You have to join this string using Collectors.joining().

Here down is code:

```<code>String result = Stream.of("do", "re", "ma", "po", "fa", "si")
                .filter(str -> str.length() > 1)
                .collect(Collectors.joining());
</code>```

Or

```<code>String result= Stream.of("do","re","ma","po","fa","si")
                .filter(str -> str.length() > 1)
                .peek(System.out::println)
                .collect(Collectors.joining());
</code>```

Body:
I want to convert Stream<String> to String and print all the string.

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

Body:
In java 8, there is method joining(), Which is the part of Collectors class. You have to join this string using Collectors.joining().

Here down is code:

String result = Stream.of("do", "re", "ma", "po", "fa", "si")
                .filter(str -> str.length() > 1)
                .collect(Collectors.joining());

Or

String result= Stream.of("do","re","ma","po","fa","si")
                .filter(str -> str.length() > 1)
                .peek(System.out::println)
                .collect(Collectors.joining());


问:
Record in Android Emulator flickers
I have tried recording in Android Studio with different emulated devices and programs, but all my records flicker heavily.

The screen of the emulator itself doesn't flicker.

I have tried using Nexus 5X, Nexus 7 and Pixel 2 on 25 and 28 API level.

I'm running the emulator on Windows 10 with Intel Core i7-4720HQ, 16GB memory and NVIDIA GeForce GTX 970M.

I have set the mode to Maximum Performance in NVIDIA Control Panel.

When I record the same programs with real phone, everything works fine.

The version of Android Studio is up-to-date.

答: Try by unchecking "Use Emulator Recording (webm)".

Title: Record in Android Emulator flickers


问:
Odoo13-CE: Module: sale.order: What inherit_id do I need to inherit quotation tree/list view?
Module: sale.order: What inherit_id do I need to inherit quotation tree/list view (see the screenshot)?

I tried this  inherit_id ="sale.view_quotation_tree_with_onboarding", but it does not work.

答:
You can simply follow the steps after activating developer mode.

You can see the External ID: Which you need to use in 'inherit_id'.


问:
Stripe API - get success url using paymentIntentID
Through Stripe API - is there a way to retrieve the original checkout_session using paymentIntentId (e.g. pi_XYZABC2423) or chargeId (e.g. ch_3QOXYZABCD)?

I specifically need success url (or cancel url), which I believe are parts of the checkout session

Thanks.

答: You can use the List Checkout Sessions API which comes with a payment_intent parameter to search through all Sessions and return the one associated with your PaymentIntent id pi_123. Then you can look at the results, which would return one Session if any matched.


问:
How do I use to pass output from command as parameter to another (complex)?
I am trying to somewhat automate the certificate bundle update on the F5 devices.
There is not one command that can check for SSL bundle expiry and match it to the server SSL profile name. So I am trying to do it with greps (as its all I know =)
There are two commands:

tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}'

This will give an output of expired bundle names, one on each line, like this

```<code>Common/somebundle.crt
Common/someotherbundlename.crt
Common/whoknowswhatthisbundleisfor.crt
</code>```

tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain'

This command will get a list of all server-ssl profile names and its links to certs/bundles etc. I am them using | grep Common/somebundle.crt -B 1 to only give me info about a particular output from the command 1 output.  So command 2 becomes:
tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep Common/somebundle.crt -B 1
Then I have to manually repeat for each of the found bundles in command 1 output.

I am trying to somehow use command 1 and then either xargs (or whatever I can) to run the command 2, passing the output from 1 into the grep in 2

It does not have to be one-liner, I just dont know bash enough to write a script

I have created something that works, though not very clean looking =)

```<code>for i in $(tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}'); do echo -n "$i -> "; tmsh -c "cd /;list ltm profile server-ssl recursive" | grep -B20 $i  >> /dev/null || echo "Not Found" && tmsh -c "cd /;list ltm profile server-ssl recursive" | grep -B20 $i |grep -i "ltm profile" | tail -n1 | awk -F "{" '{print $1}' ; done
</code>```

答:
It should be possible with bash while loop and read function. You can pipe your first command into while loop, reading line-by-line your output:

```<code>tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}' | while read bundle;do tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep "$bundle" -B 1 |...do whatever else is needed ;done
</code>```

It also can be splitted into normal multiline script:

```<code>tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}' | while read bundle
do
echo "===== $bundle ===="
tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep "$bundle" -B 1 |...do whatever else is needed

done
</code>```

Body:
I am trying to somewhat automate the certificate bundle update on the F5 devices.
There is not one command that can check for SSL bundle expiry and match it to the server SSL profile name. So I am trying to do it with greps (as its all I know =)
There are two commands:

tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}'

This will give an output of expired bundle names, one on each line, like this

Common/somebundle.crt
Common/someotherbundlename.crt
Common/whoknowswhatthisbundleisfor.crt

tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain'

This command will get a list of all server-ssl profile names and its links to certs/bundles etc. I am them using | grep Common/somebundle.crt -B 1 to only give me info about a particular output from the command 1 output.  So command 2 becomes:
tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep Common/somebundle.crt -B 1
Then I have to manually repeat for each of the found bundles in command 1 output.

I am trying to somehow use command 1 and then either xargs (or whatever I can) to run the command 2, passing the output from 1 into the grep in 2

It does not have to be one-liner, I just dont know bash enough to write a script

I have created something that works, though not very clean looking =)

for i in $(tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}'); do echo -n "$i -> "; tmsh -c "cd /;list ltm profile server-ssl recursive" | grep -B20 $i  >> /dev/null || echo "Not Found" && tmsh -c "cd /;list ltm profile server-ssl recursive" | grep -B20 $i |grep -i "ltm profile" | tail -n1 | awk -F "{" '{print $1}' ; done

Body:
It should be possible with bash while loop and read function. You can pipe your first command into while loop, reading line-by-line your output:

tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}' | while read bundle;do tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep "$bundle" -B 1 |...do whatever else is needed ;done

It also can be splitted into normal multiline script:

tmsh -c "cd /;list sys file ssl-cert recursive is-bundle expiration-string" | grep true -B 2 | grep "2018 GMT\|2019 GMT\|2020 GMT\|2021 GMT\|2022 GTM" -B 1 | grep ssl-cert | awk -F[\ \{] '{print $4}' | while read bundle
do
echo "===== $bundle ===="
tmsh -c 'cd /;list ltm profile server-ssl recursive ca-file chain' | grep "$bundle" -B 1 |...do whatever else is needed

done


问:
Flutter DropDownButton won't display selected value even when I update it
So I created my own widget that uses the DropDownButton class and it used to work, it would update in a way where after you select a value, it would display the selected value. I refactored my code to involve the whole model-view/viewmodel technique and now after you select a value from the list it still just displays the default first value of the list after you click it.

Here is the code for my DropDownWidget class:

```<code>class DropDownWidget extends StatefulWidget {
  //const DropDownWidget({Key? key}) : super(key: key);

  List<String> dropdownOptions = [];
  String? dropdownValue;

  DropDownWidget(List<String> options) {
    dropdownOptions = options;
    dropdownValue = dropdownOptions.isNotEmpty ? dropdownOptions[0] : null;
  }

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget>
    with TickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..addListener(() {
        setState(() {});
      });
    controller.repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var dropdownOptions = widget.dropdownOptions;
    var dropdownValue = widget.dropdownValue;
    if (dropdownOptions.isEmpty) {
      return LinearProgressIndicator(
        value: controller.value, //0.75,
        color: const Color(0xFFFFA663),
        backgroundColor: const Color(0x3498DBA5),
      );
    }
    return DropdownButton<String>(
      value: dropdownValue, //?? dropdownOptions[0],
      icon: const Icon(
        Icons.agriculture_rounded,
        color: Color(0xFF773608), //Color(0xFF2E7D32), //Colors.green,
      ),
      elevation: 16,
      underline: Container(
        height: 2,
        color: vo.shade200,
      ),
      onChanged: (String? newValue) {
        setState(() {
          dropdownValue = newValue!;
          print(newValue);
        });
      },
      items: dropdownOptions.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}
</code>```

Let me know if any more code is needed.

答:
So from the code i see is that you are intializing the varialbles in the build method, instead you have to do it in the initState.

Why was the item not getting changed:

the item was getting changed but the setstate method would reasign it to the 1st item from the list.

as setstate will rebuild the the build method and you did assigned the items in the build method. So that was the reason it was not changing.

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

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: DropDownWidget(['one', 'two']),
      ),
    );
  }
}

class DropDownWidget extends StatefulWidget {
  //const DropDownWidget({Key? key}) : super(key: key);

  List<String> dropdownOptions = [];
  String? dropdownValue;

  DropDownWidget(List<String> options) {
    dropdownOptions = options;
    dropdownValue = dropdownOptions.isNotEmpty ? dropdownOptions[0] : null;
  }

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget>
    with TickerProviderStateMixin {
  late AnimationController controller;
  late List<String> dropdownOptions;
  late String? dropdownValue;

  @override
  void initState() {
    dropdownOptions = widget.dropdownOptions;
    dropdownValue = widget.dropdownValue;
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..addListener(() {
        setState(() {});
      });
    controller.repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (dropdownOptions.isEmpty) {
      return LinearProgressIndicator(
        value: controller.value, //0.75,
        color: const Color(0xFFFFA663),
        backgroundColor: const Color(0x3498DBA5),
      );
    }
    return DropdownButton<String>(
      value: dropdownValue, //?? dropdownOptions[0],
      icon: const Icon(
        Icons.agriculture_rounded,
        color: Color(0xFF773608), //Color(0xFF2E7D32), //Colors.green,
      ),
      elevation: 16,
      underline: Container(
        height: 2,
        color: Colors.black,
      ),
      onChanged: (String? newValue) {
        setState(() {
          dropdownValue = newValue!;
          print(newValue);
        });
      },
      items: dropdownOptions.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}

</code>```

Body:
So I created my own widget that uses the DropDownButton class and it used to work, it would update in a way where after you select a value, it would display the selected value. I refactored my code to involve the whole model-view/viewmodel technique and now after you select a value from the list it still just displays the default first value of the list after you click it.

Here is the code for my DropDownWidget class:

class DropDownWidget extends StatefulWidget {
  //const DropDownWidget({Key? key}) : super(key: key);

  List<String> dropdownOptions = [];
  String? dropdownValue;

  DropDownWidget(List<String> options) {
    dropdownOptions = options;
    dropdownValue = dropdownOptions.isNotEmpty ? dropdownOptions[0] : null;
  }

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget>
    with TickerProviderStateMixin {
  late AnimationController controller;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..addListener(() {
        setState(() {});
      });
    controller.repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var dropdownOptions = widget.dropdownOptions;
    var dropdownValue = widget.dropdownValue;
    if (dropdownOptions.isEmpty) {
      return LinearProgressIndicator(
        value: controller.value, //0.75,
        color: const Color(0xFFFFA663),
        backgroundColor: const Color(0x3498DBA5),
      );
    }
    return DropdownButton<String>(
      value: dropdownValue, //?? dropdownOptions[0],
      icon: const Icon(
        Icons.agriculture_rounded,
        color: Color(0xFF773608), //Color(0xFF2E7D32), //Colors.green,
      ),
      elevation: 16,
      underline: Container(
        height: 2,
        color: vo.shade200,
      ),
      onChanged: (String? newValue) {
        setState(() {
          dropdownValue = newValue!;
          print(newValue);
        });
      },
      items: dropdownOptions.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}

Let me know if any more code is needed.

Body:
So from the code i see is that you are intializing the varialbles in the build method, instead you have to do it in the initState.

Why was the item not getting changed:

the item was getting changed but the setstate method would reasign it to the 1st item from the list.

as setstate will rebuild the the build method and you did assigned the items in the build method. So that was the reason it was not changing.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: DropDownWidget(['one', 'two']),
      ),
    );
  }
}

class DropDownWidget extends StatefulWidget {
  //const DropDownWidget({Key? key}) : super(key: key);

  List<String> dropdownOptions = [];
  String? dropdownValue;

  DropDownWidget(List<String> options) {
    dropdownOptions = options;
    dropdownValue = dropdownOptions.isNotEmpty ? dropdownOptions[0] : null;
  }

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget>
    with TickerProviderStateMixin {
  late AnimationController controller;
  late List<String> dropdownOptions;
  late String? dropdownValue;

  @override
  void initState() {
    dropdownOptions = widget.dropdownOptions;
    dropdownValue = widget.dropdownValue;
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..addListener(() {
        setState(() {});
      });
    controller.repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (dropdownOptions.isEmpty) {
      return LinearProgressIndicator(
        value: controller.value, //0.75,
        color: const Color(0xFFFFA663),
        backgroundColor: const Color(0x3498DBA5),
      );
    }
    return DropdownButton<String>(
      value: dropdownValue, //?? dropdownOptions[0],
      icon: const Icon(
        Icons.agriculture_rounded,
        color: Color(0xFF773608), //Color(0xFF2E7D32), //Colors.green,
      ),
      elevation: 16,
      underline: Container(
        height: 2,
        color: Colors.black,
      ),
      onChanged: (String? newValue) {
        setState(() {
          dropdownValue = newValue!;
          print(newValue);
        });
      },
      items: dropdownOptions.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}


问:
Eclipse text-search over all files?
I'm optimizing my code at the moment (android game), and wanted to replace all foreach(for(:)) with normal fors. Is there a way to find them all? Ctrl-F only looks through the current file and Ctrl-H doesn't seem to find any java constructs (not sure if right word: ifs, whiles, accessors etc.). Preferably without a plugin, but any answer accepted. It would also be nice if there would be a possibility to search for any string (* in Search).

TL;DR: Looking for way to find all foreaches in eclipse.

答:
First of all, I must say, this sounds like a really strange optimization. Keep in mind that if you have, say, a LinkedList you would be far worse of going through a

```<code>for (int i = 0; i < list.size(); i++) {
    element = list.get(i);
    ...
</code>```

loop, than using an iterator (which for-each loops does). Smells micro-optimizations long way to me.

That said, here's a solution for you:

Make sure the root source folder is selected

Click Search / File Search

Mark Scope as "Selected resources"

Mark Regular expression

Search for a regular expression such as for\s*\(.*:

The expression matches strings on the form for, followed by some white whitespace, followed by ( followed by some characters, followed by : (which kind of characterizes a Java for-each loop).

Title: Eclipse text-search over all files?

Body:
First of all, I must say, this sounds like a really strange optimization. Keep in mind that if you have, say, a LinkedList you would be far worse of going through a

for (int i = 0; i < list.size(); i++) {
    element = list.get(i);
    ...

loop, than using an iterator (which for-each loops does). Smells micro-optimizations long way to me.

That said, here's a solution for you:

Make sure the root source folder is selected

Click Search / File Search

Mark Scope as "Selected resources"

Mark Regular expression

Search for a regular expression such as for\s*\(.*:

The expression matches strings on the form for, followed by some white whitespace, followed by ( followed by some characters, followed by : (which kind of characterizes a Java for-each loop).


问:
How to make audio player with play/pause button and seekbar in recycleview
I need some help, I want to make a recycle view containing audio in each item, how to play the audio when press play button and set progress to seekbar and at the same time pause other sound and convert the play button to play mode in all row except the playing one be in pause mode
such as  or chats in facebook messenger

This is my code:
MyAdapter.class

```<code>    private List<String> positions = new ArrayList<>();

  public myAdapter(Activity activity, ArrayList<Tweet> list) {
    this.activity = activity;
    this.list = list;
    mPlayer = new MediaPlayer();
    }
    public void onBindViewHolder(final viewHolder holder, final int position) {
        if (!positions.contains(String.valueOf(position)))
            positions.add(String.valueOf(position));
        }
        }
</code>```

viewHolder.class

```<code>  public class viewHolder extends RecyclerView.ViewHolder implements
        SeekBar.OnSeekBarChangeListener, View.OnClickListener {
    LinearLayout parentPanel;
    int viewType;
    private RelativeLayout pauseLayout, playLayout;
    private ImageView pauseIcon, playIcon;
    private SeekBar seekBar;
    private TextView periodTime;
    AudioCallbacks mAudioCallbacks;
    private int last_position;

    viewHolder(final View itemView, int viewType) {
        super(itemView);
        this.viewType = viewType;

            playLayout = (RelativeLayout) itemView.findViewById(R.id.play_layout);
            pauseLayout = (RelativeLayout) itemView.findViewById(R.id.pause_layout);
            playIcon = (ImageView) itemView.findViewById(R.id.play_icon);
            pauseIcon = (ImageView) itemView.findViewById(R.id.pause_icon);
            seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
            periodTime = (TextView) itemView.findViewById(R.id.period_time);

            seekBar.setOnSeekBarChangeListener(this);
            playLayout.setOnClickListener(this);
            pauseLayout.setOnClickListener(this);
            mAudioCallbacks = new AudioCallbacks() {
                @Override
                public void onUpdate(int percentage) {
                    seekBar.setProgress(percentage);
                    if (percentage == 100)
                        mAudioCallbacks.onStop();
                }
                @Override
                public void onPause() {
                    Log.i("on pause audio", " pause");
                }
                @Override
                public void onStop() {
                    Log.i("on stop audio", " stop");
                    stopPlayingAudio();
                }
            };
    }

    void stopPlayingAudio() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                updateAudioProgressBar();
                mPlayer.stop();
                mPlayer.reset();
                seekBar.setProgress(0);
                playLayout.setVisibility(View.VISIBLE);
                pauseLayout.setVisibility(View.GONE);
            }
        }
    }

    void pausePlayingAudio() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                updateAudioProgressBar();
                mAudioCallbacks.onPause();
            }
        }
    }
    void playingAudio(Tweet message) {
        updateAudioProgressBar();
        if (mPlayer != null) {
            try {
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(message.getAudioUrl());
                mPlayer.prepare();
                mPlayer.start();
                periodTime.setVisibility(View.VISIBLE);
                periodTime.setText(String.valueOf(message.getAudioDuration()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    void updateAudioProgressBar() {
        durationHandler.postDelayed(mUpdateTimeTask, 100);
    }
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            try {
                if (mPlayer.isPlaying()) {
                    long totalDuration = mPlayer.getDuration();
                    long currentDuration = mPlayer.getCurrentPosition();
                    int progress = Utils.getProgressPercentage(currentDuration, totalDuration);
                    mAudioCallbacks.onUpdate(progress);
                    periodTime.setText(Utils.getFileTime(currentDuration));
                    durationHandler.postDelayed(this, 100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        durationHandler.removeCallbacks(mUpdateTimeTask);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int totalDuration = mPlayer.getDuration();
        int currentPosition = Utils.progressToTimer(seekBar.getProgress(), totalDuration);
        mPlayer.seekTo(currentPosition);
        updateAudioProgressBar();
    }

    @Override
    public void onClick(View view) {
        Log.e("getAdapterPosition()L", last_position + " /");
        for (String pos : positions) {
            if (!pos.equals(String.valueOf(getAdapterPosition())))
                notifyItemChanged(Integer.parseInt(pos));
        }
        last_position = getAdapterPosition();
        Log.e("getAdapterPosition()F", last_position + " /");
        Tweet message = list.get(getAdapterPosition());
        switch (view.getId()) {
            case R.id.pause_layout:
                playLayout.setVisibility(View.VISIBLE);
                pauseLayout.setVisibility(View.GONE);
                pausePlayingAudio();
                break;
            case R.id.play_layout:
                playLayout.setVisibility(View.GONE);
                pauseLayout.setVisibility(View.VISIBLE);
                mAudioCallbacks.onStop();
                playingAudio(message);
                break;
        }
    }
    }
    public interface AudioCallbacks {
    void onUpdate(int percentage);
    void onPause();
    void onStop();
    }
</code>```

the problem of this code is :

some time the image not reversed of other object when play specific item .

when scrolled the pause button appear in multiple row.

when play one then play another, stop the first and run the new one but when return to the previous not playing.

when leave the activity or press back press button the sound not stopped.

Can someone helped me, please?

答:
```<code>    public class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.AudioItemsViewHolder> {

static MediaPlayer mediaPlayer;
Activity activity;

private final ArrayList<GroupItems> audioItems;//change it() to your items
private int currentPlayingPosition;
private final SeekBarUpdater seekBarUpdater;
private AudioItemsViewHolder playingHolder;

   public MyAdapter2(Activity activity, ArrayList<GroupItems> items_pro) {
    this.audioItems = items_pro;
    this.currentPlayingPosition = -1;
    seekBarUpdater = new SeekBarUpdater();
    this.activity = activity;

}

@Override
public AudioItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  //put YourItemsLayout;
    return new AudioItemsViewHolder(LayoutInflater.from(parent.getContext()).inflate(YourItemsLayout, parent, false));
}

@Override
public void onBindViewHolder(AudioItemsViewHolder holder, int position) {
if (position == currentPlayingPosition) {
        playingHolder = holder;
        updatePlayingView();
    } else {
        updateNonPlayingView(holder);
    }
}
   private void updateNonPlayingView(AudioItemsViewHolder holder) {
    holder.sbProgress.removeCallbacks(seekBarUpdater);
    holder.sbProgress.setEnabled(false);
    holder.sbProgress.setProgress(0);
    holder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}

private void updatePlayingView() {
    playingHolder.sbProgress.setMax(mediaPlayer.getDuration());
    playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
    playingHolder.sbProgress.setEnabled(true);
    if (mediaPlayer.isPlaying()) {
        playingHolder.sbProgress.postDelayed(seekBarUpdater, 100);
        playingHolder.ivPlayPause.setImageResource(R.drawable.ic_pause);
    } else {
        playingHolder.sbProgress.removeCallbacks(seekBarUpdater);
        playingHolder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
    }
}
  private class SeekBarUpdater implements Runnable {
    @Override
    public void run() {
        if (null != playingHolder && null != mediaPlayer) {
            playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
            playingHolder.sbProgress.postDelayed(this, 100);
        }
    }
}

@Override
public int getItemCount() {
    return audioItems.size();
}

    class AudioItemsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    SeekBar sbProgress;
    ImageView ivPlayPause;
    AudioItemsViewHolder(View itemView) {
        super(itemView);
     ivPlayPause = itemView.findViewById(R.id.sound_btn);
        ivPlayPause.setOnClickListener(this);
        sbProgress = itemView.findViewById(R.id.seekBar);
        sbProgress.setOnSeekBarChangeListener(this);
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.seekBar:
                break;

            case R.id.sound_btn: {
                if (getAdapterPosition() == currentPlayingPosition) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                    } else {
                        if (mediaPlayer != null)
                            mediaPlayer.start();
                    }
                } else {
                    currentPlayingPosition = getAdapterPosition();
                    if (mediaPlayer != null) {
                        if (null != playingHolder) {
                            updateNonPlayingView(playingHolder);
                        }
                        mediaPlayer.release();
                    }
                    playingHolder = this;

                        PlaySound(YOUR AUDIO FILE);//put your audio file

                }
                if (mediaPlayer != null)
                    updatePlayingView();
            }
            break;
    }

    }

     @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mediaPlayer.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
}
 private void PlaySound(File filesound) {

    mediaPlayer = MediaPlayer.create(activity, Uri.parse(String.valueOf(filesound)));

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayer();
        }
    });
    mediaPlayer.start();
}
    private void releaseMediaPlayer() {
    if (null != playingHolder) {
        updateNonPlayingView(playingHolder);
    }
    if (outputFile.exists())
        outputFile.delete();

    mediaPlayer.release();
    mediaPlayer = null;
    currentPlayingPosition = -1;
}
}
</code>```

Body:
I need some help, I want to make a recycle view containing audio in each item, how to play the audio when press play button and set progress to seekbar and at the same time pause other sound and convert the play button to play mode in all row except the playing one be in pause mode
such as  or chats in facebook messenger

This is my code:
MyAdapter.class

    private List<String> positions = new ArrayList<>();

  public myAdapter(Activity activity, ArrayList<Tweet> list) {
    this.activity = activity;
    this.list = list;
    mPlayer = new MediaPlayer();
    }
    public void onBindViewHolder(final viewHolder holder, final int position) {
        if (!positions.contains(String.valueOf(position)))
            positions.add(String.valueOf(position));
        }
        }

viewHolder.class

  public class viewHolder extends RecyclerView.ViewHolder implements
        SeekBar.OnSeekBarChangeListener, View.OnClickListener {
    LinearLayout parentPanel;
    int viewType;
    private RelativeLayout pauseLayout, playLayout;
    private ImageView pauseIcon, playIcon;
    private SeekBar seekBar;
    private TextView periodTime;
    AudioCallbacks mAudioCallbacks;
    private int last_position;

    viewHolder(final View itemView, int viewType) {
        super(itemView);
        this.viewType = viewType;

            playLayout = (RelativeLayout) itemView.findViewById(R.id.play_layout);
            pauseLayout = (RelativeLayout) itemView.findViewById(R.id.pause_layout);
            playIcon = (ImageView) itemView.findViewById(R.id.play_icon);
            pauseIcon = (ImageView) itemView.findViewById(R.id.pause_icon);
            seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
            periodTime = (TextView) itemView.findViewById(R.id.period_time);

            seekBar.setOnSeekBarChangeListener(this);
            playLayout.setOnClickListener(this);
            pauseLayout.setOnClickListener(this);
            mAudioCallbacks = new AudioCallbacks() {
                @Override
                public void onUpdate(int percentage) {
                    seekBar.setProgress(percentage);
                    if (percentage == 100)
                        mAudioCallbacks.onStop();
                }
                @Override
                public void onPause() {
                    Log.i("on pause audio", " pause");
                }
                @Override
                public void onStop() {
                    Log.i("on stop audio", " stop");
                    stopPlayingAudio();
                }
            };
    }

    void stopPlayingAudio() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                updateAudioProgressBar();
                mPlayer.stop();
                mPlayer.reset();
                seekBar.setProgress(0);
                playLayout.setVisibility(View.VISIBLE);
                pauseLayout.setVisibility(View.GONE);
            }
        }
    }

    void pausePlayingAudio() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                updateAudioProgressBar();
                mAudioCallbacks.onPause();
            }
        }
    }
    void playingAudio(Tweet message) {
        updateAudioProgressBar();
        if (mPlayer != null) {
            try {
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(message.getAudioUrl());
                mPlayer.prepare();
                mPlayer.start();
                periodTime.setVisibility(View.VISIBLE);
                periodTime.setText(String.valueOf(message.getAudioDuration()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    void updateAudioProgressBar() {
        durationHandler.postDelayed(mUpdateTimeTask, 100);
    }
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            try {
                if (mPlayer.isPlaying()) {
                    long totalDuration = mPlayer.getDuration();
                    long currentDuration = mPlayer.getCurrentPosition();
                    int progress = Utils.getProgressPercentage(currentDuration, totalDuration);
                    mAudioCallbacks.onUpdate(progress);
                    periodTime.setText(Utils.getFileTime(currentDuration));
                    durationHandler.postDelayed(this, 100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        durationHandler.removeCallbacks(mUpdateTimeTask);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int totalDuration = mPlayer.getDuration();
        int currentPosition = Utils.progressToTimer(seekBar.getProgress(), totalDuration);
        mPlayer.seekTo(currentPosition);
        updateAudioProgressBar();
    }

    @Override
    public void onClick(View view) {
        Log.e("getAdapterPosition()L", last_position + " /");
        for (String pos : positions) {
            if (!pos.equals(String.valueOf(getAdapterPosition())))
                notifyItemChanged(Integer.parseInt(pos));
        }
        last_position = getAdapterPosition();
        Log.e("getAdapterPosition()F", last_position + " /");
        Tweet message = list.get(getAdapterPosition());
        switch (view.getId()) {
            case R.id.pause_layout:
                playLayout.setVisibility(View.VISIBLE);
                pauseLayout.setVisibility(View.GONE);
                pausePlayingAudio();
                break;
            case R.id.play_layout:
                playLayout.setVisibility(View.GONE);
                pauseLayout.setVisibility(View.VISIBLE);
                mAudioCallbacks.onStop();
                playingAudio(message);
                break;
        }
    }
    }
    public interface AudioCallbacks {
    void onUpdate(int percentage);
    void onPause();
    void onStop();
    }

the problem of this code is :

some time the image not reversed of other object when play specific item .

when scrolled the pause button appear in multiple row.

when play one then play another, stop the first and run the new one but when return to the previous not playing.

when leave the activity or press back press button the sound not stopped.

Can someone helped me, please?


问:
Why are there no monadic operations in std::expected?
In C++23, monadic operations in std::optional was adopted, and later on std::expected. Why were monadic operations like and_then, transform, and or_else not included in the main paper?

答:
Update: std::expected in C++23 will have monadic operations.

The std::expected proposal is very old. The adopted revision is P0323R12, which already suggests a long life, but that paper even predates the P-numbering system and started out as N4015, dated May 2014.

I bring this up because std::expected, even by itself, has taken a very long time to wind its way through the process. In contrast, the monadic operations for std::optional paper only first appeared in October 2017. And since then it was just a long slog just to get std::expected at all.

There is a paper proposing monadic operations for std::expected, that's P2505R0, but at this point it's very incomplete and needs a lot of work. The design window for new C++23 features is closed, but I wouldn't be surprised if there were an NB comment requesting it in later anyway.

At least we finally have std::expected.

Coming in here a few months later, there was an NB comment requesting the monadic operators for std::expected and P2505R5 was adopted for C++23 in Kona in November 2022.


问:
Godot: Getting a node results in Nil Value
i am trying to get into Godot. In my project i want to access a Timer called Duration Timer in the Dash Script attached to the Dash Node.

Screenshot - Godot get Duration Timer

Already, i tried 3 ways of accessing the Node seen in line 4,5 and 6 of the screenshot.

```<code>onready var duration_timer = $DurationTimer
#onready var duration_timer = get_node("DurationTimer")
#onready var duration_timer = get_node("Movement/Dash/DurationTimer")
</code>```

All 3 lines result in the highlighted errormessage

"Invalid set index 'wait_time' (on base:
'Nil') with value of type 'int'.

The error appears in line 14 by trying to set a wait_time to the Timer element.

```<code>duration_timer.wait_time = 1
</code>```

Does someone have a clue why i cant get the Timer element?

答:
I don't know what is causing the problem.

I do not think get_node("DurationTimer") or $DurationTimer are wrong. But if that is the problem, we can solve it by using a NodePath:

```<code>export var duration_timer_path:NodePath
onready var duration_timer = get_node(duration_timer_path)
</code>```

Then set the NodePath from the inspector panel.

If the path is not wrong. It could be that the code is running before _ready. or that something (I don't know what) removed the timer or set it to null. You can add an breakpoint and check on the remote tab of the scene tree panel when the game is running from the editor, to see if the timer is there.

We can sidestep the problem by making a new timer if we don't have one. For example:

```<code>if not is_instance_valid(duration_timer):
    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)

# use duration_timer here
</code>```

However, if the timer is there but we had failed to get it, we would have two timers in the scene tree. You could also check in the remote tab of the scene tree panel if this resulted in two timers.

So, let us try to get the node again, in case we failed the first time. And let us put it all in a method. Something like this:

```<code>func get_duration_timer() -> Timer:
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = get_node("DurationTimer") # or use a NodePath
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)
    return duration_timer
</code>```

In fact, if we are in this scenario, then onready is not helping us. So we could have duration_timer defined without onready and without initialization. And always use the method to get the timer.

If we are going to always use the method, why not let the method add the timer instead of adding it in the scene tree? We could then remove the step of trying to get it:

```<code>func get_duration_timer() -> Timer:
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)
    return duration_timer
</code>```

What we have here is a lazy initialization pattern: The timer is created when we first need it, on demand, not before.

Body:
i am trying to get into Godot. In my project i want to access a Timer called Duration Timer in the Dash Script attached to the Dash Node.

Screenshot - Godot get Duration Timer

Already, i tried 3 ways of accessing the Node seen in line 4,5 and 6 of the screenshot.

onready var duration_timer = $DurationTimer
#onready var duration_timer = get_node("DurationTimer")
#onready var duration_timer = get_node("Movement/Dash/DurationTimer")

All 3 lines result in the highlighted errormessage

"Invalid set index 'wait_time' (on base:
'Nil') with value of type 'int'.

The error appears in line 14 by trying to set a wait_time to the Timer element.

duration_timer.wait_time = 1

Does someone have a clue why i cant get the Timer element?

Body:
I don't know what is causing the problem.

I do not think get_node("DurationTimer") or $DurationTimer are wrong. But if that is the problem, we can solve it by using a NodePath:

export var duration_timer_path:NodePath
onready var duration_timer = get_node(duration_timer_path)

Then set the NodePath from the inspector panel.

If the path is not wrong. It could be that the code is running before _ready. or that something (I don't know what) removed the timer or set it to null. You can add an breakpoint and check on the remote tab of the scene tree panel when the game is running from the editor, to see if the timer is there.

We can sidestep the problem by making a new timer if we don't have one. For example:

if not is_instance_valid(duration_timer):
    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)

# use duration_timer here

However, if the timer is there but we had failed to get it, we would have two timers in the scene tree. You could also check in the remote tab of the scene tree panel if this resulted in two timers.

So, let us try to get the node again, in case we failed the first time. And let us put it all in a method. Something like this:

func get_duration_timer() -> Timer:
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = get_node("DurationTimer") # or use a NodePath
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)
    return duration_timer

In fact, if we are in this scenario, then onready is not helping us. So we could have duration_timer defined without onready and without initialization. And always use the method to get the timer.

If we are going to always use the method, why not let the method add the timer instead of adding it in the scene tree? We could then remove the step of trying to get it:

func get_duration_timer() -> Timer:
    if is_instance_valid(duration_timer):
        return duration_timer

    duration_timer = Timer.new()
    duration_timer.name = "DurationTimer"
    add_child(duration_timer)
    return duration_timer

What we have here is a lazy initialization pattern: The timer is created when we first need it, on demand, not before.