问:
How to convert objects or string to time format when the input string/object is malformed that is %H does not exist for all rows
A similar question has been asked before but has received no responses

I have looked through a number of forums for a solution. The other questions involve a year but mine does not - it is simply H:M:S

I web scraped this data which returned

Time - 36:42   38:34   1:38:32   1:41:18

Data samples here: Source data 1 and Source data 2

I need this time in minutes like so
36.70  38.57 98.53 101.30

To do this I tried this:

time_mins = []
for i in time_list:
    h, m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    time_mins.append(math)
```

<p>But that didn't work because 36:42 is not in the format H:M:S, so I tried to convert 36:42 using this</p>

<pre class="lang-py prettyprint-override"><code>df1.loc[1:,6] = df1[6]+ timedelta(hours=0)
</code>```

and this

df1['minutes'] = pd.to_datetime(df1[6], format='%H:%M:%S')
```

<p>but have had no luck.</p>

<p>Can I do it at the extraction stage? I have to do it for over 500 rows</p>

<pre class="lang-py prettyprint-override"><code>row_td = soup.find_all('td')
</code>```

If not, how can it do it after conversion into a data frame

Thanks in advance

答:
I had earlier commented that @NileshIngle's response above was not working as it was giving me a

```<code>NameError: name 'h' is not defined.
</code>```

A simple correction was required - moving h above m,s as it is the first variable referenced

```<code>h = 0 # move this above
m, s = i.split(':')

 def get_time(i):
    ilist = i.split(':')
    if(len(ilist)==3):
        h, m, s = i.split(':')
    else:
        h = 0
        m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    return np.round(math, 2)
</code>```

I would like to thank @MrFuppes, @NileshIngle and @KaustubhBadrike for taking the time to respond. I have learned three different methods.

Body:
A similar question has been asked before but has received no responses

I have looked through a number of forums for a solution. The other questions involve a year but mine does not - it is simply H:M:S

I web scraped this data which returned

Time - 36:42   38:34   1:38:32   1:41:18

Data samples here: Source data 1 and Source data 2

I need this time in minutes like so
36.70  38.57 98.53 101.30

To do this I tried this:

time_mins = []
for i in time_list:
    h, m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    time_mins.append(math)

But that didn't work because 36:42 is not in the format H:M:S, so I tried to convert 36:42 using this

df1.loc[1:,6] = df1[6]+ timedelta(hours=0)

and this

df1['minutes'] = pd.to_datetime(df1[6], format='%H:%M:%S')

but have had no luck.

Can I do it at the extraction stage? I have to do it for over 500 rows

row_td = soup.find_all('td')

If not, how can it do it after conversion into a data frame

Thanks in advance

Body:
I had earlier commented that @NileshIngle's response above was not working as it was giving me a

NameError: name 'h' is not defined.

A simple correction was required - moving h above m,s as it is the first variable referenced

h = 0 # move this above
m, s = i.split(':')

 def get_time(i):
    ilist = i.split(':')
    if(len(ilist)==3):
        h, m, s = i.split(':')
    else:
        h = 0
        m, s = i.split(':')
    math = (int(h) * 3600 + int(m) * 60 + int(s))/60
    return np.round(math, 2)

I would like to thank @MrFuppes, @NileshIngle and @KaustubhBadrike for taking the time to respond. I have learned three different methods.


来源: stackexchange

问:
Calling Typescript function from JavaScript file in Angular
I have a plain old .js file that draws svg on my Angular component.
I have some events in that file and I want to call functions defined in my component code from that .js file.

I haven't found any solution to this problem? Is this achievable? If yes how?

Thank you.

答:
I think that you can create a custom event in javascript and "listen" in your Angular app, but I'm not prety sure if this work

To create a custom event in javascript see this link

```<code>var event = new Event('build',{ data: 'hello word' });
// Dispatch the event.
window.dispatchEvent(event);
</code>```

To listen the event in Angular, use fromEvent rxjs

```<code>ngOnInit()
{
    fromEvent(window,'build').subscribe(event=>{
       console.log(event.data)
    })
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I think that you can create a custom event in javascript and "listen" in your Angular app, but I'm not prety sure if this work

To create a custom event in javascript see this link

var event = new Event('build',{ data: 'hello word' });
// Dispatch the event.
window.dispatchEvent(event);

To listen the event in Angular, use fromEvent rxjs

ngOnInit()
{
    fromEvent(window,'build').subscribe(event=>{
       console.log(event.data)
    })
}


问:
Can´t import qiskit, attribute error in numpy: " 'numpy.random' has no attribute 'default_rng'"
I´m using Python 3 and I´m working in jupyter, when I try to import qiskit the following error is showed:</p>

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-578b7f7e9727> in <module>
----> 1 import qiskit

~\AppData\Roaming\Python\Python36\site-packages\qiskit\quantum_info\synthesis\two_qubit_decompose.py in __init__(self, unitary_matrix)
    169         # D, P = la.eig(M2)  # this can fail for certain kinds of degeneracy
    170         for i in range(100):  # FIXME: this randomized algorithm is horrendous
--> 171             state = np.random.default_rng(i)
    172             M2real = state.normal()*M2.real + state.normal()*M2.imag
    173             _, P = la.eigh(M2real)

AttributeError: module 'numpy.random' has no attribute 'default_rng'
</code>```

答: You need NumPy 1.17 or later to have the new RNG functions that Qiskit needs </p>

Body:
I´m using Python 3 and I´m working in jupyter, when I try to import qiskit the following error is showed:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-578b7f7e9727> in <module>
----> 1 import qiskit

~\AppData\Roaming\Python\Python36\site-packages\qiskit\quantum_info\synthesis\two_qubit_decompose.py in __init__(self, unitary_matrix)
    169         # D, P = la.eig(M2)  # this can fail for certain kinds of degeneracy
    170         for i in range(100):  # FIXME: this randomized algorithm is horrendous
--> 171             state = np.random.default_rng(i)
    172             M2real = state.normal()*M2.real + state.normal()*M2.imag
    173             _, P = la.eigh(M2real)

AttributeError: module 'numpy.random' has no attribute 'default_rng'


问:
How to get a scrollable left-hand-side menu in this Wordpress theme
I am trying to modify the CSS code for the underlying Worpress theme for this site: https://isspm2021.webs.upv.es/. The theme is this one: https://wordpress.org/themes/escapade/.

What I am trying to do is get a vertically scrollable left menu when the screen size is, say, 1024 × 768.

This is what I get now:

As you can see, the last items of the left menu remain hidden and inaccessible, depending on the screen size. I would like the left-hand-side menu to be vertically scrollable when needed.

I've tried several CSS instructions, like overflow:scroll, without success.

I think it is because of the theme itself; more precisely, because of the way the different div elements are defined to be placed regarding others (position:relative and so on).

Any hint of how to modify the CSS style of this theme to get what I need?

答:
I would suggest these for the menu to be scrollable:

Set a height for the menu part,

Set Overflow-y:auto;

Here's the solution:

```<code>.main-navigation-container, .main-navigation.open, .main-navigation ul ul, .main-navigation .sub-menu {
background-color: #f5f5f5;
overflow-y: auto;
height: 400px;
}
</code>```

Also, If you want the scroll to appear when the browser size is less than 1024px, put the code below:

```<code>@media all and (max-width:1024px){
 .main-navigation-container, .main-navigation.open, .main-navigation ul ul, .main-navigation .sub-menu {
background-color: #f5f5f5;
overflow-y: auto;
height: 400px;
}
}
</code>```

The above are two options.Please don't insert both of them.Only use one at a time to see the changes.

Body:
I would suggest these for the menu to be scrollable:

Set a height for the menu part,

Set Overflow-y:auto;

Here's the solution:

.main-navigation-container, .main-navigation.open, .main-navigation ul ul, .main-navigation .sub-menu {
background-color: #f5f5f5;
overflow-y: auto;
height: 400px;
}

Also, If you want the scroll to appear when the browser size is less than 1024px, put the code below:

@media all and (max-width:1024px){
 .main-navigation-container, .main-navigation.open, .main-navigation ul ul, .main-navigation .sub-menu {
background-color: #f5f5f5;
overflow-y: auto;
height: 400px;
}
}

The above are two options.Please don't insert both of them.Only use one at a time to see the changes.


问:
Triggering :hover on second element when hovering on first using pure CSS
I have two elements and I'd like to trigger the hover of second element when the first element is hovered over.

Example:

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

/* suggested proposal */
#element1:hover >> #element2:hover {
   font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div></code>```

I'd like to know if it's possible yet OR if there any plans for this in CSS specification. If there's no proposals I can suggest something like #myElementId:hover >> #mySecondElementID:hover.

There are a few related questions to this but acknowledges that it is not possible and with the new follow feature people can follow for any updates.

Related Questions:

Triggering :hover on second element when hovering on first

Do not close. This is not the same as the other questions. It is asking about current status, future specification and gives a place to answer.

UPDATE:

It looks like I can select any element as the second element as long as it's sibling or a descendant of the first element.

Reference to combinators:

https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

Update: The question is specifically about selecting a second element any where on the page. The current answers will work as long as the mentioned conditions are met.

答:
Hello use the "+" selector to manage his sibbling.

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover+#element2 {
   font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div></code>```

