问:
How to convert JSON to CSV format and store in a variable
I have a link that opens up JSON data in the browser, but unfortunately I have no clue how to read it. Is there a way to convert this data using JavaScript in CSV format and save it in JavaScript file?

The data looks like:

```<code>{
  "count": 2,
  "items": [{
    "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
    "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China\u2019s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store\u2019s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309201303",
    "timestamp": 1326439500,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "2388575404943858468"
  }, {
    "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
    "description": "SHANGHAI \u2013 Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309198933",
    "timestamp": 1326439320,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "16209851193593872066"
  }]
}
</code>```

The closest I could find was: Convert JSON format to CSV format for MS Excel

But it downloads in a CSV file, I store it in a variable, the whole converted data.

Also would like to know how to change escape characters: '\u2019' back to normal.

I tried this code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>JSON to CSV</title>
  <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    var json3 = {
      "count": 2,
      "items": [{
          "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
          "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
          "link": "http://wik.io/info/US/309201303",
          "timestamp": 1326439500,
          "image": null,
          "embed": null,
          "language": null,
          "user": null,
          "user_image": null,
          "user_link": null,
          "user_id": null,
          "geo": null,
          "source": "wikio",
          "favicon": "http://wikio.com/favicon.ico",
          "type": "blogs",
          "domain": "wik.io",
          "id": "2388575404943858468"
        },
        {
          "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
          "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
          "link": "http://wik.io/info/US/309198933",
          "timestamp": 1326439320,
          "image": null,
          "embed": null,
          "language": null,
          "user": null,
          "user_image": null,
          "user_link": null,
          "user_id": null,
          "geo": null,
          "source": "wikio",
          "favicon": "http://wikio.com/favicon.ico",
          "type": "blogs",
          "domain": "wik.io",
          "id": "16209851193593872066"
        }
      ]
    }
    //var objJson = JSON.parse(json3.items);

    DownloadJSON2CSV(json3.items);

    function DownloadJSON2CSV(objArray) {
      var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

      var str = '';

      for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
          line += array[i][index] + ',';
        }

        line.slice(0, line.Length - 1);

        str += line + '\r\n';
      }
      $('div').html(str);
    }
  </script>

</head>

<body>
  <div></div>
</body>

</html>
</code>```

But it doesn't seem to work. Can someone please help?

答:
I found the accepted answer extremely useful but needed my solution to work with unstructured json objects.

I have modified the accepted answer to work with an array of unstructured objects of varying size and schema.

Input:

```<code>[
  {
    "name": "Item 1",
    "color": "Green",
    "sizerange": {
      "max": "X-Large",
      "min": "X-Small"
    }
  },
  {
    "name": "Item 2",
    "color": "Green",
    "size": "X-Large",
    "owner": {
      "name": "Bill",
      "address": {
        "line1": "1 test st",
        "suburb": "testville"
      }
    }
  },
  {
    "name": "Item 3",
    "color": "Green",
    "sizes": [
      "X-Large",
      "Large",
      "Small"
    ]
  }
]
</code>```

Output:

```<code>"name","color","sizerange.max","sizerange.min","size","owner.name","owner.address.line1","owner.address.suburb","sizes.0","sizes.1","sizes.2"
"Item 1","Green","X-Large","X-Small","","","","","","",""
"Item 2","Green","","","X-Large","Bill","1 test st","testville","","",""
"Item 3","Green","","","","","","","X-Large","Large","Small"
</code>```

// JSON to CSV Converter

//https://www.codegrepper.com/code-examples/javascript/javascript+array+to+csv+string
function objectToCSVRow(dataObject) {
  var dataArray = [];
  for (var o in dataObject) {
    var innerValue = typeof dataObject[o] == 'undefined' ? '' : dataObject[o].toString();
    var result = innerValue.replace(/"/g, '""');
    result = '"' + result + '"';
    dataArray.push(result);
  }
  return dataArray.join(',') + '\r\n';
}

//https://stackoverflow.com/a/6491621
function findbystring(o, s) {
  s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  s = s.replace(/^\./, ''); // strip a leading dot
  var a = s.split('.');
  for (var i = 0, n = a.length; i < n; ++i) {
    var k = a[i];
    if (k in o) {
      o = o[k];
    } else {
      return;
    }
  }
  return o;
}

function pushUnique(arr, item) {
  if (item != "" && !arr.includes(item))
    arr.push(item);
}

function getLabels(name, item, labels) {
  if (typeof item == 'object') {
    for (var index in item) {
      thisname = ""
      if (name != "") thisname = name + ".";
      thisname += index;
      getLabels(thisname, item[index], labels);
    }
  } else {
    pushUnique(labels, name);
  }
}

function ConvertToCSV(objArray) {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  var str = '';

  var labels = [];

  for (var i = 0; i < array.length; i++) {
    getLabels("", array[i], labels);

  }

  str += objectToCSVRow(labels);

  for (var i = 0; i < array.length; i++) {

    var line = [];
    for (var label in labels) {

      line.push(findbystring(array[i], labels[label]));

    }

    str += objectToCSVRow(line);
  }

  return str;
}

// Example
$(document).ready(function() {

  // Create Object
  var items = [{
      name: "Item 1",
      color: "Green",
      sizerange: {
        max: "X-Large",
        min: "X-Small"
      }
    },
    {
      name: "Item 2",
      color: "Green",
      size: "X-Large",
      owner: {
        name: "Bill",
        address: {
          line1: "1 test st",
          suburb: "testville"
        }
      }
    },
    {
      name: "Item 3",
      color: "Green",
      sizes: ["X-Large", "Large", "Small"]
    }
  ];

  // Convert Object to JSON
  var jsonObject = JSON.stringify(items, null, 2);

  // Display JSON
  $('#json').text(jsonObject);

  // Convert JSON to CSV & Display CSV
  $('#csv').text(ConvertToCSV(jsonObject));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>Demo - Covnert JSON to CSV</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>

  <script type="text/javascript">
  </script>
</head>

<body>
  <h1>
    JSON</h1>
  <pre id="json">```

    CSV

```
</body>

</html></code>```

Body:
I have a link that opens up JSON data in the browser, but unfortunately I have no clue how to read it. Is there a way to convert this data using JavaScript in CSV format and save it in JavaScript file?

The data looks like:

{
  "count": 2,
  "items": [{
    "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
    "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China\u2019s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store\u2019s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309201303",
    "timestamp": 1326439500,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "2388575404943858468"
  }, {
    "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
    "description": "SHANGHAI \u2013 Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309198933",
    "timestamp": 1326439320,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "16209851193593872066"
  }]
}

The closest I could find was: Convert JSON format to CSV format for MS Excel

But it downloads in a CSV file, I store it in a variable, the whole converted data.

Also would like to know how to change escape characters: '\u2019' back to normal.

I tried this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>JSON to CSV</title>

But it doesn't seem to work. Can someone please help?

Body:
I found the accepted answer extremely useful but needed my solution to work with unstructured json objects.

I have modified the accepted answer to work with an array of unstructured objects of varying size and schema.

Input:

[
  {
    "name": "Item 1",
    "color": "Green",
    "sizerange": {
      "max": "X-Large",
      "min": "X-Small"
    }
  },
  {
    "name": "Item 2",
    "color": "Green",
    "size": "X-Large",
    "owner": {
      "name": "Bill",
      "address": {
        "line1": "1 test st",
        "suburb": "testville"
      }
    }
  },
  {
    "name": "Item 3",
    "color": "Green",
    "sizes": [
      "X-Large",
      "Large",
      "Small"
    ]
  }
]

Output:

"name","color","sizerange.max","sizerange.min","size","owner.name","owner.address.line1","owner.address.suburb","sizes.0","sizes.1","sizes.2"
"Item 1","Green","X-Large","X-Small","","","","","","",""
"Item 2","Green","","","X-Large","Bill","1 test st","testville","","",""
"Item 3","Green","","","","","","","X-Large","Large","Small"

// JSON to CSV Converter

