问:
Getting failed assertion with setting brightness: Brightness.dark for darkTheme
I'm getting this error:

```<code>'package:flutter/src/material/theme_data.dart': Failed assertion: line 412 pos 12: 'colorScheme?.brightness == null || brightness == null || colorScheme!.brightness == brightness': is not true.
</code>```

I've used this brightness: Brightness.dark parameter for my dark mode without any problems until a recent update. I updated several things at once, so I'm not sure what caused the change.
Do I need to be setting up my dark mode differently now?

Current dark theme:

```<code>darkTheme: ThemeData(
           toggleableActiveColor: Colors.blue,
           visualDensity: VisualDensity.adaptivePlatformDensity,
           textTheme: _textTheme(),
           colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue).copyWith(secondary: Colors.blueAccent),
           brightness: Brightness.dark,
         ),
</code>```

答:
This is a consequence of tightening up the ThemeData constructor wrt the brightness parameter and the ColorScheme's brightness parameter in an update of Flutter. In your example the brightness of the ColorScheme is light (the default), but the ThemeData's brightness is dark.

To get your darkTheme working, you need to remove the brightness parameter and put that in the colorScheme, like so:

```<code>darkTheme: ThemeData(
            toggleableActiveColor: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
            colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue)
                .copyWith(
                    secondary: Colors.blueAccent, brightness: Brightness.dark),
          ),
</code>```

Body:
I'm getting this error:

'package:flutter/src/material/theme_data.dart': Failed assertion: line 412 pos 12: 'colorScheme?.brightness == null || brightness == null || colorScheme!.brightness == brightness': is not true.

I've used this brightness: Brightness.dark parameter for my dark mode without any problems until a recent update. I updated several things at once, so I'm not sure what caused the change.
Do I need to be setting up my dark mode differently now?

Current dark theme:

darkTheme: ThemeData(
           toggleableActiveColor: Colors.blue,
           visualDensity: VisualDensity.adaptivePlatformDensity,
           textTheme: _textTheme(),
           colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue).copyWith(secondary: Colors.blueAccent),
           brightness: Brightness.dark,
         ),

Body:
This is a consequence of tightening up the ThemeData constructor wrt the brightness parameter and the ColorScheme's brightness parameter in an update of Flutter. In your example the brightness of the ColorScheme is light (the default), but the ThemeData's brightness is dark.

To get your darkTheme working, you need to remove the brightness parameter and put that in the colorScheme, like so:

darkTheme: ThemeData(
            toggleableActiveColor: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
            colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue)
                .copyWith(
                    secondary: Colors.blueAccent, brightness: Brightness.dark),
          ),


来源: stackexchange

问:
How to run same function on multiple elements?
I created a web page with 3 counters that can be triggered separately, but I have a problem with the count function I can't use it on the 3 counters.

I manage to retrieve the index of each button but I don't know how to use it to trigger each counter separately.

can you help me to solve this problem please ?

Here is my code.

"use strict";

/* ___________________________Déclarer les variables et les fonctions______________________________ */

/* Déclaration des variables */
var item = document.querySelectorAll('.slider-item');
var str = document.querySelectorAll('.buttons--start');
var stp = document.querySelectorAll('.button--stop');
var start = 0;
var end = 0;
var diff = 0;
var timer = 0;

/* Fonction chrono */
function chrono(){
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout("chrono()", 10);
}

/* Fonction pour déclancher le chrono */
function chronoStart(i){
    start = new Date();
    chrono();
    console.log('start '+i);
}

/* Fonction pour arrêter et rénitialiser le chrono */
function chronoStop(i){
    clearTimeout(timer)
    item[i].innerHTML = "0";
    start = new Date();
    console.log('stop '+i);
}

/* Fonction qui change la couleur du background */
function changeColor(i){
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item[i].style.backgroundColor = bgColor;
}

/* ___________________________Écouter les événements__________________________________ */

/* Appeler la fonction qui déclanche le chrono lorsqu'on clique sur start*/
for (let i=0; i<item.length; i++)
{
    str[i].addEventListener('click',(e)=>{
        chronoStart(i);
    });
    //currentPos = i ;
}

/* Appeler la fonction qui arrête le chrono lorsqu'on clique sur stop*/
for (let i=0; i<item.length; i++)
{
    stp[i].addEventListener('click',(e)=>{
        chronoStop(i);
    });
}

/* Appeler la fonction qui change la couleur du background lorsque l'évenement est déclancher*/