Body:
I have two elements and I'd like to trigger the hover of second element when the first element is hovered over.

Example:

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

/* suggested proposal */
#element1:hover >> #element2:hover {
   font-weight: bold;
}

  Hover over this element for more info

   Here is more info

I'd like to know if it's possible yet OR if there any plans for this in CSS specification. If there's no proposals I can suggest something like #myElementId:hover >> #mySecondElementID:hover.

There are a few related questions to this but acknowledges that it is not possible and with the new follow feature people can follow for any updates.

Related Questions:

Triggering :hover on second element when hovering on first

Do not close. This is not the same as the other questions. It is asking about current status, future specification and gives a place to answer.

UPDATE:

It looks like I can select any element as the second element as long as it's sibling or a descendant of the first element.

Reference to combinators:

https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

Update: The question is specifically about selecting a second element any where on the page. The current answers will work as long as the mentioned conditions are met.

Body:
Hello use the "+" selector to manage his sibbling.

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover+#element2 {
   font-weight: bold;
}

<div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div>


问:
Use fake domain locally in Visual Studio without modifying the host file directly
I have an application that runs here http://localhost:10205/ but I need it run locally as http://somethingelse.com/.

This needs to happen on other computers as well without the need to alter the host file.

How do I do that?

答: If you are all within the same network, you can add an A Record to your domain controller.  Beyond that, there's not much you can do when you're dealing with multiple endpoints.  As far as actually performing that task, you may want to discuss on serverfault.</p>

ContentLicense: CC BY-SA 3.0


问:
Mounting a configuration file structure in job pod
In our application we will have a Kubernetes job that will bootstrap microservices based on a set of (legacy) configuration files. These are in the legacy application packaged as a file structure, and we'd like to keep this so that we don't need to maintain different packaging of the configuration files for the Kubernetes variant and the legacy variant, and there is a lot of legacy code that we still want to use that expects this file structure.

My approach was that I wanted to mount a ConfigMap in the job pod since I naively assumed you could map a entire folder tree, but a ConfigMap is a flat key-value storage.

We're using Helm, so the idea is that the microservice will include the job and apply it with hooks. What would be a good way to map the configuration file structure into the job pod? Can you easily create a volume, populate it with the file strucutre, and then mount it in the job pod?

答:
You can create a configmap from a file or directory and add configmap data to a volume. This will create read-only files from configmap keys in mounted directory. However, it's not possible to keep directory structure in Configmap, as it will fail with error

```<code>... a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name',  or 'KEY_NAME',  or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+')
</code>```

configmap.yaml

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
data:
  some.properties: |
    foo=bar
  other.properties: |
    baz=qux
</code>```

pod.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      args:
      - /bin/sh
      - -c
      - ls -la /etc/config; cat /etc/config/some/some.properties; cat /etc/config/other.properties
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        - key: some.properties
          path: some/some.properties
        - key: other.properties
          path: other.properties
</code>```

checking logs with kubectl logs test

```<code> drwxrwxrwx    3 root     root            95 May 29 09:14 .
 drwxr-xr-x    1 root     root            20 May 29 09:14 ..
 drwxr-xr-x    3 root     root            42 May 29 09:14 ..2020_05_29_09_14_34.418889646
 lrwxrwxrwx    1 root     root            31 May 29 09:14 ..data -> ..2020_05_29_09_14_34.418889646
 lrwxrwxrwx    1 root     root            23 May 29 09:14 other.properties -> ..data/other.properties
 lrwxrwxrwx    1 root     root            11 May 29 09:14 some -> ..data/some
 foo=bar
 baz=qux
</code>```

Body:
You can create a configmap from a file or directory and add configmap data to a volume. This will create read-only files from configmap keys in mounted directory. However, it's not possible to keep directory structure in Configmap, as it will fail with error

... a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name',  or 'KEY_NAME',  or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+')

configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
data:
  some.properties: |
    foo=bar
  other.properties: |
    baz=qux

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      args:
      - /bin/sh
      - -c
      - ls -la /etc/config; cat /etc/config/some/some.properties; cat /etc/config/other.properties
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        - key: some.properties
          path: some/some.properties
        - key: other.properties
          path: other.properties

checking logs with kubectl logs test

 drwxrwxrwx    3 root     root            95 May 29 09:14 .
 drwxr-xr-x    1 root     root            20 May 29 09:14 ..
 drwxr-xr-x    3 root     root            42 May 29 09:14 ..2020_05_29_09_14_34.418889646
 lrwxrwxrwx    1 root     root            31 May 29 09:14 ..data -> ..2020_05_29_09_14_34.418889646
 lrwxrwxrwx    1 root     root            23 May 29 09:14 other.properties -> ..data/other.properties
 lrwxrwxrwx    1 root     root            11 May 29 09:14 some -> ..data/some
 foo=bar
 baz=qux


问:
Avoiding undefined behaviour: temporary objects
I've written a class for using it as a convenient view e.g. in range-based fors. Overall, it is just a pair of iterators with bound checking:

```<code>template<typename I> class Range {
private:
  I begin;
  I end;

public:
  Range(I const begin, I const end)
    : begin(begin), end(end)
  {}

  Range<I>& skip(int const amount) {
    begin = std::min(begin + amount, end);
    return *this;
  }
};

template<typename C> auto whole(C const& container) {
  using Iterator = decltype(std::begin(container));
  return Range<Iterator>(std::begin(container), std::end(container));
}
</code>```

Here's the intended usage of it (which led to UB):

```<code>std::vector<int> const vector{1, 2, 3};
for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}
</code>```

Removing the skip(1) part helps, same about the following refactoring of Range::skip:

```<code>Range<I> skip(int const amount) const {
  I const new_begin = std::min(begin + amount, end);
  return Range<I>(new_begin, end);
}
</code>```

It seems like a temporary mustn't return a reference to itself. Here's what cppreference says:

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

Though I'm not sure it's the case and I don't now how to interpret it practically. What's the actual problem and how can I reliably avoid such UB? Are alike expressions e.g. auto string = std::string("abc").append("def") also unsafe?

答:
Regarding std::string and the append function, the append function returns a reference to the string it appends to. Keeping this reference after the string object is destructed will lead to undefined behavior if you use it.

However if you copy the string object, then you're safe, because you will have a copy of the string and not a reference to a non-existing object:

```<code>std::string s = std::string("abc").append("def");
</code>```

Here s will be a copy, initialized through copy-initialization (it passes std::string("abc").append("def") to the copy-constructor for s, and the temporary object will live all throughout that constructor).

As for

```<code>for (int const value : whole(vector).skip(1)) { ... }
</code>```

If the Range<T> class was modified to be iterable (you need a begin and end functions to return the iterators), then it still would not be UB.

That's because such a range-for loop is corresponding to a loop like

```<code>for (auto iter = whole(vector).skip(1).begin();
     iter != whole(vector).skip(1).end();
     ++iter)
{
    ...
}
</code>```

The Range<T> class doesn't contain a copy of the vector, it contains copies of the iterator of the vector (for your shown example). These iterators would be copied or used before the temporary Range<T> object is destructed.

Body:
I've written a class for using it as a convenient view e.g. in range-based fors. Overall, it is just a pair of iterators with bound checking:

template<typename I> class Range {
private:
  I begin;
  I end;

public:
  Range(I const begin, I const end)
    : begin(begin), end(end)
  {}

  Range& skip(int const amount) {
    begin = std::min(begin + amount, end);
    return *this;
  }
};

template<typename C> auto whole(C const& container) {
  using Iterator = decltype(std::begin(container));
  return Range<Iterator>(std::begin(container), std::end(container));
}

Here's the intended usage of it (which led to UB):

std::vector<int> const vector{1, 2, 3};
for (int const value : whole(vector).skip(1)) {
  std::cout << value << ' ';
}

Removing the skip(1) part helps, same about the following refactoring of Range::skip:

Range skip(int const amount) const {
  I const new_begin = std::min(begin + amount, end);
  return Range(new_begin, end);
}

It seems like a temporary mustn't return a reference to itself. Here's what cppreference says:

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

Though I'm not sure it's the case and I don't now how to interpret it practically. What's the actual problem and how can I reliably avoid such UB? Are alike expressions e.g. auto string = std::string("abc").append("def") also unsafe?

Body:
Regarding std::string and the append function, the append function returns a reference to the string it appends to. Keeping this reference after the string object is destructed will lead to undefined behavior if you use it.

However if you copy the string object, then you're safe, because you will have a copy of the string and not a reference to a non-existing object:

std::string s = std::string("abc").append("def");

Here s will be a copy, initialized through copy-initialization (it passes std::string("abc").append("def") to the copy-constructor for s, and the temporary object will live all throughout that constructor).

As for

for (int const value : whole(vector).skip(1)) { ... }

If the Range<T> class was modified to be iterable (you need a begin and end functions to return the iterators), then it still would not be UB.

That's because such a range-for loop is corresponding to a loop like

for (auto iter = whole(vector).skip(1).begin();
     iter != whole(vector).skip(1).end();
     ++iter)
{
    ...
}

The Range<T> class doesn't contain a copy of the vector, it contains copies of the iterator of the vector (for your shown example). These iterators would be copied or used before the temporary Range<T> object is destructed.


问:
Xamarin.Forms: Disable iOS picker from "auto picking and closing" when stopped and WAIT for "DONE" button click
I am using the regular picker from xamarin.forms:

```<code>      <Picker
x:Name="picker_subcat2_mainmenu"
                                Margin="10,0,10,0"
                                Grid.Column="3"
                                TitleColor="#ffffff"
                                Title=" + "
                                Grid.Row="1"
                                FontFamily="arial"
                                BackgroundColor="#00000000"
                                TextColor="#ffffff"
                                HorizontalOptions="Center"
                                VerticalOptions="Center">
                    </Picker>
</code>```

However, this picker has an issue on iOS.
It contains a long list with elemens, but when you stop scrolling, the picker automatically accepts the item that was highlighted and closes. But this is an issue, since you can only drag your finger up so far. If the list hasnt reached its end yet, it is super finicky getting to the next items (you have to use both fingers to deliver uninterrupted touch).

How can I make the picker close only when the "DONE" button is pressed not and simply by no longer touching it?

THank you!

答:
According to the Picker Item Selection on iOS docs, the Picker has 2 types of selection:

Immediately – item selection occurs as the user browses items in the Picker. This is the default behavior in Xamarin.Forms.

WhenFinished – item selection only occurs once the user has pressed the Done button in the Picker.

In your case you want the second one.

If your code is in xml, you do this:

<ContentPage ...
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout Margin="20">
        <Picker ... Title="Select a monkey" ios:Picker.UpdateMode="WhenFinished">
          ...
        </Picker>
        ...
    </StackLayout>
</ContentPage>
```

<p>If your code is in code-behind file:</p>

<pre class="lang-cs prettyprint-override"><code>using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
...

picker.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
</code>```

Body:
I am using the regular picker from xamarin.forms:

      <Picker
x:Name="picker_subcat2_mainmenu"
                                Margin="10,0,10,0"
                                Grid.Column="3"
                                TitleColor="#ffffff"
                                Title=" + "
                                Grid.Row="1"
                                FontFamily="arial"
                                BackgroundColor="#00000000"
                                TextColor="#ffffff"
                                HorizontalOptions="Center"
                                VerticalOptions="Center">
                    </Picker>

However, this picker has an issue on iOS.
It contains a long list with elemens, but when you stop scrolling, the picker automatically accepts the item that was highlighted and closes. But this is an issue, since you can only drag your finger up so far. If the list hasnt reached its end yet, it is super finicky getting to the next items (you have to use both fingers to deliver uninterrupted touch).

How can I make the picker close only when the "DONE" button is pressed not and simply by no longer touching it?

THank you!

Body:
According to the Picker Item Selection on iOS docs, the Picker has 2 types of selection:

Immediately – item selection occurs as the user browses items in the Picker. This is the default behavior in Xamarin.Forms.

WhenFinished – item selection only occurs once the user has pressed the Done button in the Picker.

In your case you want the second one.

If your code is in xml, you do this:

<ContentPage ...
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout Margin="20">
        <Picker ... Title="Select a monkey" ios:Picker.UpdateMode="WhenFinished">
          ...
        </Picker>
        ...
    </StackLayout>
</ContentPage>

If your code is in code-behind file:

using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
...

picker.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);


问:
In subversion I want to Revert back to a revison then step through each revision to see where it broke
My project broke somewhere in the past 25 revisions. I need to isolate the file causing the problem, and would like to find the revision where the problem was introduced.

I was thinking of using svn update  -r 404 and then each one after that 405,406 ... etc

Is there a better way?

答:
I am surprised people haven't mentioned svn-bisect</p>

```<code>$ svn-bisect --min 404 --max 429 start
$ svn-bisect bad
$ svn-bisect bad
$ svn-bisect good
[etc etc]
$ svn-bisect reset
</code>```

Body:
I am surprised people haven't mentioned svn-bisect

$ svn-bisect --min 404 --max 429 start
$ svn-bisect bad
$ svn-bisect bad
$ svn-bisect good
[etc etc]
$ svn-bisect reset


问:
Calculating max time in four different columns in R
Using R in a dataframe I have four columns of time format that I want to calculate the max time of each row. In some cases there are NAs in random cells. I used apply(X,1,max) but it didn't work. I then tried to replace the NAs with X[is.na(x)]<-0 but it was not successful as well. Can anyone help  me with those two issues?

Body:
How about adding the column directly with tidyverse and pmax?

Example below:

library(tidyverse)
Date1 = c(as.Date('2020-01-01'), as.Date('2020-05-06'), NA, NA, NA)
Date2 = c(as.Date('2020-07-06'), as.Date('2020-03-06'), NA, NA, NA)
Date3 = c(as.Date('2020-08-06'), NA, NA, NA, as.Date('2020-03-06'))
df = data.frame(Date1 = Date1, Date2 = Date2, Date3 = Date3)

df %>%
  mutate(maxdate = pmax(Date1, Date2, Date3, na.rm = TRUE))

Date1         Date2      Date3       maxdate
2020-01-01   2020-07-06  2020-08-06  2020-08-06
2020-05-06   2020-03-06  <NA>        2020-05-06
   <NA>       <NA>       <NA>        <NA>
   <NA>       <NA>       <NA>        <NA>
   <NA>      <NA>        2020-03-06  2020-03-06


问:
Android WebView does not display web page even though the page has successfully finished loading
I have added internet-permissions and I also used the WebViewClient.onPageFinished method to check whether the page has loaded which turns out it did. JavaScript is also enabled for my WebView.

The code I use to set up my web view

webView.webChromeClient = KeplerWebChromeClient(progressBar)
webView.webViewClient = keplerWebViewClient

webView.settings.javaScriptEnabled = true
webView.settings.useWideViewPort = true
webView.settings.loadWithOverviewMode = true
webView.settings.setSupportZoom(true)
webView.settings.setSupportMultipleWindows(true)
webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
webView.setBackgroundColor(Color.WHITE)
```

I am using KeplerWebChromeClient to display web page loading progress.

keplerWebViewClient is an object of WebViewClient class which I use to load webpages and to track for whether the webpage has finished loading or not.

And I must mention that this issue doesn't always arise. Sometimes when I run my app, the WebView does work and it does load and display the web page correctly and other times it doesn't. I have found the below stated logcat entries to be unique to when the web page isn't displayed.

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

[ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content  may not draw

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

What is the issue here and how do I fix it? Thanks in advance.

Edit:
I cleared all the app data from my phone and then I restarted my app. After doing so, everything was working just fine. I was able to browse using the WebView but after using the app a few more times i.e. closing and opening it, the problem reappeared. Clearing all data solves the problem temporarily. What aid can this be in solving the problem?

答:
I have to try and it's working fine for me.

```<code>private fun setupWebView(url: String) {
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.settings.setPluginState(WebSettings.PluginState.ON);
        webView.settings.allowFileAccess = true;
        webView.webViewClient = WebClient()
        webView.webChromeClient = CustomWebChromeClient()
        webView.loadUrl(url)
    }

    private inner class WebClient : WebViewClient() {

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageCommitVisible(view: WebView, url: String) {
            super.onPageCommitVisible(view, url)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView,
            url: String
        ): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
        }
    }

    private inner class CustomWebChromeClient : WebChromeClient() {
        override fun onJsAlert(
            view: WebView,
            url: String,
            message: String,
            result: JsResult
        ): Boolean {
            return false
        }
    }