//https://www.codegrepper.com/code-examples/javascript/javascript+array+to+csv+string
function objectToCSVRow(dataObject) {
  var dataArray = [];
  for (var o in dataObject) {
    var innerValue = typeof dataObject[o] == 'undefined' ? '' : dataObject[o].toString();
    var result = innerValue.replace(/"/g, '""');
    result = '"' + result + '"';
    dataArray.push(result);
  }
  return dataArray.join(',') + '\r\n';
}

//https://stackoverflow.com/a/6491621
function findbystring(o, s) {
  s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  s = s.replace(/^\./, ''); // strip a leading dot
  var a = s.split('.');
  for (var i = 0, n = a.length; i < n; ++i) {
    var k = a[i];
    if (k in o) {
      o = o[k];
    } else {
      return;
    }
  }
  return o;
}

function pushUnique(arr, item) {
  if (item != "" && !arr.includes(item))
    arr.push(item);
}

function getLabels(name, item, labels) {
  if (typeof item == 'object') {
    for (var index in item) {
      thisname = ""
      if (name != "") thisname = name + ".";
      thisname += index;
      getLabels(thisname, item[index], labels);
    }
  } else {
    pushUnique(labels, name);
  }
}

function ConvertToCSV(objArray) {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  var str = '';

  var labels = [];

  for (var i = 0; i < array.length; i++) {
    getLabels("", array[i], labels);

  }

  str += objectToCSVRow(labels);

  for (var i = 0; i < array.length; i++) {

    var line = [];
    for (var label in labels) {

      line.push(findbystring(array[i], labels[label]));

    }

    str += objectToCSVRow(line);
  }

  return str;
}

// Example
$(document).ready(function() {

  // Create Object
  var items = [{
      name: "Item 1",
      color: "Green",
      sizerange: {
        max: "X-Large",
        min: "X-Small"
      }
    },
    {
      name: "Item 2",
      color: "Green",
      size: "X-Large",
      owner: {
        name: "Bill",
        address: {
          line1: "1 test st",
          suburb: "testville"
        }
      }
    },
    {
      name: "Item 3",
      color: "Green",
      sizes: ["X-Large", "Large", "Small"]
    }
  ];

  // Convert Object to JSON
  var jsonObject = JSON.stringify(items, null, 2);

  // Display JSON
  $('#json').text(jsonObject);

  // Convert JSON to CSV & Display CSV
  $('#csv').text(ConvertToCSV(jsonObject));
});

<html>

<head>
  <title>Demo - Covnert JSON to CSV</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>

  <script type="text/javascript">
  </script>
</head>

<body>
  <h1>
    JSON</h1>
  <pre id="json"></pre>
  <h1>
    CSV</h1>
  <pre id="csv"></pre>
</body>

</html>


来源: stackexchange

问:
Check if PySaprk column values exists in another dataframe column values
I'm trying to figure out the condition to check if the values of one PySpark dataframe exist in another PySpark dataframe, and if so extract the value and compare again. I was thinking of doing a multiple withColumn() with a when() function.

For example my two dataframes can be something like:

df1
| id    | value |
| ----- | ----  |
| hello | 1111  |
| world | 2222  |

df2
| id     | value |
| ------ | ----  |
| hello  | 1111  |
| world  | 3333  |
| people | 2222  |
```
<p>And the result I wish to obtain is to check first if the value of <code>df1.id</code> exists in <code>df2.id</code> and if true return me the <code>df2.value</code>, for example I was trying something like:</p>
```df1 = df1.withColumn("df2_value", when(df1.id == df2.id, df2.value))
```
<p>So I get something like:</p>
<pre class="lang-none prettyprint-override"><code>df1
| id    | value | df2_value |
| ----- | ----  | --------- |
| hello | 1111  | 1111      |
| world | 2222  | 3333      |
</code>```

So that now I can do another check between these two value columns in the df1 dataframe, and return a boolean column (1or 0) in a new dataframe.

The result I wish to get would be something like:

df3
| id    | value | df2_value | match |
| ----- | ----  | --------- | ----- |
| hello | 1111  | 1111      | 1     |
| world | 2222  | 3333      | 0     |
```

答:
Left join df1 with df2 on id after prefixing all df2 columns except id with df2_*:

```<code>from pyspark.sql import functions as F

df1 = spark.createDataFrame([("hello", 1111), ("world", 2222)], ["id", "value"])
df2 = spark.createDataFrame([("hello", 1111), ("world", 3333), ("people", 2222)], ["id", "value"])

df = df1.join(
    df2.select("id", *[F.col(c).alias(f"df2_{c}") for c in df2.columns if c != 'id']),
    ["id"],
    "left"
)
</code>```

Then using functools.reduce you can construct a boolean expression to check if columns match in the 2 dataframes like this:

```<code>from functools import reduce

check_expr = reduce(
    lambda acc, x: acc & (F.col(x) == F.col(f"df2_{x}")),
    [c for c in df1.columns if c != 'id'],
    F.lit(True)
)

df.withColumn("match", check_expr.cast("int")).show()
#+-----+-----+---------+-----+
#|   id|value|df2_value|match|
#+-----+-----+---------+-----+
#|hello| 1111|     1111|    1|
#|world| 2222|     3333|    0|
#+-----+-----+---------+-----+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to figure out the condition to check if the values of one PySpark dataframe exist in another PySpark dataframe, and if so extract the value and compare again. I was thinking of doing a multiple withColumn() with a when() function.

For example my two dataframes can be something like:

df1
| id    | value |
| ----- | ----  |
| hello | 1111  |
| world | 2222  |

df2
| id     | value |
| ------ | ----  |
| hello  | 1111  |
| world  | 3333  |
| people | 2222  |

And the result I wish to obtain is to check first if the value of df1.id exists in df2.id and if true return me the df2.value, for example I was trying something like:

df1 = df1.withColumn("df2_value", when(df1.id == df2.id, df2.value))

So I get something like:

df1
| id    | value | df2_value |
| ----- | ----  | --------- |
| hello | 1111  | 1111      |
| world | 2222  | 3333      |

So that now I can do another check between these two value columns in the df1 dataframe, and return a boolean column (1or 0) in a new dataframe.

The result I wish to get would be something like:

df3
| id    | value | df2_value | match |
| ----- | ----  | --------- | ----- |
| hello | 1111  | 1111      | 1     |
| world | 2222  | 3333      | 0     |

Body:
Left join df1 with df2 on id after prefixing all df2 columns except id with df2_*:

from pyspark.sql import functions as F

df1 = spark.createDataFrame([("hello", 1111), ("world", 2222)], ["id", "value"])
df2 = spark.createDataFrame([("hello", 1111), ("world", 3333), ("people", 2222)], ["id", "value"])

df = df1.join(
    df2.select("id", *[F.col(c).alias(f"df2_{c}") for c in df2.columns if c != 'id']),
    ["id"],
    "left"
)

Then using functools.reduce you can construct a boolean expression to check if columns match in the 2 dataframes like this:

from functools import reduce

check_expr = reduce(
    lambda acc, x: acc & (F.col(x) == F.col(f"df2_{x}")),
    [c for c in df1.columns if c != 'id'],
    F.lit(True)
)

df.withColumn("match", check_expr.cast("int")).show()
#+-----+-----+---------+-----+
#|   id|value|df2_value|match|
#+-----+-----+---------+-----+
#|hello| 1111|     1111|    1|
#|world| 2222|     3333|    0|
#+-----+-----+---------+-----+


问:
Angular Object Array Sorting
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);```
</div>
</div>
</p>
<p>getting output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]
```
<p>How I can get the Expected output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]
```

答:
You could check for numbers and move number to top and sort by numbers or by string.

let test = [{ Code: '16', Color: "Red" }, { Code: '54', Color: "Yellow" }, { Code: '24', Color: "Yellow" }, { Code: '1600', Color: "Blue" }, { Code: '16a', Color: "Green" }, { Code: '22', Color: "Yellow" }, { Code: '23', Color: "Yellow" }];

test.sort(({ Code: a }, { Code: b }) =>
    isFinite(b) - isFinite(a) ||
    a - b ||
    a.localeCompare(b)
);
console.log(test);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Angular Object Array Sorting

Body:
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);

getting output as

[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]

How I can get the Expected output as

[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]

Body:
You could check for numbers and move number to top and sort by numbers or by string.

let test = [{ Code: '16', Color: "Red" }, { Code: '54', Color: "Yellow" }, { Code: '24', Color: "Yellow" }, { Code: '1600', Color: "Blue" }, { Code: '16a', Color: "Green" }, { Code: '22', Color: "Yellow" }, { Code: '23', Color: "Yellow" }];

test.sort(({ Code: a }, { Code: b }) =>
    isFinite(b) - isFinite(a) ||
    a - b ||
    a.localeCompare(b)
);
console.log(test);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to use pybind11 in omnet++ projects like veins
please suggest how to use pybind11 in omnet++ projects like veins. I am getting compile time errors. I can see so many posibilities with python being used in omnet++ simulation tool.

I tried this link Windows/Cygwin - Can't use pybind11 - make error for setting flags but not was successful.

I am using Instant veins vm.

答:
Just added

Include directories /usr/include/pybind11, /usr/include/python2.7 in paths and symbols

In Omnet++ Makemake options --> link added python2.7

It works...

Thanks SO.


问:
Why my react native radio button work very slowly when load another component?
Below you can see my react native page code. Here I am going to change content when click the radio button named 'x' and 'y'.

```<code>const Signup = () => {

         const [type, setType] = React.useState('')

            const data = [
                {
                  label: 'x'
                 },
                 {
                  label: 'y'
                 }
                ];

            const radioHandler = (e) => {

                let value = e.label;
               if(value==="Orgaization"){
                console.log(value)
                setType(value)
               }
               else{
                console.log(value)
                setType(value)
               }

            };

            return(
           <View style={styles.container}>

                    <RadioButtonRN
                    style={{padding:0,width: 'auto'}}
                    data={data}
                    selectedBtn={(e) => radioHandler(e)}

                   {type==='x' && x()}
                   {type==='y' && y()}

                    </View>
        )

      const x = ()=>{
        return(//Here some components)

      const y = ()=>{
          return(//Here some components)
</code>```

This code work without any error.
But when I going to load x and y components radio button work very slowly how can I fix this issue.

答:
Remove all of the console logs

run on real  device
or cancel other tasks for emulator to run fast

Body:
Below you can see my react native page code. Here I am going to change content when click the radio button named 'x' and 'y'.

const Signup = () => {

         const [type, setType] = React.useState('')

            const data = [
                {
                  label: 'x'
                 },
                 {
                  label: 'y'
                 }
                ];

            const radioHandler = (e) => {

                let value = e.label;
               if(value==="Orgaization"){
                console.log(value)
                setType(value)
               }
               else{
                console.log(value)
                setType(value)
               }

            };

            return(
           <View style={styles.container}>

                    <RadioButtonRN
                    style={{padding:0,width: 'auto'}}
                    data={data}
                    selectedBtn={(e) => radioHandler(e)}

                   {type==='x' && x()}
                   {type==='y' && y()}

                    </View>
        )

      const x = ()=>{
        return(//Here some components)

      const y = ()=>{
          return(//Here some components)

This code work without any error.
But when I going to load x and y components radio button work very slowly how can I fix this issue.


问:
not secure in another pc but in my aws rdp is installed
Here the problem I'm get aws windows server 2019 and install xampp for easy use and tried to install ssl and virtual host 443 and he install i follow so many way to install ssl but in my own browser is not secure suddenly open rdp and install chrome want see he secure how in rdp secure outside not working</p>

答: You can connect to windows Server through any linux instance (such as your NAT Instance in public subnet) in same VPC by SSH tunnel.</p>


问:
How do you retrieve the latest value from an array in MQL4?
How would I retrieve the latest value stored in an array in mql4? I need it so that the latest order open price is shown when I run my code below.</p>
```<code>double OrderOpenPriceBuyArray[];
int count = 0;

ArraySetAsSeries(OrderOpenPriceBuyArray,True);

for(double n = 0; n < OrdersTotal(); n++){
if(OrderSelect(n,SELECT_BY_POS) && OrderType() == OP_BUY && OrderSymbol() == Symbol()
){
if(OrderOpenPrice() != OrderOpenPriceBuyArray[count]){
OrderOpenPriceBuyArray[count] = OrderOpenPrice();
++count;
}}
}

Print(OrderOpenPriceBuyArray[0]);
</code>```

答:
The method that you are using to retrieve the latest opening price is fundamentally flawed and will not work. Why not use:</p>
```<code>datetime  latestBuyOrderOpen;
double    latestBuyOrderPrice;

void OnTick()
{
   for(int n=OrdersTotal()-1; n>=0; n--)
   {
      if(OrderSelect(n, SELECT_BY_POS) && OrderType()==OP_BUY && OrderSymbol()==Symbol())
      {
         if(OrderOpenTime()>latestBuyOrderOpen)
         {
            latestBuyOrderOpen=OrderOpenTime();
            latestBuyOrderPrice=OrderOpenPrice();
         }
      }
   }
   Comment(latestBuyOrderPrice);
}
</code>```

Body:
How would I retrieve the latest value stored in an array in mql4? I need it so that the latest order open price is shown when I run my code below.

double OrderOpenPriceBuyArray[];
int count = 0;

ArraySetAsSeries(OrderOpenPriceBuyArray,True);

for(double n = 0; n < OrdersTotal(); n++){
if(OrderSelect(n,SELECT_BY_POS) && OrderType() == OP_BUY && OrderSymbol() == Symbol()
){
if(OrderOpenPrice() != OrderOpenPriceBuyArray[count]){
OrderOpenPriceBuyArray[count] = OrderOpenPrice();
++count;
}}
}

Print(OrderOpenPriceBuyArray[0]);

Body:
The method that you are using to retrieve the latest opening price is fundamentally flawed and will not work. Why not use:

datetime  latestBuyOrderOpen;
double    latestBuyOrderPrice;

void OnTick()
{
   for(int n=OrdersTotal()-1; n>=0; n--)
   {
      if(OrderSelect(n, SELECT_BY_POS) && OrderType()==OP_BUY && OrderSymbol()==Symbol())
      {
         if(OrderOpenTime()>latestBuyOrderOpen)
         {
            latestBuyOrderOpen=OrderOpenTime();
            latestBuyOrderPrice=OrderOpenPrice();
         }
      }
   }
   Comment(latestBuyOrderPrice);
}


问:
cassandra is logging timeout of node URGENT_MESSAGES
URGENT_MESSAGES-[no-channel] dropping message of type GOSSIP_DIGEST_SYN whose timeout expired before reaching the network</p>

答:
Thank you for your message. Yesterday we solved the Problem.
The reason was a "dead node" oviously leaved form a change in the kubernetes deployment.
So, allways look out for dead nodes, after changing something in the cluster deployment.</p>


问:
extract 7z file on S3 using node.js
can someone suggest npm package for extract 7z file for node.js.

I can see some npm package available for ZIP file but that does not work for the 7Z file.

I'm basically looking to extract 7z password protect file on S3 and read the data from 7z file.

答:
Give node-7z package a try:

npm i node-7z
```
<pre class="lang-js prettyprint-override"><code>import Seven from 'node-7z'

// myStream is a Readable stream
const myStream = Seven.extractFull('./archive.7z', './output/dir/', {
  $progress: true
})

myStream.on('data', function (data) {
  doStuffWith(data) //? { status: 'extracted', file: 'extracted/file.txt" }
})

myStream.on('progress', function (progress) {
  doStuffWith(progress) //? { percent: 67, fileCount: 5, file: undefinded }
})

myStream.on('end', function () {
    // end of the operation, get the number of folders involved in the operation
  myStream.info.get('Folders') //? '4'
})

myStream.on('error', (err) => handleError(err))
</code>```

It also supports password feature you were requesting mate.

Title: extract 7z file on S3 using node.js

Body:
Give node-7z package a try:

npm i node-7z

import Seven from 'node-7z'

// myStream is a Readable stream
const myStream = Seven.extractFull('./archive.7z', './output/dir/', {
  $progress: true
})

myStream.on('data', function (data) {
  doStuffWith(data) //? { status: 'extracted', file: 'extracted/file.txt" }
})

myStream.on('progress', function (progress) {
  doStuffWith(progress) //? { percent: 67, fileCount: 5, file: undefinded }
})

myStream.on('end', function () {
    // end of the operation, get the number of folders involved in the operation
  myStream.info.get('Folders') //? '4'
})

myStream.on('error', (err) => handleError(err))

It also supports password feature you were requesting mate.


问:
ERROR: ORA-01830: date format picture ends before converting entire input string
```<code>AND trunc(ITOH.CREATION_DATE) = NVL(:CREATION_DATE,ITOH.CREATION_DATE)
</code>```

Here Iam Explicitly trying to pass date using 'CREATION_DATE' parameter

The CREATION_DATE will be coming in 'MM-dd-yyyy' format and the IOTH.CREATION_DATE is a timestamp.

Please help me.

答:
The way you put it,

```<code>AND TRUNC(ITOH.CREATION_DATE) = NVL(TO_DATE(:CREATION_DATE, 'mm-dd-yyyy'),
                                    TRUNC(ITOH.CREATION_DATE)
                                   )
</code>```

(don't forget TRUNC within NVL, otherwise you might get unexpected result)

Body:
AND trunc(ITOH.CREATION_DATE) = NVL(:CREATION_DATE,ITOH.CREATION_DATE)

Here Iam Explicitly trying to pass date using 'CREATION_DATE' parameter

The CREATION_DATE will be coming in 'MM-dd-yyyy' format and the IOTH.CREATION_DATE is a timestamp.

Please help me.

Body:
The way you put it,

AND TRUNC(ITOH.CREATION_DATE) = NVL(TO_DATE(:CREATION_DATE, 'mm-dd-yyyy'),
                                    TRUNC(ITOH.CREATION_DATE)
                                   )

(don't forget TRUNC within NVL, otherwise you might get unexpected result)


问:
How to fix java.net.SocketException: Broken pipe?
I am using apache commons http client to call url using post method to post the parameters and it is throwing the below error rarely.

```<code>java.net.SocketException: Broken pipe
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
        at org.apache.commons.httpclient.methods.ByteArrayRequestEntity.writeRequest(ByteArrayRequestEntity.java:90)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
</code>```

Can someone suggest what is causing this Exception and how to debug it?

答:
I have implemented data downloading functionality through FTP server and found the same exception there too while resuming that download.
To resolve this exception, you will always have to disconnect from the previous session and create new instance of the Client and new connection with the server. This same approach could be helpful for HTTPClient too.</p>

OwnerDisplayName: Mani

ContentLicense: CC BY-SA 3.0

Body:
I am using apache commons http client to call url using post method to post the parameters and it is throwing the below error rarely.

java.net.SocketException: Broken pipe
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
        at org.apache.commons.httpclient.methods.ByteArrayRequestEntity.writeRequest(ByteArrayRequestEntity.java:90)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)

Can someone suggest what is causing this Exception and how to debug it?


问:
Pyarrow Unable to Recognize Map Data Type
There is some data that was stored in parquet file format that I want to read in using Dask. Unfortunately, it's not able to interpret the map data type. Is there a way to read in this data without relying on Spark? I am using pyarrow==6.0.1

Example:

```<code>import dask.dataframe as dd
df = dd.read_parquet("s3://data/part=0", engine='pyarrow')
df.compute()
</code>```

Error:

```<code>ArrowNotImplementedError: Not implemented type for Arrow list to pandas: map<string, double>
</code>```

答:
Not sure if this will work on your case (having a reproducible snippet could help), but a basic delayed wrapper might help, something like this:

@delayed
def custom_load(file_path):
    # xx could be pandas, pyarrow or something else that opens the file without a problem
    df = xx.open_file(file_path)
    ...
    return df

df = dd.from_delayed([custom_load(f) for f in list_files])
```

Body:
There is some data that was stored in parquet file format that I want to read in using Dask. Unfortunately, it's not able to interpret the map data type. Is there a way to read in this data without relying on Spark? I am using pyarrow==6.0.1

Example:

import dask.dataframe as dd
df = dd.read_parquet("s3://data/part=0", engine='pyarrow')
df.compute()

Error:

ArrowNotImplementedError: Not implemented type for Arrow list to pandas: map<string, double>


问:
Module not found: Can't resolve 'react-linkedin-login-oauth2'
I'm trying to install a 'Log in with LinkedIn' functionality into a React app. Therefore I've used npx create-react-app kekap and ran npm install nvh95/react-linkedin-login-oauth2#pull/42/head, considering the current version install of react-linkedin-login-oauth2 wasn't working. After adding the sample files as proposed in the GitHub readme as a means of testing the application can't seem to find the module.

Failed to compile.

./src/App.js
Module not found: Can't resolve 'react-linkedin-login-oauth2' in 'D:\workspaces\kekap\src'

My App.js:

```<code>import { Component } from 'react';
import { LinkedInPopUp } from 'react-linkedin-login-oauth2';

import { BrowserRouter, Route, Switch } from 'react-router-dom';

import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
        <BrowserRouter>
          <Switch >
            <Route exact path="/linkedin" component={LinkedInPopUp} />
          </Switch>
        </BrowserRouter>
        </header>
      </div>
    );
  }

}

export default App;
</code>```

package.json:

```<code>{
  "name": "kekap",
  "homepage": "/wp-content/themes/screenr/templates/build/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-linkedin-login-oauth2": "github:nvh95/react-linkedin-login-oauth2#pull/42/head",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

npm audit is giving me 82 moderate severity vulnerabilities. Fixes however switch me between versions @4.0.3 (current) and @1.1.5 (required by outdated module I'm guessing) of react-scripts.

Does anyone know how to fix this? How could I troubleshoot this further? Until now I've only followed a React course on Coursera, so I have little experience beyond what a simple Google query can solve.

Much thanks in advance!

答:
For anyone who has tried above steps.
If you still face the issue make sure you are using react 17 or above
In my case i was using react v 16, tried all these steps but wasn't able to fix the issue. But upgrading to v 17 fixed the issue..</p>

Body:
I'm trying to install a 'Log in with LinkedIn' functionality into a React app. Therefore I've used npx create-react-app kekap and ran npm install nvh95/react-linkedin-login-oauth2#pull/42/head, considering the current version install of react-linkedin-login-oauth2 wasn't working. After adding the sample files as proposed in the GitHub readme as a means of testing the application can't seem to find the module.

Failed to compile.

./src/App.js
Module not found: Can't resolve 'react-linkedin-login-oauth2' in 'D:\workspaces\kekap\src'

My App.js:

import { Component } from 'react';
import { LinkedInPopUp } from 'react-linkedin-login-oauth2';

import { BrowserRouter, Route, Switch } from 'react-router-dom';

import './App.css';

class App extends Component {
  render() {
    return (

        <BrowserRouter>
          <Switch >
            <Route exact path="/linkedin" component={LinkedInPopUp} />
          </Switch>
        </BrowserRouter>

    );
  }

}

export default App;

package.json:

{
  "name": "kekap",
  "homepage": "/wp-content/themes/screenr/templates/build/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-linkedin-login-oauth2": "github:nvh95/react-linkedin-login-oauth2#pull/42/head",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

npm audit is giving me 82 moderate severity vulnerabilities. Fixes however switch me between versions @4.0.3 (current) and @1.1.5 (required by outdated module I'm guessing) of react-scripts.

Does anyone know how to fix this? How could I troubleshoot this further? Until now I've only followed a React course on Coursera, so I have little experience beyond what a simple Google query can solve.

Much thanks in advance!


问:
ggplot2 not printing font when knit, but shows up in chunks
I am trying to create pdf reports using R Markdown.  I changed the mainfont in the YAML header and in my function for the plots to Georgia.  The text in the report is fine, and when I run the individual code chunks, I see my plot text, but when I knit the report, the plots print without any text.  Here is an example of what I have...

```<code>---
title: ''
output:
  pdf_document:
    latex_engine: xelatex
  html_document: default
  word_document: default
mainfont: Georgia
urlcolor: blue
classoption: landscape
always_allow_html: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(autodep = TRUE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(fig.dim = c(11,7))
options(digits=3)
library(dplyr)
library(ggplot2)
library(tidyr)
library(readr)
library(ggpubr)
library(gridExtra)
library(stringr)
library(tinytex)
library(knitr)
library(kableExtra)
library(cowplot)
library(reshape2)
library(extrafont)
font_import()
loadfonts(device = "win")
run_chunk <- FALSE
```

```{r data, include=FALSE}
### Create df from scratch here
measure <- c('msr1', 'msr2', 'msr3')
rate <- c(50, 70, 95)

df <- data.frame(measure, rate)
```

The Markdown text outside of the code chunks works fine.

```{r lollipop_plot,   eval=run_chunk}
lolli <- ggplot(df, aes(x=measure, y=rate)) +
  geom_segment(aes(x=measure, xend=measure, y=0, yend=rate), color='grey') +
  geom_point(size=4, alpha=0.6) +
  ylim(0, 100) +
  theme_classic() +
  theme(axis.text.x=element_text(size=12)) +
  theme(axis.text.y=element_text(size=12)) +
  xlab('') +
  ylab('Measure Percentile') +
  ggtitle('Lollipop Plot') +
  theme(axis.title.x=element_text(size=14)) +
  theme(text=element_text(family="Georgia")) +
  coord_flip() +
  geom_hline(yintercept=50) +
  theme(legend.position='bottom')

print(lolli)
```
</code>```

I know there are other similar questions, but I have not seen a solution for this issue.

答:
EDIT

The showtext package seems to perform a lot better (and system-independent) than the extrafont package which relies on very old libraries. It is on CRAN here and their self-explaining vignette can be found here.

Original answer

I had the same problem, while using TinyTeX on Windows 10 to render my R Markdown file as PDF document (the template tex file uses the Calibri font):

If I run extrafont::font_import() (as suggested in above comments), all fonts are actually skipped:

```<code>Scanning ttf files in C:\WINDOWS\Fonts ...
Extracting .afm files from .ttf files...
C:\Windows\Fonts\AGENCYB.TTF : No FontName. Skipping.
C:\Windows\Fonts\AGENCYR.TTF : No FontName. Skipping.
C:\Windows\Fonts\ALGER.TTF : No FontName. Skipping.
...
</code>```

So R still does not "know" about Calibri, hence the missing plot labels. Then I found out that it was actually due to a problem in the Rttf2pt1 R package for which a solution was provided here: https://stackoverflow.com/a/68642855/4575331. The current version of Rttf2pt1 is 1.3.9 which introduced this problem, so downgrading to 1.3.8 helps:

```<code>remotes::install_version("Rttf2pt1", version = "1.3.8")
extrafont::font_import()
</code>```

Then everything was fine after restarting R and knitting again.

Body:
I am trying to create pdf reports using R Markdown.  I changed the mainfont in the YAML header and in my function for the plots to Georgia.  The text in the report is fine, and when I run the individual code chunks, I see my plot text, but when I knit the report, the plots print without any text.  Here is an example of what I have...

---
title: ''
output:
  pdf_document:
    latex_engine: xelatex
  html_document: default
  word_document: default
mainfont: Georgia
urlcolor: blue
classoption: landscape
always_allow_html: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(autodep = TRUE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(fig.dim = c(11,7))
options(digits=3)
library(dplyr)
library(ggplot2)
library(tidyr)
library(readr)
library(ggpubr)
library(gridExtra)
library(stringr)
library(tinytex)
library(knitr)
library(kableExtra)
library(cowplot)
library(reshape2)
library(extrafont)
font_import()
loadfonts(device = "win")
run_chunk <- FALSE
```

```{r data, include=FALSE}
### Create df from scratch here
measure <- c('msr1', 'msr2', 'msr3')
rate <- c(50, 70, 95)

df <- data.frame(measure, rate)
```

The Markdown text outside of the code chunks works fine.

```{r lollipop_plot,   eval=run_chunk}
lolli <- ggplot(df, aes(x=measure, y=rate)) +
  geom_segment(aes(x=measure, xend=measure, y=0, yend=rate), color='grey') +
  geom_point(size=4, alpha=0.6) +
  ylim(0, 100) +
  theme_classic() +
  theme(axis.text.x=element_text(size=12)) +
  theme(axis.text.y=element_text(size=12)) +
  xlab('') +
  ylab('Measure Percentile') +
  ggtitle('Lollipop Plot') +
  theme(axis.title.x=element_text(size=14)) +
  theme(text=element_text(family="Georgia")) +
  coord_flip() +
  geom_hline(yintercept=50) +
  theme(legend.position='bottom')

print(lolli)
```

I know there are other similar questions, but I have not seen a solution for this issue.

Body:
EDIT

The showtext package seems to perform a lot better (and system-independent) than the extrafont package which relies on very old libraries. It is on CRAN here and their self-explaining vignette can be found here.

Original answer

I had the same problem, while using TinyTeX on Windows 10 to render my R Markdown file as PDF document (the template tex file uses the Calibri font):

If I run extrafont::font_import() (as suggested in above comments), all fonts are actually skipped:

Scanning ttf files in C:\WINDOWS\Fonts ...
Extracting .afm files from .ttf files...
C:\Windows\Fonts\AGENCYB.TTF : No FontName. Skipping.
C:\Windows\Fonts\AGENCYR.TTF : No FontName. Skipping.
C:\Windows\Fonts\ALGER.TTF : No FontName. Skipping.
...

So R still does not "know" about Calibri, hence the missing plot labels. Then I found out that it was actually due to a problem in the Rttf2pt1 R package for which a solution was provided here: https://stackoverflow.com/a/68642855/4575331. The current version of Rttf2pt1 is 1.3.9 which introduced this problem, so downgrading to 1.3.8 helps:

remotes::install_version("Rttf2pt1", version = "1.3.8")
extrafont::font_import()

Then everything was fine after restarting R and knitting again.


问:
Table align="center" doesn't seem to be working
Why would the align="center" not be working on the first table on the page below:

http://eurochlor.amaze.com/chlorinated-solvents-%28ecsa%29/about-chlorinated-solvents/facts-figures/trichloroethylene.aspx

答:
You need to set this on the  elements.

You should also use text-align: center in css, not align="center" in html.

Body:
You need to set this on the <td> elements.

You should also use text-align: center in css, not align="center" in html.


问:
Python email checker script shows only unread messages, but not ones received since the program was opened
I'm writing a program, and part of it is to check for new emails every 10 seconds. It does fine and only shows me unread messages when I start the program, but on its next loop it doesn't show newly sent messages since the program was opened. Is there some particular reason, or am I doing something wrong?

Edit: Yes, I've sent messages to the account in question after the program has started, and let it sit for a few minutes, and still get nothing

```<code>while(1):
        time.sleep(10)
        print("\n\nRefreshing....")

        rv, data = M.search(None, 'UNSEEN') #Check for new messages, which works fine the first run

        print(rv)
        print(data)
        if rv != 'OK':
            print("No messages found!")
            return

        for num in data[0].split():
            print("num: " + str(num))
            rv, data = M.fetch(num, '(RFC822)')
            if rv != 'OK':
                print("ERROR getting message", num)
                return

            msg = email.message_from_bytes(data[0][1])
            hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
            subject = str(hdr)

            print('Message: %s\n' % (subject))
            if "blabla" in subject:
                 #do stuff here
</code>```

答:
Bit late, I suppose… what you're seeing is an effect of IMAP's message numbering synchronisation.

When you open a mailbox, the server assigns numbers 1, 2, 3… to the messages, and that numbering is stable for as long as the client only uses certain commands. Most/all servers delay telling the client about new mail until they're permitted to change the numbers (and there are reasons for that). SEARCH is one of the (four) commands that keep stable numbers. Sending a NOOP before each search would solve the bug, switching from SEARCH to UID SEARCH ditto.

Body:
I'm writing a program, and part of it is to check for new emails every 10 seconds. It does fine and only shows me unread messages when I start the program, but on its next loop it doesn't show newly sent messages since the program was opened. Is there some particular reason, or am I doing something wrong?

Edit: Yes, I've sent messages to the account in question after the program has started, and let it sit for a few minutes, and still get nothing

while(1):
        time.sleep(10)
        print("\n\nRefreshing....")

        rv, data = M.search(None, 'UNSEEN') #Check for new messages, which works fine the first run

        print(rv)
        print(data)
        if rv != 'OK':
            print("No messages found!")
            return

        for num in data[0].split():
            print("num: " + str(num))
            rv, data = M.fetch(num, '(RFC822)')
            if rv != 'OK':
                print("ERROR getting message", num)
                return

            msg = email.message_from_bytes(data[0][1])
            hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
            subject = str(hdr)

            print('Message: %s\n' % (subject))
            if "blabla" in subject:
                 #do stuff here


问:
Create column from all possible combination of two columns in dataframe based on groupby in Python
I have a dataframe in like below

id
group
log

10
UU1Q
23

10
UU1Q
12

10
UU2Q
15

11
UU2Q
17

11
UU3Q
35.6

11
UU1Q
29.8

11
UU1Q
33

11
UU1Q
44

13
UU2Q
17.77

13
UU2Q
19.90

13
UU2Q
55

14
UU3Q
33

15
UU3Q
22

For Each ID and group I want to create all possible combination of log values present in the dataframe in a new column.
Desired Output

id
group
log
new_col

10
UU1Q
23
(23,23)

10
UU1Q
12
(23,12)

10
UU2Q
15
(15,15)

11
UU2Q
17
(17,17)

11
UU3Q
35.6
(35.6,35.6)

11
UU1Q
29.8
(29.8, 29.8)

11
UU1Q
33
(29.8,33)

11
UU1Q
44
(29.8,44)

11
UU1Q

(33,44)

13
UU2Q
17.77
(17.77,17.77)

13
UU2Q
19.90
(17.77,19.90)

13
UU2Q
55
(17.77,55)

13
UU2Q

(19.90,55)

14
UU3Q
33
(33,33)

15
UU3Q
22
(22,22)

I used shift function but it is only generating combinations with next matching cell. I want to get all the possible combination in each group.

dummy['new'] = dummy.groupby(['ID', 'group'])['log'].shift()

答:
This is close what need - added all combinations and if one element per group is created tuple with same values:

```<code>from  itertools import  combinations

df = (df.groupby(['id','group'])['log']
        .apply(lambda x: list(combinations(x, 2)) if len(x) > 1 else [(*x, *x)])
        .explode()
        .reset_index(name='comb'))
print (df)
    id group           comb
0   10  UU1Q   (23.0, 12.0)
1   10  UU2Q   (15.0, 15.0)
2   11  UU1Q   (29.8, 33.0)
3   11  UU1Q   (29.8, 44.0)
4   11  UU1Q   (33.0, 44.0)
5   11  UU2Q   (17.0, 17.0)
6   11  UU3Q   (35.6, 35.6)
7   13  UU2Q  (17.77, 19.9)
8   13  UU2Q  (17.77, 55.0)
9   13  UU2Q   (19.9, 55.0)
10  14  UU3Q   (33.0, 33.0)
11  15  UU3Q   (22.0, 22.0)
</code>```

Or is possible create same values tuples of first rows per ['id','group'] and join to DataFrame df1 filled by combinations:

```<code>from  itertools import  combinations

df1 = (df.groupby(['id','group'])['log']
        .apply(lambda x: list(combinations(x, 2)))
        .explode()
        .dropna()
        .reset_index(name='comb'))

df2 = df.groupby(['id','group']).head(1).copy()
df2['comb'] = df2.pop('log').map(lambda x: (x,x))

df = pd.concat([df2, df1]).sort_values(['id','group'], ignore_index=True)
print (df)
    id group            comb
0   10  UU1Q    (23.0, 23.0)
1   10  UU1Q    (23.0, 12.0)
2   10  UU2Q    (15.0, 15.0)
3   11  UU1Q    (29.8, 29.8)
4   11  UU1Q    (29.8, 33.0)
5   11  UU1Q    (29.8, 44.0)
6   11  UU1Q    (33.0, 44.0)
7   11  UU2Q    (17.0, 17.0)
8   11  UU3Q    (35.6, 35.6)
9   13  UU2Q  (17.77, 17.77)
10  13  UU2Q   (17.77, 19.9)
11  13  UU2Q   (17.77, 55.0)
12  13  UU2Q    (19.9, 55.0)
13  14  UU3Q    (33.0, 33.0)
14  15  UU3Q    (22.0, 22.0)
</code>```

Body:
This is close what need - added all combinations and if one element per group is created tuple with same values:

from  itertools import  combinations

df = (df.groupby(['id','group'])['log']
        .apply(lambda x: list(combinations(x, 2)) if len(x) > 1 else [(*x, *x)])
        .explode()
        .reset_index(name='comb'))
print (df)
    id group           comb
0   10  UU1Q   (23.0, 12.0)
1   10  UU2Q   (15.0, 15.0)
2   11  UU1Q   (29.8, 33.0)
3   11  UU1Q   (29.8, 44.0)
4   11  UU1Q   (33.0, 44.0)
5   11  UU2Q   (17.0, 17.0)
6   11  UU3Q   (35.6, 35.6)
7   13  UU2Q  (17.77, 19.9)
8   13  UU2Q  (17.77, 55.0)
9   13  UU2Q   (19.9, 55.0)
10  14  UU3Q   (33.0, 33.0)
11  15  UU3Q   (22.0, 22.0)

Or is possible create same values tuples of first rows per ['id','group'] and join to DataFrame df1 filled by combinations:

from  itertools import  combinations

df1 = (df.groupby(['id','group'])['log']
        .apply(lambda x: list(combinations(x, 2)))
        .explode()
        .dropna()
        .reset_index(name='comb'))

df2 = df.groupby(['id','group']).head(1).copy()
df2['comb'] = df2.pop('log').map(lambda x: (x,x))

df = pd.concat([df2, df1]).sort_values(['id','group'], ignore_index=True)
print (df)
    id group            comb
0   10  UU1Q    (23.0, 23.0)
1   10  UU1Q    (23.0, 12.0)
2   10  UU2Q    (15.0, 15.0)
3   11  UU1Q    (29.8, 29.8)
4   11  UU1Q    (29.8, 33.0)
5   11  UU1Q    (29.8, 44.0)
6   11  UU1Q    (33.0, 44.0)
7   11  UU2Q    (17.0, 17.0)
8   11  UU3Q    (35.6, 35.6)
9   13  UU2Q  (17.77, 17.77)
10  13  UU2Q   (17.77, 19.9)
11  13  UU2Q   (17.77, 55.0)
12  13  UU2Q    (19.9, 55.0)
13  14  UU3Q    (33.0, 33.0)
14  15  UU3Q    (22.0, 22.0)


问:
Minecraft | Spigot | Set Double or argument Decimal limit in command
I am currently working on my own currency system and am now looking for a solution to limit the decimal places in the argument to solve this problem.

Example

"/command username
4.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555565555555555555555555555555555555555555555555555555555555555555555555555551"

```<code>public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        if (sender instanceof Player) {
            Player player = (Player) sender;

            if (args.length == 0) {
                player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                player.sendMessage(Main.prefix + "§7Dein Kontostand: §a" + moneyapi.getMoney(player.getUniqueId()));
                return false;
            } else {
                Player target = Bukkit.getPlayer(args[0]);

                if (args.length == 1) {
                    player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                    return false;
                } else {
                    if (args.length == 2) {
                        if (isDouble(args[1])) {
                            if (Double.parseDouble(args[1]) >= 1) {
                                if (target != null) {
                                    if (target != player) {
                                        if (moneyapi.hasEnough(player.getUniqueId(), Double.parseDouble(args[1]))) {
                                            moneyapi.removeMoney(player.getUniqueId(), Double.parseDouble(args[1]));
                                            moneyapi.addMoney(target.getUniqueId(), Double.parseDouble(args[1]));

                                            player.sendMessage(Main.prefix + "§7Bezahlt: §a" + target.getName().toString() + "§8(§c-" + args[1] + "§8)");
                                            target.sendMessage(Main.prefix + "§7Erhalten: §c" + player.getName().toString() + "§8(§a+" + args[1] + "§8)");
                                            return true;
                                        }
                                    } else {
                                        player.sendMessage(Main.prefix + "§7Du kannst dir kein Geld senden!");
                                        return false;
                                    }
                                } else {
                                    player.sendMessage(Main.prefix + "§7Dieser Spieler ist nicht online! " + "§8(§a" + args[0] + "§8)");
                                    return false;
                                }
                            } else {
                                player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                                return false;
                            }
                        } else {
                            player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                            return false;
                        }
                    }
                }
            }
        } else {
            sender.sendMessage(Main.consoleblocker);
            return false;
        }
        return false;
    }
}
</code>```

Could you guys possibly help me with this?

答:
There is multiple way to limit the decimal when showing the value.

Number format. This is good if you want to limit with minimal and maximal amount of char for integers and fractions. Example:

```<code>NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(3);
</code>```

Then, to show value, use: nf.format(amount).

String format. Easiet way :

```<code>String.format("%.3f", amount);
</code>```

Body:
I am currently working on my own currency system and am now looking for a solution to limit the decimal places in the argument to solve this problem.

Example

"/command username
4.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555565555555555555555555555555555555555555555555555555555555555555555555555551"

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        if (sender instanceof Player) {
            Player player = (Player) sender;

            if (args.length == 0) {
                player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                player.sendMessage(Main.prefix + "§7Dein Kontostand: §a" + moneyapi.getMoney(player.getUniqueId()));
                return false;
            } else {
                Player target = Bukkit.getPlayer(args[0]);

                if (args.length == 1) {
                    player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                    return false;
                } else {
                    if (args.length == 2) {
                        if (isDouble(args[1])) {
                            if (Double.parseDouble(args[1]) >= 1) {
                                if (target != null) {
                                    if (target != player) {
                                        if (moneyapi.hasEnough(player.getUniqueId(), Double.parseDouble(args[1]))) {
                                            moneyapi.removeMoney(player.getUniqueId(), Double.parseDouble(args[1]));
                                            moneyapi.addMoney(target.getUniqueId(), Double.parseDouble(args[1]));

                                            player.sendMessage(Main.prefix + "§7Bezahlt: §a" + target.getName().toString() + "§8(§c-" + args[1] + "§8)");
                                            target.sendMessage(Main.prefix + "§7Erhalten: §c" + player.getName().toString() + "§8(§a+" + args[1] + "§8)");
                                            return true;
                                        }
                                    } else {
                                        player.sendMessage(Main.prefix + "§7Du kannst dir kein Geld senden!");
                                        return false;
                                    }
                                } else {
                                    player.sendMessage(Main.prefix + "§7Dieser Spieler ist nicht online! " + "§8(§a" + args[0] + "§8)");
                                    return false;
                                }
                            } else {
                                player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                                return false;
                            }
                        } else {
                            player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                            return false;
                        }
                    }
                }
            }
        } else {
            sender.sendMessage(Main.consoleblocker);
            return false;
        }
        return false;
    }
}

Could you guys possibly help me with this?

Body:
There is multiple way to limit the decimal when showing the value.

Number format. This is good if you want to limit with minimal and maximal amount of char for integers and fractions. Example:

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(3);

Then, to show value, use: nf.format(amount).

String format. Easiet way :

String.format("%.3f", amount);


问:
Write command to store tennis rally in memcached
Use Memcached to store the points of Roger Federer (referred as F) and Rafael Nadal (referred as N). The initial scores are 0-0.

Unix command

```<code>$ sudo apt-get update && sudo apt-get install memcached

$ add F 1 0 1
  0
  STORED
$ add N 1 0 1
  0
  STORED
</code>```

But it seems that is not exact solution.

No error message displayed

答:
For the tennis rally problem below is the solution

add F 1 0 3

0-0

add N 1 0 3

0-0

set F 1 0 5

45-15

set N 1 0 5

45-15

Body:
Use Memcached to store the points of Roger Federer (referred as F) and Rafael Nadal (referred as N). The initial scores are 0-0.

Unix command

$ sudo apt-get update && sudo apt-get install memcached

$ add F 1 0 1
  0
  STORED
$ add N 1 0 1
  0
  STORED

But it seems that is not exact solution.

No error message displayed


问:
How to change variant of typography on condition when it's text are too long
I am new to using Material UI with ReactJs, TypeScript and trying to reduce the font size of typography when its text gets too large (3 or more lines)
Here is my code snippet:-

```<code>     const x =() => {

    if(text.length > 12 )
        return "body1";
    else
        return "subtitle2";
  };

  const renderTitle = () => {
    return (
      <Typography variant= {x} textAlign="center" lineHeight={1.2}>
        {text}
      </Typography>
    );
  };
</code>```

But its given error like

```<code>Type '() => "subtitle2" | "body1"' is not assignable to type '"button" | "caption" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "inherit" | "subtitle1" | "subtitle2" | "body1" | "body2" | "overline" | undefined'.
</code>```

is there any way to change variant="body1" when the text comes in 3rd line?
Please help me

答: Try variant={x()}, because x in your case is a function.

Body:
I am new to using Material UI with ReactJs, TypeScript and trying to reduce the font size of typography when its text gets too large (3 or more lines)
Here is my code snippet:-

     const x =() => {

    if(text.length > 12 )
        return "body1";
    else
        return "subtitle2";
  };

  const renderTitle = () => {
    return (
      <Typography variant= {x} textAlign="center" lineHeight={1.2}>
        {text}
      </Typography>
    );
  };

But its given error like

Type '() => "subtitle2" | "body1"' is not assignable to type '"button" | "caption" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "inherit" | "subtitle1" | "subtitle2" | "body1" | "body2" | "overline" | undefined'.

is there any way to change variant="body1" when the text comes in 3rd line?
Please help me


问:
How to render a generated component template in React?
Suppose i have a Parent and Child component in client side, server side returns a template string like below:

<Parent name="parent"><Child>i am child</Child></Parent>
```
<p>now i need to show that inside the container in client side</p>
<pre class="lang-html prettyprint-override"><code><div id="container">{__templateplaceholder}</div>
</code>```

Does anybody know how could i render the Parent and Child component in that placeholder area? thank you.

答:
You can directly use your template string inside the tag but make sure to re render the page when the backend returns the data
You can use React.useState() function to set the template string value returned from the backend

```<code>const [templateString , setTemplateString] = React.useState('');
</code>```

wherever you recieve the data from backend in your react code add this
this line will rerender the page after updating the value of template string so that it renders properly on the client side

```<code>setTemplateString(template_string_recieved_from_backend)
</code>```

And React Function Should Look like

```<code>const App = () => {
 return (

    <div id = "container"   dangerouslySetInnerHTML={{ __html: templateString
      }}>

    </div>

 )
}
export default App;
</code>```

Body:
Suppose i have a Parent and Child component in client side, server side returns a template string like below:

<Parent name="parent"><Child>i am child</Child></Parent>

now i need to show that inside the container in client side

{__templateplaceholder}

Does anybody know how could i render the Parent and Child component in that placeholder area? thank you.

Body:
You can directly use your template string inside the tag but make sure to re render the page when the backend returns the data
You can use React.useState() function to set the template string value returned from the backend

const [templateString , setTemplateString] = React.useState('');

wherever you recieve the data from backend in your react code add this
this line will rerender the page after updating the value of template string so that it renders properly on the client side

setTemplateString(template_string_recieved_from_backend)

And React Function Should Look like

const App = () => {
 return (

    <div id = "container"   dangerouslySetInnerHTML={{ __html: templateString
      }}>

    </div>

 )
}
export default App;


问:
How to prevent Axios from encoding my request parameters?
I'm trying to pass in an API key through the URL parameters in my GET request.

However, I notice that Axios encodes the characters in my API key when sending the request. This causes the API to reject my request as it couldn't recognise my key.

How can I prevent Axios from encoding my GET parameters?

答:
In case you are using qs library (or similar encoding lib) you can also do

import qs from 'qs';

axios.get('https://foobar.com/api', {
    params,
    paramsSerializer: (params) => qs.stringify(params, { encode: false }),
});
```


问:
How to load a template from full path in the template engine TWIG
I'm wondering how to load a template from it's full path (like FILE constant give).

Actually you have to set a "root" path for template like this :

```<code>require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
   'cache' => '/path/to/compilation_cache',
));
</code>```

And then :

```<code>$template = $twig->loadTemplate('index.html');
echo $template->render(array('the' => 'variables', 'go' => 'here'));
</code>```

I want to call the loadTemplate method with a full path and not the just the name of the file.

How can i do ?

I don't want to create my own loader for such an thing..

Thanks

答:
In Symfony's (version 5.4) config add new core path to folder with your templates.

```<code>twig:
    default_path: '%kernel.project_dir%/templates'
    paths:
        '%kernel.project_dir%/src/Service/SendEmail/EmailTpl': EmailTpl
</code>```

Now you can render template.

In controller:

```<code>$this->render('@EmailTpl/bobo_reg.html.twig')
</code>```

In any other place:

```<code>$content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');
</code>```

Body:
I'm wondering how to load a template from it's full path (like FILE constant give).

Actually you have to set a "root" path for template like this :

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
   'cache' => '/path/to/compilation_cache',
));

And then :

$template = $twig->loadTemplate('index.html');
echo $template->render(array('the' => 'variables', 'go' => 'here'));

I want to call the loadTemplate method with a full path and not the just the name of the file.

How can i do ?

I don't want to create my own loader for such an thing..

Thanks

Body:
In Symfony's (version 5.4) config add new core path to folder with your templates.

twig:
    default_path: '%kernel.project_dir%/templates'
    paths:
        '%kernel.project_dir%/src/Service/SendEmail/EmailTpl': EmailTpl

Now you can render template.

In controller:

$this->render('@EmailTpl/bobo_reg.html.twig')

In any other place:

$content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');


问:
How to handle multiple custom "Catch" error messages in Powershell?
I have 3 commands inside of a Try and I want custom Catch error messages for each of them in case of an error

e.g. If the first will fail then I would like to get the following message: "Error creating a directory!"

If the second will fail then: "Copy items failed"

If the third will fail then: "Content is not created"

How can I apply that?

```<code>    Try{

        New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force

        Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force

        Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force

    }
    Catch{
        " what code do I need here?"
    }
</code>```

Thanks for your help.

答:
The answer zett42 gave is correct. Here is how you would implement it in your solution:

```<code>$errorAction = "STOP"
Try{
    $errorMsg = "New-Item failed"
    New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force -ErrorAction $errorAction
    $errorMsg = "Copy-Item failed"
    Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force -ErrorAction $errorAction
    $errorMsg = "Set-Content failed"
    Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force -ErrorAction $errorAction
}Catch{
    $errorMsg + " with error: $_"
}
</code>```

The output would be for instance:

Copy-Item failed with error: Cannot bind argument to parameter 'Path'
because it is null.

I have added the ErrorAction to make sure it stops on every error right after the execution.

Body:
I have 3 commands inside of a Try and I want custom Catch error messages for each of them in case of an error

e.g. If the first will fail then I would like to get the following message: "Error creating a directory!"

If the second will fail then: "Copy items failed"

If the third will fail then: "Content is not created"

How can I apply that?

    Try{

        New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force

        Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force

        Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force

    }
    Catch{
        " what code do I need here?"
    }

Thanks for your help.

Body:
The answer zett42 gave is correct. Here is how you would implement it in your solution:

$errorAction = "STOP"
Try{
    $errorMsg = "New-Item failed"
    New-Item -ItemType Directory -Name "Script" -Path "C:\Temp\" -Force -ErrorAction $errorAction
    $errorMsg = "Copy-Item failed"
    Copy-Item -Path $FilePath_ps1 -Destination C:\temp\script -Force -ErrorAction $errorAction
    $errorMsg = "Set-Content failed"
    Set-Content -Value "test" -Path "C:\Temp\Script\test.txt" -Force -ErrorAction $errorAction
}Catch{
    $errorMsg + " with error: $_"
}

The output would be for instance:

Copy-Item failed with error: Cannot bind argument to parameter 'Path'
because it is null.

I have added the ErrorAction to make sure it stops on every error right after the execution.


问:
EXCEL 365 - Use wildcard with the lookup_array part of the INDEX MATCH function
I am attempting to use excel INDEX MATCH with the MATCH lookup_array (refdata!$A$2:refdata!$A$150) containing a string e.g. 'AMAZON' which might be part of the MATCH lookup_value ($C2), which is a longer string e.g.''AMZNMKTPLACE AMAZON.CO AMAZON.CO.UK GBR'.

=INDEX(refdata!$A$2:refdata!$C$150,MATCH($C2,refdata!$A$2:refdata!$A$150,0),3)

Is it possible to have the MATCH lookup_array string values set to use wildcards and produce 'AMAZON' from 'AMAZON' and have this then successfully compared to (or found in?) the MATCH lookup_value which would be ''AMZNMKTPLACE AMAZON.CO AMAZON.CO.UK GBR'?

答:
I'm not sure I understand your structure, but this might work:

```<code>=INDEX(FILTER(refdata!$A$2:refdata!$C$150,ISNUMBER(FIND(refdata!$A$2:refdata!$A$150,$C2))),,3)
</code>```

It is looking for AMAZON inside of all strings in Column A and then filtering on it. It will spill if there are multiple matches, so if you don't want that, you can do:

```<code>=INDEX(FILTER(refdata!$A$2:refdata!$C$150,ISNUMBER(FIND(refdata!$A$2:refdata!$A$150,C2))),1,3)
</code>```

Body:
I'm not sure I understand your structure, but this might work:

=INDEX(FILTER(refdata!$A$2:refdata!$C$150,ISNUMBER(FIND(refdata!$A$2:refdata!$A$150,$C2))),,3)

It is looking for AMAZON inside of all strings in Column A and then filtering on it. It will spill if there are multiple matches, so if you don't want that, you can do:

=INDEX(FILTER(refdata!$A$2:refdata!$C$150,ISNUMBER(FIND(refdata!$A$2:refdata!$A$150,C2))),1,3)


问:
React-admin rendering runtime resources multiple times
I'm following this design pattern from React-admin to define the parent Team resource,
but the useEffect hook is being called 4 times on every page refresh

The context provider is just to be able to pass the Teams list to a select in the layout, if I remove it, the same problem happens

Is this expected behaviour?

```<code>const AdminEnterprise = () => {
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};

const TeamResources = () => {
  const dataProvider = useDataProvider();
  const [state, dispatch] = useReducer(teamReducer, {
    loading : true,
    teams : []
  })

  useEffect(() => {
    //This is called 4 times on page refresh
    console.log('querying user teams')
    dataProvider.getList('userTeams')
      .then(({data}) =>{
        dispatch({
          teams: data,
          selected: data[0].id,
          loading: false
        })
      })
      .catch(error => {
        dispatch({
          error: error,
          loading: false
        })
      })
  }, [])

  return (
    <TeamContext.Provider value={[state, dispatch]}>
      {state.loading? <></> : (
        <AdminUI layout={MyLayout} loginPage={CustomLoginPage} theme={myTheme}>
          <Resource name={`teams/${state.selected}/projects`} list={ProjectList} options={{label: 'Projects' }}/>
          <Resource name={`teams/${state.selected}`} />
        </AdminUI>
      )}
    </TeamContext.Provider>
  )
}
</code>```

答:
I think your authProvider or dataProvider change asynchronously. Therefore AdminContext component re-renders is again. So check it in the AdminEnterprise component.

```<code>const AdminEnterprise = () => {
  if (!authProvider || !dataProvider) return null;
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};
</code>```

Body:
I'm following this design pattern from React-admin to define the parent Team resource,
but the useEffect hook is being called 4 times on every page refresh

The context provider is just to be able to pass the Teams list to a select in the layout, if I remove it, the same problem happens

Is this expected behaviour?

const AdminEnterprise = () => {
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};

const TeamResources = () => {
  const dataProvider = useDataProvider();
  const [state, dispatch] = useReducer(teamReducer, {
    loading : true,
    teams : []
  })

  useEffect(() => {
    //This is called 4 times on page refresh
    console.log('querying user teams')
    dataProvider.getList('userTeams')
      .then(({data}) =>{
        dispatch({
          teams: data,
          selected: data[0].id,
          loading: false
        })
      })
      .catch(error => {
        dispatch({
          error: error,
          loading: false
        })
      })
  }, [])

  return (
    <TeamContext.Provider value={[state, dispatch]}>
      {state.loading? <></> : (
        <AdminUI layout={MyLayout} loginPage={CustomLoginPage} theme={myTheme}>
          <Resource name={`teams/${state.selected}/projects`} list={ProjectList} options={{label: 'Projects' }}/>
          <Resource name={`teams/${state.selected}`} />
        </AdminUI>
      )}
    </TeamContext.Provider>
  )
}

Body:
I think your authProvider or dataProvider change asynchronously. Therefore AdminContext component re-renders is again. So check it in the AdminEnterprise component.

const AdminEnterprise = () => {
  if (!authProvider || !dataProvider) return null;
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};


问:
EF CORE 2.1 HasConversion on all properties of type datetime
I previously used DateTimeKindEntityMaterializerSource (Git) to convert all DateTime to UTC when reading entities because the default was unspecified.

With EF core 2.1 the DateTimeKindEntityMaterializerSource no longer works but we can actually do this

```<code>         builder
        .Entity<ESDataQuotation>()
        .Property(e => e.CreatedDate)
        .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
</code>```

However, I have many properties of DateTime and I would like if there is a way to make the conversion for all property of type DateTime.

答:
As of EF core v6.0.0-preview6, there is a more elegant solution to register a ValueConverter globally. In this example I use a custom ISO8601 converter that converts to/from ISO8601 in UTC, always appending the Z in the end:

public class DateTimeToIso8601StringConverter : ValueConverter<DateTime, string>
{
    public DateTimeToIso8601StringConverter() : base(Serialize, Deserialize, null)
    {
    }

    static Expression<Func<string, DateTime>> Deserialize = x => DateTime.Parse(x).ToUniversalTime();
    static Expression<Func<DateTime, string>> Serialize = x => x.ToString("o", System.Globalization.CultureInfo.InvariantCulture);
}
```
<p>and inside your <code>DbContext</code> class:</p>
<pre class="lang-cs prettyprint-override"><code>protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.Properties<DateTime>().HaveConversion<DateTimeToIso8601StringConverter>();
}
</code>```

This avoids having to specify the converter for every model property individually.

Body:
I previously used DateTimeKindEntityMaterializerSource (Git) to convert all DateTime to UTC when reading entities because the default was unspecified.

With EF core 2.1 the DateTimeKindEntityMaterializerSource no longer works but we can actually do this

         builder
        .Entity<ESDataQuotation>()
        .Property(e => e.CreatedDate)
        .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));

However, I have many properties of DateTime and I would like if there is a way to make the conversion for all property of type DateTime.

Body:
As of EF core v6.0.0-preview6, there is a more elegant solution to register a ValueConverter globally. In this example I use a custom ISO8601 converter that converts to/from ISO8601 in UTC, always appending the Z in the end:

public class DateTimeToIso8601StringConverter : ValueConverter<DateTime, string>
{
    public DateTimeToIso8601StringConverter() : base(Serialize, Deserialize, null)
    {
    }

    static Expression<Func<string, DateTime>> Deserialize = x => DateTime.Parse(x).ToUniversalTime();
    static Expression<Func<DateTime, string>> Serialize = x => x.ToString("o", System.Globalization.CultureInfo.InvariantCulture);
}

and inside your DbContext class:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.Properties<DateTime>().HaveConversion<DateTimeToIso8601StringConverter>();
}