for (let i=0; i<item.length; i++)
{
    item[i].addEventListener("click",(e)=>{
        changeColor(i);
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: Arial, sans-serif;
}

.wrapper {
    /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;
}

.slider-item {
    font-size: 120px;
    font-weight: bold;
    padding: 15px;
    background-color: yellow;
    user-select: none;
}

.buttons {
    margin-top: 15px;
    text-align: center;
}

.buttons button {
    display: inline-block;
    padding: 15px;
    font-size: 16px;
    color: #fff;
    border: none;
    outline: none;
    background-color: #000;
    cursor: pointer;
}</code>```

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

```

答:
The issue is because you have multiple instances of the same repeated HTML content yet within your logic you do not keep the relevant references to the correct elements when an event occurs.

A simpler way to achieve this would be to loop through the containing elements and find the relevant child elements to bind event handlers to, or to update the content of.

The simple version of this logic would be something like this:

"use strict";

document.querySelectorAll('.chrono-wrapper').forEach(el => {
  const container = el;
  const item = el.querySelector('.slider-item');
  const str = el.querySelector('.buttons--start');
  const stp = el.querySelector('.button--stop');

  var start = 0;
  var end = 0;
  var diff = 0;
  var timer = 0;

  function chrono() {
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout(chrono, 10);
  }

  function chronoStart() {
    start = new Date();
    chrono();
  }

  function chronoStop() {
    clearTimeout(timer)
    item.innerHTML = "0";
    start = new Date();
  }

  function changeColor(i) {
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item.style.backgroundColor = bgColor;
  }

  str.addEventListener('click', chronoStart);
  stp.addEventListener('click', chronoStop);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: Arial, sans-serif;
}

.chrono-wrapper {
  /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.slider-item {
  font-size: 120px;
  font-weight: bold;
  padding: 15px;
  background-color: yellow;
  user-select: none;
}

.buttons {
  margin-top: 15px;
  text-align: center;
}

.buttons button {
  display: inline-block;
  padding: 15px;
  font-size: 16px;
  color: #fff;
  border: none;
  outline: none;
  background-color: #000;
  cursor: pointer;
}</code>```

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

0

    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>

```

ContentLicense: CC BY-SA 4.0

Body:
I created a web page with 3 counters that can be triggered separately, but I have a problem with the count function I can't use it on the 3 counters.

I manage to retrieve the index of each button but I don't know how to use it to trigger each counter separately.

can you help me to solve this problem please ?

Here is my code.

"use strict";

/* ___________________________Déclarer les variables et les fonctions______________________________ */

/* Déclaration des variables */
var item = document.querySelectorAll('.slider-item');
var str = document.querySelectorAll('.buttons--start');
var stp = document.querySelectorAll('.button--stop');
var start = 0;
var end = 0;
var diff = 0;
var timer = 0;

/* Fonction chrono */
function chrono(){
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout("chrono()", 10);
}

/* Fonction pour déclancher le chrono */
function chronoStart(i){
    start = new Date();
    chrono();
    console.log('start '+i);
}

/* Fonction pour arrêter et rénitialiser le chrono */
function chronoStop(i){
    clearTimeout(timer)
    item[i].innerHTML = "0";
    start = new Date();
    console.log('stop '+i);
}

/* Fonction qui change la couleur du background */
function changeColor(i){
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item[i].style.backgroundColor = bgColor;
}

/* ___________________________Écouter les événements__________________________________ */

/* Appeler la fonction qui déclanche le chrono lorsqu'on clique sur start*/
for (let i=0; i<item.length; i++)
{
    str[i].addEventListener('click',(e)=>{
        chronoStart(i);
    });
    //currentPos = i ;
}

/* Appeler la fonction qui arrête le chrono lorsqu'on clique sur stop*/
for (let i=0; i<item.length; i++)
{
    stp[i].addEventListener('click',(e)=>{
        chronoStop(i);
    });
}

/* Appeler la fonction qui change la couleur du background lorsque l'évenement est déclancher*/

for (let i=0; i<item.length; i++)
{
    item[i].addEventListener("click",(e)=>{
        changeColor(i);
    });
}

body {
    font-family: Arial, sans-serif;
}

.wrapper {
    /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;
}

.slider-item {
    font-size: 120px;
    font-weight: bold;
    padding: 15px;
    background-color: yellow;
    user-select: none;
}

.buttons {
    margin-top: 15px;
    text-align: center;
}

.buttons button {
    display: inline-block;
    padding: 15px;
    font-size: 16px;
    color: #fff;
    border: none;
    outline: none;
    background-color: #000;
    cursor: pointer;
}

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

0

                <button class="buttons--start" type="button">Start</button>
                <button class="button--stop" type="button">Stop</button>

Body:
The issue is because you have multiple instances of the same repeated HTML content yet within your logic you do not keep the relevant references to the correct elements when an event occurs.

A simpler way to achieve this would be to loop through the containing elements and find the relevant child elements to bind event handlers to, or to update the content of.

The simple version of this logic would be something like this:

"use strict";

document.querySelectorAll('.chrono-wrapper').forEach(el => {
  const container = el;
  const item = el.querySelector('.slider-item');
  const str = el.querySelector('.buttons--start');
  const stp = el.querySelector('.button--stop');

  var start = 0;
  var end = 0;
  var diff = 0;
  var timer = 0;

  function chrono() {
    end = new Date();
    diff = end - start;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    item.innerHTML = sec;
    timer = setTimeout(chrono, 10);
  }

  function chronoStart() {
    start = new Date();
    chrono();
  }

  function chronoStop() {
    clearTimeout(timer)
    item.innerHTML = "0";
    start = new Date();
  }

  function changeColor(i) {
    let bgColor = '#' + Math.random().toString(16).substr(-6);
    item.style.backgroundColor = bgColor;
  }

  str.addEventListener('click', chronoStart);
  stp.addEventListener('click', chronoStop);
});

body {
  font-family: Arial, sans-serif;
}

.chrono-wrapper {
  /* display: flex;
    flex-flow: column wrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    padding: 50px; */
}

.slider {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.slider-item {
  font-size: 120px;
  font-weight: bold;
  padding: 15px;
  background-color: yellow;
  user-select: none;
}

.buttons {
  margin-top: 15px;
  text-align: center;
}

.buttons button {
  display: inline-block;
  padding: 15px;
  font-size: 16px;
  color: #fff;
  border: none;
  outline: none;
  background-color: #000;
  cursor: pointer;
}

<div class="chrono-wrapper">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>
</div>
<div class="chrono-wrapper">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>
</div>
<div class="chrono-wrapper">
  <div class="slider">
    <div class="slider-item">0</div>
  </div>
  <div class="buttons">
    <button class="buttons--start" type="button">Start</button>
    <button class="button--stop" type="button">Stop</button>
  </div>
</div>


问:
How to add optional chaining to JSON object?
I am trying to compare a value within a JSON object with a variable:

```<code>if (resp.userdetails.name == username) {
// do something
}
</code>```

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

```<code>if (resp.userdetails?.name == username)
</code>```

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

答:
Lodash is a popular javascript based library which provides 200+
functions to facilitate web development. It provides helper functions
like map, filter, invoke as well as function binding, javascript
templating, deep equality checks, creating indexes and so on. Lodash
can be used directly inside a browser and also with Node.js.

Working with objects using JavaScript can be quite challenging,
specifically if you have lots of manipulation to be done with them.
Lodash comes with lots of features that eases your work with objects.

Lodash is an open source project and you can easily contribute to the
library and add features in the form of plugins and make it available
on GitHub and in Node.js.

Syntax

_.get(object, path, [defaultValue]) Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in
its place.

Arguments

object (Object) − The object to query.

path (Array|string) − The path of the property to get.

[defaultValue] (*) − The value returned for undefined resolved values.

If you installed lodash into your project, then you can use

```<code>_.get(resp,"userdetails.name")
</code>```

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.

command to install Lodash

```<code>npm install loadash
</code>```

Eg:-

```<code>  var _ = require("lodash");

var data = [
  { userdetails: { name: "d" } },
  {},
  { userdetails: {} },
  { userdetails: { name: "d" } },
];

for (i = 0; i < data.length; i++) {
  var resp = data[i];
  if (_.get(resp, "userdetails.name") == "d") {
    //   if (resp.userdetails && resp.userdetails.name == "d") {    use without loadlash
    console.log("Success");
  } else {
    console.log("failed");
  }
}
</code>```

Here loadash is super complex. But you can use this to avoid runtime errors. Below both expressions get the same result

```<code>   resp.userdetails && resp.userdetails.name == "d"

                        ===

         _.get(resp, "userdetails.name") == "d"
</code>```

Body:
I am trying to compare a value within a JSON object with a variable:

if (resp.userdetails.name == username) {
// do something
}

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

if (resp.userdetails?.name == username)

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

Body:
Lodash is a popular javascript based library which provides 200+
functions to facilitate web development. It provides helper functions
like map, filter, invoke as well as function binding, javascript
templating, deep equality checks, creating indexes and so on. Lodash
can be used directly inside a browser and also with Node.js.

Working with objects using JavaScript can be quite challenging,
specifically if you have lots of manipulation to be done with them.
Lodash comes with lots of features that eases your work with objects.

Lodash is an open source project and you can easily contribute to the
library and add features in the form of plugins and make it available
on GitHub and in Node.js.

Syntax

_.get(object, path, [defaultValue]) Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in
its place.

Arguments

object (Object) − The object to query.

path (Array|string) − The path of the property to get.

[defaultValue] (*) − The value returned for undefined resolved values.

If you installed lodash into your project, then you can use

_.get(resp,"userdetails.name")

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.

command to install Lodash

npm install loadash

Eg:-

  var _ = require("lodash");

var data = [
  { userdetails: { name: "d" } },
  {},
  { userdetails: {} },
  { userdetails: { name: "d" } },
];

for (i = 0; i < data.length; i++) {
  var resp = data[i];
  if (_.get(resp, "userdetails.name") == "d") {
    //   if (resp.userdetails && resp.userdetails.name == "d") {    use without loadlash
    console.log("Success");
  } else {
    console.log("failed");
  }
}

Here loadash is super complex. But you can use this to avoid runtime errors. Below both expressions get the same result

   resp.userdetails && resp.userdetails.name == "d"

                        ===

         _.get(resp, "userdetails.name") == "d"


问:
Create new boolean fields based on specific terms appearing in a tokenized pandas dataframe
Looping over a list of terms to search for, I need to create a boolean field for each term according to whether or not it is present in a tokenized pandas series.

List of search terms:

```<code>terms = ['innovative', 'data', 'rf']
</code>```

Dataframe:

```<code>df = pd.DataFrame(data={'job_description': [['innovative', 'data', 'science'],
                                            ['scientist', 'have', 'a', 'masters'],
                                            ['database', 'rf', 'innovative'],
                                            ['sciencedata', 'data', 'performance']]})
</code>```

Desired output for df:

```<code>                     job_description  innovative   data     rf
0        [innovative, data, science]        True   True  False
1      [scientist, have, a, masters]       False  False  False
2         [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]        False   True  False
</code>```

Criteria:

Only exact matches should be replaced (for example, flagging for 'rf' should return True for 'rf' but False for 'performance')

each search term should get it's own field and be concatenated to the original df

What I've tried:
Failed, as it creates a boolean for each term in the series:

```<code>df['innovative'] = df['job_description'].explode().str.contains(r'innovative').groupby(level=-1).agg(list)
</code>```

Failed:

```<code>df['innovative'] = df['job_description'].str.contains('innovative').astype(int, errors='ignore')
</code>```

Failed:

```<code>df.loc[df['job_description'].str.contains(terms)] = 1
</code>```

Failed: I tried implementing what was documented here (See if item in each row of pandas series), but could not adapt it to create new fields or flag properly

Thanks for any help you can provide!

答:
Seems like you can use a nested list comprehension to evaluate if each term exists in each row and assign the list to columns in df:

```<code>df[terms] = [[any(w==term for w in lst) for term in terms] for lst in df['job_description']]
</code>```

Output:

```<code>                    job_description  innovative   data     rf
0       [innovative, data, science]        True   True  False
1     [scientist, have, a, masters]       False  False  False
2        [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]       False   True  False
</code>```

Body:
Looping over a list of terms to search for, I need to create a boolean field for each term according to whether or not it is present in a tokenized pandas series.

List of search terms:

terms = ['innovative', 'data', 'rf']

Dataframe:

df = pd.DataFrame(data={'job_description': [['innovative', 'data', 'science'],
                                            ['scientist', 'have', 'a', 'masters'],
                                            ['database', 'rf', 'innovative'],
                                            ['sciencedata', 'data', 'performance']]})

Desired output for df:

                     job_description  innovative   data     rf
0        [innovative, data, science]        True   True  False
1      [scientist, have, a, masters]       False  False  False
2         [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]        False   True  False

Criteria:

Only exact matches should be replaced (for example, flagging for 'rf' should return True for 'rf' but False for 'performance')

each search term should get it's own field and be concatenated to the original df

What I've tried:
Failed, as it creates a boolean for each term in the series:

df['innovative'] = df['job_description'].explode().str.contains(r'innovative').groupby(level=-1).agg(list)

Failed:

df['innovative'] = df['job_description'].str.contains('innovative').astype(int, errors='ignore')

Failed:

df.loc[df['job_description'].str.contains(terms)] = 1

Failed: I tried implementing what was documented here (See if item in each row of pandas series), but could not adapt it to create new fields or flag properly

Thanks for any help you can provide!

Body:
Seems like you can use a nested list comprehension to evaluate if each term exists in each row and assign the list to columns in df:

df[terms] = [[any(w==term for w in lst) for term in terms] for lst in df['job_description']]

Output:

                    job_description  innovative   data     rf
0       [innovative, data, science]        True   True  False
1     [scientist, have, a, masters]       False  False  False
2        [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]       False   True  False


问:
Opening large file (200mb) on iPhone?
want to open a large text file and then search the content of it.
I loaded the file with stringWithContentsOfFile into a NSString.
Every thing works on a 30mb file. But I am concerned what happens if I load a 200mb file, which I want to do.
Is the complete NSString in the memory? if so it wouldn't work on iPhone. is there a solution for such large files on the iPhone?</p>

答: Since the limit isn't documented the way to check would be actually profiling it on target. People may be able to give their limits here but that is totally relative. Also a good memory management scheme and design would help you avoid problems of running out of memory.</p>

ContentLicense: CC BY-SA 3.0

Title: Opening large file (200mb) on iPhone?


问:
Angular/TypeScript treats array as object and throws an Error: Cannot find a differ supporting object
My code is the following in my component, I defined this:

```<code>public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];
</code>```

In my template:

```<code>  <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
     <button class="dropdown-item" *ngFor="let format of outputFormats"
         (click)="onOutputFormatChanged(format)">{{format}}
     </button>
  </div>
</code>```

But I get the following error on init.

```<code>  ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.ngDoCheck (common.js:3323:1)
      at callHook (core.js:2536:1)
      at callHooks (core.js:2495:1)
      at executeInitAndCheckHooks (core.js:2446:1)
      at selectIndexInternal (core.js:8447:1)
      at Module.ɵɵadvance (core.js:8430:1)
      at PrintComponent_Template (print.component.html:41:48)
      at executeTemplate (core.js:9598:1)
      at refreshView (core.js:9464:1)
      at refreshComponent (core.js:10635:1)
  defaultErrorLogger @ core.js:6479
  handleError @ core.js:6527
  (anonymous) @ core.js:29723
  invoke @ zone.js:372
  run @ zone.js:134
  runOutsideAngular @ core.js:28604
  tick @ core.js:29723
  (anonymous) @ core.js:29571
  invoke @ zone.js:372
  onInvoke @ core.js:28705
  invoke @ zone.js:371
  run @ zone.js:134
  run @ core.js:28559
  next @ core.js:29570
  __tryOrUnsub @ Subscriber.js:183
  next @ Subscriber.js:122
  _next @ Subscriber.js:72
  next @ Subscriber.js:49
  next @ Subject.js:39
  emit @ core.js:25968
  checkStable @ core.js:28627
  onLeave @ core.js:28755
  onInvokeTask @ core.js:28699
  invokeTask @ zone.js:405
  runTask @ zone.js:178
  invokeTask @ zone.js:487
  invokeTask @ zone.js:1600
  globalZoneAwareCallback @ zone.js:1626
</code>```

When I did console.log(typeof this.outputFormats), it returns object. I tried to convert it to array using Array.from(this.outputFormats), Object.values(this.outputFormats) but the result is still the same, it is output is still an object.

Versions:
Angular Cli 12.1.4
TypeScript 4.3.5

Solutions that didn't work for me:

https://github.com/angular/angular/issues/6392

Angular error : Cannot find a differ supporting object '[object Object]'

Angular: Cannot find a differ supporting object '[object Object]'

答:
The issue was not related to the code that was in the question. I made a mistake in assigning enum to a property called printModes then I used that property in another ngFor in the template.
Error:

```<code>enum PrintModes {
  CurrentView = 'Current View',
  AdjustableBox = 'Adjustable Box',
  DrawnBoundary = 'Drawn Boundary'
}
</code>```

Then inside the component:

```<code>public printModes = PrintModes
</code>```

In the template:

```<code>     <div ngbDropdown class="d-block print-area-cont">
        <button class="btn btn-sm btn-outline-primary" ngbDropdownToggle>
          {{printMode}}
        </button>
        <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
          <button class="dropdown-item" *ngFor="let area of printModes"
                  (click)="onPrintAreaChanged(area)">{{area}}
          </button>
        </div>
      </div>
</code>```

The error in the forked stackblitz is correct and relevant to the mistake but in my app, it does not show the original error. Somehow, the original error made typescript misbehave.

Stackblitz error:

```<code>Error in src/app/dropdown-basic.html (7:54)
Type 'typeof PrintModes' is not assignable to type 'NgIterable<any>'.
Type 'typeof PrintModes' is not assignable to type 'Iterable<any>'.
</code>```

To fix the issue, inside the component I just need to change

```<code>public printModes = PrintModes;
</code>```

To

```<code>public printModes = Object.values(PrintModes);
</code>```

Body:
My code is the following in my component, I defined this:

public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];

In my template:

     <button class="dropdown-item" *ngFor="let format of outputFormats"
         (click)="onOutputFormatChanged(format)">{{format}}
     </button>

But I get the following error on init.

  ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.ngDoCheck (common.js:3323:1)
      at callHook (core.js:2536:1)
      at callHooks (core.js:2495:1)
      at executeInitAndCheckHooks (core.js:2446:1)
      at selectIndexInternal (core.js:8447:1)
      at Module.ɵɵadvance (core.js:8430:1)
      at PrintComponent_Template (print.component.html:41:48)
      at executeTemplate (core.js:9598:1)
      at refreshView (core.js:9464:1)
      at refreshComponent (core.js:10635:1)
  defaultErrorLogger @ core.js:6479
  handleError @ core.js:6527
  (anonymous) @ core.js:29723
  invoke @ zone.js:372
  run @ zone.js:134
  runOutsideAngular @ core.js:28604
  tick @ core.js:29723
  (anonymous) @ core.js:29571
  invoke @ zone.js:372
  onInvoke @ core.js:28705
  invoke @ zone.js:371
  run @ zone.js:134
  run @ core.js:28559
  next @ core.js:29570
  __tryOrUnsub @ Subscriber.js:183
  next @ Subscriber.js:122
  _next @ Subscriber.js:72
  next @ Subscriber.js:49
  next @ Subject.js:39
  emit @ core.js:25968
  checkStable @ core.js:28627
  onLeave @ core.js:28755
  onInvokeTask @ core.js:28699
  invokeTask @ zone.js:405
  runTask @ zone.js:178
  invokeTask @ zone.js:487
  invokeTask @ zone.js:1600
  globalZoneAwareCallback @ zone.js:1626

When I did console.log(typeof this.outputFormats), it returns object. I tried to convert it to array using Array.from(this.outputFormats), Object.values(this.outputFormats) but the result is still the same, it is output is still an object.

Versions:
Angular Cli 12.1.4
TypeScript 4.3.5

Solutions that didn't work for me:

https://github.com/angular/angular/issues/6392

Angular error : Cannot find a differ supporting object '[object Object]'

Angular: Cannot find a differ supporting object '[object Object]'

Body:
The issue was not related to the code that was in the question. I made a mistake in assigning enum to a property called printModes then I used that property in another ngFor in the template.
Error:

enum PrintModes {
  CurrentView = 'Current View',
  AdjustableBox = 'Adjustable Box',
  DrawnBoundary = 'Drawn Boundary'
}

Then inside the component:

public printModes = PrintModes

In the template:

     <div ngbDropdown class="d-block print-area-cont">
        <button class="btn btn-sm btn-outline-primary" ngbDropdownToggle>
          {{printMode}}
        </button>
        <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
          <button class="dropdown-item" *ngFor="let area of printModes"
                  (click)="onPrintAreaChanged(area)">{{area}}
          </button>
        </div>
      </div>

The error in the forked stackblitz is correct and relevant to the mistake but in my app, it does not show the original error. Somehow, the original error made typescript misbehave.

Stackblitz error:

Error in src/app/dropdown-basic.html (7:54)
Type 'typeof PrintModes' is not assignable to type 'NgIterable<any>'.
Type 'typeof PrintModes' is not assignable to type 'Iterable<any>'.

To fix the issue, inside the component I just need to change

public printModes = PrintModes;

To

public printModes = Object.values(PrintModes);


问:
How to see all device list in Firebase Analytics?
In our App we're using FCM, so Firebase analytics is also working.
However, from the dashboard, we can only see top devices.

Is there a way to see more details about devices?

All the models

All OS

Region of all the devices?
etc.

For instance, we want to verify whether some users are being tracked in analytics (by their models), but can't find anyway to do that.

答: You can see the device list in Firebase Analytics. In dashboard -> device model click in view device model. You can see list of all the devices with details.


问:
JetBrains dotTrace: confusing `await` time for async function calls
While profiling the app which is using async/await functionality with dotTrace I noticed that there is some inconsistency in await time for parent and children methods. Let's consider this example:

```<code>static async Task Main()
{
    await ChildMethod();
}

static async Task ChildMethod()
{
    await SomeOperationAsync();
}
</code>```

The interesting thing is that await time of Main method might be (or even will be) less than the await time of the ChildMethod which looks strange to me, because intuitively await time of parent should be at least as await time of child.

For real numbers let's go back to the previous example and assume that SomeOperationAsync is Task.Delay(n). So the await time of the parent will be x (x is ~n for the app targeting .NET 6.0 and <n for the app targeting .NET Core 3.1) and the await time of child will be ~2*x.

This is the screenshot from dotTrace to get an idea how it looks (for the app targeting .NET Core 3.1 and for Task.Delay(800)):

This is await time of the method Main. 567ms for await ChildMethod(), I expect this to be ~800, because
ChildMethod awaits Task.Delay(800)

This is await time of the method ChildMethod. 1140ms for await Task.Delay(800). I also expect this to be ~800.

Probably I misunderstand what await time in dotTrace is, so please correct me if so. I understand it as the time needed to schedule a task + real task execution.

Would be great if someone knew if this behavior is expected and could explain how to analyze it.

I'm using Timeline Viewer in dotTrace 2021.3.3.

UPDATE

I think I understand the first part of my confusion, namely why await time is less than time passed to Task.Delay in the Main method. This is because the timer of the task started earlier than continuation attached (internal call toAwaitUnsafeOnCompleted), therefore it awaits only for the remaining time. In my case this call takes about 300ms so that await time becomes time passed to Task.Delay - time spent on attaching continuation.

答:
I think you have misunderstood the way async/await works in dotnet. You can check it in the official Microsoft docs: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/operators/await

Basically when you execute async code (a method that returns a task) the execution of that method will occur in another thread independent of the original thread, and when you need the result of that task the original thread will wait until the completion of the second thread to retrieve the result. You can read this in their docs:

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.

see this example

```<code>public async Task<Person> Main()
{
    string name = await GetName(personId);
    int age = await GetAge(personId);
    return new Person(name, age)
}

public async Task<string> GetName(int personId)
{
    //imagine you have a HttpClient in this class that calls an API to get people info
    return _httpClient.GetAsync($"https://someurl.com/getName/{personId}");
}

public async Task<int> GetAge(int personId)
{
    return _httpClient.GetAsync($"https://someurl.com/getAge/{personId}");
}
</code>```

this way the main execution thread will create two other threads to get the info of the age and the name of that personId, and won't stop until the moment this thread needs to retrieve some information of the other two threads (the line which returns a new Person)
So what happens in your code is, as nothing uses the result of that async operation it just continues the original thread without stopping, so it's normal that the async task with the delay lasts longer than the original thread.

Body:
While profiling the app which is using async/await functionality with dotTrace I noticed that there is some inconsistency in await time for parent and children methods. Let's consider this example:

static async Task Main()
{
    await ChildMethod();
}

static async Task ChildMethod()
{
    await SomeOperationAsync();
}

The interesting thing is that await time of Main method might be (or even will be) less than the await time of the ChildMethod which looks strange to me, because intuitively await time of parent should be at least as await time of child.

For real numbers let's go back to the previous example and assume that SomeOperationAsync is Task.Delay(n). So the await time of the parent will be x (x is ~n for the app targeting .NET 6.0 and <n for the app targeting .NET Core 3.1) and the await time of child will be ~2*x.

This is the screenshot from dotTrace to get an idea how it looks (for the app targeting .NET Core 3.1 and for Task.Delay(800)):

This is await time of the method Main. 567ms for await ChildMethod(), I expect this to be ~800, because
ChildMethod awaits Task.Delay(800)

This is await time of the method ChildMethod. 1140ms for await Task.Delay(800). I also expect this to be ~800.

Probably I misunderstand what await time in dotTrace is, so please correct me if so. I understand it as the time needed to schedule a task + real task execution.

Would be great if someone knew if this behavior is expected and could explain how to analyze it.

I'm using Timeline Viewer in dotTrace 2021.3.3.

UPDATE

I think I understand the first part of my confusion, namely why await time is less than time passed to Task.Delay in the Main method. This is because the timer of the task started earlier than continuation attached (internal call toAwaitUnsafeOnCompleted), therefore it awaits only for the remaining time. In my case this call takes about 300ms so that await time becomes time passed to Task.Delay - time spent on attaching continuation.

Body:
I think you have misunderstood the way async/await works in dotnet. You can check it in the official Microsoft docs: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/operators/await

Basically when you execute async code (a method that returns a task) the execution of that method will occur in another thread independent of the original thread, and when you need the result of that task the original thread will wait until the completion of the second thread to retrieve the result. You can read this in their docs:

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.

see this example

public async Task<Person> Main()
{
    string name = await GetName(personId);
    int age = await GetAge(personId);
    return new Person(name, age)
}

public async Task<string> GetName(int personId)
{
    //imagine you have a HttpClient in this class that calls an API to get people info
    return _httpClient.GetAsync($"https://someurl.com/getName/{personId}");
}

public async Task<int> GetAge(int personId)
{
    return _httpClient.GetAsync($"https://someurl.com/getAge/{personId}");
}

this way the main execution thread will create two other threads to get the info of the age and the name of that personId, and won't stop until the moment this thread needs to retrieve some information of the other two threads (the line which returns a new Person)
So what happens in your code is, as nothing uses the result of that async operation it just continues the original thread without stopping, so it's normal that the async task with the delay lasts longer than the original thread.


问:
Unable to link Smart Home Action
I am trying to link my Smart Home action and it is not working for some specific accounts. I have traced out some logs on our server and found that our API is taking longer for some of the accounts which have more number of devices connected than usual.
So when I try to link the Smart Home Action on the Google Home App, it loads for like 10 seconds and then lands back to the previous screen without getting linked.
My question is, Is there a default timeout for the requests that Google Home is sending at my end, which I am exceeding?

答:
You can visit the following link https://developers.google.com/assistant/smarthome/develop/troubleshooting#platform_error_codes and if scroll down to the description for RESPONSE_TIMEOUT error code then it is mentioned that the timeout period for sending a response is 9 seconds for most requests.

If this is not the exact error you are facing then it might be because testing hasn't been enabled on the project. To fix in case this is the issue, AoG Console > Develop > Account Linking > Test (Upper Right Corner).

Title: Unable to link Smart Home Action


问:
Flask set local html as the src of the iframe
I am trying to understand how to render an html inside another html using iframe and flask
I have tried using the way however the server is having a weird Not Found error "GET /%3C!DOCTYPE%20html%3E%3Chtml%20lang= HTTP/1.1" 404
I have also tried using another method, as well  and in the flask

status_render = os.path.join(app.root_path, 'templates', 'status.html')

@app.route("/")
def main():
    return render_template(
        "index.html",
        status=status_render
    )
```

Using the second method I am getting this error "GET /home/dimitris/Documents/SmartHome/MobileApp/templates/status.html HTTP/1.1" 404 despite of the fact that the status.html does exist on the above path
I read online that it should be a a separate request which means another flask route, however I am not really sure that I am understanding how this should be implemented.

答:
I am not sure but there is some problem is displaying any kind of static or predefined urls of html/image in flask.
In order to achieve the desired output, follow the below steps:

In the  tag, give a value that will be used as a route in app.py. For example, let say you need to display iframe in the index.html. Then create iframe tag in index.html as:

<iframe src="/statusRoute" height="200", width="500">

Now create a route with the same name in the app.py as:

@app.route('/statusRoute')

def showStatus():

  return flask.render_template('status.html')

Ensure that the status.html is present inside the templates folder.

This would render the status.html inside an iframe of the index.html page.

Body:
I am trying to understand how to render an html inside another html using iframe and flask
I have tried using the way however the server is having a weird Not Found error "GET /%3C!DOCTYPE%20html%3E%3Chtml%20lang= HTTP/1.1" 404
I have also tried using another method, as well  and in the flask

status_render = os.path.join(app.root_path, 'templates', 'status.html')

@app.route("/")
def main():
    return render_template(
        "index.html",
        status=status_render
    )

Using the second method I am getting this error "GET /home/dimitris/Documents/SmartHome/MobileApp/templates/status.html HTTP/1.1" 404 despite of the fact that the status.html does exist on the above path
I read online that it should be a a separate request which means another flask route, however I am not really sure that I am understanding how this should be implemented.

Body:
I am not sure but there is some problem is displaying any kind of static or predefined urls of html/image in flask.
In order to achieve the desired output, follow the below steps:

In the <iframe> tag, give a value that will be used as a route in app.py. For example, let say you need to display iframe in the index.html. Then create iframe tag in index.html as:

<iframe src="/statusRoute" height="200", width="500">

Now create a route with the same name in the app.py as:

@app.route('/statusRoute')

def showStatus():

  return flask.render_template('status.html')

Ensure that the status.html is present inside the templates folder.

This would render the status.html inside an iframe of the index.html page.


问:
C++ vector member initialization
I am confused about the output in the following program about the vec in Test. Why it's a vector with size 100 instead of 1? I thought std::vector<T> var{a} is the same as std::vector<T> var = {a}.

```<code>#include <iostream>
#include <vector>

using namespace std;
struct Value {
   int a;
   int b;
};

class Test {
  public:
    std::vector<struct Value> vec{100};
};

class Test2 {
  public:
    std::vector<int> vec{100};
};

int main()
{
    Test test;
    std::cout << "test size: " << test.vec.size() << std::endl;
    Test2 test2;
    std::cout << "test2 size: " << test2.vec.size();

    return 0;
}
</code>```

Output:

```<code>test size: 100
test2 size: 1
</code>```

答:
std::vector has a constructor with a std::initializer_list<T> argument. When using an initializer list like {100} this constructor will always take priority, if it is applicable.

For a std::vector<int> the initializer {100} is compatible with std::initializer_list<int> so that constructor will be used. It will create a vector containing the collection {100} which is a single int with the value 100.

For std::vector<Value> the initializer {100} is NOT compatible with a std::initializer_list<Value> argument. Value has no converting constructor for turning an int to a Value so you cannot construct a std::initializer_list<Value> from {100}. You can verify that this conversion is not allowed with this example. The compiler will try to take a lower priority constructor instead, and will use the constructor which initializes 100 default constructed Value.

If you add a Value::Value(int) constructor or use {{100}} as the initializer for Test2 you will find that the std::vector<Value> will now only contain a single element. In both cases, the initializer list is convertible to std::initializer_list<Value> and that constructor will now be used.

Title: C++ vector member initialization

Body:
I am confused about the output in the following program about the vec in Test. Why it's a vector with size 100 instead of 1? I thought std::vector<T> var{a} is the same as std::vector<T> var = {a}.

#include <iostream>
#include <vector>

using namespace std;
struct Value {
   int a;
   int b;
};

class Test {
  public:
    std::vector<struct Value> vec{100};
};

class Test2 {
  public:
    std::vector<int> vec{100};
};

int main()
{
    Test test;
    std::cout << "test size: " << test.vec.size() << std::endl;
    Test2 test2;
    std::cout << "test2 size: " << test2.vec.size();

    return 0;
}

Output:

test size: 100
test2 size: 1


问:
Accessing data from list in python/django
I have this code:

```<code>list_of_objects = [{
"object": "a",
"object": "b",
"object": "c",
}]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)

</code>```

It only outputs:

{c}

I want to display every object on the list
like:
{a,b,c}

答:
Okay as @Mark said in comments, I was using a single dictionary and one key, because each time I declare the object's value it just overwrite the previous.

```<code>list_of_objects = [{
"object": "a",
"object": "b",
"object": "c",
}]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)
</code>```

The solution is to add curly braces to each object {object:a},{object:b},{...}

```<code>list_of_objects = [
{"object": "a"},
{"object": "b"},
{"object": "c"},
]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)
</code>```

Body:
I have this code:

list_of_objects = [{
"object": "a",
"object": "b",
"object": "c",
}]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)

It only outputs:

{c}

I want to display every object on the list
like:
{a,b,c}

Body:
Okay as @Mark said in comments, I was using a single dictionary and one key, because each time I declare the object's value it just overwrite the previous.

list_of_objects = [{
"object": "a",
"object": "b",
"object": "c",
}]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)

The solution is to add curly braces to each object {object:a},{object:b},{...}

list_of_objects = [
{"object": "a"},
{"object": "b"},
{"object": "c"},
]

list = []

for objects in list_of_object:
    list.append(objects['object'])

print(list)


问:
Prevent console window from being created in custom node.js build
I'm creating a custom build of node.js that should not show a console window to the user.

I've tried changing the linker config in the gyp file to 2 (which should set the linker flag /SUBSYSTEM:WINDOWS), but I still get a console window when I run the resulting node.exe binary.

How can I prevent the console window from appearing?

Edit: Further investigation reveals that the linker config in node.gyp is not taking effect.  The generated node.vcxproj still has <Link><SubSystem>Console</SubSystem></Link> (which is very strange to me, since adding 'UACUIAccess': 'true' in the same part of node.gyp did take effect), so the built binary is incorrectly linked.

答:
You have to change the SubSystem field value in node.exe PE optional header. The current value is 3 which is defined as Windows Console. If you change it to 2 (which is defined as Windows GUI) there would be no console window. In order to patch the executable file, you have to use utilities to change Optional Header of PE.
One example of such a tool is PE tools.

Click on Optinal Header and then change the Subsystem from 3 to 2.

That`s all.

Remember that with this change you can only run js files. You can not use interactive mode.


问:
Heroku API Client returning my data instead of user's
I created an API Client on heroku on my account (hereinafter account A), and got it to install on another account (hereinafter account B) using the OAuth flow as described here: https://devcenter.heroku.com/articles/oauth#web-application-authorization

Started the flow on account B, accepted the permissions, which triggered the callback, where I exchanged the code to get the final tokens in the expected format:

```<code>{
  "access_token":"811235f4-16d3-476e-b940-ed5dfc7d6513",
  "expires_in":7199,
  "refresh_token":"036b9495-b39d-4626-b53a-34399e7bc737",
  "token_type":"Bearer",
  "user_id":"01234567-89ab-cdef-0123-456789abcdef",
  "session_nonce":"2bf3ec81701ec291"
}
</code>```

( just to be clear, this is dummy data taken from the heroku documentation )

Up to here all was fine, however when I tried to use the token**, I got a very unexpected result: when I called the GET /apps endpoint, it returned the apps from account A instead of account B.

I can't make sense of why that would be the case, I have looked through the documentation profusely and can't find any explanation for that. If anyone has experienced this or has some explanation, I will gladly listen.

** by "use the token", I mean setting my header as Authorization: Bearer {access_token}, using python's requests library.

答:
It turns out it wasn't related to heroku directly, but instead to a very sly linux file, .netrc. To make it brief, this file can be used by applications to store tokens in plain text. The very strange thing is that the python module requests uses it by default, overwriting the header you give it with one generated from that file, if there is a match.

To check whether you have the same issue, simply check the existence of the .netrc file in your home folder, or check the logs to verify if the headers sent are the ones you expected.

Body:
I created an API Client on heroku on my account (hereinafter account A), and got it to install on another account (hereinafter account B) using the OAuth flow as described here: https://devcenter.heroku.com/articles/oauth#web-application-authorization

Started the flow on account B, accepted the permissions, which triggered the callback, where I exchanged the code to get the final tokens in the expected format:

{
  "access_token":"811235f4-16d3-476e-b940-ed5dfc7d6513",
  "expires_in":7199,
  "refresh_token":"036b9495-b39d-4626-b53a-34399e7bc737",
  "token_type":"Bearer",
  "user_id":"01234567-89ab-cdef-0123-456789abcdef",
  "session_nonce":"2bf3ec81701ec291"
}

( just to be clear, this is dummy data taken from the heroku documentation )

Up to here all was fine, however when I tried to use the token**, I got a very unexpected result: when I called the GET /apps endpoint, it returned the apps from account A instead of account B.

I can't make sense of why that would be the case, I have looked through the documentation profusely and can't find any explanation for that. If anyone has experienced this or has some explanation, I will gladly listen.

** by "use the token", I mean setting my header as Authorization: Bearer {access_token}, using python's requests library.


问:
Setting defaultContent globally across all datatables
I just updated my Datatable library from 1.10.12 to 1.11.4.

I use datatables extensively in my web app and after this upgrade I keep getting this error: https://datatables.net/manual/tech-notes/4

I understand that this warning basically wants me to set a "defaultContent": "" to my column definition.
The problem is that I would need to update over 200 tables in the webapp to fix the issue.

Is there a way to set this defaultContent:'' globally ?

I have attempted a few things, but the most recent was to extend the defaults in datatables.js with this code

```<code>$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});
</code>```

The problem with that, I think, is that in my tables I do this:

```<code> let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

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

Which overrides the previous definition of the columnDefs.

Similar to this post: datatables default render function for empty cells

So going back to what I am trying to accomplish:

Is there a way to set this defaultContent:'' globally once and have it applied to all columnDefs?

答:
One solution would be to change:

```<code> let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

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

to

```<code> let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columns: [ <----- NOTE THIS CHANGE and no defaultContent
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder
            },
            targets: columnCount++
        }
    ],
 });
</code>```

and have

```<code>$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});
</code>```

This would still involve changing part of the datatables but not every single column definition at least.

Body:
I just updated my Datatable library from 1.10.12 to 1.11.4.

I use datatables extensively in my web app and after this upgrade I keep getting this error: https://datatables.net/manual/tech-notes/4

I understand that this warning basically wants me to set a "defaultContent": "" to my column definition.
The problem is that I would need to update over 200 tables in the webapp to fix the issue.

Is there a way to set this defaultContent:'' globally ?

I have attempted a few things, but the most recent was to extend the defaults in datatables.js with this code

$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});

