问:
Transient vs Singleton vs Scoped instances in C#
I mostly use singleton instance however I can't differentiate with other instance.

What exactly singleton, transient, scooped instances and what are the best scenarios to use them.


来源: stackexchange

问:
Git-Bash / MinGW: Cancel command after file has been created
I have a git-bash command that builds an Android apk file but never finishes after building it. So the rest of my script is never executed.

How can I check whether that file exists and if so cancel the command in git-bash?

I assume I need to

execute the build command in some background process

then run an infinite while loop that keeps checking for the apk file to be build

if file appears -> kill background process and exit while loop

else continue / or timeout after n minutes

However, I'm not sure something like this is even possible using git-bash / mingw.

Note: I cannot switch to Linux / WSL as I need Unity under Windows to compile my Game

ContentLicense: CC BY-SA 4.0


问:
Jackson handling XML arrays with dynamic fields using the hashmap approach
I have to write a message handler that will process incoming XML messages and pass them on to another module as JSON representations. There are a relatively high of possible messages and I would rather use a single POJO for my purpose. Here is an example XML message.

```<code><Message name="GenericMsg">
    <StartTime>533798131</StartTime> <!-- Unix Timestamp -->

                .
                .
    <!-- Some other fields -->
                .
    <NumberOfItems>2</NumberOfItems>
    <List>
        <ListItem>
            <Speed>100</Speed>
            <Location>
                <lat>38.165748</lat>
                <lon>37.125363</lon>
                <alt>800</alt>
            </Location>
        </ListItem>
        <ListItem>
            <Speed>120</Speed>
            <Location>
                <lat>39.123748</lat>
                <lon>41.312645</lon>
                <alt>850</alt>
            </Location>
        </ListItem>
    </List>
</Message>
</code>```

And my POJO

```<code>public class MsgRepr {
    private Map<String, Object> details = new LinkedHashMap<>();

    public Object get(String key) {
        return this.details.get(key);
    }

    @JsonAnyGetter
    public Map<String, Object> getDetails() {
        return this.details;
    }
    @JsonAnySetter
    public void setDetails(String key, Object value) {
        this.details.put(key,value);
    }
}
</code>```

This gets converted to the following JSON:

```<code>{
  "name" : "GenericMsg",
  "NumberOfItems" : "2",
  "StartTime" : "533798131"
  "List" : {
    "ListItem" :
    [
      {
        "Speed" : "100",
        "Location" : {
          "lat" : "38.165748",
          "lon" : "37.125363",
          "alt" : "800"
        }
      },
      {
        "Speed" : "150",
        "Location" : {
          "lat" : "48.564866",
          "lon" : "35.18795",
          "alt" : "850"
        }
      }
    ]
  }
}
</code>```

I tried the defaultUseWrapper=false option with no avail. Also, omitting the List/ListItem duality results in only the last element being present.

I know that this can be done by writing a seperate POJO for each message, but I would rather avoid doing that. Is there an alternative XML representation or an alternative approach I can use to correctly convert the json to something similar to the following format?

```<code>{
  "name" : "GenericMsg",
  "NumberOfItems" : "2",
  "StartTime" : "533798131"
  "List" :
  [
    {
      "Speed" : "100",
      "Location" : {
        "lat" : "38.165748",
        "lon" : "37.125363",
        "alt" : "800"
      }
    },
    {
      "Speed" : "150",
      "Location" : {
        "lat" : "48.564866",
        "lon" : "35.18795",
        "alt" : "850"
      }
    }
  ]
}
</code>```

Jackson version 2.13.0

Body:
I have to write a message handler that will process incoming XML messages and pass them on to another module as JSON representations. There are a relatively high of possible messages and I would rather use a single POJO for my purpose. Here is an example XML message.

<Message name="GenericMsg">
    <StartTime>533798131</StartTime>

                .
                .

                .
    <NumberOfItems>2</NumberOfItems>
    <List>
        <ListItem>
            <Speed>100</Speed>
            <Location>
                <lat>38.165748</lat>
                <lon>37.125363</lon>
                <alt>800</alt>
            </Location>
        </ListItem>
        <ListItem>
            <Speed>120</Speed>
            <Location>
                <lat>39.123748</lat>
                <lon>41.312645</lon>
                <alt>850</alt>
            </Location>
        </ListItem>
    </List>
</Message>

And my POJO

public class MsgRepr {
    private Map<String, Object> details = new LinkedHashMap<>();

    public Object get(String key) {
        return this.details.get(key);
    }

    @JsonAnyGetter
    public Map<String, Object> getDetails() {
        return this.details;
    }
    @JsonAnySetter
    public void setDetails(String key, Object value) {
        this.details.put(key,value);
    }
}

This gets converted to the following JSON:

{
  "name" : "GenericMsg",
  "NumberOfItems" : "2",
  "StartTime" : "533798131"
  "List" : {
    "ListItem" :
    [
      {
        "Speed" : "100",
        "Location" : {
          "lat" : "38.165748",
          "lon" : "37.125363",
          "alt" : "800"
        }
      },
      {
        "Speed" : "150",
        "Location" : {
          "lat" : "48.564866",
          "lon" : "35.18795",
          "alt" : "850"
        }
      }
    ]
  }
}

I tried the defaultUseWrapper=false option with no avail. Also, omitting the List/ListItem duality results in only the last element being present.

I know that this can be done by writing a seperate POJO for each message, but I would rather avoid doing that. Is there an alternative XML representation or an alternative approach I can use to correctly convert the json to something similar to the following format?

{
  "name" : "GenericMsg",
  "NumberOfItems" : "2",
  "StartTime" : "533798131"
  "List" :
  [
    {
      "Speed" : "100",
      "Location" : {
        "lat" : "38.165748",
        "lon" : "37.125363",
        "alt" : "800"
      }
    },
    {
      "Speed" : "150",
      "Location" : {
        "lat" : "48.564866",
        "lon" : "35.18795",
        "alt" : "850"
      }
    }
  ]
}

Jackson version 2.13.0


问:
What Exactly is Preventing NivoSlider from Scaling Pictures Down Automatically when the Site is on Mobile View?
I’ve been trying to make our “normal” website mobile friendly by using CSS´s media queries and after successfully resizing the NivoSlider to fit the smaller screen on mobile portrait mode I’ve been stuck at having the slider not being able to resize the pictures themselves automatically. The pictures should fit the new smaller viewport/slider size instead of just showing cropped, non scaled-down versions of them.

I have read answers to similar questions on this site and tried to turn the width to 100% and height to “auto !important!; “ but I’m still getting no results. What could I try? The slider is using the Default Theme. Here’s a link to the website:

www.sandino-hostel-berlin.de

I’ve added the media query details to custom.css which I keep commented out so that people visiting the site on mobile won´t see my css testing mess. I´ve tried to changed the width and height of the slider there (custom.css) as well as in nivo-slider.css and default.css but dice. Thank you very much for your help in advance and I’ll try to provide more technical details as they are needed.


问:
How to select an element that doesn't have any descendants with specific class?
Given the sample below, how do I select all p that do not have any descendants with the avoid class?

```<code><div class="avoid">
  <div>
    <p>I don't want to style this one</p>
  </div>
</div>
<div>
  <div>
    <p>Style only this one</p>
  </div>
</div>
</code>```

I tried :not(.avoid) p, but it doesn't work because some descendants of p don't have the avoid class, which is expected in my codebase.

I can't use :has

Body:
Given the sample below, how do I select all p that do not have any descendants with the avoid class?

I don't want to style this one

Style only this one

I tried :not(.avoid) p, but it doesn't work because some descendants of p don't have the avoid class, which is expected in my codebase.

I can't use :has


问:
CICD AWS Secrets Manager - How to determine which secrets to inject?
I am working on implementing "secrets injection" on a GitLab CI pipeline. The secrets are stored on AWS Secrets Manager.

The goal is to create a appsettings.json file containing the secrets and add this file to the build artefacts before deploying the solution.

Consider these two scenarios A) and B):

A)

One database DB1.

One Lambda Function that uses a Lambda Layer that has code to access DB1.

How does the pipeline for the lambda function know that the function needs to talk to a database (and therefore inject credentials before deploying the function)?

|------------------------------------|

B)

Four databases DB1, DB2, DB3 and DB4.

One Lambda Function that uses two Lambda Layers, each of which has code to access different databases - the first layer can access DB1, the other layer can access DB3.

Same question as 1. from scenario A)

How does the pipeline for the lambda function know which DB the function needs to call (and therefore inject the right credentials)?

|------------------------------------|


问:
how to wrap text and add space between polylines using d3.js
I have found this donut chart example. it is good one but I am having trouble understanding it and I am having problems with long text (wrappping) and labels overlapping one another when text is wrapped?

https://plnkr.co/edit/sAbnep00GMRkx5Xey6gL?p=preview&preview

This is the code: I removed the css as it was taking a lot of space.