</code>```

I hope it's work for you!

Body:
I have added internet-permissions and I also used the WebViewClient.onPageFinished method to check whether the page has loaded which turns out it did. JavaScript is also enabled for my WebView.

The code I use to set up my web view

webView.webChromeClient = KeplerWebChromeClient(progressBar)
webView.webViewClient = keplerWebViewClient

webView.settings.javaScriptEnabled = true
webView.settings.useWideViewPort = true
webView.settings.loadWithOverviewMode = true
webView.settings.setSupportZoom(true)
webView.settings.setSupportMultipleWindows(true)
webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
webView.setBackgroundColor(Color.WHITE)

I am using KeplerWebChromeClient to display web page loading progress.

keplerWebViewClient is an object of WebViewClient class which I use to load webpages and to track for whether the webpage has finished loading or not.

And I must mention that this issue doesn't always arise. Sometimes when I run my app, the WebView does work and it does load and display the web page correctly and other times it doesn't. I have found the below stated logcat entries to be unique to when the web page isn't displayed.

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

[ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content  may not draw

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

E/chromium: [ERROR:tile_manager.cc(778)] WARNING: tile memory limits exceeded, some content may not draw

What is the issue here and how do I fix it? Thanks in advance.

Edit:
I cleared all the app data from my phone and then I restarted my app. After doing so, everything was working just fine. I was able to browse using the WebView but after using the app a few more times i.e. closing and opening it, the problem reappeared. Clearing all data solves the problem temporarily. What aid can this be in solving the problem?

Body:
I have to try and it's working fine for me.

private fun setupWebView(url: String) {
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.settings.setPluginState(WebSettings.PluginState.ON);
        webView.settings.allowFileAccess = true;
        webView.webViewClient = WebClient()
        webView.webChromeClient = CustomWebChromeClient()
        webView.loadUrl(url)
    }

    private inner class WebClient : WebViewClient() {

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageCommitVisible(view: WebView, url: String) {
            super.onPageCommitVisible(view, url)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView,
            url: String
        ): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
        }
    }

    private inner class CustomWebChromeClient : WebChromeClient() {
        override fun onJsAlert(
            view: WebView,
            url: String,
            message: String,
            result: JsResult
        ): Boolean {
            return false
        }
    }

I hope it's work for you!


问:
How to replace substring in a string
I have a string (i.e If you ask the makers of paper products, they will tell you that to be Agile you need to write ...) and the search terms (i.e ['makers', 'to be Agile']).

I expect this result If you ask the makers of paper products, they will tell you that to be Agile you need to write ...

I implement that with this method but sometimes doesn't work correctly.

```<code>private emphasize(text: string, highlights: string[]) {
    return highlights
      .filter(highlight => text.includes(highlight))
      .map(highlight => highlight.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'))
      .reduce((txt, highlight) => {
        return txt.replace(new RegExp(highlight, 'gi'), '<strong>$&</strong>');
      }, text);
  }
</code>```

答:
Create a RegExp by joining the highlights with the pipe | symbol, and wrapping with word boundaries (\b). Now use String.replace() to wrap found strings with . This will wrap entire expressions (to be Agile) with .

function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join('|')}\\b`, 'gi');

  return text.replace(pattern, '$&');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);```
</div>
</div>
</p>

<p>If you really want single words, join the highlights with spaces, then split by spaces and join again with the pipe symbol:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join(' ').split(' ').join('|')}\\b`, 'gi');

  return text.replace(pattern, '<strong>$&</strong>');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);</code>```

Title: How to replace substring in a string

Body:
I have a string (i.e If you ask the makers of paper products, they will tell you that to be Agile you need to write ...) and the search terms (i.e ['makers', 'to be Agile']).

I expect this result If you ask the makers of paper products, they will tell you that to be Agile you need to write ...

I implement that with this method but sometimes doesn't work correctly.

private emphasize(text: string, highlights: string[]) {
    return highlights
      .filter(highlight => text.includes(highlight))
      .map(highlight => highlight.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'))
      .reduce((txt, highlight) => {
        return txt.replace(new RegExp(highlight, 'gi'), '$&');
      }, text);
  }

Body:
Create a RegExp by joining the highlights with the pipe | symbol, and wrapping with word boundaries (\b). Now use String.replace() to wrap found strings with <strong>. This will wrap entire expressions (to be Agile) with <strong>.

function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join('|')}\\b`, 'gi');

  return text.replace(pattern, '<strong>$&</strong>');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);

If you really want single words, join the highlights with spaces, then split by spaces and join again with the pipe symbol:

function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join(' ').split(' ').join('|')}\\b`, 'gi');

  return text.replace(pattern, '<strong>$&</strong>');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);


问:
404 Flask Deploy in 2008R2 - iis7
I am using wfastcgi3.0 with python3.4.

Even though I strictly followed this guide in https://netdot.co/2015/03/09/flask-on-iis/

I still got 404.....

My webconfig:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="FlaskFastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python34\python.exe|C:\Python34\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" />
        </handlers>
    </system.webServer>
    <appSettings>
        <add key="PYTHONPATH" value="D:\app\FLASKTEST" />
        <add key="WSGI_HANDLER" value="myapp.app" />
    </appSettings>
</configuration>
</code>```

myapp.py:

```<code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "Hello from FastCGI via IIS!"
if __name__ == "__main__":
    app.run()
</code>```

答:
Use python version after 3.6 with iis.follow this post steps https://stackoverflow.com/a/59171787/11147346.

assign the iis_iusrs and iusr permission to the site and python folder. and at the tim eof installation install the python for all users.

Title: 404 Flask Deploy in 2008R2 - iis7

Body:
I am using wfastcgi3.0 with python3.4.

Even though I strictly followed this guide in https://netdot.co/2015/03/09/flask-on-iis/

I still got 404.....

My webconfig:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="FlaskFastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python34\python.exe|C:\Python34\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" />
        </handlers>
    </system.webServer>
    <appSettings>
        <add key="PYTHONPATH" value="D:\app\FLASKTEST" />
        <add key="WSGI_HANDLER" value="myapp.app" />
    </appSettings>
</configuration>

myapp.py:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "Hello from FastCGI via IIS!"
if __name__ == "__main__":
    app.run()


问:
substracting dataframe columns with different granularity on datetime index
I have some price data (such as from yahoo finance) with a daily granularity datetime variable as index, lets call that df and lets say its the microsoft closing price as value variable. To get the monthly average closing price I can obviously do one of these two:

```<code>import yfinance as yf
import pandas as pd
df = yf.download("CMG", start="2012-01-01",end="2020-01-01" )
dfm = df.resample("M").mean()
dfm2 = df.groupby(df.index.to_period("M")).mean()
</code>```

To me they look very similar only difference I can tell is that on the resample the new datetime index is the end of the month and the groupby to_period will have an index of yyyy-mm.

I now want to add a column to df with daily granularity that has for each daily closing price the deviation from its monthly mean. So 1/jan/2020 - mean(jan-20), 2/jan/2020 - mean(jan-20), 1/feb/2020 - mean(feb-20).

Because dfm and df have different indices I cannot just do df-dfm.