The problem with that, I think, is that in my tables I do this:

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

        }
    ],
 });

Which overrides the previous definition of the columnDefs.

Similar to this post: datatables default render function for empty cells

So going back to what I am trying to accomplish:

Is there a way to set this defaultContent:'' globally once and have it applied to all columnDefs?

Body:
One solution would be to change:

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

        }
    ],
 });

to

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columns: [ <----- NOTE THIS CHANGE and no defaultContent
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder
            },
            targets: columnCount++
        }
    ],
 });

and have

$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});

This would still involve changing part of the datatables but not every single column definition at least.


问:
How to inflate options menu from ponTouchEvent(MotionEvent me) in View
I have my menu which is called by clicking the button on android tablet. But I need to inflate the same menu by a click on view.

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    return true;
}
</code>```

Any suggestions?

答:
You will want to use something like:

```<code>View myView = findViewById(R.id.my_view);
registerForContextMenu(myView);
</code>```

in onCreate(...). Now when this View is clicked, it will open the context menu, and you can handle it in onCreateContextMenu(...). To be certain that this context menu has the same options as the main menu, you can inflate the same menu with the following code (though it will look like a Context Menu, not like the regular menu):

```<code>@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
}
</code>```

Body:
I have my menu which is called by clicking the button on android tablet. But I need to inflate the same menu by a click on view.

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    return true;
}

Any suggestions?

Body:
You will want to use something like:

View myView = findViewById(R.id.my_view);
registerForContextMenu(myView);

in onCreate(...). Now when this View is clicked, it will open the context menu, and you can handle it in onCreateContextMenu(...). To be certain that this context menu has the same options as the main menu, you can inflate the same menu with the following code (though it will look like a Context Menu, not like the regular menu):

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
}


问:
Align header in Dash DataTable
I want to align the header to the left in a Dash DataTable. I use the example code from the Dash DataTable documentation. Then I have implemented the style_header dicitionary as suggested in the DataTable reference.

```<code>from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)