This avoids having to specify the converter for every model property individually.


问:
Error: "Cannot find reference to loads in json.py"
I am a newbie to python. I am learning the how python works with json.
After writing this code in pycharm, I am getting unresolved references at several locations.
 "Import resolves to its containing file".
"Cannot find reference to dumps in json.py "
"Cannot find reference to loads in json.py "

I am getting this error while importing json, loads() and dumps() method are called.
This is the video link from where I am learning to code python.

https://www.youtube.com/watch?v=9N6a-VLBa2I&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=44

Please help me in resolving this.

```<code> import json

# Decoding json string to python.

# This a python string that happens to be a valid json also.

people_string = '''
{
"people": [
{
"name": "Sumedha",
"phone":"0987654312"
"City": "Middletown"
},

{
"name": "Ankit",
"phone":"9999999999"
"City": "Middletown2"
},
{
"name": "Hemlata",
"phone":"9865656475"
"City": "Chandigarh"
}
]
}
'''

# loads method loads the string.
data = json.loads(people_string)

for person in data['people']:
    print(person['name'])
    del person['phone']

new_string = json.dumps(data, indent=2, sort_keys=True)
</code>```

答:
The error seems to appear when you have both JSON & pandas packages in the same python environment.

I found a cheap solution by having a separate project file for pandas & JSON so that I install the packages in different virtual environments.