```<code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="normalize.css">

</head>

<body>

  <div id="chart"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
  <script>
    (function(d3) {
      'use strict';

      var width = 660;
      var height = 690;
      var radius = 150;
      var donutWidth = 75;
      var legendRectSize = 18;
      var legendSpacing = 4;

      var color = d3.scale.category20(); //builtin range of colors

      var s = d3.select('#chart')
        .append('svg')
        .attr('width', width)
        .attr('height', height);

      var legend_group = s.append('g').attr('transform',
        'translate(' + (width / 3) + ',' + (height / 1.4) + ')');
      var svg = s.append('g')
        .attr('transform', 'translate(' + (width / 2) +
          ',' + (radius) + ')');

      var arc = d3.svg.arc()
        .innerRadius(radius - donutWidth)
        .outerRadius(radius);

      var outerArc = d3.svg.arc()
        .innerRadius(radius * 0.9)
        .outerRadius(radius * 0.9);

      var pie = d3.layout.pie()
        .value(function(d) {
          console.log(d);
          return +d.count;
        })
        .sort(null);

      var tooltip = d3.select('#chart')
        .append('div')
        .attr('class', 'tooltip');

      tooltip.append('div')
        .attr('class', 'label');

      tooltip.append('div')
        .attr('class', 'count');

      tooltip.append('div')
        .attr('class', 'percent');

      d3.csv('weekdays.csv', function(error, dataset) {
        dataset.forEach(function(d) {
          d.count = +d.count;
          d.enabled = true; // NEW
        });

        var path = svg.selectAll('path')
          .data(pie(dataset))
          .enter()
          .append('path')
          .attr('d', arc)
          .attr('fill', function(d, i) {
            return color(d.data.label);
          }) // UPDATED (removed semicolon)
          .each(function(d) {
            this._current = d;
          }); // NEW

        path.on('mouseover', function(d) {
          var total = d3.sum(dataset.map(function(d) {
            return (d.enabled) ? d.count : 0; // UPDATED
          }));
          var percent = Math.round(1000 * d.data.count / total) / 10;
          tooltip.select('.label').html(d.data.label);
          tooltip.select('.count').html(d.data.count);
          tooltip.select('.percent').html(percent + '%');
          tooltip.style('display', 'block');
        });

        path.on('mouseout', function() {
          tooltip.style('display', 'none');
        });
        var key = function(d) {
          return d.data.label;
        };

        makeTexts();
        makePolyLines();

        /* OPTIONAL
        path.on('mousemove', function(d) {
          tooltip.style('top', (d3.event.pageY + 10) + 'px')
            .style('left', (d3.event.pageX + 10) + 'px');
        });
        */

        var legend = legend_group.selectAll('.legend')
          .data(color.domain())
          .enter()
          .append('g')
          .attr('class', 'legend')
          .attr('transform', function(d, i) {
            var height = legendRectSize + legendSpacing;
            var offset = height * color.domain().length / 2;
            var horz = -2 * legendRectSize;
            var vert = i * height - offset;
            return 'translate(' + horz + ',' + vert + ')';
          });

        legend.append('rect')
          .attr('width', legendRectSize)
          .attr('height', legendRectSize)
          .style('fill', color)
          .style('stroke', color) // UPDATED (removed semicolon)
          .on('click', function(label) { // NEW
            var rect = d3.select(this); // NEW
            var enabled = true; // NEW
            var totalEnabled = d3.sum(dataset.map(function(d) { // NEW
              return (d.enabled) ? 1 : 0; // NEW
            })); // NEW

            if (rect.attr('class') === 'disabled') { // NEW
              rect.attr('class', ''); // NEW
            } else { // NEW
              if (totalEnabled < 2) return; // NEW
              rect.attr('class', 'disabled'); // NEW
              enabled = false; // NEW
            } // NEW

            pie.value(function(d) { // NEW
              if (d.label === label) d.enabled = enabled; // NEW
              return (d.enabled) ? d.count : 0; // NEW
            }); // NEW

            path = path.data(pie(dataset)); // NEW

            path.transition() // NEW
              .duration(750) // NEW
              .attrTween('d', function(d) { // NEW
                var interpolate = d3.interpolate(this._current, d); // NEW
                this._current = interpolate(0); // NEW
                return function(t) { // NEW
                  return arc(interpolate(t)); // NEW
                }; // NEW
              }); // NEW
            makeTexts();
            makePolyLines();

          }); // NEW

        legend.append('text')
          .attr('x', legendRectSize + legendSpacing)
          .attr('y', legendRectSize - legendSpacing)
          .text(function(d) {
            return d;
          });

        function midAngle(d) {
          return d.startAngle + (d.endAngle - d.startAngle) / 2;
        }

        function makeTexts() {
          var text = svg.selectAll(".labels")
            .data(pie(dataset), key);

          text.enter()
            .append("text")
            .attr("dy", ".35em")
            .classed("labels", true)
            .text(function(d) {
              return d.data.label + " (" + d.data.count + ")";
            });

          svg.selectAll(".labels").style("display", function(d) {
            if (d.value == 0) {
              return "none";
            } else {
              return "block";
            }
          });

          text.transition().duration(1000)
            .attrTween("transform", function(d) {

              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                return "translate(" + pos + ")";
              };
            })
            .styleTween("text-anchor", function(d) {
              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                var d2 = interpolate(t);
                return midAngle(d2) < Math.PI ? "start" : "end";
              };
            });

          text.exit()
            .remove();
        }

        function makePolyLines() {
          var polyline = svg.selectAll("polyline")
            .data(pie(dataset), key);

          polyline.enter()
            .append("polyline");

          svg.selectAll("polyline").style("display", function(d) {
            console.log(d, "hello")
            if (d.value == 0) {
              return "none";
            } else {
              return "block";
            }
          });

          polyline.transition().duration(1000)
            .attrTween("points", function(d) {
              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                return [arc.centroid(d2), outerArc.centroid(d2), pos];
              };
            });

          polyline.exit()
            .remove();
        }

      });

    })(window.d3);
  </script>
</body>

</html>

label,count
Testing with some long textAnd it conitues,3
Active_Integrated,286
Assigned,19
Active_not_Integrated,56
Assigned_Waiting,13
Complete,184
Dev_Waiting,17
Global_Screening,23
In Progress,14
In_Development,12
New,76
Pending_CTL_Approval,38
Test,1
Rejected,50
RETIRED with long text and contiues,37
</code>```

This is the wrap function:

```<code>const wrap=(_text: {  each: (arg0: (i: any, d: any, p: any) => void) => void; }, width: number)=> {
    _text.each((d: any,i: any,nodes: any[])=> {
      var text = d3.select(nodes[i]),
        words = text.text().split(/\s+/).reverse(),
        word,
        line: string[] = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy") || "0"),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
      while (word = words.pop()) {
        line.push(word);
        tspan.text(line.join(" "));
        if (tspan?.node()!.getComputedTextLength() > width) {
          line.pop();
          tspan.text(line.join(" "));
          line = [word];
          tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", lineHeight + "em").text(word);
        }
      }
    });
  }
</code>```

If you uncheck some of the labels (see print screen below), it will move the labels and they start overlapping.

Any help, please?

Body:
I have found this donut chart example. it is good one but I am having trouble understanding it and I am having problems with long text (wrappping) and labels overlapping one another when text is wrapped?

https://plnkr.co/edit/sAbnep00GMRkx5Xey6gL?p=preview&preview

This is the code: I removed the css as it was taking a lot of space.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="normalize.css">

label,count
Testing with some long textAnd it conitues,3
Active_Integrated,286
Assigned,19
Active_not_Integrated,56
Assigned_Waiting,13
Complete,184
Dev_Waiting,17
Global_Screening,23
In Progress,14
In_Development,12
New,76
Pending_CTL_Approval,38
Test,1
Rejected,50
RETIRED with long text and contiues,37

This is the wrap function:

const wrap=(_text: {  each: (arg0: (i: any, d: any, p: any) => void) => void; }, width: number)=> {
    _text.each((d: any,i: any,nodes: any[])=> {
      var text = d3.select(nodes[i]),
        words = text.text().split(/\s+/).reverse(),
        word,
        line: string[] = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy") || "0"),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
      while (word = words.pop()) {
        line.push(word);
        tspan.text(line.join(" "));
        if (tspan?.node()!.getComputedTextLength() > width) {
          line.pop();
          tspan.text(line.join(" "));
          line = [word];
          tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", lineHeight + "em").text(word);
        }
      }
    });
  }

If you uncheck some of the labels (see print screen below), it will move the labels and they start overlapping.

Any help, please?


问:
Unable to update react range values through input
I'm writing a code where I'm using react-range to create a range bar. along with it, I've got 2 textboxes that have the min and max values of the range. Currently, I'm able to update the range values by dragging and the text boxes get updated automatically. And I also want to update the price range using the textboxes mentioned, currently, the min box value works fine, but, when I try to update the max value, the value gets appended instead of updating. Unable to know where I'm going wrong.

Here is the code of the same.

```<code>import { useState } from "react";
import { Range, getTrackBackground } from "react-range";

export const PriceRange = () => {
  const [priceValues, setPriceValues] = useState([1, 100]);
  let step = 1;

  const handleChange = (values: number[]) => {
    if (values[0] > values[1]) {
      values[0] = values[1];
    }
    if (values[1] < values[0]) {
      values[1] = values[0];
    }
    setPriceValues(values);
  };

  return (
    <>
      {
        <div
          style={{
            width: "50%",
            maxWidth: "50%",
            marginLeft: "auto",
            marginRight: "auto"
          }}
        >
          <div className="mb-8 text-gray-900 text-sm font-medium text-left">
            Price
          </div>
          <div
            style={{ padding: "1rem", marginTop: "1rem", marginBottom: "1rem" }}
          >
            <Range
              step={step}
              min={priceValues[0]}
              max={priceValues[1]}
              values={priceValues}
              onChange={(values) => handleChange(values)}
              renderTrack={({ props, children }) => (
                <div
                  {...props}
                  style={{
                    ...props.style,
                    background: getTrackBackground({
                      values: priceValues,
                      colors: ["#c4c4c442", "black", "#c4c4c442"],
                      min: priceValues[0],
                      max: priceValues[1]
                    }),
                    height: "0.5rem",
                    width: "100%"
                  }}
                >
                  {children}
                </div>
              )}
              renderThumb={({ index, props }) => (
                <div
                  {...props}
                  style={{
                    ...props.style
                  }}
                  className="thumbs"
                >
                  <div className="priceValues">{`$${
                    priceValues[index] === priceValues.length - 1
                      ? priceValues[index] + "+"
                      : priceValues[index]
                  }`}</div>
                </div>
              )}
            />
          </div>
          <div className="rangeBoxesContainer">
            <div className="rangeBox">
              <div style={{ display: "flex" }}>Min $</div>
              <input
                className="rangeInputbox"
                type="number"
                value={priceValues[0]}
                onChange={(e) => {
                  if (Number(e.target.value) < Number(priceValues[1])) {
                    let newValue = [...priceValues];
                    newValue[0] = Number(e.target.value);
                    setPriceValues(newValue);
                  }
                }}
              />
            </div>
            <div className="rangeBox">
              <div style={{ display: "flex" }}>Max $</div>
              <input
                className="rangeInputbox"
                type="number"
                value={priceValues[1]}
                onChange={(e) => {
                  if (Number(e.target.value) > Number(priceValues[1])) {
                    let newValue = [...priceValues];
                    newValue[1] = Number(e.target.value);
                    setPriceValues(newValue);
                  }
                }}
              />
            </div>
          </div>
        </div>
      }
    </>
  );
};
</code>```

And here is a working code sandbox link.  Can someone let me know where I'm going wrong?

Thanks

Body:
I'm writing a code where I'm using react-range to create a range bar. along with it, I've got 2 textboxes that have the min and max values of the range. Currently, I'm able to update the range values by dragging and the text boxes get updated automatically. And I also want to update the price range using the textboxes mentioned, currently, the min box value works fine, but, when I try to update the max value, the value gets appended instead of updating. Unable to know where I'm going wrong.