df = pd.DataFrame(data)

app = Dash(__name__)

app.layout = dash_table.DataTable(
    data=df.to_dict('records'),
    columns=[{'id': c, 'name': c} for c in df.columns],
    style_header={'textAlign': 'left'},
    style_cell={'textAlign': 'left'}
)

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

I would expect the same behaviour as in style_cell, but it has no effect, the columns are left-aligned and the header is right-aligned. I'm not sure, but it occurs to me since I have updated to Dash 2.1.0. How can I align the header to the left?

答:
The behavior seems to be caused by these styles

```<code>.dash-table-container .dash-spreadsheet-container .dash-spreadsheet-inner .column-header-name {
    margin-left: auto;
}
</code>```

As a workaround you could add your own styles to overwrite the above

```<code>div.dash-table-container .dash-spreadsheet-container .dash-spreadsheet-inner .column-header-name {
    margin-left: unset;
}
</code>```

Title: Align header in Dash DataTable

Body:
I want to align the header to the left in a Dash DataTable. I use the example code from the Dash DataTable documentation. Then I have implemented the style_header dicitionary as suggested in the DataTable reference.

from dash import Dash, dash_table
import pandas as pd
from collections import OrderedDict

data = OrderedDict(
    [
        ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
        ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
        ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
        ("Humidity", [10, 20, 30, 40, 50, 60]),
        ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
    ]
)