Body:
I am a newbie to python. I am learning the how python works with json.
After writing this code in pycharm, I am getting unresolved references at several locations.
 "Import resolves to its containing file".
"Cannot find reference to dumps in json.py "
"Cannot find reference to loads in json.py "

I am getting this error while importing json, loads() and dumps() method are called.
This is the video link from where I am learning to code python.

https://www.youtube.com/watch?v=9N6a-VLBa2I&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=44

Please help me in resolving this.

 import json

# Decoding json string to python.

# This a python string that happens to be a valid json also.

people_string = '''
{
"people": [
{
"name": "Sumedha",
"phone":"0987654312"
"City": "Middletown"
},

{
"name": "Ankit",
"phone":"9999999999"
"City": "Middletown2"
},
{
"name": "Hemlata",
"phone":"9865656475"
"City": "Chandigarh"
}
]
}
'''

# loads method loads the string.
data = json.loads(people_string)

for person in data['people']:
    print(person['name'])
    del person['phone']

new_string = json.dumps(data, indent=2, sort_keys=True)


问:
check valid date in java
I tried to check a String input that is a valid date using the format dd/MM/yyyy like this:

```<code>String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)
</code>```

But it can't check some rules below:

```<code>Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.
</code>```

When I use input = "30/02/2022", it's legal.
I use netbeans 8.2 and jdk 1.8. Do they support some methods for checking these rules?

答:
There are two things you need to change in your formatter:

Use uuuu instead of yyyy. It's easy to try the latter, but y means "year within ERA". It doesn't know whether it's BC or AD. u means "year" including ERA information.

The default resolver style is SMART. Use .withResolverStyle(ResolverStyle.STRICT) to return a strict copy of the formatter.

Title: check valid date in java

Body:
I tried to check a String input that is a valid date using the format dd/MM/yyyy like this:

String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)

But it can't check some rules below:

Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.

When I use input = "30/02/2022", it's legal.
I use netbeans 8.2 and jdk 1.8. Do they support some methods for checking these rules?