Here is the code of the same.

import { useState } from "react";
import { Range, getTrackBackground } from "react-range";

export const PriceRange = () => {
  const [priceValues, setPriceValues] = useState([1, 100]);
  let step = 1;

  const handleChange = (values: number[]) => {
    if (values[0] > values[1]) {
      values[0] = values[1];
    }
    if (values[1] < values[0]) {
      values[1] = values[0];
    }
    setPriceValues(values);
  };

  return (
    <>
      {

            Price

            <Range
              step={step}
              min={priceValues[0]}
              max={priceValues[1]}
              values={priceValues}
              onChange={(values) => handleChange(values)}
              renderTrack={({ props, children }) => (

                  {children}

              )}
              renderThumb={({ index, props }) => (

{`$${
                    priceValues[index] === priceValues.length - 1
                      ? priceValues[index] + "+"
                      : priceValues[index]
                  }`}

              )}
            />

Min $

              <input
                className="rangeInputbox"
                type="number"
                value={priceValues[0]}
                onChange={(e) => {
                  if (Number(e.target.value) < Number(priceValues[1])) {
                    let newValue = [...priceValues];
                    newValue[0] = Number(e.target.value);
                    setPriceValues(newValue);
                  }
                }}
              />

Max $

              <input
                className="rangeInputbox"
                type="number"
                value={priceValues[1]}
                onChange={(e) => {
                  if (Number(e.target.value) > Number(priceValues[1])) {
                    let newValue = [...priceValues];
                    newValue[1] = Number(e.target.value);
                    setPriceValues(newValue);
                  }
                }}
              />

      }
    </>
  );
};

And here is a working code sandbox link.  Can someone let me know where I'm going wrong?

Thanks


问:
Host React App using docker & windows server
i want to host my react app with use of docker and windows server. So that other users on my LAN will be able to visit a static ip and see the application hsoted there.

Is there anyone out there who did it before ?


问:
How to get SetMultiline(true) to honor wrapping of text
I'm attempting to add form fields to an existing PDF in a .NET 7.0.0 app using iText7 7.2.4 on Mac and I cannot get multiline text fields to honor wrapping without doing a weird hack.

The following code illustrates the issue:

```<code>using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;

// Create a new PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter("my_document.pdf"));

// Create a page and add it to the document
PdfPage page = pdf.AddNewPage();

// Create an AcroForm and add it to the document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);

// Create a multiline text field that should wrap but does not.
PdfTextFormField nonWrapping = PdfFormField.CreateText
    (pdf,
    new Rectangle(25, 727, 100, 100),
    "multiline-field-without-wrapping",
    String.Concat(Enumerable.Repeat("Hello World ", 10)),
    PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
    9.0F);

nonWrapping.SetMultiline(true);
form.AddField(nonWrapping);

 // Create a multiline text field that DOES wrap but
// only because we set a background color.
PdfTextFormField wrapping = PdfFormField.CreateText
    (pdf,
    new Rectangle(150, 727, 100, 100),
    "multiline-field-with-wrapping",
    String.Concat(Enumerable.Repeat("Hello World ", 10)),
    PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
    9.0F);

wrapping.SetMultiline(true);
wrapping.SetBackgroundColor(new DeviceRgb(0.9F, 0.9F, 0.99F));
form.AddField(wrapping);

// Close the document
pdf.Close();
</code>```

It will result in a PDF that looks like this in Preview:

The only way I can get wrapping to work is by including background color. I don't want to do this but it's the only thing that works.

If I could set the opacity of the background color, that might also be acceptable but so far, I've been unable to find anything in the code or docs that would support this.

Body:
I'm attempting to add form fields to an existing PDF in a .NET 7.0.0 app using iText7 7.2.4 on Mac and I cannot get multiline text fields to honor wrapping without doing a weird hack.

The following code illustrates the issue:

using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;

// Create a new PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter("my_document.pdf"));

// Create a page and add it to the document
PdfPage page = pdf.AddNewPage();

// Create an AcroForm and add it to the document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);

// Create a multiline text field that should wrap but does not.
PdfTextFormField nonWrapping = PdfFormField.CreateText
    (pdf,
    new Rectangle(25, 727, 100, 100),
    "multiline-field-without-wrapping",
    String.Concat(Enumerable.Repeat("Hello World ", 10)),
    PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
    9.0F);

nonWrapping.SetMultiline(true);
form.AddField(nonWrapping);

 // Create a multiline text field that DOES wrap but
// only because we set a background color.
PdfTextFormField wrapping = PdfFormField.CreateText
    (pdf,
    new Rectangle(150, 727, 100, 100),
    "multiline-field-with-wrapping",
    String.Concat(Enumerable.Repeat("Hello World ", 10)),
    PdfFontFactory.CreateFont(StandardFonts.HELVETICA),
    9.0F);

wrapping.SetMultiline(true);
wrapping.SetBackgroundColor(new DeviceRgb(0.9F, 0.9F, 0.99F));
form.AddField(wrapping);

// Close the document
pdf.Close();

It will result in a PDF that looks like this in Preview:

The only way I can get wrapping to work is by including background color. I don't want to do this but it's the only thing that works.

If I could set the opacity of the background color, that might also be acceptable but so far, I've been unable to find anything in the code or docs that would support this.


问:
Append Array from different .txt file
I have 63 .txt file with 26 headers lines and then 19 columns of float data.
I would like to read all the files and store (in row) the first 6 columns of the .txt files (x,y,z,u,v,w). Then for each .txt file I would like to append these data in a new row.

This is the code that I did but after the first j (j=1) then the script crash because the sizes of the arrays are not the same, indeed for some reasons during the first iteration it is skipping not 26 but 52 lines (so also the first 26 of numbers that I want), while in the second is (in a correct way skiiping only 26 headers line).

```<code>inpDir = "\\ftac\Folder\CD";
files = dir(fullfile(inpDir, '*.txt'));
n_file = size(files,1);
for j=1:n_file
    fid = fopen(files(j).name, 'r');
    data = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f', 'HeaderLines', 26, 'Delimiter',' ');
    fclose(fid);
    x(j, :) = data{1}'; % x coordinate
    y(j, :) = data{2}'; % y coordinate
    z(j, :) = data{3}'; % y coordinate
    u(j, :) = data{4}';% u velocity
    v(j, :) = data{5}'; % v velocity
    w(j, :) = data{6}'; % w velocity
end
</code>```

How can I solve this issue? Thanks in advance

Title: Append Array from different .txt file

Body:
I have 63 .txt file with 26 headers lines and then 19 columns of float data.
I would like to read all the files and store (in row) the first 6 columns of the .txt files (x,y,z,u,v,w). Then for each .txt file I would like to append these data in a new row.

This is the code that I did but after the first j (j=1) then the script crash because the sizes of the arrays are not the same, indeed for some reasons during the first iteration it is skipping not 26 but 52 lines (so also the first 26 of numbers that I want), while in the second is (in a correct way skiiping only 26 headers line).

inpDir = "\\ftac\Folder\CD";
files = dir(fullfile(inpDir, '*.txt'));
n_file = size(files,1);
for j=1:n_file
    fid = fopen(files(j).name, 'r');
    data = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f', 'HeaderLines', 26, 'Delimiter',' ');
    fclose(fid);
    x(j, :) = data{1}'; % x coordinate
    y(j, :) = data{2}'; % y coordinate
    z(j, :) = data{3}'; % y coordinate
    u(j, :) = data{4}';% u velocity
    v(j, :) = data{5}'; % v velocity
    w(j, :) = data{6}'; % w velocity
end

How can I solve this issue? Thanks in advance


问:
get last row in multi-page table
I would like to page through a table until the last page, then click on the last row. I tried with a try/catch block, but it waits too long time for clicking the last row. It does not find the next-button on the last page, so the "catch" works.

I would like to find a better solution, which first paginates through until the last page is found, then immediately click on its last element.

```<code>while (true) {
    try {
        nextButton.click();
    } catch (Exception e) {
        clickLastRow();
        break;
    }
}
</code>```

Title: get last row in multi-page table

Body:
I would like to page through a table until the last page, then click on the last row. I tried with a try/catch block, but it waits too long time for clicking the last row. It does not find the next-button on the last page, so the "catch" works.

I would like to find a better solution, which first paginates through until the last page is found, then immediately click on its last element.

while (true) {
    try {
        nextButton.click();
    } catch (Exception e) {
        clickLastRow();
        break;
    }
}


问:
Iterate .pdf conversion in python using Tabula
I'm new to Python and I have problem, its gonna be great having solution from all of you here. I have a 23 pages Pdf file and i want to convert it to separate .csv file for each page. How could I iterate the file name using Tabula? My current code has a syntax error.


问:
getValue not working on SAMLUserDetailsServiceImpl
I'm trying to implement SAML SSO on my project but there's a weird problem, the method getValue() is not working, it just says "Cannot resolve method 'getValue()'". Right on credential.getNameID().getValue() the getValue gets red and it shows that message, I've searched everywhere but found no answer

`

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.saml.SAMLCredential;
import org.springframework.security.saml.userdetails.SAMLUserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SAMLUserDetailsServiceImpl implements SAMLUserDetailsService {

    // Logger
    private static final Logger LOG = LoggerFactory.getLogger(SAMLUserDetailsServiceImpl.class);

    public Object loadUserBySAML(SAMLCredential credential)
            throws UsernameNotFoundException {

        // The method is supposed to identify local account of user referenced by
        // data in the SAML assertion and return UserDetails object describing the user.

        //PROBLEM RIGHT HERE
        String userID = credential.getNameID().getValue();

        LOG.info(userID + " is logged in");
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
        authorities.add(authority);

        // In a real scenario, this implementation has to locate user in a arbitrary
        // dataStore based on information present in the SAMLCredential and
        // returns such a date in a form of application specific UserDetails object.
        return new User(userID, "<abc123>", true, true, true, true, authorities);
    }

}
</code>```