df = pd.DataFrame(data)

app = Dash(__name__)

app.layout = dash_table.DataTable(
    data=df.to_dict('records'),
    columns=[{'id': c, 'name': c} for c in df.columns],
    style_header={'textAlign': 'left'},
    style_cell={'textAlign': 'left'}
)

if __name__ == '__main__':
    app.run_server(debug=True)

I would expect the same behaviour as in style_cell, but it has no effect, the columns are left-aligned and the header is right-aligned. I'm not sure, but it occurs to me since I have updated to Dash 2.1.0. How can I align the header to the left?

Body:
The behavior seems to be caused by these styles

.dash-table-container .dash-spreadsheet-container .dash-spreadsheet-inner .column-header-name {
    margin-left: auto;
}

As a workaround you could add your own styles to overwrite the above

div.dash-table-container .dash-spreadsheet-container .dash-spreadsheet-inner .column-header-name {
    margin-left: unset;
}


问:
Assembly enter protected mode and jump back to real mode
I am developing a toy OS in assembly and I have a problem when switching from protected mode back to real mode. I have successfully switched to protected mode, called the kernel that writes text to [0xb8000] video memory, returned to the caller and (probably) switched back to real mode. I am trying to use bios interrupts from real mode so I don't have to write my own device drivers.

Interrupts however don't seem to be executed after switching back to real mode.
They don't crash the system as they would in protected mode so I guess I am in real mode.