The only thing I can come up with is loop through df, put a counter on dfm and put an if statement in the loop, very much a c-type approach but not very pythonic. I guess it would look sth like this (but this didn't work):

```<code>counter = 0
df["dailyminusmonthly"] =""

for i in df:
if i.index <= dfm[counter].index:
    i.dailyminusmonthly = i.close - dfm.close[counter]
else:
    counter = counter +1
    i.dailyminusmonthly = i.close - dfm.close[counter]
</code>```

Body:
I have some price data (such as from yahoo finance) with a daily granularity datetime variable as index, lets call that df and lets say its the microsoft closing price as value variable. To get the monthly average closing price I can obviously do one of these two:

import yfinance as yf
import pandas as pd
df = yf.download("CMG", start="2012-01-01",end="2020-01-01" )
dfm = df.resample("M").mean()
dfm2 = df.groupby(df.index.to_period("M")).mean()

To me they look very similar only difference I can tell is that on the resample the new datetime index is the end of the month and the groupby to_period will have an index of yyyy-mm.

I now want to add a column to df with daily granularity that has for each daily closing price the deviation from its monthly mean. So 1/jan/2020 - mean(jan-20), 2/jan/2020 - mean(jan-20), 1/feb/2020 - mean(feb-20).

Because dfm and df have different indices I cannot just do df-dfm.

The only thing I can come up with is loop through df, put a counter on dfm and put an if statement in the loop, very much a c-type approach but not very pythonic. I guess it would look sth like this (but this didn't work):

counter = 0
df["dailyminusmonthly"] =""

for i in df:
if i.index <= dfm[counter].index:
    i.dailyminusmonthly = i.close - dfm.close[counter]
else:
    counter = counter +1
    i.dailyminusmonthly = i.close - dfm.close[counter]

Body:
You can convert DatetimeIndex to monthly period, so you can subtract dfm2, only then is necessary convert to numpy array, because index of subtracted Series is different like original df for prevent full NaNs column:

df['dailyminusmonthly1']= (df['Close'].to_period('M')
                                    .sub(df.groupby(df.index.to_period("M"))['Close'].mean())
                                    .to_numpy())

Another simplier solution is use Resampler.transform with same index like original:

df['dailyminusmonthly2']= df['Close'].sub(df.resample("M")['Close'].transform('mean'))

print (df)
                  Open        High         Low       Close   Adj Close  \
Date
2012-01-03  343.700012  350.489990  340.000000  341.269989  341.269989
2012-01-04  346.000000  349.980011  345.010010  348.750000  348.750000
2012-01-05  346.880005  351.980011  342.570007  350.480011  350.480011
2012-01-06  348.880005  352.630005  347.350006  348.950012  348.950012
2012-01-09  349.000000  349.489990  336.290009  339.739990  339.739990
               ...         ...         ...         ...         ...
2019-12-24  827.099976  829.409973  823.159973  828.890015  828.890015
2019-12-26  829.409973  839.280029  828.239990  838.599976  838.599976
2019-12-27  839.969971  840.000000  835.000000  836.789978  836.789978
2019-12-30  838.169983  838.750000  829.010010  836.070007  836.070007
2019-12-31  837.239990  842.270020  833.359985  837.109985  837.109985

            Volume  dailyminusmonthly1  dailyminusmonthly2
Date
2012-01-03  728100          -13.559013          -13.559013
2012-01-04  743100           -6.079002           -6.079002
2012-01-05  672300           -4.348991           -4.348991
2012-01-06  370700           -5.878990           -5.878990
2012-01-09  748600          -15.089012          -15.089012
           ...                 ...                 ...
2019-12-24   91900            3.640494            3.640494
2019-12-26  255400           13.350455           13.350455
2019-12-27  201900           11.540458           11.540458
2019-12-30  211400           10.820487           10.820487
2019-12-31  282200           11.860465           11.860465

[2012 rows x 8 columns]


问:
Filter data going through Nivo Bar Chart
Using react-table, I can filter the data really well, but would like it to be more dynamic

Now what I'm struggling to complete is filtering the data in the graph, so that it's more meaningful, partly by clumping products from singular brands together in one bar chart, and also by removing excess amounts of brands that make the information harder to understand.

This is the Table component I am using

```<code>import React from 'react'
import {
    useTable,
    usePagination,
    useSortBy,
    useFilters,
    useGroupBy,
    useExpanded,
    useRowSelect,
  } from 'react-table'
  import matchSorter from 'match-sorter'

  // import makeData from '../example/makedata.js'

  // Create an editable cell renderer
  const EditableCell = ({
    value: initialValue,
    row: { index },
    column: { id },
    updateMyData, // This is a custom function that we supplied to our table instance
    editable,
  }) => {
    // We need to keep and update the state of the cell normally
    const [value, setValue] = React.useState(initialValue)

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

    // We'll only update the external data when the input is blurred
    const onBlur = () => {
      updateMyData(index, id, value)
    }

    // If the initialValue is changed externall, sync it up with our state
    React.useEffect(() => {
      setValue(initialValue)
    }, [initialValue])

    if (!editable) {
      return `${initialValue}`
    }

    return <input value={value} onChange={onChange} onBlur={onBlur} />
  }

  // Define a default UI for filtering
  function DefaultColumnFilter({
    column: { filterValue, preFilteredRows, setFilter },
  }) {
    const count = preFilteredRows.length

    return (
      <input
        value={filterValue || ''}
        onChange={e => {
          setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
        }}
        placeholder={`Search ${count} records...`}
      />
    )
  }

  // This is a custom filter UI for selecting
  // a unique option from a list
  function SelectColumnFilter({
    column: { filterValue, setFilter, preFilteredRows, id },
  }) {
    // Calculate the options for filtering
    // using the preFilteredRows
    const options = React.useMemo(() => {
      const options = new Set()
      preFilteredRows.forEach(row => {
        options.add(row.values[id])
      })
      return [...options.values()]
    }, [id, preFilteredRows])

    // Render a multi-select box
    return (
      <select
        value={filterValue}
        onChange={e => {
          setFilter(e.target.value || undefined)
        }}
      >
        <option value="">All</option>
        {options.map((option, i) => (
          <option key={i} value={option}>
            {option}
          </option>
        ))}
      </select>
    )
  }

  // This is a custom filter UI that uses a
  // slider to set the filter value between a column's
  // min and max values
  function SliderColumnFilter({
    column: { filterValue, setFilter, preFilteredRows, id },
  }) {
    // Calculate the min and max
    // using the preFilteredRows

    const [min, max] = React.useMemo(() => {
      let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      preFilteredRows.forEach(row => {
        min = Math.min(row.values[id], min)
        max = Math.max(row.values[id], max)
      })
      return [min, max]
    }, [id, preFilteredRows])

    return (
      <>
        <input
          type="range"
          min={min}
          max={max}
          value={filterValue || min}
          onChange={e => {
            setFilter(parseInt(e.target.value, 10))
          }}
        />
        <button onClick={() => setFilter(undefined)}>Off</button>
      </>
    )
  }

  // This is a custom UI for our 'between' or number range
  // filter. It uses two number boxes and filters rows to
  // ones that have values between the two
  function NumberRangeColumnFilter({
    column: { filterValue = [], preFilteredRows, setFilter, id },
  }) {
    const [min, max] = React.useMemo(() => {
      let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      preFilteredRows.forEach(row => {
        min = Math.min(row.values[id], min)
        max = Math.max(row.values[id], max)
      })
      return [min, max]
    }, [id, preFilteredRows])

    return (
      <div
        style={{
          display: 'flex',
        }}
      >
        <input
          value={filterValue[0] || ''}
          type="number"
          onChange={e => {
            const val = e.target.value
            setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
          }}
          placeholder={`Min (${min})`}
          style={{
            width: '70px',
            marginRight: '0.5rem',
          }}
        />
        to
        <input
          value={filterValue[1] || ''}
          type="number"
          onChange={e => {
            const val = e.target.value
            setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
          }}
          placeholder={`Max (${max})`}
          style={{
            width: '70px',
            marginLeft: '0.5rem',
          }}
        />
      </div>
    )
  }

  function fuzzyTextFilterFn(rows, id, filterValue) {
    return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
  }

  // Let the table remove the filter if the string is empty
  fuzzyTextFilterFn.autoRemove = val => !val

  // Be sure to pass our updateMyData and the skipReset option
  function Table({ columns, data, updateMyData, skipReset }) {
    const td_header = "px-4 py-2"
  const td_style = "border px-4 py-2"
    const filterTypes = React.useMemo(
      () => ({
        // Add a new fuzzyTextFilterFn filter type.
        fuzzyText: fuzzyTextFilterFn,
        // Or, override the default text filter to use
        // "startWith"
        text: (rows, id, filterValue) => {
          return rows.filter(row => {
            const rowValue = row.values[id]
            return rowValue !== undefined
              ? String(rowValue)
                  .toLowerCase()
                  .startsWith(String(filterValue).toLowerCase())
              : true
          })
        },
      }),
      []
    )

    const defaultColumn = React.useMemo(
      () => ({
        // Let's set up our default Filter UI
        Filter: DefaultColumnFilter,
        // And also our default editable cell
        Cell: EditableCell,
      }),
      []
    )

    // Use the state and functions returned from useTable to build your UI
    const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      prepareRow,
      page, // Instead of using 'rows', we'll use page,
      // which has only the rows for the active page

      // The rest of these things are super handy, too ;)
      canPreviousPage,
      canNextPage,
      pageOptions,
      pageCount,
      gotoPage,
      nextPage,
      previousPage,
      setPageSize,
      state: {
        pageIndex,
        pageSize,
        sortBy,
        groupBy,
        expanded,
        filters,
        selectedRowIds,
      },
    } = useTable(
      {
        columns,
        data,
        defaultColumn,
        filterTypes,
        // updateMyData isn't part of the API, but
        // anything we put into these options will
        // automatically be available on the instance.
        // That way we can call this function from our
        // cell renderer!
        updateMyData,
        // We also need to pass this so the page doesn't change
        // when we edit the data.
        autoResetPage: !skipReset,
        autoResetSelectedRows: !skipReset,
        disableMultiSort: true,
      },
      useFilters,
      useGroupBy,
      useSortBy,
      useExpanded,
      usePagination,
      useRowSelect,
      // Here we will use a plugin to add our selection column
      hooks => {
        hooks.visibleColumns.push(columns => {
          return [
            {
              id: 'selection',
              // Make this column a groupByBoundary. This ensures that groupBy columns
              // are placed after it
              groupByBoundary: true,
              // The header can use the table's getToggleAllRowsSelectedProps method
              // to render a checkbox
              Header: ({ getToggleAllRowsSelectedProps }) => (
                <div>
                  <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
                </div>
              ),
              // The cell can use the individual row's getToggleRowSelectedProps method
              // to the render a checkbox
              Cell: ({ row }) => (
                <div>
                  <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
                </div>
              ),
            },
            ...columns,
          ]
        })
      }
    )

    // Render the UI for your table
    return (
      <>
        <table className="w-full text-md bg-white shadow-md rounded mb-4" {...getTableProps()}>
          <thead>
            {headerGroups.map(headerGroup => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map(column => (
                  <th className={td_header} {...column.getHeaderProps()}>
                    <div>
                      {column.canGroupBy ? (
                        // If the column can be grouped, let's add a toggle
                        <span {...column.getGroupByToggleProps()}>
                          {column.isGrouped ? 'Click to Un-Group  Click to Sort!' : ' Click to Group  Click to Sort!'}
                        </span>
                      ) : null}
                      <span {...column.getSortByToggleProps()}>
                        {column.render('Header')}
                        {/* Add a sort direction indicator */}
                        {column.isSorted
                          ? column.isSortedDesc
                            ? ' '
                            : ' '
                          : ''}
                      </span>
                    </div>
                    {/* Render the columns filter UI */}
                    <div>{column.canFilter ? column.render('Filter') : null}</div>
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody {...getTableBodyProps()}>
            {page.map(row => {
              prepareRow(row)
              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map(cell => {
                    return (
                      <td className = {td_style} {...cell.getCellProps()}>
                        {cell.isGrouped ? (
                          // If it's a grouped cell, add an expander and row count
                          <>
                            <span {...row.getToggleRowExpandedProps()}>
                              {row.isExpanded ? '' : ''}
                            </span>{' '}
                            {cell.render('Cell', { editable: false })} (
                            {row.subRows.length})
                          </>
                        ) : cell.isAggregated ? (
                          // If the cell is aggregated, use the Aggregated
                          // renderer for cell
                          cell.render('Aggregated')
                        ) : cell.isPlaceholder ? null : ( // For cells with repeated values, render null
                          // Otherwise, just render the regular cell
                          cell.render('Cell', { editable: true })
                        )}
                      </td>
                    )
                  })}
                </tr>
              )
            })}
          </tbody>
        </table>
        {/*
          Pagination can be built however you'd like.
          This is just a very basic UI implementation:
        */}
        <div className="pagination">
          <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
            {'<<'}
          </button>{' '}
          <button onClick={() => previousPage()} disabled={!canPreviousPage}>
            {'<'}
          </button>{' '}
          <button onClick={() => nextPage()} disabled={!canNextPage}>
            {'>'}
          </button>{' '}
          <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
            {'>>'}
          </button>{' '}
          <span>
            Page{' '}
            <strong>
              {pageIndex + 1} of {pageOptions.length}
            </strong>{' '}
          </span>
          <span>
            | Go to page:{' '}
            <input
              type="number"
              defaultValue={pageIndex + 1}
              onChange={e => {
                const page = e.target.value ? Number(e.target.value) - 1 : 0
                gotoPage(page)
              }}
              style={{ width: '100px' }}
            />
          </span>{' '}
          <select
            value={pageSize}
            onChange={e => {
              setPageSize(Number(e.target.value))
            }}
          >
            {[10, 20, 30, 40, 50].map(pageSize => (
              <option key={pageSize} value={pageSize}>
                Show {pageSize}
              </option>
            ))}
          </select>
        </div>
        ```
          {/*
            {JSON.stringify(
              {
                pageIndex,
                pageSize,
                pageCount,
                canNextPage,
                canPreviousPage,
                sortBy,
                groupBy,
                expanded: expanded,
                filters,
                selectedRowIds: selectedRowIds,
              },
              null,
              2
            )}
           */}
        ```
      </>
    )
  }

  // Define a custom filter filter function!
  function filterGreaterThan(rows, id, filterValue) {
    return rows.filter(row => {
      const rowValue = row.values[id]
      return rowValue >= filterValue
    })
  }

  // This is an autoRemove method on the filter function that
  // when given the new filter value and returns true, the filter
  // will be automatically removed. Normally this is just an undefined
  // check, but here, we want to remove the filter if it's not a number
  filterGreaterThan.autoRemove = val => typeof val !== 'number'

  // This is a custom aggregator that
  // takes in an array of leaf values and
  // returns the rounded median
  function roundedMedian(leafValues) {
    let min = leafValues[0] || 0
    let max = leafValues[0] || 0

    leafValues.forEach(value => {
      min = Math.min(min, value)
      max = Math.max(max, value)
    })

    return Math.round((min + max) / 2)
  }

  const IndeterminateCheckbox = React.forwardRef(
    ({ indeterminate, ...rest }, ref) => {
      const defaultRef = React.useRef()
      const resolvedRef = ref || defaultRef

      React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate
      }, [resolvedRef, indeterminate])

      return (
        <>
          <input type="checkbox" ref={resolvedRef} {...rest} />
        </>
      )
    }
  )

  export default Table
</code>```

I would love some help in having the react-table filtered data being updated into the graph component above, dynamically or on a button push, and having the initial call be filtered to make it more usable.

Update

Brilliant code below, I am now getting this error:

```<code>Uncaught TypeError: Cannot read property 'Price' of undefined
    at stackValue (stack.js:7)
    at stack (stack.js:26)
    at generateVerticalStackedBars (nivo-bar.esm.js:212)
    at generateStackedBars (nivo-bar.esm.js:343)
    at Bar (nivo-bar.esm.js:809)
    at renderWithHooks (react-dom.development.js:14803)
    at updateFunctionComponent (react-dom.development.js:17034)
    at beginWork (react-dom.development.js:18610)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at react-dom.development.js:11089
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
    at flushSyncCallbackQueue (react-dom.development.js:11072)
    at discreteUpdates$1 (react-dom.development.js:21893)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)
index.js:1 The above error occurred in the <Bar> component:
    in Bar (created by pure(Bar))
    in pure(Bar) (created by withPropsOnChange(pure(Bar)))
    in withPropsOnChange(pure(Bar)) (created by withPropsOnChange(withPropsOnChange(pure(Bar))))
    in withPropsOnChange(withPropsOnChange(pure(Bar))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))) (created by defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))
    in defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))) (created by withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))
    in withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))) (created by defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))))
    in defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))) (created by withPropsOnChange(defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))))
    in withPropsOnChange(defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))) (created by Bar)
    in Bar (at Chart.js:6)
    in div (at Chart.js:5)
    in Chart (at smartSpy.tsx:276)
    in div (at smartSpy.tsx:275)
    in div (at smartSpy.tsx:274)
    in div (at smartSpy.tsx:273)
    in div (at smartSpy.tsx:222)
    in div (at LayoutExampleEcommerce.js:26)
    in div (at LayoutExampleEcommerce.js:21)
    in div (at LayoutExampleEcommerce.js:14)
    in Layout (at smartSpy.tsx:220)
    in SmartSpy (at _app.js:8)
    in MyApp
    in Container (created by AppContainer)
    in AppContainer

React will try to recreate this component tree from scratch using the error boundary you provided, MyApp.
console.<computed> @ index.js:1
_app.js:7 Uncaught TypeError: Cannot read property 'Price' of undefined
    at stackValue (stack.js:7)
    at stack (stack.js:26)
    at generateVerticalStackedBars (nivo-bar.esm.js:212)
    at generateStackedBars (nivo-bar.esm.js:343)
    at Bar (nivo-bar.esm.js:809)
    at renderWithHooks (react-dom.development.js:14803)
    at updateFunctionComponent (react-dom.development.js:17034)
    at beginWork (react-dom.development.js:18610)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at react-dom.development.js:11089
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
    at flushSyncCallbackQueue (react-dom.development.js:11072)
    at discreteUpdates$1 (react-dom.development.js:21893)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)
</code>```

This is occuring when the data is grouped by the react-table function (changing the values of the rows completely, by grouping the clicked on column).

Thanks again

Not all linked together, but should make it easy to understand how to solve this issue.

Thanks so much!

答:
What you can do is communicate between Table and Chart with the help of parent. With react table you can get the filtered data from rows. You can use that and pass on that information to the parent which in turn will pass the data to Chart

    import OriginalData from 'path/to/data';

    const App = () => {
       const [data, setData] = useState(OriginalData);
       const updateData = useCallback((data) => {
           setData(data);
       }, []);

       return (
           <>
              <Chart data={data} />

           </>
       )
    }
```
<p>Now in Table</p>
```const Table = ({data, updateData}) => {
    // Use the state and functions returned from useTable to build your UI
    ...
    const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      prepareRow,
      rows,
      page, // Instead of using 'rows', we'll use page,
      // which has only the rows for the active page

      // The rest of these things are super handy, too ;)
      canPreviousPage,
      canNextPage,
      pageOptions,
      pageCount,
      gotoPage,
      nextPage,
      previousPage,
      setPageSize,
      state: {
        pageIndex,
        pageSize,
        sortBy,
        groupBy,
        expanded,
        filters,
        selectedRowIds,
      },
    } = useTable(
      {
        columns,
        data,
        defaultColumn,
        filterTypes,
        // updateMyData isn't part of the API, but
        // anything we put into these options will
        // automatically be available on the instance.
        // That way we can call this function from our
        // cell renderer!
        updateMyData,
        // We also need to pass this so the page doesn't change
        // when we edit the data.
        autoResetPage: !skipReset,
        autoResetSelectedRows: !skipReset,
        disableMultiSort: true,
      },
      useFilters,
      useGroupBy,
      useSortBy,
      useExpanded,
      usePagination,
      useRowSelect,
      // Here we will use a plugin to add our selection column
      hooks => {
        hooks.visibleColumns.push(columns => {
          return [
            {
              id: 'selection',
              // Make this column a groupByBoundary. This ensures that groupBy columns
              // are placed after it
              groupByBoundary: true,
              // The header can use the table's getToggleAllRowsSelectedProps method
              // to render a checkbox
              Header: ({ getToggleAllRowsSelectedProps }) => (

                  <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />

              ),
              // The cell can use the individual row's getToggleRowSelectedProps method
              // to the render a checkbox
              Cell: ({ row }) => (

                  <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />

              ),
            },
            ...columns,
          ]
        })
      }
    )

    useEffect(() => {
        const newData = rows.map(r => r.original);
        updateData(newData); // update to parent based on change in row
    }, [rows])

    ...
}
```

Body:
Using react-table, I can filter the data really well, but would like it to be more dynamic

Now what I'm struggling to complete is filtering the data in the graph, so that it's more meaningful, partly by clumping products from singular brands together in one bar chart, and also by removing excess amounts of brands that make the information harder to understand.

This is the Table component I am using

import React from 'react'
import {
    useTable,
    usePagination,
    useSortBy,
    useFilters,
    useGroupBy,
    useExpanded,
    useRowSelect,
  } from 'react-table'
  import matchSorter from 'match-sorter'

  // import makeData from '../example/makedata.js'

  // Create an editable cell renderer
  const EditableCell = ({
    value: initialValue,
    row: { index },
    column: { id },
    updateMyData, // This is a custom function that we supplied to our table instance
    editable,
  }) => {
    // We need to keep and update the state of the cell normally
    const [value, setValue] = React.useState(initialValue)

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

    // We'll only update the external data when the input is blurred
    const onBlur = () => {
      updateMyData(index, id, value)
    }

    // If the initialValue is changed externall, sync it up with our state
    React.useEffect(() => {
      setValue(initialValue)
    }, [initialValue])

    if (!editable) {
      return `${initialValue}`
    }

    return <input value={value} onChange={onChange} onBlur={onBlur} />
  }

  // Define a default UI for filtering
  function DefaultColumnFilter({
    column: { filterValue, preFilteredRows, setFilter },
  }) {
    const count = preFilteredRows.length

    return (
      <input
        value={filterValue || ''}
        onChange={e => {
          setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
        }}
        placeholder={`Search ${count} records...`}
      />
    )
  }

  // This is a custom filter UI for selecting
  // a unique option from a list
  function SelectColumnFilter({
    column: { filterValue, setFilter, preFilteredRows, id },
  }) {
    // Calculate the options for filtering
    // using the preFilteredRows
    const options = React.useMemo(() => {
      const options = new Set()
      preFilteredRows.forEach(row => {
        options.add(row.values[id])
      })
      return [...options.values()]
    }, [id, preFilteredRows])

    // Render a multi-select box
    return (
      <select
        value={filterValue}
        onChange={e => {
          setFilter(e.target.value || undefined)
        }}
      >
        <option value="">All</option>
        {options.map((option, i) => (
          <option key={i} value={option}>
            {option}
          </option>
        ))}
      </select>
    )
  }

  // This is a custom filter UI that uses a
  // slider to set the filter value between a column's
  // min and max values
  function SliderColumnFilter({
    column: { filterValue, setFilter, preFilteredRows, id },
  }) {
    // Calculate the min and max
    // using the preFilteredRows

    const [min, max] = React.useMemo(() => {
      let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      preFilteredRows.forEach(row => {
        min = Math.min(row.values[id], min)
        max = Math.max(row.values[id], max)
      })
      return [min, max]
    }, [id, preFilteredRows])

    return (
      <>
        <input
          type="range"
          min={min}
          max={max}
          value={filterValue || min}
          onChange={e => {
            setFilter(parseInt(e.target.value, 10))
          }}
        />
        <button onClick={() => setFilter(undefined)}>Off</button>
      </>
    )
  }

  // This is a custom UI for our 'between' or number range
  // filter. It uses two number boxes and filters rows to
  // ones that have values between the two
  function NumberRangeColumnFilter({
    column: { filterValue = [], preFilteredRows, setFilter, id },
  }) {
    const [min, max] = React.useMemo(() => {
      let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
      preFilteredRows.forEach(row => {
        min = Math.min(row.values[id], min)
        max = Math.max(row.values[id], max)
      })
      return [min, max]
    }, [id, preFilteredRows])

    return (

        <input
          value={filterValue[0] || ''}
          type="number"
          onChange={e => {
            const val = e.target.value
            setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
          }}
          placeholder={`Min (${min})`}
          style={{
            width: '70px',
            marginRight: '0.5rem',
          }}
        />
        to
        <input
          value={filterValue[1] || ''}
          type="number"
          onChange={e => {
            const val = e.target.value
            setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
          }}
          placeholder={`Max (${max})`}
          style={{
            width: '70px',
            marginLeft: '0.5rem',
          }}
        />

    )
  }

  function fuzzyTextFilterFn(rows, id, filterValue) {
    return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
  }

  // Let the table remove the filter if the string is empty
  fuzzyTextFilterFn.autoRemove = val => !val

  // Be sure to pass our updateMyData and the skipReset option
  function Table({ columns, data, updateMyData, skipReset }) {
    const td_header = "px-4 py-2"
  const td_style = "border px-4 py-2"
    const filterTypes = React.useMemo(
      () => ({
        // Add a new fuzzyTextFilterFn filter type.
        fuzzyText: fuzzyTextFilterFn,
        // Or, override the default text filter to use
        // "startWith"
        text: (rows, id, filterValue) => {
          return rows.filter(row => {
            const rowValue = row.values[id]
            return rowValue !== undefined
              ? String(rowValue)
                  .toLowerCase()
                  .startsWith(String(filterValue).toLowerCase())
              : true
          })
        },
      }),
      []
    )

    const defaultColumn = React.useMemo(
      () => ({
        // Let's set up our default Filter UI
        Filter: DefaultColumnFilter,
        // And also our default editable cell
        Cell: EditableCell,
      }),
      []
    )

    // Use the state and functions returned from useTable to build your UI
    const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      prepareRow,
      page, // Instead of using 'rows', we'll use page,
      // which has only the rows for the active page

      // The rest of these things are super handy, too ;)
      canPreviousPage,
      canNextPage,
      pageOptions,
      pageCount,
      gotoPage,
      nextPage,
      previousPage,
      setPageSize,
      state: {
        pageIndex,
        pageSize,
        sortBy,
        groupBy,
        expanded,
        filters,
        selectedRowIds,
      },
    } = useTable(
      {
        columns,
        data,
        defaultColumn,
        filterTypes,
        // updateMyData isn't part of the API, but
        // anything we put into these options will
        // automatically be available on the instance.
        // That way we can call this function from our
        // cell renderer!
        updateMyData,
        // We also need to pass this so the page doesn't change
        // when we edit the data.
        autoResetPage: !skipReset,
        autoResetSelectedRows: !skipReset,
        disableMultiSort: true,
      },
      useFilters,
      useGroupBy,
      useSortBy,
      useExpanded,
      usePagination,
      useRowSelect,
      // Here we will use a plugin to add our selection column
      hooks => {
        hooks.visibleColumns.push(columns => {
          return [
            {
              id: 'selection',
              // Make this column a groupByBoundary. This ensures that groupBy columns
              // are placed after it
              groupByBoundary: true,
              // The header can use the table's getToggleAllRowsSelectedProps method
              // to render a checkbox
              Header: ({ getToggleAllRowsSelectedProps }) => (

                  <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />

              ),
              // The cell can use the individual row's getToggleRowSelectedProps method
              // to the render a checkbox
              Cell: ({ row }) => (

                  <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />

              ),
            },
            ...columns,
          ]
        })
      }
    )

    // Render the UI for your table
    return (
      <>

            {headerGroups.map(headerGroup => (

                {headerGroup.headers.map(column => (

                      {column.canGroupBy ? (
                        // If the column can be grouped, let's add a toggle

                          {column.isGrouped ? 'Click to Un-Group  Click to Sort!' : ' Click to Group  Click to Sort!'}

                      ) : null}

                        {column.render('Header')}
                        {/* Add a sort direction indicator */}
                        {column.isSorted
                          ? column.isSortedDesc
                            ? ' '
                            : ' '
                          : ''}

                    {/* Render the columns filter UI */}

{column.canFilter ? column.render('Filter') : null}

                ))}

            ))}

            {page.map(row => {
              prepareRow(row)
              return (

                  {row.cells.map(cell => {
                    return (

                        {cell.isGrouped ? (
                          // If it's a grouped cell, add an expander and row count
                          <>

                              {row.isExpanded ? '' : ''}
                            {' '}
                            {cell.render('Cell', { editable: false })} (
                            {row.subRows.length})
                          </>
                        ) : cell.isAggregated ? (
                          // If the cell is aggregated, use the Aggregated
                          // renderer for cell
                          cell.render('Aggregated')
                        ) : cell.isPlaceholder ? null : ( // For cells with repeated values, render null
                          // Otherwise, just render the regular cell
                          cell.render('Cell', { editable: true })
                        )}

                    )
                  })}

              )
            })}

        {/*
          Pagination can be built however you'd like.
          This is just a very basic UI implementation:
        */}

          <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
            {'<<'}
          </button>{' '}
          <button onClick={() => previousPage()} disabled={!canPreviousPage}>
            {'<'}
          </button>{' '}
          <button onClick={() => nextPage()} disabled={!canNextPage}>
            {'>'}
          </button>{' '}
          <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
            {'>>'}
          </button>{' '}

            Page{' '}

              {pageIndex + 1} of {pageOptions.length}
            {' '}

            | Go to page:{' '}
            <input
              type="number"
              defaultValue={pageIndex + 1}
              onChange={e => {
                const page = e.target.value ? Number(e.target.value) - 1 : 0
                gotoPage(page)
              }}
              style={{ width: '100px' }}
            />
          {' '}
          <select
            value={pageSize}
            onChange={e => {
              setPageSize(Number(e.target.value))
            }}
          >
            {[10, 20, 30, 40, 50].map(pageSize => (
              <option key={pageSize} value={pageSize}>
                Show {pageSize}
              </option>
            ))}
          </select>

          {/*
            {JSON.stringify(
              {
                pageIndex,
                pageSize,
                pageCount,
                canNextPage,
                canPreviousPage,
                sortBy,
                groupBy,
                expanded: expanded,
                filters,
                selectedRowIds: selectedRowIds,
              },
              null,
              2
            )}
           */}

      </>
    )
  }

  // Define a custom filter filter function!
  function filterGreaterThan(rows, id, filterValue) {
    return rows.filter(row => {
      const rowValue = row.values[id]
      return rowValue >= filterValue
    })
  }

  // This is an autoRemove method on the filter function that
  // when given the new filter value and returns true, the filter
  // will be automatically removed. Normally this is just an undefined
  // check, but here, we want to remove the filter if it's not a number
  filterGreaterThan.autoRemove = val => typeof val !== 'number'

  // This is a custom aggregator that
  // takes in an array of leaf values and
  // returns the rounded median
  function roundedMedian(leafValues) {
    let min = leafValues[0] || 0
    let max = leafValues[0] || 0

    leafValues.forEach(value => {
      min = Math.min(min, value)
      max = Math.max(max, value)
    })

    return Math.round((min + max) / 2)
  }

  const IndeterminateCheckbox = React.forwardRef(
    ({ indeterminate, ...rest }, ref) => {
      const defaultRef = React.useRef()
      const resolvedRef = ref || defaultRef

      React.useEffect(() => {
        resolvedRef.current.indeterminate = indeterminate
      }, [resolvedRef, indeterminate])

      return (
        <>
          <input type="checkbox" ref={resolvedRef} {...rest} />
        </>
      )
    }
  )

  export default Table

I would love some help in having the react-table filtered data being updated into the graph component above, dynamically or on a button push, and having the initial call be filtered to make it more usable.

Update

Brilliant code below, I am now getting this error:

Uncaught TypeError: Cannot read property 'Price' of undefined
    at stackValue (stack.js:7)
    at stack (stack.js:26)
    at generateVerticalStackedBars (nivo-bar.esm.js:212)
    at generateStackedBars (nivo-bar.esm.js:343)
    at Bar (nivo-bar.esm.js:809)
    at renderWithHooks (react-dom.development.js:14803)
    at updateFunctionComponent (react-dom.development.js:17034)
    at beginWork (react-dom.development.js:18610)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at react-dom.development.js:11089
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
    at flushSyncCallbackQueue (react-dom.development.js:11072)
    at discreteUpdates$1 (react-dom.development.js:21893)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)
index.js:1 The above error occurred in the <Bar> component:
    in Bar (created by pure(Bar))
    in pure(Bar) (created by withPropsOnChange(pure(Bar)))
    in withPropsOnChange(pure(Bar)) (created by withPropsOnChange(withPropsOnChange(pure(Bar))))
    in withPropsOnChange(withPropsOnChange(pure(Bar))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))) (created by withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))
    in withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))) (created by defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))
    in defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))) (created by withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))
    in withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))) (created by defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))))
    in defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar)))))))))))) (created by withPropsOnChange(defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))))
    in withPropsOnChange(defaultProps(withPropsOnChange(defaultProps(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(pure(Bar))))))))))))) (created by Bar)
    in Bar (at Chart.js:6)
    in div (at Chart.js:5)
    in Chart (at smartSpy.tsx:276)
    in div (at smartSpy.tsx:275)
    in div (at smartSpy.tsx:274)
    in div (at smartSpy.tsx:273)
    in div (at smartSpy.tsx:222)
    in div (at LayoutExampleEcommerce.js:26)
    in div (at LayoutExampleEcommerce.js:21)
    in div (at LayoutExampleEcommerce.js:14)
    in Layout (at smartSpy.tsx:220)
    in SmartSpy (at _app.js:8)
    in MyApp
    in Container (created by AppContainer)
    in AppContainer

React will try to recreate this component tree from scratch using the error boundary you provided, MyApp.
console.<computed> @ index.js:1
_app.js:7 Uncaught TypeError: Cannot read property 'Price' of undefined
    at stackValue (stack.js:7)
    at stack (stack.js:26)
    at generateVerticalStackedBars (nivo-bar.esm.js:212)
    at generateStackedBars (nivo-bar.esm.js:343)
    at Bar (nivo-bar.esm.js:809)
    at renderWithHooks (react-dom.development.js:14803)
    at updateFunctionComponent (react-dom.development.js:17034)
    at beginWork (react-dom.development.js:18610)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at react-dom.development.js:11089
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
    at flushSyncCallbackQueue (react-dom.development.js:11072)
    at discreteUpdates$1 (react-dom.development.js:21893)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)

This is occuring when the data is grouped by the react-table function (changing the values of the rows completely, by grouping the clicked on column).

Thanks again

Not all linked together, but should make it easy to understand how to solve this issue.

Thanks so much!

Body:
What you can do is communicate between Table and Chart with the help of parent. With react table you can get the filtered data from rows. You can use that and pass on that information to the parent which in turn will pass the data to Chart

    import OriginalData from 'path/to/data';

    const App = () => {
       const [data, setData] = useState(OriginalData);
       const updateData = useCallback((data) => {
           setData(data);
       }, []);

       return (
           <>
              <Chart data={data} />
              <Table updateData={updateData} data={originalData}/>
           </>
       )
    }

Now in Table

const Table = ({data, updateData}) => {
    // Use the state and functions returned from useTable to build your UI
    ...
    const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      prepareRow,
      rows,
      page, // Instead of using 'rows', we'll use page,
      // which has only the rows for the active page

      // The rest of these things are super handy, too ;)
      canPreviousPage,
      canNextPage,
      pageOptions,
      pageCount,
      gotoPage,
      nextPage,
      previousPage,
      setPageSize,
      state: {
        pageIndex,
        pageSize,
        sortBy,
        groupBy,
        expanded,
        filters,
        selectedRowIds,
      },
    } = useTable(
      {
        columns,
        data,
        defaultColumn,
        filterTypes,
        // updateMyData isn't part of the API, but
        // anything we put into these options will
        // automatically be available on the instance.
        // That way we can call this function from our
        // cell renderer!
        updateMyData,
        // We also need to pass this so the page doesn't change
        // when we edit the data.
        autoResetPage: !skipReset,
        autoResetSelectedRows: !skipReset,
        disableMultiSort: true,
      },
      useFilters,
      useGroupBy,
      useSortBy,
      useExpanded,
      usePagination,
      useRowSelect,
      // Here we will use a plugin to add our selection column
      hooks => {
        hooks.visibleColumns.push(columns => {
          return [
            {
              id: 'selection',
              // Make this column a groupByBoundary. This ensures that groupBy columns
              // are placed after it
              groupByBoundary: true,
              // The header can use the table's getToggleAllRowsSelectedProps method
              // to render a checkbox
              Header: ({ getToggleAllRowsSelectedProps }) => (
                <div>
                  <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
                </div>
              ),
              // The cell can use the individual row's getToggleRowSelectedProps method
              // to the render a checkbox
              Cell: ({ row }) => (
                <div>
                  <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
                </div>
              ),
            },
            ...columns,
          ]
        })
      }
    )

    useEffect(() => {
        const newData = rows.map(r => r.original);
        updateData(newData); // update to parent based on change in row
    }, [rows])

    ...
}