`

There's no much to try

Body:
I'm trying to implement SAML SSO on my project but there's a weird problem, the method getValue() is not working, it just says "Cannot resolve method 'getValue()'". Right on credential.getNameID().getValue() the getValue gets red and it shows that message, I've searched everywhere but found no answer

`

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.saml.SAMLCredential;
import org.springframework.security.saml.userdetails.SAMLUserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SAMLUserDetailsServiceImpl implements SAMLUserDetailsService {

    // Logger
    private static final Logger LOG = LoggerFactory.getLogger(SAMLUserDetailsServiceImpl.class);

    public Object loadUserBySAML(SAMLCredential credential)
            throws UsernameNotFoundException {

        // The method is supposed to identify local account of user referenced by
        // data in the SAML assertion and return UserDetails object describing the user.

        //PROBLEM RIGHT HERE
        String userID = credential.getNameID().getValue();

        LOG.info(userID + " is logged in");
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
        authorities.add(authority);

        // In a real scenario, this implementation has to locate user in a arbitrary
        // dataStore based on information present in the SAMLCredential and
        // returns such a date in a form of application specific UserDetails object.
        return new User(userID, "<abc123>", true, true, true, true, authorities);
    }

}

`

There's no much to try


问:
How to add oculus controllers to mozilla hubs?
I have a custom mozilla hubs client and I'm trying to add oculus-touch-controls to it but nowhere I put them I can see them in the scene. I can't even add a simple a-frame box to the scene.

I've tried adding it as html to hub.html under  I tried adding it programatically under objects-root and objects-scene. I've trying adding the component networked to the entity. The only thing that made any difference was swapping the url for the object for my custom url to a glb file. What is the proper way to add a-frame objects to hubs? And would it work with controllers? Thank you.


问:
Which files should I configure to STOP AUTO-CONVERTING input method(keyboard layout) whenever I open bash shell?
I am Korean. So I have two keyboard layouts, KR / EN.

There is a problem. I can't input Korean on bash shell. It is fine with output. I can read KR on bash, e.g file names.

Same thing happen while I am coding in vim editor(actually it is the neovim). Fine output, bad input.

I have tried hundred times to solve it. But I got just a single micro clue.
There is a icon showing which input method and which language I am using. I found out whenever I open terminal, that icon changes from one thing to another. If I come back to a browser or anything other than terminal, the icon turns back as well.

Here is my system info.

```<code>██████████████████  ████████   sy@sy-81f4
██████████████████  ████████   ----------
██████████████████  ████████   OS: Manjaro Linux x86_64
██████████████████  ████████   Host: 81F4 Lenovo ideapad 330S-14IKB
████████            ████████   Kernel: 5.10.157-1-MANJARO
████████  ████████  ████████   Uptime: 51 mins
████████  ████████  ████████   Packages: 1241 (pacman)
████████  ████████  ████████   Shell: bash 5.1.16
████████  ████████  ████████   Resolution: 1920x1080
████████  ████████  ████████   WM: i3
████████  ████████  ████████   Theme: Adapta-Nokto-Eta-Maia [GTK2/3]
████████  ████████  ████████   Icons: Papirus-Adapta-Nokto-Maia [GTK2/3]
████████  ████████  ████████   Terminal: urxvt
████████  ████████  ████████   Terminal Font: D2Coding
                               CPU: Intel i5-8250U (8) @ 3.400GHz
                               GPU: Intel UHD Graphics 620
                               Memory: 4069MiB / 11882MiB
</code>```

I apologize my poor English. Thanks for your lovely effort reading it.

I have tried to configure these files.

something like .vimrc for the neovim

something for i3 config

something for .bashrc

something named like 'inputrc'

and locale at /etc/environment

Body:
I am Korean. So I have two keyboard layouts, KR / EN.

There is a problem. I can't input Korean on bash shell. It is fine with output. I can read KR on bash, e.g file names.

Same thing happen while I am coding in vim editor(actually it is the neovim). Fine output, bad input.

I have tried hundred times to solve it. But I got just a single micro clue.
There is a icon showing which input method and which language I am using. I found out whenever I open terminal, that icon changes from one thing to another. If I come back to a browser or anything other than terminal, the icon turns back as well.

Here is my system info.

██████████████████  ████████   sy@sy-81f4
██████████████████  ████████   ----------
██████████████████  ████████   OS: Manjaro Linux x86_64
██████████████████  ████████   Host: 81F4 Lenovo ideapad 330S-14IKB
████████            ████████   Kernel: 5.10.157-1-MANJARO
████████  ████████  ████████   Uptime: 51 mins
████████  ████████  ████████   Packages: 1241 (pacman)
████████  ████████  ████████   Shell: bash 5.1.16
████████  ████████  ████████   Resolution: 1920x1080
████████  ████████  ████████   WM: i3
████████  ████████  ████████   Theme: Adapta-Nokto-Eta-Maia [GTK2/3]
████████  ████████  ████████   Icons: Papirus-Adapta-Nokto-Maia [GTK2/3]
████████  ████████  ████████   Terminal: urxvt
████████  ████████  ████████   Terminal Font: D2Coding
                               CPU: Intel i5-8250U (8) @ 3.400GHz
                               GPU: Intel UHD Graphics 620
                               Memory: 4069MiB / 11882MiB

I apologize my poor English. Thanks for your lovely effort reading it.

I have tried to configure these files.

something like .vimrc for the neovim

something for i3 config

something for .bashrc

something named like 'inputrc'

and locale at /etc/environment


问:
crash with local notification flutter -> message_codecs.dart StandardMethodCodec.decodeEnvelope
Hello I add local notification on my app, but I have some crash on firebase crashlytics.

Here is my code and error

```<code> @override
  void initState() {
  // TODO: implement initState
  super.initState();
   check_notification();
 }

check_notification()async{

FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

if(toggle_notification==false){

  _flutterLocalNotificationsPlugin.cancelAll;
}
 else{
  intialize();
  ScheduledNotification_remove();
 }
}

final _localNotificationService = FlutterLocalNotificationsPlugin();

Future<void> intialize() async {
tz.initializeTimeZones();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@drawable/ic_launcher');

final DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
  onDidReceiveLocalNotification: onDidReceiveLocalNotification,

  requestSoundPermission: true,
  requestBadgePermission: true,
  requestAlertPermission: true,

);

final InitializationSettings settings = InitializationSettings(
  android: androidInitializationSettings,
  iOS: initializationSettingsDarwin,

);

await _localNotificationService.initialize(
  settings,
  // onSelectNotification: onSelectNotification,
    );
           }

  Future<NotificationDetails> _notificationDetails() async {
  const AndroidNotificationDetails androidNotificationDetails =
   AndroidNotificationDetails('channel_id', 'channel_name',
    channelDescription: 'description',
    importance: Importance.max,
    priority: Priority.high,
    enableVibration: true,
    playSound: true

);

const DarwinNotificationDetails darwinNotificationDetails =
DarwinNotificationDetails(
    presentSound: true,
    presentAlert: true,
    presentBadge: true);

return  NotificationDetails(
  android: androidNotificationDetails,
  iOS: darwinNotificationDetails,
  );
 }

 Future<void> showScheduledNotification(
  {required int id,
    required String title,
    required String body,
    required int seconds}) async {
final details = await _notificationDetails();

await _localNotificationService.zonedSchedule(
  id,
  title,
  body,
  tz.TZDateTime.from(
    DateTime.now().add(Duration(seconds: seconds)),
    tz.local,
  ),

  details,
  androidAllowWhileIdle: true,
  uiLocalNotificationDateInterpretation:
  UILocalNotificationDateInterpretation.absoluteTime,

);
}

ScheduledNotification_remove()async{

final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

_flutterLocalNotificationsPlugin.cancel(1);
_flutterLocalNotificationsPlugin.cancel(2);
_flutterLocalNotificationsPlugin.cancel(3);
_flutterLocalNotificationsPlugin.cancel(4);
_flutterLocalNotificationsPlugin.cancel(5);

 showScheduledNotification(
      id: 1,
      title: 'title1',
      body: "body1",
      seconds: 1,
 }

showScheduledNotification(
      id: 2,
      title: 'title2',
      body: "body2",
      seconds: 2,
 }

 showScheduledNotification(
      id: 3,
      title: 'title3',
      body: "body3",
      seconds: 3,
 }

 showScheduledNotification(
      id: 4,
      title: 'title4',
      body: "body4",
      seconds: 4,
 }

 showScheduledNotification(
      id: 5,
      title: 'title5',
      body: "body5",
      seconds: 5,
  }
 }
</code>```

```<code> Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: PlatformException(error, Missing type parameter., null, java.lang.RuntimeException: Missing type parameter.
    at g.c.d.T.a.<init>(:3)
    at com.dexterous.flutterlocalnotifications.c.<init>(Unknown Source:0)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.loadScheduledNotifications(Unknown Source:25)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.removeNotificationFromCache(Unknown Source:0)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.cancelNotification(Unknown Source:53)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.cancel(:2)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(Unknown Source:389)
    at j.a.e.a.y.a(Unknown Source:17)
    at io.flutter.embedding.engine.n.q.i(Unknown Source:11)
    at io.flutter.embedding.engine.n.q.j(:3)
    at io.flutter.embedding.engine.n.c.run(Unknown Source:12)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:233)
    at android.os.Looper.loop(Looper.java:344)
    at android.app.ActivityThread.main(ActivityThread.java:8205)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
). Error thrown null.
       at StandardMethodCodec.decodeEnvelope(message_codecs.dart:607)
       at MethodChannel._invokeMethod(platform_channel.dart:177)
       at FlutterLocalNotificationsPlugin.cancel(flutter_local_notifications_plugin.dart:274)
</code>```

```<code>Fatal Exception: java.lang.RuntimeException: Unable to start receiver com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver: java.lang.RuntimeException: Missing type parameter.
       at android.app.ActivityThread.handleReceiver(ActivityThread.java:4890)
       at android.app.ActivityThread.-$$Nest$mhandleReceiver(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2417)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8741)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