minrep.asm (bootloader)

```<code>boot.header:
[BITS 16]
[ORG 0x7c00]
mov ax, cs
mov ds, ax
xor ax, ax
mov ds, ax
cli
mov ss, ax
mov sp, 0x7c00
sti
call main
jmp $
disk.read_sectors:
reset:
xor ax,ax
int 0x13
jc reset
floppy:
xor bx,bx
mov ah,0x2
mov al, [esp+6]
mov cx,[esp+4]
mov dh,0x0
mov dl, 0x80
mov bx, ds
mov es, bx
mov bx, [esp+2]
int 0x13
jc error
mov ax, 0
ret
error:
mov ax, 1
ret
main:
push word 16 ; 16 sectors for stage2
push word 2 ; starts at sector 2
push word 0x1000 ; into 0x1000 memory buffer
call disk.read_sectors
pop bx
pop bx
pop bx
jmp 0000:0x1000
mov ax, 0
ret
footer:
times 510-($-boot.header) db 0
dw 0xAA55
</code>```

minrep_st2.asm (stage2, enter prot and back to real)

```<code>[BITS 16]
[ORG 0x1000]

stage2.header:

mov ax, cs
mov ds, ax
jmp stage2.main

stage2.main:

mov al, 'B'
mov ah, 0x0E
mov bh, 0x00
mov bl, 0x07
int 0x10

call switch_to_protected
switch_to_protected:

            [ bits 16 ]

            cli

            switch_to_pm:

                lgdt [ gdt_descriptor ]
                mov eax , cr0
                or eax , 0x1
                mov cr0 , eax
                jmp CODE_SEG:init_pm

            [ bits 32 ]

            init_pm:

                   mov ax, DATA_SEG
                mov ds, ax
                mov ss, ax
                mov es, ax
                mov fs, ax
                mov gs, ax
                mov ebp , 0x90000
                mov esp , ebp

                sti

[BITS 32]
switch_to_real:

mov [0xb8000], byte 'D'

[BITS 32]
cli

mov eax, cr0
and eax, 0x7FFFFFFF    ; clear PG bit
mov cr0, eax

xor     eax,eax         ; A convenient zero
mov     cr3,eax         ; Flush the TLB

mov eax, cr0
and eax, 0xFFFFFFFE    ; clear PE bit
mov cr0, eax

lidt [idtr]

jmp 0:continue

[BITS 16]

continue:

sti

mov al, 'C'
mov ah, 0x0E
mov bh, 0x00
mov bl, 0x07
int 0x10

hlt

GDT:

            idtr:
            dw 0x3ff
            dd 0

            gdt_start:

                gdt_null:
                    dd 0x0 ;
                    dd 0x0

                gdt_code:
                    dw 0xffff
                    dw 0x0
                    db 0x0
                    db 10011010b ; 1 st flags , type flags
                    db 11001111b ; 2 nd flags , Limit ( bits 16 -19)
                    db 0x0

                gdt_data:
                    dw 0xffff
                    dw 0x0
                    db 0x0
                    db 10010010b ; 1 st flags , type flags
                    db 11001111b ; 2 nd flags , Limit ( bits 16 -19)
                    db 0x0

                gdt_end:

                gdt_descriptor:
                    dw gdt_end - gdt_start - 1
                    dd gdt_start

            CODE_SEG equ gdt_code - gdt_start
            DATA_SEG equ gdt_data - gdt_start

stage2.footer:
times 8192-($-stage2.header) db 0
</code>```

how to compile:

```<code>nasm.bat minrep.asm -o disk_p1.bin
nasm minrep_st2.asm -o disk_p2.bin
copy /b disk_pt1.bin + disk_pt2.bin disk.img
call qemu disk.img
</code>```

EDIT:

if i only do this to go protected, then movin to 0xb800 in real mode does clear the first character but doesn't print it correctly (blank char instead of byte 'Z')

```<code>        [ bits 16 ]

    cli

    switch_to_pm:

        lgdt [ gdt_descriptor ]
        mov eax , cr0
        or eax , 0x1
        mov cr0 , eax
        jmp CODE_SEG:init_pm

    [ bits 32 ]

    init_pm:
</code>```

the print char 'Z' after sti in continue:

```<code>mov ax, 0xb800;
mov es, ax;
mov [es:0000], byte 'Z'
</code>```

答: If anyone is interested after all this time, on your return to real mode you enable interrupts, print your "c", then use hlt. With interrupts enabled, execution will continue after the hlt on the first interrupt called which would likely be the timer (irq0/int8) but there is no code there so anything could happen</p>

Body:
I am developing a toy OS in assembly and I have a problem when switching from protected mode back to real mode. I have successfully switched to protected mode, called the kernel that writes text to [0xb8000] video memory, returned to the caller and (probably) switched back to real mode. I am trying to use bios interrupts from real mode so I don't have to write my own device drivers.

Interrupts however don't seem to be executed after switching back to real mode.
They don't crash the system as they would in protected mode so I guess I am in real mode.

minrep.asm (bootloader)

boot.header:
[BITS 16]
[ORG 0x7c00]
mov ax, cs
mov ds, ax
xor ax, ax
mov ds, ax
cli
mov ss, ax
mov sp, 0x7c00
sti
call main
jmp $
disk.read_sectors:
reset:
xor ax,ax
int 0x13
jc reset
floppy:
xor bx,bx
mov ah,0x2
mov al, [esp+6]
mov cx,[esp+4]
mov dh,0x0
mov dl, 0x80
mov bx, ds
mov es, bx
mov bx, [esp+2]
int 0x13
jc error
mov ax, 0
ret
error:
mov ax, 1
ret
main:
push word 16 ; 16 sectors for stage2
push word 2 ; starts at sector 2
push word 0x1000 ; into 0x1000 memory buffer
call disk.read_sectors
pop bx
pop bx
pop bx
jmp 0000:0x1000
mov ax, 0
ret
footer:
times 510-($-boot.header) db 0
dw 0xAA55

minrep_st2.asm (stage2, enter prot and back to real)

[BITS 16]
[ORG 0x1000]

stage2.header:

mov ax, cs
mov ds, ax
jmp stage2.main

stage2.main:

mov al, 'B'
mov ah, 0x0E
mov bh, 0x00
mov bl, 0x07
int 0x10

call switch_to_protected
switch_to_protected:

            [ bits 16 ]

            cli

            switch_to_pm:

                lgdt [ gdt_descriptor ]
                mov eax , cr0
                or eax , 0x1
                mov cr0 , eax
                jmp CODE_SEG:init_pm

            [ bits 32 ]

            init_pm:

                   mov ax, DATA_SEG
                mov ds, ax
                mov ss, ax
                mov es, ax
                mov fs, ax
                mov gs, ax
                mov ebp , 0x90000
                mov esp , ebp

                sti

[BITS 32]
switch_to_real:

mov [0xb8000], byte 'D'

[BITS 32]
cli

mov eax, cr0
and eax, 0x7FFFFFFF    ; clear PG bit
mov cr0, eax

xor     eax,eax         ; A convenient zero
mov     cr3,eax         ; Flush the TLB

mov eax, cr0
and eax, 0xFFFFFFFE    ; clear PE bit
mov cr0, eax

lidt [idtr]

jmp 0:continue

[BITS 16]

continue:

sti

mov al, 'C'
mov ah, 0x0E
mov bh, 0x00
mov bl, 0x07
int 0x10

hlt

GDT:

            idtr:
            dw 0x3ff
            dd 0

            gdt_start:

                gdt_null:
                    dd 0x0 ;
                    dd 0x0

                gdt_code:
                    dw 0xffff
                    dw 0x0
                    db 0x0
                    db 10011010b ; 1 st flags , type flags
                    db 11001111b ; 2 nd flags , Limit ( bits 16 -19)
                    db 0x0

                gdt_data:
                    dw 0xffff
                    dw 0x0
                    db 0x0
                    db 10010010b ; 1 st flags , type flags
                    db 11001111b ; 2 nd flags , Limit ( bits 16 -19)
                    db 0x0

                gdt_end:

                gdt_descriptor:
                    dw gdt_end - gdt_start - 1
                    dd gdt_start

            CODE_SEG equ gdt_code - gdt_start
            DATA_SEG equ gdt_data - gdt_start

stage2.footer:
times 8192-($-stage2.header) db 0

how to compile:

nasm.bat minrep.asm -o disk_p1.bin
nasm minrep_st2.asm -o disk_p2.bin
copy /b disk_pt1.bin + disk_pt2.bin disk.img
call qemu disk.img

EDIT:

if i only do this to go protected, then movin to 0xb800 in real mode does clear the first character but doesn't print it correctly (blank char instead of byte 'Z')

        [ bits 16 ]

    cli

    switch_to_pm:

        lgdt [ gdt_descriptor ]
        mov eax , cr0
        or eax , 0x1
        mov cr0 , eax
        jmp CODE_SEG:init_pm

    [ bits 32 ]

    init_pm:

the print char 'Z' after sti in continue:

mov ax, 0xb800;
mov es, ax;
mov [es:0000], byte 'Z'


问:
Expo Push Notifications Service/API - How to directi anonymous user to specific webview screen in app after engaging with Push Notification
Using Expo Push Notification Service, I currently send Push Notification to all users, which are anonymous. The only data I am collecting and writing to a Firebase Database is the "ExponentPushToken" that identifies a unique device for sending notifications using expo's service. I have been sending Push Notification in terminal using the following command:

```<code>curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": [
    "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
    "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]"
  ],
  "title": "Hello World!",
  "body": "Example text here!!",
  "sound": "default"
}'
</code>```

Now, I presume this is not the most flexible way to send notifications, but it allowed me to QUICKLY hit the ground running. My goal now, is to be able to send users that interact with (click/press on) a particular push notification when receiving it on their device to a specific "state" (webview of a particular URL) within the app... I have read through most of the documentation, but I believe some of the content is a bit beyond my ability to interpret regarding what is necessary to make this happen (E.g. setting up Listener's, etc).  Wondering if anyone can help simplify implementing this for me? Even if its a bit "janky", I am open to anything!

答:
@AleMux answer nudged me in the right direction, but for the sake of specificity here is how one can accomplish the desired outcome posed in the question.

Using Expo's Push Notification API, you'll want to ensure you have the appropriate listeners in place, which are already referenced in their API Snack/Example (https://docs.expo.dev/versions/latest/sdk/notifications/#api). For simplicity, this is what we need to focus on for this functionality:

Ensure you've you got the API installed/imported:

```<code>import * as Notifications from "expo-notifications";
</code>```

Setup references to handle notifications and notification responses/interactions:

```<code>  const [expoPushToken, setExpoPushToken] = useState("");
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();
</code>```

For this use case, we want the WebView uri to be able modified. See how this is currently working below, for context. The code below presumes you have necessary dependencies installed (ie. WebView):

```<code>  const [page, setPage] = useState("");
  const [baseURI] = useState("https://www.google.com");
//---A bunch of your app code will presumably be here as to what your app will render, but we'll focus in on the specific needs for this WebView---//
<WebView source={{uri: `${baseURI}/${page}`}} ref={webviewRef}/>
</code>```

Use the listeners shown below, which can be found/copied from the Expo Push Notification API Snack/Example. In this case I want the action to be the same if the end-user interacts with the notification whether app is in foreground, backgrounded, or killed:

```<code>    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
        const onInteraction = notification.request.content.data.event;
        setPage(onInteraction);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
        const onInteraction = response.notification.request.content.data.event;
        setPage(onInteraction);
      });
</code>```

Lastly, in our HTTP POST request (using CURL in this case) we want to pass a "data" field with a JSON Object that the listeners above can act on. The location above is mentioned regarding where the listener can collect the Object. notification.request.content.data.event. In this case the CURL HTTP POST request would look like this to setPage of webview to a page a page within the baseURI domain that is determined by the information sent to the listener above via the information located in the "data" field of the post request. The location data.event referenced above references the object sent like this "data": {"event": "insert page info here"}. Here is a working example of the complete CURL command:

```<code>curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "title": "You have new mail messages!",
  "body": "Check them out here in the app by interacting with this notification.",
  "sound": "default",
  "data": {"event": "mail"}
}'
</code>```

When the end user interacts with the push notification (ie. presses the badge) the app will open and webview will render ${baseURI}/${page} which in this case, would be https://www.google.com/mail

Body:
Using Expo Push Notification Service, I currently send Push Notification to all users, which are anonymous. The only data I am collecting and writing to a Firebase Database is the "ExponentPushToken" that identifies a unique device for sending notifications using expo's service. I have been sending Push Notification in terminal using the following command:

curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": [
    "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
    "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]"
  ],
  "title": "Hello World!",
  "body": "Example text here!!",
  "sound": "default"
}'

Now, I presume this is not the most flexible way to send notifications, but it allowed me to QUICKLY hit the ground running. My goal now, is to be able to send users that interact with (click/press on) a particular push notification when receiving it on their device to a specific "state" (webview of a particular URL) within the app... I have read through most of the documentation, but I believe some of the content is a bit beyond my ability to interpret regarding what is necessary to make this happen (E.g. setting up Listener's, etc).  Wondering if anyone can help simplify implementing this for me? Even if its a bit "janky", I am open to anything!

Body:
@AleMux answer nudged me in the right direction, but for the sake of specificity here is how one can accomplish the desired outcome posed in the question.

Using Expo's Push Notification API, you'll want to ensure you have the appropriate listeners in place, which are already referenced in their API Snack/Example (https://docs.expo.dev/versions/latest/sdk/notifications/#api). For simplicity, this is what we need to focus on for this functionality:

Ensure you've you got the API installed/imported:

import * as Notifications from "expo-notifications";

Setup references to handle notifications and notification responses/interactions:

  const [expoPushToken, setExpoPushToken] = useState("");
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

For this use case, we want the WebView uri to be able modified. See how this is currently working below, for context. The code below presumes you have necessary dependencies installed (ie. WebView):

  const [page, setPage] = useState("");
  const [baseURI] = useState("https://www.google.com");
//---A bunch of your app code will presumably be here as to what your app will render, but we'll focus in on the specific needs for this WebView---//
<WebView source={{uri: `${baseURI}/${page}`}} ref={webviewRef}/>

Use the listeners shown below, which can be found/copied from the Expo Push Notification API Snack/Example. In this case I want the action to be the same if the end-user interacts with the notification whether app is in foreground, backgrounded, or killed:

    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
        const onInteraction = notification.request.content.data.event;
        setPage(onInteraction);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
        const onInteraction = response.notification.request.content.data.event;
        setPage(onInteraction);
      });

Lastly, in our HTTP POST request (using CURL in this case) we want to pass a "data" field with a JSON Object that the listeners above can act on. The location above is mentioned regarding where the listener can collect the Object. notification.request.content.data.event. In this case the CURL HTTP POST request would look like this to setPage of webview to a page a page within the baseURI domain that is determined by the information sent to the listener above via the information located in the "data" field of the post request. The location data.event referenced above references the object sent like this "data": {"event": "insert page info here"}. Here is a working example of the complete CURL command:

curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{
  "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "title": "You have new mail messages!",
  "body": "Check them out here in the app by interacting with this notification.",
  "sound": "default",
  "data": {"event": "mail"}
}'

When the end user interacts with the push notification (ie. presses the badge) the app will open and webview will render ${baseURI}/${page} which in this case, would be https://www.google.com/mail


问:
Possible to launch Apple's default weather app from my application?
One of my client wants to open Apple's native weather app from our application. After few I don't see a possible way, unless we need to go with any 3rd party apps which provides custom url scheme.

http://developer.apple.com/library/ios/#featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007899

It would be great if someone confirm or give me a lead if it is possible.

答: Its not possible, the weather app doesn't have a known URL scheme and I dubt that it has an unknown one.</p>


问:
How to change the color of text selector (blinking) cursor for every widgets at once?
I have make a tkinter project in python which has black background so I wanted to change the color of the text selecter (the blinking one) cursor of the widgets and I know that I can do it individually by using insertbackground but the real problem is that my code is vere long it includes multiple textbox and entry widgets so is there is any easy way to set the default color of the cursor with minimum editing of the code as it is a very time taking work to edit each and every widgets manually. So please help me...

Thank in Advance..

答:
To set the default you can use the little-used option database. This is a feature what has more relevance in X11-based window systems, but is still useful on all platforms for problems such as this.

For example, after creating the root window you can set the default for the insertbackground option to "red" for all widgets like so:

```<code>root = tk.Tk()
root.option_add("*insertBackground", "red")
</code>```

This default value will be used for any new widgets created after defining the default value.

Body:
To set the default you can use the little-used option database. This is a feature what has more relevance in X11-based window systems, but is still useful on all platforms for problems such as this.

For example, after creating the root window you can set the default for the insertbackground option to "red" for all widgets like so:

root = tk.Tk()
root.option_add("*insertBackground", "red")

This default value will be used for any new widgets created after defining the default value.


问:
Finding Overlapping Buffers in R
I have coordinates which I added a 75m buffer around. I want to filter the buffers by year and then determine if any buffers from observations within the same year are overlapping. I want to be able to identify which buffers are overlapping to either omit them if they are repeated observations or merge them if they are touching.

```<code>e_af_df <- na.omit(e_af_simp_21)
e_af_obs <- st_as_sf(e_af_df, coords=c(7, 6), crs = st_crs(4326))
e_af_t <- st_transform(e_af_obs, 5070)
e_buffers = st_buffer(e_af_t, dist=75)
e_buffers$Year <- format(as.Date(e_buffers$Date, format="%m/%d/%Y"), "%Y")
b.2016 <- subset(e_buffers, e_buffers$Year == "2016")
</code>```