</code>```

Body:
Hello I add local notification on my app, but I have some crash on firebase crashlytics.

Here is my code and error

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

check_notification()async{

FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

if(toggle_notification==false){

  _flutterLocalNotificationsPlugin.cancelAll;
}
 else{
  intialize();
  ScheduledNotification_remove();
 }
}

final _localNotificationService = FlutterLocalNotificationsPlugin();

Future<void> intialize() async {
tz.initializeTimeZones();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@drawable/ic_launcher');

final DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
  onDidReceiveLocalNotification: onDidReceiveLocalNotification,

  requestSoundPermission: true,
  requestBadgePermission: true,
  requestAlertPermission: true,

);

final InitializationSettings settings = InitializationSettings(
  android: androidInitializationSettings,
  iOS: initializationSettingsDarwin,

);

await _localNotificationService.initialize(
  settings,
  // onSelectNotification: onSelectNotification,
    );
           }

  Future<NotificationDetails> _notificationDetails() async {
  const AndroidNotificationDetails androidNotificationDetails =
   AndroidNotificationDetails('channel_id', 'channel_name',
    channelDescription: 'description',
    importance: Importance.max,
    priority: Priority.high,
    enableVibration: true,
    playSound: true

);

const DarwinNotificationDetails darwinNotificationDetails =
DarwinNotificationDetails(
    presentSound: true,
    presentAlert: true,
    presentBadge: true);

return  NotificationDetails(
  android: androidNotificationDetails,
  iOS: darwinNotificationDetails,
  );
 }

 Future<void> showScheduledNotification(
  {required int id,
    required String title,
    required String body,
    required int seconds}) async {
final details = await _notificationDetails();

await _localNotificationService.zonedSchedule(
  id,
  title,
  body,
  tz.TZDateTime.from(
    DateTime.now().add(Duration(seconds: seconds)),
    tz.local,
  ),

  details,
  androidAllowWhileIdle: true,
  uiLocalNotificationDateInterpretation:
  UILocalNotificationDateInterpretation.absoluteTime,

);
}

ScheduledNotification_remove()async{

final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

_flutterLocalNotificationsPlugin.cancel(1);
_flutterLocalNotificationsPlugin.cancel(2);
_flutterLocalNotificationsPlugin.cancel(3);
_flutterLocalNotificationsPlugin.cancel(4);
_flutterLocalNotificationsPlugin.cancel(5);

 showScheduledNotification(
      id: 1,
      title: 'title1',
      body: "body1",
      seconds: 1,
 }

showScheduledNotification(
      id: 2,
      title: 'title2',
      body: "body2",
      seconds: 2,
 }

 showScheduledNotification(
      id: 3,
      title: 'title3',
      body: "body3",
      seconds: 3,
 }

 showScheduledNotification(
      id: 4,
      title: 'title4',
      body: "body4",
      seconds: 4,
 }

 showScheduledNotification(
      id: 5,
      title: 'title5',
      body: "body5",
      seconds: 5,
  }
 }

 Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: PlatformException(error, Missing type parameter., null, java.lang.RuntimeException: Missing type parameter.
    at g.c.d.T.a.<init>(:3)
    at com.dexterous.flutterlocalnotifications.c.<init>(Unknown Source:0)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.loadScheduledNotifications(Unknown Source:25)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.removeNotificationFromCache(Unknown Source:0)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.cancelNotification(Unknown Source:53)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.cancel(:2)
    at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(Unknown Source:389)
    at j.a.e.a.y.a(Unknown Source:17)
    at io.flutter.embedding.engine.n.q.i(Unknown Source:11)
    at io.flutter.embedding.engine.n.q.j(:3)
    at io.flutter.embedding.engine.n.c.run(Unknown Source:12)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:233)
    at android.os.Looper.loop(Looper.java:344)
    at android.app.ActivityThread.main(ActivityThread.java:8205)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
). Error thrown null.
       at StandardMethodCodec.decodeEnvelope(message_codecs.dart:607)
       at MethodChannel._invokeMethod(platform_channel.dart:177)
       at FlutterLocalNotificationsPlugin.cancel(flutter_local_notifications_plugin.dart:274)

Fatal Exception: java.lang.RuntimeException: Unable to start receiver com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver: java.lang.RuntimeException: Missing type parameter.
       at android.app.ActivityThread.handleReceiver(ActivityThread.java:4890)
       at android.app.ActivityThread.-$$Nest$mhandleReceiver(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2417)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8741)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)


问:
Flutter_foreground_task: how to "attach" to a running task when I restart my app?
I'm using flutter foreground task plugin in my app.

Here is my usage of the lib:

I start my app, which starts a foreground task.

I close my app with "close all" on android: all apps are closed.

The foreground task continues, and that is expected: great.

When I start again the application (not from the notification: from its icon launcher (on android), I would like to detect the foreground_task is already running, and to attach to its receivePort BUT:

when I start, await FlutterForegroundTask.isRunningService returns false

Even if I init the task before.

=> How can I do to know a foreground task is running when I start my app?

Thanks a lot.


问:
Why is Java_Home not updating for react-native?
I'm trying to run

```<code>npx react-native run-android
</code>```

I used to have a wrong version of Java installed, but this was now rectified to JDK11. I however, I still get the following error:

```<code>The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location: C:\Program Files\Java\jdk-19\bin\java.exe
</code>```

I don't understand why it keeps going to an old, uninstalled path. I already installed JDK11 and changed my variables:

```<code>echo %JAVA_HOME%
C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot
</code>```

Is there anything else I have to do in order for the script to see the new JDK location?

Body:
I'm trying to run

npx react-native run-android

I used to have a wrong version of Java installed, but this was now rectified to JDK11. I however, I still get the following error:

The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location: C:\Program Files\Java\jdk-19\bin\java.exe

I don't understand why it keeps going to an old, uninstalled path. I already installed JDK11 and changed my variables:

echo %JAVA_HOME%
C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot

Is there anything else I have to do in order for the script to see the new JDK location?


问:
expo-camera error “camera not working” on android web app upon toggleswitch camera type
I am using expo-camera on my app that can be run to a web on android/ios. Setting camera type works but when I try to switch/toggle camera on android i got an error “camera not working”

```<code><Camera type={type}...>
<Button onPress={toggleCamera} >
 <Icon name="refresh" as={MaterialIcons} color="white" />
</Button>
</Camera>