So far this works to draw my buffer (sf polygons) and filter by year, using 2016 as an example here. I then try to find the overlapping buffers using st_intersection.

```<code>o.2016 = st_intersection(b.2016)
summary(o.2016)
</code>```

This tells me that 1718 buffers are overlapping, which I find unlikely since there is only a total of 2768 for that year. I think there might be a double-counting of buffer IDs. Regardless, I am unable to see which buffers are intersecting with each other, just that intersections are occurring.

For some other years, doing the same thing results in an error.

Error in CPL_nary_intersection(x) : GEOS exception

I read that changing the precision may fix this so I used st_set_precision. Yet this only fixed the error for certain years as well.

Does anyone know of a simple way to find overlapping buffers or a way to fix this code?

答:
Let's go step by step. As I don't have access to your data, let's create some dummy polygons:

library(sf)
library(dplyr)
p <- st_point(x=c(10, 10))
area <- st_buffer(p, 10)
polygons <- st_buffer(st_sample(area, 25), 1)
```
<p>Now, let's calculate intersections between them:</p>
<pre class="lang-r prettyprint-override"><code>inter <- st_intersection(st_as_sf(polygons))
inter
#> Simple feature collection with 36 features and 2 fields
#> Geometry type: GEOMETRY
#> Dimension:     XY
#> Bounding box:  xmin: -0.264212 ymin: 1.4698 xmax: 19.96589 ymax: 20.05445
#> CRS:           NA
#> First 10 features:
#>     n.overlaps origins                              x
#> 1            1       1 POLYGON ((18.95204 14.79623...
#> 2            1       2 MULTIPOLYGON (((5.254102 3....
#> 3            1       3 POLYGON ((2.574736 14.99139...
#> 4            1       4 POLYGON ((1.735788 12.80523...
#> 5            1       5 POLYGON ((18.25878 13.02976...
#> 6            1       6 POLYGON ((2.64105 10.30672,...
#> 7            1       7 POLYGON ((8.714673 17.29225...
#> 2.1          2    2, 8 POLYGON ((5.154202 2.707236...
#> 8            1       8 POLYGON ((5.592733 3.483773...
#> 9            1       9 POLYGON ((3.852673 16.92456...
</code>```

Please note columns n.overlaps and origins. Let's filter out only intersections:

```<code>a <- inter |>
  filter(n.overlaps > 1)
plot(polygons)
plot(a, col = "blue", add = TRUE)
</code>```

Created on 2022-02-10 by the reprex package (v2.0.1)

Please note, the functions:

```<code>st_intersects(polygons)
st_overlaps(polygons)
st_touches(polygons)
</code>```

are binary predicates, they can be used to check if geometries intersect, etc. Example:

```<code>st_intersects(polygons, sparse = TRUE)
#> Sparse geometry binary predicate list of length 25, where the
#> predicate was `intersects'
#> first 10 elements:
#>  1: 1, 15, 20, 21
#>  2: 2
#>  3: 3, 9, 14
#> [...]
</code>```

Based on it you can write a simple function which will remove (or union) the geometries.

Regards,
Grzegorz

Title: Finding Overlapping Buffers in R

Body:
I have coordinates which I added a 75m buffer around. I want to filter the buffers by year and then determine if any buffers from observations within the same year are overlapping. I want to be able to identify which buffers are overlapping to either omit them if they are repeated observations or merge them if they are touching.

e_af_df <- na.omit(e_af_simp_21)
e_af_obs <- st_as_sf(e_af_df, coords=c(7, 6), crs = st_crs(4326))
e_af_t <- st_transform(e_af_obs, 5070)
e_buffers = st_buffer(e_af_t, dist=75)
e_buffers$Year <- format(as.Date(e_buffers$Date, format="%m/%d/%Y"), "%Y")
b.2016 <- subset(e_buffers, e_buffers$Year == "2016")

So far this works to draw my buffer (sf polygons) and filter by year, using 2016 as an example here. I then try to find the overlapping buffers using st_intersection.

o.2016 = st_intersection(b.2016)
summary(o.2016)

This tells me that 1718 buffers are overlapping, which I find unlikely since there is only a total of 2768 for that year. I think there might be a double-counting of buffer IDs. Regardless, I am unable to see which buffers are intersecting with each other, just that intersections are occurring.

For some other years, doing the same thing results in an error.

Error in CPL_nary_intersection(x) : GEOS exception

I read that changing the precision may fix this so I used st_set_precision. Yet this only fixed the error for certain years as well.

Does anyone know of a simple way to find overlapping buffers or a way to fix this code?

Body:
Let's go step by step. As I don't have access to your data, let's create some dummy polygons:

library(sf)
library(dplyr)
p <- st_point(x=c(10, 10))
area <- st_buffer(p, 10)
polygons <- st_buffer(st_sample(area, 25), 1)

Now, let's calculate intersections between them:

inter <- st_intersection(st_as_sf(polygons))
inter
#> Simple feature collection with 36 features and 2 fields
#> Geometry type: GEOMETRY
#> Dimension:     XY
#> Bounding box:  xmin: -0.264212 ymin: 1.4698 xmax: 19.96589 ymax: 20.05445
#> CRS:           NA
#> First 10 features:
#>     n.overlaps origins                              x
#> 1            1       1 POLYGON ((18.95204 14.79623...
#> 2            1       2 MULTIPOLYGON (((5.254102 3....
#> 3            1       3 POLYGON ((2.574736 14.99139...
#> 4            1       4 POLYGON ((1.735788 12.80523...
#> 5            1       5 POLYGON ((18.25878 13.02976...
#> 6            1       6 POLYGON ((2.64105 10.30672,...
#> 7            1       7 POLYGON ((8.714673 17.29225...
#> 2.1          2    2, 8 POLYGON ((5.154202 2.707236...
#> 8            1       8 POLYGON ((5.592733 3.483773...
#> 9            1       9 POLYGON ((3.852673 16.92456...

Please note columns n.overlaps and origins. Let's filter out only intersections:

a <- inter |>
  filter(n.overlaps > 1)
plot(polygons)
plot(a, col = "blue", add = TRUE)

Created on 2022-02-10 by the reprex package (v2.0.1)

Please note, the functions:

st_intersects(polygons)
st_overlaps(polygons)
st_touches(polygons)

are binary predicates, they can be used to check if geometries intersect, etc. Example:

st_intersects(polygons, sparse = TRUE)
#> Sparse geometry binary predicate list of length 25, where the
#> predicate was `intersects'
#> first 10 elements:
#>  1: 1, 15, 20, 21
#>  2: 2
#>  3: 3, 9, 14
#> [...]

Based on it you can write a simple function which will remove (or union) the geometries.

Regards,
Grzegorz


问:
Ungroup list items using linq c#
I have a class which stores the menus data in below format.

public class MenuCondiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long[] CondimentIds { get; set; }
}
```
<p>e.g.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>GroupId</th>
<th>Name</th>
<th>CondimentIds</th>
</tr>
</thead>
<tbody>
<tr>
<td>21</td>
<td>Veg Burger</td>
<td>100032,100033,100045,100056</td>
</tr>
<tr>
<td>22</td>
<td>Chiken Burger</td>
<td>100067,100040,100034</td>
</tr>
</tbody>
</table>
</div>
<p>Now, I want the output data as below in the class by using linq.</p>
<pre class="lang-cs prettyprint-override"><code>public class Condiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentIds { get; set; }
}
</code>```

GroupId
Name
CondimentIds

21
Veg Burger
100032

21
Veg Burger
100033

21
Veg Burger
100045

21
Veg Burger
100056

21
Chiken Burger
100067

22
Chiken Burger
100040

22
Chiken Burger
100034

Can someone assist here?

答:
You can use Linq and  SelectMany() to flatten the inner array:

```<code>var menuCondiements = // get menucondiments

var result = menuCondiements
               .SelectMany(                // flatten the
                 m => m.CondimentIds       // inner array
                   .Select(
                     c => new Condiment    // project to
                     {                     // new Condiment()
                       GroupId = m.GroupId,
                       Name = m.Name,
                       CondimentId = c    // here condimentId is 'c'
                     }));
</code>```

You should also rename your class and Id to singular rather than plural form since the class represents a single object:

```<code>public class Condiment
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentId { get; set; }
}
</code>```

Title: Ungroup list items using linq c#

Body:
I have a class which stores the menus data in below format.

public class MenuCondiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long[] CondimentIds { get; set; }
}

e.g.

GroupId
Name
CondimentIds

21
Veg Burger
100032,100033,100045,100056

22
Chiken Burger
100067,100040,100034

Now, I want the output data as below in the class by using linq.

public class Condiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentIds { get; set; }
}

GroupId
Name
CondimentIds

21
Veg Burger
100032

21
Veg Burger
100033

21
Veg Burger
100045

21
Veg Burger
100056

21
Chiken Burger
100067

22
Chiken Burger
100040

22
Chiken Burger
100034

Can someone assist here?

Body:
You can use Linq and  SelectMany() to flatten the inner array:

var menuCondiements = // get menucondiments

var result = menuCondiements
               .SelectMany(                // flatten the
                 m => m.CondimentIds       // inner array
                   .Select(
                     c => new Condiment    // project to
                     {                     // new Condiment()
                       GroupId = m.GroupId,
                       Name = m.Name,
                       CondimentId = c    // here condimentId is 'c'
                     }));

You should also rename your class and Id to singular rather than plural form since the class represents a single object:

public class Condiment
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentId { get; set; }
}