const toggleCamera = () => { setType( type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back ); };
</code>```

initial load is okay but when i try to switch camera it says "camera not working" .. but it only shows on mobile web android

Body:
I am using expo-camera on my app that can be run to a web on android/ios. Setting camera type works but when I try to switch/toggle camera on android i got an error “camera not working”

<Camera type={type}...>
<Button onPress={toggleCamera} >
 <Icon name="refresh" as={MaterialIcons} color="white" />
</Button>
</Camera>

const toggleCamera = () => { setType( type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back ); };

initial load is okay but when i try to switch camera it says "camera not working" .. but it only shows on mobile web android


问:
Safari not saving cookie value correctly
I got a JSON I need to save in cookies:

```<code>{
   "0":{
      "question":"intro 1",
      "type":"1"
   },
   "5":{
      "question":"extro 1",
      "type":"0"
   },
   "7":{
      "question":"extro 3",
      "type":"0"
   },
   "8":{
      "question":"extro 4",
      "type":"0"
   },
   "9":{
      "question":"extro 5",
      "type":"0"
   },
   "10":{
      "question":"intro 6",
      "type":"1"
   },
   "11":{
      "question":"intro 7",
      "type":"1"
   },
   "12":{
      "question":"Extro 6",
      "type":"1"
   },
   "13":{
      "question":"Extro 7",
      "type":"0"
   }
}
</code>```

Stringifying the JSON returns:

```<code>{"0":{"question":"intro 1","type":"1"},"5":{"question":"extro 1","type":"0"},"7":{"question":"extro 3","type":"0"},"8":{"question":"extro 4","type":"0"},"9":{"question":"extro 5","type":"0"},"10":{"question":"intro 6","type":"1"},"11":{"question":"intro 7","type":"1"},"12":{"question":"Extro 6","type":"1"},"13":{"question":"Extro 7","type":"0"}}
</code>```

Now when I try to save it into the cookies it only saves small part of the string.
Example:

```<code>{"0":{"question":"int
</code>```

Every other browser saves the stringified JSON fully.

Code that saves cookie and stringifies the JSON:

```<code>document.cookie = 'my_cookie=' + JSON.stringify(my_json) + '; max-age=3600; path=/';
</code>```

Body:
I got a JSON I need to save in cookies:

{
   "0":{
      "question":"intro 1",
      "type":"1"
   },
   "5":{
      "question":"extro 1",
      "type":"0"
   },
   "7":{
      "question":"extro 3",
      "type":"0"
   },
   "8":{
      "question":"extro 4",
      "type":"0"
   },
   "9":{
      "question":"extro 5",
      "type":"0"
   },
   "10":{
      "question":"intro 6",
      "type":"1"
   },
   "11":{
      "question":"intro 7",
      "type":"1"
   },
   "12":{
      "question":"Extro 6",
      "type":"1"
   },
   "13":{
      "question":"Extro 7",
      "type":"0"
   }
}

Stringifying the JSON returns:

{"0":{"question":"intro 1","type":"1"},"5":{"question":"extro 1","type":"0"},"7":{"question":"extro 3","type":"0"},"8":{"question":"extro 4","type":"0"},"9":{"question":"extro 5","type":"0"},"10":{"question":"intro 6","type":"1"},"11":{"question":"intro 7","type":"1"},"12":{"question":"Extro 6","type":"1"},"13":{"question":"Extro 7","type":"0"}}

Now when I try to save it into the cookies it only saves small part of the string.
Example:

{"0":{"question":"int

Every other browser saves the stringified JSON fully.

Code that saves cookie and stringifies the JSON:

document.cookie = 'my_cookie=' + JSON.stringify(my_json) + '; max-age=3600; path=/';


问:
How can I call an API and use .map in a filter component?
I'm trying to call an API to my filter component, which it will shows in the component a Carrousel with all the filters (located at the API). The filter component will be called in a father component (where it will be the filter functions).
OBS: in the father component it is called also Cards Components (the cards that will be show depending on the filter selection).
Something like that:

Here are the codes:

Filter Component

```<code>import React from "react";
import Carrousel from "react-elastic-carousel";
import "./filtro.css";

function Filtro({ filtros, itensFiltrado }) {

  const breakPoints = [
    { width: 1, itemsToShow: 1, pagination: false },
    { width: 600, itemsToShow: 2, pagination: false },
    { width: 860, itemsToShow: 5, pagination: false },
    { width: 1100, itemsToShow: 5, pagination: false },
    { width: 1700, itemsToShow: 6, pagination: false },
  ];

  return (
    <div className="filtro__segmento">
      <Carrousel breakPoints={breakPoints}>
        {filtros.map((filtro, id) => {
          return (
            <label
              className="card__segmento"
              key={id}
              onClick={() => itensFiltrado(filtro)}
            >
              <h2 className="segmento__titulo">{filtro}</h2>
              <input type="radio" className="input-radio" name="teste" />
              <span className="check"></span>
            </label>
          );
        })}
      </Carrousel>
    </div>
  );
}

export default Filtro;
</code>```

Father component

```<code>import React, { useEffect, useState } from "react";
import "./popupOrcamentoSimultaneo.css";
/* import profissionais from "../../../../utils/data-popupOrcamento"; */
import Filtro from "./Filtro";
import Card from "./Card";

import api from "../../../../api";

const allFilters = [
  "Todos",
  ...new Set(api.map((profissional) => profissional.segmento)),
];

function PopupOrcamentoSimultaneo({ setOpenPopup, checkedState }) {

  /* const [cardProfissionais, setCardProfissionais] = useState(profissionais); */
  const [Profissionais, setProfissionais] = useState([]);
  const [filtroProfissionais, setFiltroProfissionais] = useState([]);
  const [filtros, setFiltros] = useState(allFilters);
  const [value, setValue] = useState(
    "'Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
  );

  useEffect(() => {
    api.get("profissionais/listarTodos/").then(({ data }) => {
      setProfissionais(data);
      setFiltroProfissionais(data);
    });
  }, []);

  let cardsProfissionais = Profissionais;
  let listaCardsProfissionais = [];

  for (let i = 0; i < cardsProfissionais.length; i++) {
    listaCardsProfissionais.push(
      <Card dadosProfissionais={cardsProfissionais[i]} />
    );
  }

  const itensFiltrado = (segmentoEmpresa) => {
    if (segmentoEmpresa === "Todos") {
      setFiltroProfissionais(api);
      return;
    }

    const novosProfissionais = api.filter(
      (profissional) => profissional.segmento === segmentoEmpresa
    );
    setFiltroProfissionais(novosProfissionais);
  };

  const changeValue = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className="popup">
      <div className="popup__container">
        <div className="close-container" onClick={() => setOpenPopup(false)}>
          <i className="fa-solid fa-xmark"></i>
        </div>
        <h2 className="popup__titulo">
          Solicite orçamento à outros profissionais simultaneamente!
        </h2>
        <Filtro filtros={filtros} itensFiltrado={itensFiltrado} />
        <h3 className="popup__subtitulo">
          Profissionais recomandados para você.
        </h3>
        <div className="cards__profissionais">{listaCardsProfissionais}</div>

        <div className="input-box">
          <label for="input" className="input-label">
            Escreva sua mensagem
          </label>
          <div>
            <input
              type="text"
              id="input"
              className="input-text"
              placeholder="Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
              value={value}
              onChange={changeValue}
            />
            <i className="fa-solid fa-pencil"></i>
          </div>
        </div>
      </div>
    </div>
  );
}

export default PopupOrcamentoSimultaneo;

</code>```

If necessary, here is the Card Component:

```<code>import React, { useState } from "react";
import "./card.css";

function Card(props) {
  let nomeEmpresa = props.dadosProfissionais.nomeEmpresa;
  let segmento = props.dadosProfissionais.segmento;
  let valorMinimo = props.dadosProfissionais.valorMinimo;
  let cidade = props.dadosProfissionais.cidade;
  let estado = props.dadosProfissionais.estado;
  let idProfissional = props.dadosProfissionais.idProfissional;
  let imagemVitrine = props.dadosProfissionais.imagemMarketplace;

  let nomeArquivo = imagemVitrine ? imagemVitrine : "no-image.png";

  /*  const imagemVitrineProfissional = require(`../../../../../fileContents/imagensVitrineProfissional/${imagemVitrine}`); */

  const [checkedState, setCheckedState] = useState({});

  const handleOnChange = (e) => {
    setCheckedState((p) => ({ ...p, [e.target.name]: e.target.checked }));
  };

  return (
    <>
      <div className="card__profissional" key={idProfissional}>
        <div className="card__header">
          <img
            className="card-imagem"
            src={imagemVitrine}
            alt={`${nomeEmpresa}`}
          />
        </div>
        <div className="card__body">
          <h2 className="card__titulo">{nomeEmpresa}</h2>
          <span className="tag">{cidade}</span>
          <div className="checkbox">
            <label className="checkbox-label">
              Solicitar Orçamento
              <input
                type="checkbox"
                className="checkbox-input"
                name={nomeEmpresa}
                value={nomeEmpresa}
                checked={checkedState[nomeEmpresa] || false}
                onChange={handleOnChange}
              />
              <span className="checkmark"></span>
            </label>
          </div>
        </div>
      </div>
      <button type="submit" className="botao-orcamento">
        Solicitar Orçamento (
        {Object.keys(checkedState).filter((i) => checkedState[i]).length})
      </button>
    </>
  );
}

export default Card;

</code>```

Here is the Error showed in the console:

OBS: I didn't use the .map to call the Cards, but I would like to use in the filter Component.
Notice that I could call the API in the Card component, and it worked allright. But when I try to call the API to the Filter Component, I'm getting an full white page in the browser.

Anyone can help me?

I allready try to do the same as the Card Component, but it didn't work. Maybe the difference is because in the Card, I didn't use the .map function, and in the Filter I want to use.

Body:
I'm trying to call an API to my filter component, which it will shows in the component a Carrousel with all the filters (located at the API). The filter component will be called in a father component (where it will be the filter functions).
OBS: in the father component it is called also Cards Components (the cards that will be show depending on the filter selection).
Something like that:

Here are the codes:

Filter Component

import React from "react";
import Carrousel from "react-elastic-carousel";
import "./filtro.css";

function Filtro({ filtros, itensFiltrado }) {

  const breakPoints = [
    { width: 1, itemsToShow: 1, pagination: false },
    { width: 600, itemsToShow: 2, pagination: false },
    { width: 860, itemsToShow: 5, pagination: false },
    { width: 1100, itemsToShow: 5, pagination: false },
    { width: 1700, itemsToShow: 6, pagination: false },
  ];

  return (

      <Carrousel breakPoints={breakPoints}>
        {filtros.map((filtro, id) => {
          return (
             itensFiltrado(filtro)}
            >

{filtro}

              <input type="radio" className="input-radio" name="teste" />

          );
        })}
      </Carrousel>

  );
}

export default Filtro;

Father component

import React, { useEffect, useState } from "react";
import "./popupOrcamentoSimultaneo.css";
/* import profissionais from "../../../../utils/data-popupOrcamento"; */
import Filtro from "./Filtro";
import Card from "./Card";

import api from "../../../../api";

const allFilters = [
  "Todos",
  ...new Set(api.map((profissional) => profissional.segmento)),
];

function PopupOrcamentoSimultaneo({ setOpenPopup, checkedState }) {

  /* const [cardProfissionais, setCardProfissionais] = useState(profissionais); */
  const [Profissionais, setProfissionais] = useState([]);
  const [filtroProfissionais, setFiltroProfissionais] = useState([]);
  const [filtros, setFiltros] = useState(allFilters);
  const [value, setValue] = useState(
    "'Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
  );

  useEffect(() => {
    api.get("profissionais/listarTodos/").then(({ data }) => {
      setProfissionais(data);
      setFiltroProfissionais(data);
    });
  }, []);

  let cardsProfissionais = Profissionais;
  let listaCardsProfissionais = [];

  for (let i = 0; i < cardsProfissionais.length; i++) {
    listaCardsProfissionais.push(
      <Card dadosProfissionais={cardsProfissionais[i]} />
    );
  }

  const itensFiltrado = (segmentoEmpresa) => {
    if (segmentoEmpresa === "Todos") {
      setFiltroProfissionais(api);
      return;
    }

    const novosProfissionais = api.filter(
      (profissional) => profissional.segmento === segmentoEmpresa
    );
    setFiltroProfissionais(novosProfissionais);
  };

  const changeValue = (e) => {
    setValue(e.target.value);
  };

  return (

 setOpenPopup(false)}>

          Solicite orçamento à outros profissionais simultaneamente!

        <Filtro filtros={filtros} itensFiltrado={itensFiltrado} />

          Profissionais recomandados para você.

{listaCardsProfissionais}

            Escreva sua mensagem

            <input
              type="text"
              id="input"
              className="input-text"
              placeholder="Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
              value={value}
              onChange={changeValue}
            />

  );
}

export default PopupOrcamentoSimultaneo;

If necessary, here is the Card Component:

import React, { useState } from "react";
import "./card.css";

function Card(props) {
  let nomeEmpresa = props.dadosProfissionais.nomeEmpresa;
  let segmento = props.dadosProfissionais.segmento;
  let valorMinimo = props.dadosProfissionais.valorMinimo;
  let cidade = props.dadosProfissionais.cidade;
  let estado = props.dadosProfissionais.estado;
  let idProfissional = props.dadosProfissionais.idProfissional;
  let imagemVitrine = props.dadosProfissionais.imagemMarketplace;

  let nomeArquivo = imagemVitrine ? imagemVitrine : "no-image.png";

  /*  const imagemVitrineProfissional = require(`../../../../../fileContents/imagensVitrineProfissional/${imagemVitrine}`); */

  const [checkedState, setCheckedState] = useState({});

  const handleOnChange = (e) => {
    setCheckedState((p) => ({ ...p, [e.target.name]: e.target.checked }));
  };

  return (
    <>

          <img
            className="card-imagem"
            src={imagemVitrine}
            alt={`${nomeEmpresa}`}
          />

{nomeEmpresa}

          {cidade}

              Solicitar Orçamento
              <input
                type="checkbox"
                className="checkbox-input"
                name={nomeEmpresa}
                value={nomeEmpresa}
                checked={checkedState[nomeEmpresa] || false}
                onChange={handleOnChange}
              />

      <button type="submit" className="botao-orcamento">
        Solicitar Orçamento (
        {Object.keys(checkedState).filter((i) => checkedState[i]).length})
      </button>
    </>
  );
}

export default Card;

Here is the Error showed in the console:

OBS: I didn't use the .map to call the Cards, but I would like to use in the filter Component.
Notice that I could call the API in the Card component, and it worked allright. But when I try to call the API to the Filter Component, I'm getting an full white page in the browser.

Anyone can help me?

I allready try to do the same as the Card Component, but it didn't work. Maybe the difference is because in the Card, I didn't use the .map function, and in the Filter I want to use.


问:
Why Testing Controller not working with @RunWith(SpringRunner.class) & @WebMvcTest annotation?
I am getting the below error when I try to run my controller test. Please can you let me know what I am missing? Why should I add the @ContextConfiguration or @SpringBootTest ?

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

```<code>@Controller
public class BasketController {

@Autowired
private BasketService basketService;

@GetMapping(value="/baskets/{basketId}")
public ResponseEntity<BasketDto> getBasket(@PathVariable("basketId") UUID basketId){
    Basket basket = basketService.getBasket(basketId);
    BasketDto dto = toBasketDto(basket);
    ResponseEntity response = ResponseEntity.status(HttpStatus.OK).body(dto);
    return response;
}

private BasketDto toBasketDto(Basket basket){
    BasketDto dto = new BasketDto(basket.getBasketId(), basket.getItems());
    return dto;
}
</code>```

}

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(BasketController.class)
public class BasketControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BasketService basketService;

    @Test
    public void testGetItemsInBasketSuccessfully() throws Exception {
        UUID basketId = UUID.randomUUID();
        String URI = "/api/baskets/" + basketId;
        Basket mockBasket = new Basket(basketId);

        Mockito.when(basketService.getBasket(basketId)).thenReturn(mockBasket);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI).accept(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        String actualJson = result.getResponse().getContentAsString();
        System.out.println(actualJson);

    }
}
</code>```

Body:
I am getting the below error when I try to run my controller test. Please can you let me know what I am missing? Why should I add the @ContextConfiguration or @SpringBootTest ?

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

@Controller
public class BasketController {

@Autowired
private BasketService basketService;

@GetMapping(value="/baskets/{basketId}")
public ResponseEntity<BasketDto> getBasket(@PathVariable("basketId") UUID basketId){
    Basket basket = basketService.getBasket(basketId);
    BasketDto dto = toBasketDto(basket);
    ResponseEntity response = ResponseEntity.status(HttpStatus.OK).body(dto);
    return response;
}

private BasketDto toBasketDto(Basket basket){
    BasketDto dto = new BasketDto(basket.getBasketId(), basket.getItems());
    return dto;
}

}

@RunWith(SpringRunner.class)
@WebMvcTest(BasketController.class)
public class BasketControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BasketService basketService;

    @Test
    public void testGetItemsInBasketSuccessfully() throws Exception {
        UUID basketId = UUID.randomUUID();
        String URI = "/api/baskets/" + basketId;
        Basket mockBasket = new Basket(basketId);

        Mockito.when(basketService.getBasket(basketId)).thenReturn(mockBasket);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI).accept(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        String actualJson = result.getResponse().getContentAsString();
        System.out.println(actualJson);

    }
}


问:
Image URL on fastreport
Good evening,

Is there a way to display an image via url in fastreport? I have tried several solutions from the internet but to no avail

I tried on filelink but without success, the version is 4

Title: Image URL on fastreport


问:
File pickup from ftp directory
I have deployed an application in CloudHub with the FTP connector at the event source. It picks up the file whenever a file is dropped in the FTP directory. If I deploy application 0.1v and 2 workers, and a file arrives from the FTP directory, how should the application react?

Anyone could explain the above scenario?

Title: File pickup from ftp directory


问:
Why may a class trying to change a value in a friendly class's field be triggernig an error?
So I've been learning how friendly classes work, and I created two classes, both being friendly to one another. Howewer, as soon as I write a method to modify a value in another class's field, I get a compilator error, and Visual Studio refuses to elaborate on how to fix it. Here is the code:

```<code>#include <iostream>
#include <cstring>
using namespace std;
class Human;
class Apple;

class Human
{
public:
    Human();
    Human(int bitepower, string& name);
    void BiteApple(Apple& other)
     {
        other.weight -= this->bitepower;
    }

    void Print()
    {
        cout << "Имя = " << this->name << " Сила укуса = " << this->bitepower << " id = " << this->id << endl;
    }
    ~Human();
private:
    friend Apple;
    int bitepower;
    string name;
    int id;
    static int num;
};
Human::Human()
{
    bitepower = 0;
    num++;
    id = num;
    name = string("Unidentified " + id);
}
Human::Human(int test, string& name)
{
    this->bitepower = test;
    num++;
    id = num;
    this->name = name;
}
int Human::num = 0;
Human::~Human()
{
}

class Apple
{
public:
    Apple();
    Apple(int weight);
    void Print()
    {
        cout << "Apple id = " << this->id << " Weight = " << this->weight << endl;
    }
    ~Apple();

private:
    friend Human;
    int weight;
    static int num;
    int id;
};

Apple::Apple()
{
    weight = 0;
    num++;
    id = num;
}
Apple::Apple(int weight)
{
    this->weight = weight;
    num++;
    id = num;
}
int Apple::num = 0;
Apple::~Apple()
{
}

int main()
{
    //Apple apple1(80);
    //Human egor(20, "Егор");
    //egor.Print();
    //apple1.Print();
    //egor.BiteApple(apple1);
    //egor.Print();
    //apple1.Print();

    return 0;
}
</code>```

And this is the exact method that causes everything to stop working:

```<code>void BiteApple(Apple& other)
     {
        other.weight -= this->bitepower;
    }
</code>```

After I've localised the problem, I've tried moving the announcements of the classes around, and outlining the very function to be friendly, but to no effect. I just can't seem to find the answer nowhere.

Here is the exact error I get:enter image description here

This reads as: Compilation error occured. Continue and load the last succsessfully built version?

I have also tried moving the declaration of Apple class below the declaration of Human class as suggested, but it had no effect. I  would be grateful to be advised if this can be solved without creating a header file as I have not learned this yet, and if not, I'll need to learn file structure and return to friendly classes later.

Body:
So I've been learning how friendly classes work, and I created two classes, both being friendly to one another. Howewer, as soon as I write a method to modify a value in another class's field, I get a compilator error, and Visual Studio refuses to elaborate on how to fix it. Here is the code:

#include <iostream>
#include <cstring>
using namespace std;
class Human;
class Apple;

class Human
{
public:
    Human();
    Human(int bitepower, string& name);
    void BiteApple(Apple& other)
     {
        other.weight -= this->bitepower;
    }

    void Print()
    {
        cout << "Имя = " << this->name << " Сила укуса = " << this->bitepower << " id = " << this->id << endl;
    }
    ~Human();
private:
    friend Apple;
    int bitepower;
    string name;
    int id;
    static int num;
};
Human::Human()
{
    bitepower = 0;
    num++;
    id = num;
    name = string("Unidentified " + id);
}
Human::Human(int test, string& name)
{
    this->bitepower = test;
    num++;
    id = num;
    this->name = name;
}
int Human::num = 0;
Human::~Human()
{
}

class Apple
{
public:
    Apple();
    Apple(int weight);
    void Print()
    {
        cout << "Apple id = " << this->id << " Weight = " << this->weight << endl;
    }
    ~Apple();

private:
    friend Human;
    int weight;
    static int num;
    int id;
};

Apple::Apple()
{
    weight = 0;
    num++;
    id = num;
}
Apple::Apple(int weight)
{
    this->weight = weight;
    num++;
    id = num;
}
int Apple::num = 0;
Apple::~Apple()
{
}

int main()
{
    //Apple apple1(80);
    //Human egor(20, "Егор");
    //egor.Print();
    //apple1.Print();
    //egor.BiteApple(apple1);
    //egor.Print();
    //apple1.Print();

    return 0;
}

And this is the exact method that causes everything to stop working:

void BiteApple(Apple& other)
     {
        other.weight -= this->bitepower;
    }

After I've localised the problem, I've tried moving the announcements of the classes around, and outlining the very function to be friendly, but to no effect. I just can't seem to find the answer nowhere.

Here is the exact error I get:enter image description here

This reads as: Compilation error occured. Continue and load the last succsessfully built version?

I have also tried moving the declaration of Apple class below the declaration of Human class as suggested, but it had no effect. I  would be grateful to be advised if this can be solved without creating a header file as I have not learned this yet, and if not, I'll need to learn file structure and return to friendly classes later.


问:
android random keeps generating the same int sequence
i'm having a well known problem in android which is generating random numbers. the problem is that i need to generate 20 random numbers between 1 and 905 every time a screen is loaded. and if i use kotlin random it keeps generating the same sequence even if i'm closing and reopen the app. and java random and secure random generates different sequence only if i'm closing and reopening the app. but i want to have different sequences even if i dont close the app and open it again.
i know it has been asked before but my problem is that i tried every solution and its the same results.
i would appreciate the help if anyone knows what the hell is wrong.

here are the solutions i used:

1.

```<code>val randomIndex: List<Int> = List(20){
    java.util.Random().nextInt(905) + 1
}
</code>```

```<code>val randomIndex: MutableSet<Int> = remember{ mutableSetOf() }

while (randomIndex.size < 20){
    randomIndex.add(java.util.Random().nextInt(905) + 1)
}
</code>```

```<code>val randomIndex: List<Int> = (0..905).toList.shuffled(Random).subList(0,20)
</code>```

i'm using jetpack compose and kotlin so ignore all the mutable state and remembers. also where ever you see Random i used all java Random, SecureRandom and kotlin Random and the problem i discussed persists.
i also tried initializing Random out of loop on the second code i put here and still it does the same thing.

EDIT:
thought i mentioned these here aswell. i'm using kolin 1.6.10 and my compile sdk for android is 33. i'm also trying the app on 2 different phones with android 8 and 11.

EDIT2:
@Tenfout04 suggested to put my indexes outside of my composable so this is what i did inside of my viewmodel:

```<code>var pokemonIndex: List<Int> = mutableStateListOf()

init {
    pokemonIndex = List(20){
        java.util.Random().nextInt(905)+1
    }
}
</code>```

and in my composable:

```<code>val viewModel: PokemonGameViewModel = hiltViewModel()
val randomIndex = viewModel.pokemonIndex
</code>```

another thing i tried in my viewmodel is:

```<code>val pokemonIndex: MutableState<List<Int>>
get() = mutableStateOf(
    List(20){
        java.util.Random().nextInt(905)+1
    }
)
</code>```

results are the same :(

Body:
i'm having a well known problem in android which is generating random numbers. the problem is that i need to generate 20 random numbers between 1 and 905 every time a screen is loaded. and if i use kotlin random it keeps generating the same sequence even if i'm closing and reopen the app. and java random and secure random generates different sequence only if i'm closing and reopening the app. but i want to have different sequences even if i dont close the app and open it again.
i know it has been asked before but my problem is that i tried every solution and its the same results.
i would appreciate the help if anyone knows what the hell is wrong.

here are the solutions i used:

1.

val randomIndex: List<Int> = List(20){
    java.util.Random().nextInt(905) + 1
}

val randomIndex: MutableSet<Int> = remember{ mutableSetOf() }

while (randomIndex.size < 20){
    randomIndex.add(java.util.Random().nextInt(905) + 1)
}

val randomIndex: List<Int> = (0..905).toList.shuffled(Random).subList(0,20)

i'm using jetpack compose and kotlin so ignore all the mutable state and remembers. also where ever you see Random i used all java Random, SecureRandom and kotlin Random and the problem i discussed persists.
i also tried initializing Random out of loop on the second code i put here and still it does the same thing.

EDIT:
thought i mentioned these here aswell. i'm using kolin 1.6.10 and my compile sdk for android is 33. i'm also trying the app on 2 different phones with android 8 and 11.

EDIT2:
@Tenfout04 suggested to put my indexes outside of my composable so this is what i did inside of my viewmodel:

var pokemonIndex: List<Int> = mutableStateListOf()

init {
    pokemonIndex = List(20){
        java.util.Random().nextInt(905)+1
    }
}

and in my composable:

val viewModel: PokemonGameViewModel = hiltViewModel()
val randomIndex = viewModel.pokemonIndex

another thing i tried in my viewmodel is:

val pokemonIndex: MutableState<List<Int>>
get() = mutableStateOf(
    List(20){
        java.util.Random().nextInt(905)+1
    }
)

results are the same :(


问:
Save Edit button then disabled readonly metabox
Hello I am just starting out with php and I have managed to get a repeatable metabox and managed to add a 'Save' button which saves the input meta data to the database which works, how can I change the fields to disabled readonly when the 'Save' button is pressed, and then the 'Save' button becomes 'Edit' which when pressed the fields are editable and the button becomes 'Save'? any help will be appreciated

metabox

```<code>add_action( 'wp_ajax_handle_Inventory_in_db', 'handle_Inventory_in_db' );

function mdr_add_meta_boxes() {
    add_meta_box( 'mdrinventory-group', 'Inventory', 'Repeatable_meta_box_display', 'rvs_video', 'normal', 'high');
}

function Repeatable_meta_box_display() {
    global $post;
    global $wpdb;
    $sql="SELECT * FROM $wpdb->postmeta WHERE post_id = '".$post->ID."' AND meta_key='inventory_group'";
    $allData = $wpdb->get_results($wpdb->prepare($sql));
     wp_nonce_field( 'mdr_repeatable_meta_box_nonce', 'mdr_repeatable_meta_box_nonce' );
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function( $ ){
        $( '#add-row' ).on('click', function() {
            var row='';
            var data = {
                    'post_id':'<?=$post->ID?>',
                    'action': 'handle_Inventory_in_db',
                    'command': 'add_new_blank_row_in_db',
                }
                $.post(ajaxurl, data, function(resp){
                   row=resp;
                  $('#dynamic-rows').append(row);
                });
            return false;
        });

        $('body' ).on('click','.update-row',function() {
            var meta_id=$(this).attr('data-uid');
                var data = {
                    'meta_id': meta_id,
                    'serial': $("#serial_"+meta_id).val(),
                    'barcode':$("#barcode_"+meta_id).val(),
                    'action': 'handle_Inventory_in_db',
                    'command': 'update_row',
                }
                $.post(ajaxurl, data, function(resp){
                    console.log(resp);
                });
             $(this).val('Update');
            return false;
        });

        $('body' ).on('click','.remove-row',function() {
            var meta_id=$(this).attr('data-uid');
                var data = {
                    'meta_id': meta_id,
                    'action': 'handle_Inventory_in_db',
                    'command': 'remove_row',
                }
                $.post(ajaxurl, data, function(resp){
                    console.log(resp);
                });
            $(this).parents('tr').remove();

            return false;
        });
    });
  </script>
<table id="repeatable-fieldset-one" width="100%" class="wp-list-table widefat fixed striped table-view-list">
<thead>
  <tr>
    <th>Serial No.</th>
    <th>Barcode No.</th>
  </tr>
 </thead>
  <tbody id="dynamic-rows">
    <?php
     if ( $allData ) :
      foreach ($allData as $singleRow) {
        $save_btn_label= $singleRow->meta_value==''?'Save':'Update';
        $meta_value = unserialize( $singleRow->meta_value);
    ?>
    <tr>
      <td width="15%"><input type="text" id="serial_<?=$singleRow->meta_id;?>"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();" value="<?php if($meta_value['serial'] != '') echo esc_attr($meta_value['serial']); ?>" /></td>
      <td width="70%"><input type="text" id="barcode_<?=$singleRow->meta_id;?>" placeholder="Barcode" value="<?php if($meta_value['barcode'] != '') echo esc_attr($meta_value['barcode']); ?>" /></td>
      <td width="15%"><input data-uid="<?=$singleRow->meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="<?=$save_btn_label;?>"></td>
      <td width="15%"><a data-uid="<?=$singleRow->meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
    </tr>
    <?php
    }

    else :
    // insert a blank row
    $meta_id=add_post_meta( $post->ID, 'inventory_group', '', false ); //Add new meta to table and store id in $uid
    ?>
     <tr>
      <td width="15%"><input type="text" id="serial_<?=$meta_id;?>"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
      <td width="70%"><input type="text" id="barcode_<?=$meta_id;?>" placeholder="Barcode"/></td>
      <td width="15%"><input data-uid="<?=$meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
      <td width="15%"><a data-uid="<?=$meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
    </tr>

    <?php endif; ?>
  </tbody>
</table>
<p><a id="add-row" class="button" href="#">Add Inventory</a></p>
 <?php
}

function handle_Inventory_in_db()
{
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$conditions = array( 'meta_id' => $_POST['meta_id'] );

switch ($_POST['command']) {
    case 'add_new_blank_row_in_db':
      $meta_id=add_post_meta( $_POST['post_id'], 'inventory_group', null, false );
    $row='<tr>
      <td width="15%"><input type="text" id="serial_'.$meta_id.'"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
      <td width="70%"><input type="text" id="barcode_'.$meta_id.'" placeholder="Barcode"/></td>
      <td width="15%"><input data-uid="'.$meta_id.'" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
      <td width="15%"><a data-uid="'.$meta_id.'" class="button remove-row" href="#1">Remove</a></td>
    </tr>';
    echo $row;
    break;

    case 'update_row':
      $serial=$_POST['serial'];
      $barcode=$_POST['barcode'];
      $meta_value=serialize(array('serial'=> $serial,'barcode'=>$barcode));
      $data=array(
        'meta_value'=>$meta_value,
      );
      $result = $wpdb->update( $table_name,$data, $conditions );
      echo $response=$result?"The row successfully updated":"There was an error updating the row";
    break;

    case 'remove_row':
    $result = $wpdb->delete( $table_name, $conditions );
    echo $response=$result?"The row successfully deleted":"There was an error deleting the row";
    break;

  default:
   echo "Silence is golden";
    break;
}
  wp_die();
} ``

</code>```

Body:
Hello I am just starting out with php and I have managed to get a repeatable metabox and managed to add a 'Save' button which saves the input meta data to the database which works, how can I change the fields to disabled readonly when the 'Save' button is pressed, and then the 'Save' button becomes 'Edit' which when pressed the fields are editable and the button becomes 'Save'? any help will be appreciated

metabox

add_action( 'wp_ajax_handle_Inventory_in_db', 'handle_Inventory_in_db' );

function mdr_add_meta_boxes() {
    add_meta_box( 'mdrinventory-group', 'Inventory', 'Repeatable_meta_box_display', 'rvs_video', 'normal', 'high');
}

function Repeatable_meta_box_display() {
    global $post;
    global $wpdb;
    $sql="SELECT * FROM $wpdb->postmeta WHERE post_id = '".$post->ID."' AND meta_key='inventory_group'";
    $allData = $wpdb->get_results($wpdb->prepare($sql));
     wp_nonce_field( 'mdr_repeatable_meta_box_nonce', 'mdr_repeatable_meta_box_nonce' );
    ?>

    Serial No.
    Barcode No.

    <?php
     if ( $allData ) :
      foreach ($allData as $singleRow) {
        $save_btn_label= $singleRow->meta_value==''?'Save':'Update';
        $meta_value = unserialize( $singleRow->meta_value);
    ?>

      <input type="text" id="serial_<?=$singleRow->meta_id;?>"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();" value="<?php if($meta_value['serial'] != '') echo esc_attr($meta_value['serial']); ?>" />
      <input type="text" id="barcode_<?=$singleRow->meta_id;?>" placeholder="Barcode" value="<?php if($meta_value['barcode'] != '') echo esc_attr($meta_value['barcode']); ?>" />
      <input data-uid="<?=$singleRow->meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="<?=$save_btn_label;?>">
      <a data-uid="<?=$singleRow->meta_id;?>" class="button remove-row" href="#1">Remove

    <?php
    }

    else :
    // insert a blank row
    $meta_id=add_post_meta( $post->ID, 'inventory_group', '', false ); //Add new meta to table and store id in $uid
    ?>

      <input type="text" id="serial_<?=$meta_id;?>"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/>
      <input type="text" id="barcode_<?=$meta_id;?>" placeholder="Barcode"/>
      <input data-uid="<?=$meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="Save">
      <a data-uid="<?=$meta_id;?>" class="button remove-row" href="#1">Remove

    <?php endif; ?>

Add Inventory

 <?php
}

function handle_Inventory_in_db()
{
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$conditions = array( 'meta_id' => $_POST['meta_id'] );

switch ($_POST['command']) {
    case 'add_new_blank_row_in_db':
      $meta_id=add_post_meta( $_POST['post_id'], 'inventory_group', null, false );
    $row='

      <input type="text" id="serial_'.$meta_id.'"  placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/>
      <input type="text" id="barcode_'.$meta_id.'" placeholder="Barcode"/>
      <input data-uid="'.$meta_id.'" type="button" class="update-row mdr_bk_btn1" value="Save">
      Remove

';
    echo $row;
    break;

    case 'update_row':
      $serial=$_POST['serial'];
      $barcode=$_POST['barcode'];
      $meta_value=serialize(array('serial'=> $serial,'barcode'=>$barcode));
      $data=array(
        'meta_value'=>$meta_value,
      );
      $result = $wpdb->update( $table_name,$data, $conditions );
      echo $response=$result?"The row successfully updated":"There was an error updating the row";
    break;

    case 'remove_row':
    $result = $wpdb->delete( $table_name, $conditions );
    echo $response=$result?"The row successfully deleted":"There was an error deleting the row";
    break;

  default:
   echo "Silence is golden";
    break;
}
  wp_die();
} ``