问:
Capturing the tab click event in Android Tabview
I have a tabview in my android app with 3 tabs. The tabs are all working fine.

Now I want to perform some additional logic when the tab (on the top) of the currently active tab is clicked.

Here is an example:

In one of my tabs, I provide an option for the user to sort things in different order. When the press the tab of the currently active tab, I want to reset all these sorting.

Is it possible to capture the tab click event in tabview and perform some additional logic?

Edit: Edited for clarity.

答:
```<code>    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
    {
        getTabWidget().getChildAt(i).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (getTabHost().getCurrentTabTag().equals(v.getTag()))
                {
                    int nextTab = getTabHost().getCurrentTab();
                    tabHost.setCurrentTab(prevTab);
                    tabHost.setCurrentTab(nextTab);
                    prevTab = nextTab;
                }
                else
                    tabHost.setCurrentTabByTag((String) v.getTag());
            }
        });
    }
</code>```

You need a global variable;

```<code>    private int prevTab = 1;   //any tab except the initial one.
</code>```

This code works for me. A little ugly thing is you must set same tag for tab and view
For example;

```<code>    intent = new Intent().setClass(this, AnaSayfa.class);
    spec = tabHost.newTabSpec("firstTab").setIndicator(makeTabIndicator(R.drawable.firstTab, "First Tab" , "firstTab"))
                  .setContent(intent);
    tabHost.addTab(spec);
</code>```

and makeTabIndicator method is like that,

```<code>    private View makeTabIndicator(int drawable, String text, String viewTag){

        View view = LayoutInflater.from(this).inflate(R.layout.tab_layout, null);

        ImageView image = (ImageView) view.findViewById(R.id.imageView1);
        image.setImageResource(drawable);
        image.setAdjustViewBounds(true);

        TextView tv = (TextView) view.findViewById(R.id.textView1);
        tv.setText(text);

        view.setTag(viewTag);
        return view;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
    {
        getTabWidget().getChildAt(i).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (getTabHost().getCurrentTabTag().equals(v.getTag()))
                {
                    int nextTab = getTabHost().getCurrentTab();
                    tabHost.setCurrentTab(prevTab);
                    tabHost.setCurrentTab(nextTab);
                    prevTab = nextTab;
                }
                else
                    tabHost.setCurrentTabByTag((String) v.getTag());
            }
        });
    }

You need a global variable;

    private int prevTab = 1;   //any tab except the initial one.

This code works for me. A little ugly thing is you must set same tag for tab and view
For example;

    intent = new Intent().setClass(this, AnaSayfa.class);
    spec = tabHost.newTabSpec("firstTab").setIndicator(makeTabIndicator(R.drawable.firstTab, "First Tab" , "firstTab"))
                  .setContent(intent);
    tabHost.addTab(spec);

and makeTabIndicator method is like that,

    private View makeTabIndicator(int drawable, String text, String viewTag){

        View view = LayoutInflater.from(this).inflate(R.layout.tab_layout, null);

        ImageView image = (ImageView) view.findViewById(R.id.imageView1);
        image.setImageResource(drawable);
        image.setAdjustViewBounds(true);

        TextView tv = (TextView) view.findViewById(R.id.textView1);
        tv.setText(text);

        view.setTag(viewTag);
        return view;
    }


来源: stackexchange

问:
Pythonic way to a double comprehension
I have to get a list of handles and labels from a figure, except in the cases where the label is "True" or "False". The following code accomplishes this:

```<code># h, l = [a for a in ax.get_legend_handles_labels()] #redundant
h, l = ax.get_legend_handles_labels()
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

Nevertheless, this seems completely "not-pythonic". Is there a more elegant way to solve this?
I tried the following 2-liner but I got a ValueError: too many values to unpack (expected 2) on line 2:

```<code>h, l = [a for a in ax.get_legend_handles_labels()]
handles, labels = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

I'd expect Python to have a one-line solution...is there any?

For reproducibility:

```<code>(h,l)=(['handle1','handle2', 'handle3'],['label1','True', 'False'])
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]
</code>```

The intended output for this reproducible example is

```<code>handles=['handle1']
labels=['label1']
</code>```

答:
There is a technique called "unzipping" an iterator (see fourth line in my code example), which is kind of a reshape of nested elements. It's a little bit like numpy's swapaxes if you are familiar with it. Combining python's iterators zip and filter you can achieve the desired behaviour in the following way:

```<code>h, l = ax.get_legend_handles_labels()
zipped = zip(h, l)
filtered = filter(lambda t: t[1] != 'True' and t[1] != 'False', zipped)
handles, labels = zip(*filtered)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pythonic way to a double comprehension

Body:
I have to get a list of handles and labels from a figure, except in the cases where the label is "True" or "False". The following code accomplishes this:

# h, l = [a for a in ax.get_legend_handles_labels()] #redundant
h, l = ax.get_legend_handles_labels()
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

Nevertheless, this seems completely "not-pythonic". Is there a more elegant way to solve this?
I tried the following 2-liner but I got a ValueError: too many values to unpack (expected 2) on line 2:

h, l = [a for a in ax.get_legend_handles_labels()]
handles, labels = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]

I'd expect Python to have a one-line solution...is there any?

For reproducibility:

(h,l)=(['handle1','handle2', 'handle3'],['label1','True', 'False'])
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

The intended output for this reproducible example is

handles=['handle1']
labels=['label1']

Body:
There is a technique called "unzipping" an iterator (see fourth line in my code example), which is kind of a reshape of nested elements. It's a little bit like numpy's swapaxes if you are familiar with it. Combining python's iterators zip and filter you can achieve the desired behaviour in the following way:

h, l = ax.get_legend_handles_labels()
zipped = zip(h, l)
filtered = filter(lambda t: t[1] != 'True' and t[1] != 'False', zipped)
handles, labels = zip(*filtered)


问:
MySQL - How can I group music together when the names are similar?
I would like to be able to return a single line when the name of some musics are the same or similar, as for example this case:
music with similar names

You can see that the names are the same with an extension like " - JP Ver." or something like that, I would like to be able to group them in one row with the first column incrementing the whole.

My current request to return these lines is as follows:

```<code>select count(id) number, name, sec_to_time(floor(sum(duration) / 1000)) time
from track
where user_id = 'value'
group by name, duration
order by number desc, time desc;
</code>```

I would like to get a result like this

Thank you for reading and responding! I wish you all a good day!

答:
Use GROUP_CONCAT
Here is a proof of concept script. You can add your other columns. I have grouped by the first 4 letters. You will probably want to use more.

```<code>CREATE TABLE track (
        idd INT,
        nam CHAR(50),
        tim INT
        );
INSERT INTO track VALUES (1,'Abba 1',5);
INSERT INTO track VALUES (2,'Abba 2',6);
INSERT INTO track VALUES (3,'Beta 1',12);
INSERT INTO track VALUES (4,'Beta 4',8);

SELECT
        LEFT(nam,4) AS 'Group',
        COUNT(idd) AS 'Number',
        GROUP_CONCAT(DISTINCT idd ORDER BY idd ASC SEPARATOR ' & ') AS IDs,
        GROUP_CONCAT(DISTINCT nam ORDER BY nam ASC SEPARATOR ', ') AS 'track names',
        SUM(tim) AS 'total time'
FROM track
GROUP BY LEFT(nam,4);
DROP TABLE track;
</code>```

Output

```<code>Group   Number  IDs     track names     total time
Abba    2       1 & 2   Abba 1, Abba 2  11
Beta    2       3 & 4   Beta 1, Beta 4  20
</code>```

Body:
I would like to be able to return a single line when the name of some musics are the same or similar, as for example this case:
music with similar names

You can see that the names are the same with an extension like " - JP Ver." or something like that, I would like to be able to group them in one row with the first column incrementing the whole.

My current request to return these lines is as follows:

select count(id) number, name, sec_to_time(floor(sum(duration) / 1000)) time
from track
where user_id = 'value'
group by name, duration
order by number desc, time desc;

I would like to get a result like this

Thank you for reading and responding! I wish you all a good day!

Body:
Use GROUP_CONCAT
Here is a proof of concept script. You can add your other columns. I have grouped by the first 4 letters. You will probably want to use more.

CREATE TABLE track (
        idd INT,
        nam CHAR(50),
        tim INT
        );
INSERT INTO track VALUES (1,'Abba 1',5);
INSERT INTO track VALUES (2,'Abba 2',6);
INSERT INTO track VALUES (3,'Beta 1',12);
INSERT INTO track VALUES (4,'Beta 4',8);

SELECT
        LEFT(nam,4) AS 'Group',
        COUNT(idd) AS 'Number',
        GROUP_CONCAT(DISTINCT idd ORDER BY idd ASC SEPARATOR ' & ') AS IDs,
        GROUP_CONCAT(DISTINCT nam ORDER BY nam ASC SEPARATOR ', ') AS 'track names',
        SUM(tim) AS 'total time'
FROM track
GROUP BY LEFT(nam,4);
DROP TABLE track;

Output

Group   Number  IDs     track names     total time
Abba    2       1 & 2   Abba 1, Abba 2  11
Beta    2       3 & 4   Beta 1, Beta 4  20


问:
How do I access google drive files with the same name in 2 different folders - Python
I am currently trying to access files with the same name in different google drive folders but do not know how to code this. Below is the file paths and names of the files that I am trying to access.

```<code>/content/drive/My Drive/Jacob_Images/Ground_Truths/a (3).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (7).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (6).jpg

/content/drive/My Drive/Jacob_Images/Originals/a (3).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (7).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (6).jpg
</code>```

Below is the code, that I started to make but I am unable to finish it. There are several files in each folder that is why there is an *.

```<code>file = '/content/drive/My Drive/Jacob_Images/Originals/*.jpg'
mask = '/content/drive/My Drive/Jacob_Images/Ground_Truths/*.jpg'
glob.glob(file)
glob.glob(mask)

for x in glob.glob(file):
  for y in glob.glob(mask):

</code>```

答:
In this case, the easiest way I can think of would be something like that

import os

original_folder = "data/originals"
ground_truth_folder = "data/ground_truths"

# get file names of all files in folder without the whole path
original_images = os.listdir(original_folder )
ground_truth_images = os.listdir(ground_truth_folder)

for img in original_images:
    # For every images in the original folder, check if it is in the Ground_truth one
    if img in ground_truth_images
        print(f"{img} is in {original_folder} and {ground_truth_folder}"):
        # Do your comparison here
        same_shape, same_img = compare_images(img, original_folder,ground_truth_folder)

    else:
        print(f"{img} is in {original_folder} but not in {ground_truth_folder}")

```
<p>For your comparison you could have a function like below, that returns both if they have the same shape and if it's the same image:</p>
<pre class="lang-py prettyprint-override"><code>def compare_images(img,original_folder, ground_truth_folder):
    original_img = np.array(Image.open(os.path.join(original_folder, img)))
    ground_truth_img = np.array(Image.open(os.path.join(ground_truth_folder, img)))
    return original_img.shape == ground_truth_img.shape, np.all(original_img == ground_truth_img)
</code>```

Body:
I am currently trying to access files with the same name in different google drive folders but do not know how to code this. Below is the file paths and names of the files that I am trying to access.

/content/drive/My Drive/Jacob_Images/Ground_Truths/a (3).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (7).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (6).jpg

/content/drive/My Drive/Jacob_Images/Originals/a (3).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (7).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (6).jpg

Below is the code, that I started to make but I am unable to finish it. There are several files in each folder that is why there is an *.

file = '/content/drive/My Drive/Jacob_Images/Originals/*.jpg'
mask = '/content/drive/My Drive/Jacob_Images/Ground_Truths/*.jpg'
glob.glob(file)
glob.glob(mask)

for x in glob.glob(file):
  for y in glob.glob(mask):

Body:
In this case, the easiest way I can think of would be something like that

import os

original_folder = "data/originals"
ground_truth_folder = "data/ground_truths"

# get file names of all files in folder without the whole path
original_images = os.listdir(original_folder )
ground_truth_images = os.listdir(ground_truth_folder)

for img in original_images:
    # For every images in the original folder, check if it is in the Ground_truth one
    if img in ground_truth_images
        print(f"{img} is in {original_folder} and {ground_truth_folder}"):
        # Do your comparison here
        same_shape, same_img = compare_images(img, original_folder,ground_truth_folder)

    else:
        print(f"{img} is in {original_folder} but not in {ground_truth_folder}")

For your comparison you could have a function like below, that returns both if they have the same shape and if it's the same image:

def compare_images(img,original_folder, ground_truth_folder):
    original_img = np.array(Image.open(os.path.join(original_folder, img)))
    ground_truth_img = np.array(Image.open(os.path.join(ground_truth_folder, img)))
    return original_img.shape == ground_truth_img.shape, np.all(original_img == ground_truth_img)


问:
Multiple substring replacement in bash
I'm working in an HPC cluster which has a lot of partitions ($HOME, $SCRATCH, $WORKDIR, $SHARED,...) and was trying to find a way to clearly identify which partition I'm at the moment.

After some digging, I found that

```<code>export PS1="\e[33;1m\u@\h: \e[31m\w\e[0m\$ "
</code>```

would show me what I'm looking for. However, the path becomes really cumbersome since all of these partitions have a really long pwd output.

I found out that this command,

```<code>aaa@bbb: ~$ echo $PROMPT_COMMAND
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" ${PWD/#$HOME/~}"
</code>```

mainly the ${PWD/#$HOME/~} part, might be why the $HOME directory appears simply with ~.

Is there a way to change this environment variable (or any other alternative) for me to have something like:

```<code>aaa@bbb: ~/foo/bar$          # when I'm working in $HOME
aaa@bbb: scratch/foo/bar$    # when I'm working in $SCRATCH
aaa@bbb: shared/foo/bar$     # when I'm working in $SHARED
</code>```

答:
In ~/.bashrc you can define :

```<code>PROMPT_DIRTRIM=3
</code>```

to keep the last 3 compoments of $PWD

Title: Multiple substring replacement in bash

Body:
I'm working in an HPC cluster which has a lot of partitions ($HOME, $SCRATCH, $WORKDIR, $SHARED,...) and was trying to find a way to clearly identify which partition I'm at the moment.

After some digging, I found that

export PS1="\e[33;1m\u@\h: \e[31m\w\e[0m\$ "

would show me what I'm looking for. However, the path becomes really cumbersome since all of these partitions have a really long pwd output.

I found out that this command,

aaa@bbb: ~$ echo $PROMPT_COMMAND
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" ${PWD/#$HOME/~}"

mainly the ${PWD/#$HOME/~} part, might be why the $HOME directory appears simply with ~.

Is there a way to change this environment variable (or any other alternative) for me to have something like:

aaa@bbb: ~/foo/bar$          # when I'm working in $HOME
aaa@bbb: scratch/foo/bar$    # when I'm working in $SCRATCH
aaa@bbb: shared/foo/bar$     # when I'm working in $SHARED

Body:
In ~/.bashrc you can define :

PROMPT_DIRTRIM=3

to keep the last 3 compoments of $PWD


问:
DataGrid not updating when items added to ObservableCollection in Silverlight
I have a Silverlight application which interacts with a WCF service. It periodically receives new items to add to a list from this service, and each new element is added to the end of an ObservableCollection (collection.Add() for each new element).

The items themselves don't change once they are received, and the items' class inherits INotifyPropertyChanged, however when I add new items (received from WCF), the DataGrid doesn't update.

I am also using a custom formatter for the DataGrid binding, but I don't think this is a problem as the initial set of items appear correctly (when the ItemsSource is first set).

I would have expected the new elements to appear, as I have confirmed that the ObservableCollection is emitting the correct add event. Since ObservableCollection inherits from INotifyCollectionChanged, shouldn't it update the DataGrid?

The only solution I have found so far is:

```<code>dataGrid.ItemsSource = null;
dataGrid.ItemsSource = collection;
</code>```

Any ideas on how to get it updating? This method blocks the UI for a noticable amount of time.

Thanks

UPDATE: Code

The elements are expanded and extracted in the WCF callback event:

```<code>// The ItemWrapper allows the Binding converter to be passed the entire trade object, rather than just each property.
ObservableCollection<ItemWrapper<ExpandedTrade>> pastTrades = new ObservableCollection<ItemWrapper<ExpandedTrade>>();
....

       // Extract and expand data - MinimalTrade is the data sent through WCF
       var convertedTrades = from MinimalTrade t in e.trades
                                  select new ItemWrapper<ExpandedTrade>(
                                      new ExpandedTrade(t,
                                          usernames.ContainsKey(t.UserToId) ? usernames[t.UserToId] : null, potentialWealth != null ? potentialWealth.CurrentWealth : null)); // Get name, otherwise null.
       // Data now expanded (to show full information like usernames
       // pastTrades is an observableCollection
            foreach (var trade in convertedTrades)
            {
                pastTrades.Add(trade);
            }
            OnNewMyTradeHistory(pastTrades);
</code>```

The OnNewMyTradeHistory event then does this:

```<code>if (tradeHistory.ItemsSource == null) tradeHistory.ItemsSource = trades;
</code>```

This only sets ItemsSource once (to the ObservableCollection) and the add events are firing, but nothing is happening on the UI side.

The WCF callbacks might be happening in another thread.

答:
Tell me if this flow is correct:

DataGrid.ItemsSource == null;

[Update]

Create new observable collection: CollectionA

Get items and add them to CollectionA

[Event]

DataGrid.ItemsSource == null -> ItemsSource = CollectionA

[Update]

Create new observable collection: CollectionB

Get items and add them to CollectionB

[Event]

DataGrid.ItemsSource != null -> Do Nothing

=> DataGrid.ItemsSource == CollectionA?

Or is pastTrades a field which is only initialized once? Brackets and method boundaries would help.

ContentLicense: CC BY-SA 3.0

Body:
I have a Silverlight application which interacts with a WCF service. It periodically receives new items to add to a list from this service, and each new element is added to the end of an ObservableCollection (collection.Add() for each new element).

The items themselves don't change once they are received, and the items' class inherits INotifyPropertyChanged, however when I add new items (received from WCF), the DataGrid doesn't update.

I am also using a custom formatter for the DataGrid binding, but I don't think this is a problem as the initial set of items appear correctly (when the ItemsSource is first set).

I would have expected the new elements to appear, as I have confirmed that the ObservableCollection is emitting the correct add event. Since ObservableCollection inherits from INotifyCollectionChanged, shouldn't it update the DataGrid?

The only solution I have found so far is:

dataGrid.ItemsSource = null;
dataGrid.ItemsSource = collection;

Any ideas on how to get it updating? This method blocks the UI for a noticable amount of time.

Thanks

UPDATE: Code

The elements are expanded and extracted in the WCF callback event:

// The ItemWrapper allows the Binding converter to be passed the entire trade object, rather than just each property.
ObservableCollection<ItemWrapper<ExpandedTrade>> pastTrades = new ObservableCollection<ItemWrapper<ExpandedTrade>>();
....

       // Extract and expand data - MinimalTrade is the data sent through WCF
       var convertedTrades = from MinimalTrade t in e.trades
                                  select new ItemWrapper<ExpandedTrade>(
                                      new ExpandedTrade(t,
                                          usernames.ContainsKey(t.UserToId) ? usernames[t.UserToId] : null, potentialWealth != null ? potentialWealth.CurrentWealth : null)); // Get name, otherwise null.
       // Data now expanded (to show full information like usernames
       // pastTrades is an observableCollection
            foreach (var trade in convertedTrades)
            {
                pastTrades.Add(trade);
            }
            OnNewMyTradeHistory(pastTrades);

The OnNewMyTradeHistory event then does this:

if (tradeHistory.ItemsSource == null) tradeHistory.ItemsSource = trades;

This only sets ItemsSource once (to the ObservableCollection) and the add events are firing, but nothing is happening on the UI side.

The WCF callbacks might be happening in another thread.


问:
No major tick marks showing using seaborn white style and cannot restore
When I generate plots using the seaborn "white" style I see major tick labels but I don't see any major tick marks.

Setting major tick marks to be bigger using...

```<code>%matplotlib inline

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})
plt.rcParams['xtick.major.size'] = 20
plt.rcParams['xtick.major.width'] = 4

fig, ax = plt.subplots()
plt.show()
</code>```

...has no effect.

I can't find any option that would make the tick marks visible/invisible.

Anybody have any clues?

答:
In case one wants to not mess with global rcParams, but manually tune by plot, one can use ax.tick_params()

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})

fig, ax = plt.subplots()
ax.tick_params(bottom=True, left=True)
plt.show()
```

The critical part is "enabling" the tick marks - in this case the bottom and left marks were enabled. If one wants marks on the four sides, using ax.tick_params(reset=True) might also be an option, though I'm not sure how this might affect other Seaborn tunings.

There are also a number of options listed in the function documentation that might be useful, although they do not apply directly to OP.

Note: this answer also works for other styles, including the default one, not just 'white'.

Body:
When I generate plots using the seaborn "white" style I see major tick labels but I don't see any major tick marks.

Setting major tick marks to be bigger using...

%matplotlib inline

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})
plt.rcParams['xtick.major.size'] = 20
plt.rcParams['xtick.major.width'] = 4

fig, ax = plt.subplots()
plt.show()

...has no effect.

I can't find any option that would make the tick marks visible/invisible.

Anybody have any clues?

Body:
In case one wants to not mess with global rcParams, but manually tune by plot, one can use ax.tick_params()

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style('white', {'axes.linewidth': 0.5})

fig, ax = plt.subplots()
ax.tick_params(bottom=True, left=True)
plt.show()

The critical part is "enabling" the tick marks - in this case the bottom and left marks were enabled. If one wants marks on the four sides, using ax.tick_params(reset=True) might also be an option, though I'm not sure how this might affect other Seaborn tunings.

There are also a number of options listed in the function documentation that might be useful, although they do not apply directly to OP.

Note: this answer also works for other styles, including the default one, not just 'white'.


问:
Unable to signinWithPhoneNumber using react-native-firebase
We keep on getting this error  "We have blocked all requests from this device due to unusual activity. Try again later."
When we try to signInWithPhoneNumber . This also blocks all the requests from same device even if I try to change the phone number.
We have already setup SHA-256 certificate fingerprint to SHA key from "Upload key certificate" on Google PlayStore. We are generating a signed Apk with release mode on android and distribution IPA for iOS.
We are unable to resolve this issue, please help us to identify the issue. We are developing this in React-Native.

```await firebase.auth().signInWithPhoneNumber(<code>+${callingCode}${phoneNoText}</code>)
.then((confirmResult) => {</p>
```    this.hideDialog();
    this.props.navigation.navigate("verification", {
      confirmResult: confirmResult,
      registerOwnerData: data,
    });
  })
  .catch((error) => {
    this.hideDialog();
```
<p>}
}```

答:
The error message "We have blocked all requests from this device due to unusual activity. Try again later." is usually thrown when a user is making SMS authentication requests a certain number of times using the same phone number or IP address. These repeated requests are considered suspicious behavior that temporarily blocks the device or IP address.

Additionally, there's a limit of 5 SMS per phone number per 4 hours. With this, you may try doing the following to resolve the issue:

Reduce the frequency of attempts to avoid triggering the anti-abuse system Try using whitelisted phone numbers for testing your app Use multiple testing devices (as the limits are applied per IP or device) Wait for an hour for the quota to lift.

Also, if we are testing our app then we can use a test number along with it we can set the default OTP code to test signing.

We can add the test number as shown in the attached image.

Body:
We keep on getting this error  "We have blocked all requests from this device due to unusual activity. Try again later."
When we try to signInWithPhoneNumber . This also blocks all the requests from same device even if I try to change the phone number.
We have already setup SHA-256 certificate fingerprint to SHA key from "Upload key certificate" on Google PlayStore. We are generating a signed Apk with release mode on android and distribution IPA for iOS.
We are unable to resolve this issue, please help us to identify the issue. We are developing this in React-Native.

```await firebase.auth().signInWithPhoneNumber(<code>+${callingCode}${phoneNoText}</code>)
.then((confirmResult) => {</p>
<pre><code>    this.hideDialog();
    this.props.navigation.navigate("verification", {
      confirmResult: confirmResult,
      registerOwnerData: data,
    });
  })
  .catch((error) => {
    this.hideDialog();
</code></pre>
<p>}
}```


问:
How to Repeat a Row on All Pages When Printing in Excel js- row to repat at top in exceljs
I want to use the following option, or something similar, in the Excel Js library

This option repeats a row when printing on all pages.

I know it is possible to freeze a row in Excel Js but I want a row to be repeated on all pages when printing

答:
The solution to this question is the following code:

```<code>worksheet.pageSetup.printTitlesColumn = "1:1";
</code>```

You may want to place more rows on each page.

for example for 3 row of top write this string for printTitlesColumn  propperty:

```<code>worksheet.pageSetup.printTitlesColumn = "1:3";
</code>```

Body:
The solution to this question is the following code:

worksheet.pageSetup.printTitlesColumn = "1:1";

You may want to place more rows on each page.

for example for 3 row of top write this string for printTitlesColumn  propperty:

worksheet.pageSetup.printTitlesColumn = "1:3";


问:
How to save current cmd-output
Is there a way to get whats currently displayed on the windows command prompt?

For example:

```<code>print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'
</code>```

答:
I suggest wrap the print with your own function

```<code>>>> output_file_name = "output.txt"

>>> def cmd_print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> cmd_print("you can do strings", ["lists", "too"])
</code>```

The answer assumes that you have control over the code
which means you can choose to replace print commands

if its not the case the quick and dirty way is to overwrite print

```<code>>>> output_file_name = "output.txt"
>>> pythonic_print = print
>>> def print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             pythonic_print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> print("you can do strings", ["lists", "too"])
</code>```

Title: How to save current cmd-output

Body:
Is there a way to get whats currently displayed on the windows command prompt?

For example:

print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'

Body:
I suggest wrap the print with your own function

>>> output_file_name = "output.txt"

>>> def cmd_print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> cmd_print("you can do strings", ["lists", "too"])

The answer assumes that you have control over the code
which means you can choose to replace print commands

if its not the case the quick and dirty way is to overwrite print

>>> output_file_name = "output.txt"
>>> pythonic_print = print
>>> def print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             pythonic_print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> print("you can do strings", ["lists", "too"])


问:
calculate standard deviation by grouping two columns
Originally, I had a dataset that looked like this:

```<code>Value         Theme
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather
-0.929755     Weather
</code>```

I wanted to find std of values according to their themes. A general forumla for Standard deviation can be this:

```<code>def calculateSD(sumOfSquares, mean, n):
    nominator = sumOfSquares - ((mean*mean)*n)
    denominator = n-1
    variance = nominator/denominator
    std = variance**0.5
    return std
</code>```

Here, n is the number of occurences of a theme so far. At first, I thought it might be a good idea to calculate the sumOfsquares and mean for each row.
This is how I calculated the values (and they are correct) - more details about the calculation here (calculate sum of squares with rows above):

```<code>df['sumOfSquares'] = df['value'].pow(2).groupby(df['theme']).cumsum()
df['mean'] = df.groupby('theme', as_index=False)['value'].expanding().mean().sort_index(level=1).droplevel(0)
df['n'] = df.groupby(['themes']).cumcount()+1    #number of occurences of a theme so far
df['std'] = calculateSD(df['sumOfSquares'], df['mean'], df['n'])
</code>```

However, the method does not seem efficient. How can I directly calculate the standard deviation without doing these three steps separately? Are there any library functions?

Because now, I have a dataset that looks like this:

```<code>Value         Theme       Country
-1.975767     Weather     China
-0.540979     Fruits      China
-2.359127     Fruits      China
-2.815604     Corona      Brazil
-0.929755     Weather     UK
-0.929755     Weather     UK
</code>```

So instead of just theme, I also want a separation/grouping for Counry.

For example, I wanted to consider these three separately:

```<code>Value         Theme       Country   n
-1.975767     Weather     China     1
</code>```
```<code>Value         Theme       Country   n
-0.540979     Fruits      China.    1
-2.359127     Fruits      China     2
</code>```
```<code>Value         Theme       Country   n
-0.929755     Weather     UK        1
-0.929755     Weather     UK        2
</code>```

What's the best way to calculate std in this case?

答:
You can use groupby:

```<code>df.groupby(['Theme', 'Country']).Value.std()
</code>```

If you also want the n:

```<code>df.groupby(['Theme', 'Country']).agg(Value=('Value', 'std'),
                                     n=('Value', 'count')).reset_index()
</code>```

Body:
Originally, I had a dataset that looked like this:

Value         Theme
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather
-0.929755     Weather

I wanted to find std of values according to their themes. A general forumla for Standard deviation can be this:

def calculateSD(sumOfSquares, mean, n):
    nominator = sumOfSquares - ((mean*mean)*n)
    denominator = n-1
    variance = nominator/denominator
    std = variance**0.5
    return std

Here, n is the number of occurences of a theme so far. At first, I thought it might be a good idea to calculate the sumOfsquares and mean for each row.
This is how I calculated the values (and they are correct) - more details about the calculation here (calculate sum of squares with rows above):

df['sumOfSquares'] = df['value'].pow(2).groupby(df['theme']).cumsum()
df['mean'] = df.groupby('theme', as_index=False)['value'].expanding().mean().sort_index(level=1).droplevel(0)
df['n'] = df.groupby(['themes']).cumcount()+1    #number of occurences of a theme so far
df['std'] = calculateSD(df['sumOfSquares'], df['mean'], df['n'])

However, the method does not seem efficient. How can I directly calculate the standard deviation without doing these three steps separately? Are there any library functions?

Because now, I have a dataset that looks like this:

Value         Theme       Country
-1.975767     Weather     China
-0.540979     Fruits      China
-2.359127     Fruits      China
-2.815604     Corona      Brazil
-0.929755     Weather     UK
-0.929755     Weather     UK

So instead of just theme, I also want a separation/grouping for Counry.

For example, I wanted to consider these three separately:

Value         Theme       Country   n
-1.975767     Weather     China     1

Value         Theme       Country   n
-0.540979     Fruits      China.    1
-2.359127     Fruits      China     2

Value         Theme       Country   n
-0.929755     Weather     UK        1
-0.929755     Weather     UK        2

What's the best way to calculate std in this case?

Body:
You can use groupby:

df.groupby(['Theme', 'Country']).Value.std()

If you also want the n:

df.groupby(['Theme', 'Country']).agg(Value=('Value', 'std'),
                                     n=('Value', 'count')).reset_index()


问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答:
There is no general answer.  It depends on the hardware, the number and
type of its arguments, and what is done in the function.  And how often
it is called, and where.  On a Sparc, for example, arguments (and the
return value) are passed in registers, and each function gets 16 new
registers: if the function is complex enough, those new registers may
avoid spilling that would occur if the function were inlined, and the
non-inline version may end up faster than the inlined one.  On an Intel,
which is register poor, and passes arguments in registers, just the
opposite might be true, for the same function in the same program.  More
generally, inlining may increase program size, reducing locality.  Or
for very simple functions, it may reduce program size; but that again
depends on the architecture.  The only possible way to know is to try
both, measuring the time.  And even then you'll only know for that
particular program, on that particular hardware.</p>


问:
Get all gameobjects that begin with a certain string
I am trying to collect all gameObjects that begin with certain string or a tag. For example, the string/tag is "Sub-". I would like to add all of them to my list. How do I achieve this?</p>
```<code>public List<GameObject> subs = new List<GameObject>();

private void Start(){
   foreach(GameObject subGroup in GameObject.FindGameObjectsWithTag("Sub-")) {

             subs.Add(subGroup);
         }
 }
</code>```

答:
using Linq you could do something like e.g.

```<code>using System.Linq;

...

// get all Transform components of the scene
// pass in true to include inactive ones
var all = FindObjectsOfType<Transform>(true);

// Filter and only keep the ones whee the name starts with your string
subs = all.Where(obj => obj.name.StartsWith(nameOfObj)).ToList();
// Or use a certain tag
subs = all.Where(obj => obj.CompareTag(nameOfObj)).ToList();
// or check if the tag starts with your string
subs = all.Where(obj => obj.tag.StartsWith(nameOfObj)).ToList();
</code>```

see Object.FindObjectsOfType and Linq Where

Body:
I am trying to collect all gameObjects that begin with certain string or a tag. For example, the string/tag is "Sub-". I would like to add all of them to my list. How do I achieve this?

public List<GameObject> subs = new List<GameObject>();

private void Start(){
   foreach(GameObject subGroup in GameObject.FindGameObjectsWithTag("Sub-")) {

             subs.Add(subGroup);
         }
 }

Body:
using Linq you could do something like e.g.

using System.Linq;

...

// get all Transform components of the scene
// pass in true to include inactive ones
var all = FindObjectsOfType<Transform>(true);

// Filter and only keep the ones whee the name starts with your string
subs = all.Where(obj => obj.name.StartsWith(nameOfObj)).ToList();
// Or use a certain tag
subs = all.Where(obj => obj.CompareTag(nameOfObj)).ToList();
// or check if the tag starts with your string
subs = all.Where(obj => obj.tag.StartsWith(nameOfObj)).ToList();

see Object.FindObjectsOfType and Linq Where


问:
Why is my header data missing from my Azure Function Http Trigger in .Net 5 when calling from HttpClient.GetAsync
I have a client using HttpClient.GetAsync to call into a Azure Function Http Trigger in .Net 5.

When I call the function using PostMan, I get my custom header data.

However, when I try to access my response object (HttpResponseMessage) that is returned from HttpClient.GetAsync, my header data empty.

I have my Content data and my Status Code.  But my custom header data are missing.

Any insight would be appreciated since I have looking at this for hours.

Thanks for you help.

Edit: Here is the code where I am making the http call:

```<code>        public async Task<HttpResponseMessage> GetQuotesAsync(int? pageNo, int? pageSize, string searchText)
        {
            var requestUri = $"{RequestUri.Quotes}?pageNo={pageNo}&pageSize={pageSize}&searchText={searchText}";
            return await _httpClient.GetAsync(requestUri);
        }

</code>```

Edit 8/8/2021: See my comment below. The issue has something to do with using Blazor Wasm Client.

答:
The issue is not with Blazor WASM, rather if that header has been exposed on your API Side. In your azure function, add the following -

Note: Postman will still show the headers even if you don't expose the headers like below. That's because, Postman doesn't care about CORS headers. CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources and that's all.

First create a Startup File to inject the HttpContextAccessor

Package Required: Microsoft.Azure.Functions.Extensions

```<code>[assembly: FunctionsStartup(typeof(FuncAppName.Startup))]

namespace FuncAppName
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<HttpContextAccessor>();
        }
    }
}
</code>```

Next, inject it into your main Function -

```<code>using Microsoft.AspNetCore.Http;
namespace FuncAppName
{
    public class SomeFunction
    {
        private readonly HttpContext _httpContext;
        public SomeFunction(HttpContextAccessor contextAccessor)
        {
             _httpContext = contextAccessor.HttpContext;
        }

        [FunctionName("SomeFunc")]
        public override Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, new[] { "post" }, Route = "run")] HttpRequest req)
        {
            var response = "Some Response"
            _httpContext.Response.Headers.Add("my-custom-header", "some-custom-value");
            _httpContext.Response.Headers.Add("my-other-header", "some-other-value");
            _httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "my-custom-header, my-other-header");
            return new OkObjectResult(response)
        }
</code>```

If you want to allow all headers you can use wildcard (I think, not tested) -

```<code>_httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "*");
</code>```

You still need to add your web-app url to the azure platform CORS. You can add * wildcard, more info here - https://iotespresso.com/allowing-all-cross-origin-requests-azure-functions/

to enable CORS for Local Apps during development - https://stackoverflow.com/a/60109518/9276081

Now to access those headers in your Blazor WASM, as an e.g. you can -

```<code>protected override async Task OnInitializedAsync()
{
    var content = JsonContent.Create(new { query = "" });
    using (var client = new HttpClient())
    {
        var result = await client.PostAsync("https://func-app-name.azurewebsites.net/api/run", content);
        var headers = result.Headers.ToList();
    }
}
</code>```

Body:
I have a client using HttpClient.GetAsync to call into a Azure Function Http Trigger in .Net 5.

When I call the function using PostMan, I get my custom header data.

However, when I try to access my response object (HttpResponseMessage) that is returned from HttpClient.GetAsync, my header data empty.

I have my Content data and my Status Code.  But my custom header data are missing.

Any insight would be appreciated since I have looking at this for hours.

Thanks for you help.

Edit: Here is the code where I am making the http call:

        public async Task<HttpResponseMessage> GetQuotesAsync(int? pageNo, int? pageSize, string searchText)
        {
            var requestUri = $"{RequestUri.Quotes}?pageNo={pageNo}&pageSize={pageSize}&searchText={searchText}";
            return await _httpClient.GetAsync(requestUri);
        }

Edit 8/8/2021: See my comment below. The issue has something to do with using Blazor Wasm Client.

Body:
The issue is not with Blazor WASM, rather if that header has been exposed on your API Side. In your azure function, add the following -

Note: Postman will still show the headers even if you don't expose the headers like below. That's because, Postman doesn't care about CORS headers. CORS is just a browser concept and not a strong security mechanism. It allows you to restrict which other web apps may use your backend resources and that's all.

First create a Startup File to inject the HttpContextAccessor

Package Required: Microsoft.Azure.Functions.Extensions

[assembly: FunctionsStartup(typeof(FuncAppName.Startup))]

namespace FuncAppName
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped<HttpContextAccessor>();
        }
    }
}

Next, inject it into your main Function -

using Microsoft.AspNetCore.Http;
namespace FuncAppName
{
    public class SomeFunction
    {
        private readonly HttpContext _httpContext;
        public SomeFunction(HttpContextAccessor contextAccessor)
        {
             _httpContext = contextAccessor.HttpContext;
        }

        [FunctionName("SomeFunc")]
        public override Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, new[] { "post" }, Route = "run")] HttpRequest req)
        {
            var response = "Some Response"
            _httpContext.Response.Headers.Add("my-custom-header", "some-custom-value");
            _httpContext.Response.Headers.Add("my-other-header", "some-other-value");
            _httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "my-custom-header, my-other-header");
            return new OkObjectResult(response)
        }

If you want to allow all headers you can use wildcard (I think, not tested) -

_httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "*");

You still need to add your web-app url to the azure platform CORS. You can add * wildcard, more info here - https://iotespresso.com/allowing-all-cross-origin-requests-azure-functions/

to enable CORS for Local Apps during development - https://stackoverflow.com/a/60109518/9276081

Now to access those headers in your Blazor WASM, as an e.g. you can -

protected override async Task OnInitializedAsync()
{
    var content = JsonContent.Create(new { query = "" });
    using (var client = new HttpClient())
    {
        var result = await client.PostAsync("https://func-app-name.azurewebsites.net/api/run", content);
        var headers = result.Headers.ToList();
    }
}


问:
Get CDSID from JWT?
I am wondering if there is any way to be able to fetch the CDSID from a JWT?
I can get this information, as of now:

So this question is kind of related to this, might be able to add the CDSID to the JWT in the app manifest in some way? Otherwise I could just split on @ but that doesn't feel to safe :P

答:
Looking a bit more in the related question, the "upn" value actually is the user principle name. So I guess the solution could look like this:</p>
```<code>var cdsId = user.Identity.Name.Split('@')[0]
</code>```

Title: Get CDSID from JWT?

Body:
Looking a bit more in the related question, the "upn" value actually is the user principle name. So I guess the solution could look like this:

var cdsId = user.Identity.Name.Split('@')[0]


问:
What's the best way to check if a non-numeric value is in a range?
Sometimes, thinking about the best algorithm is tricky. Well I have to work with some ranges of the form "letter/number/number", for example X86-Z95 would be a range. Actually I need to see if a given code is in the code range. I thought I'd generate an array containing the ranges and check if the code is in the array. But as I had a lot of work to implement the algorithm, I think there is an easier way to implement it. I would like to see some more efficient or elegant solution. I leave my code below.

Thanks in advance!

```<code>library(stringr)
generateInterval = function(str_interval) {
  limits = strsplit(str_interval, '-')[[1]]
  letters_limits = substr(limits, 1, 1)
  numbers_limits = as.numeric(substr(limits, 2, 3))
  if (letters_limits[1] == letters_limits[2]) {
    interval = paste0(letters_limits[1], numbers_limits[1]:numbers_limits[2])
  } else {
    pos = which(LETTERS %in% letters_limits)
    interval_letters = LETTERS[pos[1]:pos[2]]
    numbers = as.numeric(substr(limits, 2, 3))
    interval = c()
    for (i in 1:length(interval_letters)) {
      if (i == 1) {
        interval = c(interval, paste0(interval_letters[i], numbers[1]:99))
      } else if (i == length(interval_letters)) {
        interval = c(interval, paste0(interval_letters[i], 0:numbers[2]))
      } else {
        interval = c(interval, paste0(interval_letters[i], 0:99))
      }
    }
  }
  interval = ifelse(str_length(interval) == 2,
                    paste0(substr(interval, 1, 1), 0, substr(interval, 2, 2)),
                    interval)

  return(interval)
}

generateInterval('A72-B10')
</code>```

答:
Following the OP's comment here is a way in base R. The only thing that needs to be done is to realize that R can compare strings. And the one-line function will check if the codes are within range.

within_range <- function(x, lower, upper) lower <= x & x <= upper

within_range(c("X92", "X84", "A10", "Y30"), lower = "X86", upper = "Z95")
#> [1]  TRUE FALSE FALSE  TRUE
```

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

Body:
Sometimes, thinking about the best algorithm is tricky. Well I have to work with some ranges of the form "letter/number/number", for example X86-Z95 would be a range. Actually I need to see if a given code is in the code range. I thought I'd generate an array containing the ranges and check if the code is in the array. But as I had a lot of work to implement the algorithm, I think there is an easier way to implement it. I would like to see some more efficient or elegant solution. I leave my code below.

Thanks in advance!

library(stringr)
generateInterval = function(str_interval) {
  limits = strsplit(str_interval, '-')[[1]]
  letters_limits = substr(limits, 1, 1)
  numbers_limits = as.numeric(substr(limits, 2, 3))
  if (letters_limits[1] == letters_limits[2]) {
    interval = paste0(letters_limits[1], numbers_limits[1]:numbers_limits[2])
  } else {
    pos = which(LETTERS %in% letters_limits)
    interval_letters = LETTERS[pos[1]:pos[2]]
    numbers = as.numeric(substr(limits, 2, 3))
    interval = c()
    for (i in 1:length(interval_letters)) {
      if (i == 1) {
        interval = c(interval, paste0(interval_letters[i], numbers[1]:99))
      } else if (i == length(interval_letters)) {
        interval = c(interval, paste0(interval_letters[i], 0:numbers[2]))
      } else {
        interval = c(interval, paste0(interval_letters[i], 0:99))
      }
    }
  }
  interval = ifelse(str_length(interval) == 2,
                    paste0(substr(interval, 1, 1), 0, substr(interval, 2, 2)),
                    interval)

  return(interval)
}

generateInterval('A72-B10')

Body:
Following the OP's comment here is a way in base R. The only thing that needs to be done is to realize that R can compare strings. And the one-line function will check if the codes are within range.

within_range <- function(x, lower, upper) lower <= x & x <= upper

within_range(c("X92", "X84", "A10", "Y30"), lower = "X86", upper = "Z95")
#> [1]  TRUE FALSE FALSE  TRUE

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


问:
Tone.js Error: 'Start time must be strictly greater than previous start time'
I am having a hard time understanding why I am getting thrown this error:

Debug.ts:8 Uncaught Error: Start time must be strictly greater than
previous start time

The weird part is that it only throws me this error about 4/5 times I refresh the page. There is a 1/5 chance roughly that it will work with no problem. Here is my code:

```<code>let synth = new Tone.MetalSynth({
  portamento: 0,
  volume: -15,
  envelope: {
    attack: 0.001,
    decay: 1.4,
    release: 1,
  },
  harmonicity: 18.1,
  modulationIndex: 12,
  resonance: 1000,
  octaves: 1.5,
});

synth.chain(Tone.Destination);

let notes = ['A2', 'B2', 'C3', 'D3', 'E3', 'F3', 'G#3'];
let html = '';
for (let i = 0; i < notes.length; i++) {
  html += `<div class="whitenote" onmouseover="noteDown(this)" data-note="${notes[i]}"></div>`;
}

document.querySelector('.container-4').innerHTML = html;

function noteDown(el) {
  let note = el.dataset.note;
  synth.triggerAttackRelease(note, '16n');
}
</code>```

答:
I also had the same issue. You have to add the time to it.

This worked for me:

```<code>const synth = new Tone.Synth().toDestination();

melody.forEach(tune => {
      const now = Tone.now()
      synth.triggerAttackRelease(tune.note, tune.duration, now + tune.timing)
})
</code>```

and my data (melody) looks like that:

```<code>[{ note: "E5", duration: "8n", timing: 0 },
{ note: "D#5", duration: "8n", timing: 0.25 },
{ note: "E5", duration: "8n", timing: 0.5 },
{ note: "D#5", duration: "8n", timing: 0.75 },
{ note: "E5", duration: "8n", timing: 1 },
{ note: "B4", duration: "8n", timing: 1.25 }]
</code>```

Body:
I am having a hard time understanding why I am getting thrown this error:

Debug.ts:8 Uncaught Error: Start time must be strictly greater than
previous start time

The weird part is that it only throws me this error about 4/5 times I refresh the page. There is a 1/5 chance roughly that it will work with no problem. Here is my code:

let synth = new Tone.MetalSynth({
  portamento: 0,
  volume: -15,
  envelope: {
    attack: 0.001,
    decay: 1.4,
    release: 1,
  },
  harmonicity: 18.1,
  modulationIndex: 12,
  resonance: 1000,
  octaves: 1.5,
});

synth.chain(Tone.Destination);

let notes = ['A2', 'B2', 'C3', 'D3', 'E3', 'F3', 'G#3'];
let html = '';
for (let i = 0; i < notes.length; i++) {
  html += `<div class="whitenote" onmouseover="noteDown(this)" data-note="${notes[i]}"></div>`;
}

document.querySelector('.container-4').innerHTML = html;

function noteDown(el) {
  let note = el.dataset.note;
  synth.triggerAttackRelease(note, '16n');
}

Body:
I also had the same issue. You have to add the time to it.

This worked for me:

const synth = new Tone.Synth().toDestination();

melody.forEach(tune => {
      const now = Tone.now()
      synth.triggerAttackRelease(tune.note, tune.duration, now + tune.timing)
})

and my data (melody) looks like that:

[{ note: "E5", duration: "8n", timing: 0 },
{ note: "D#5", duration: "8n", timing: 0.25 },
{ note: "E5", duration: "8n", timing: 0.5 },
{ note: "D#5", duration: "8n", timing: 0.75 },
{ note: "E5", duration: "8n", timing: 1 },
{ note: "B4", duration: "8n", timing: 1.25 }]


问:
How to convert String to TimeOfDay in Flutter?
I have a String, lets say '16:00' and I want to convert it to a TimeOfDay type. I checked the documentation and it only provides a converter from DateTime to TimeOfDay, but I can't find a way to convert from String to TimeOfDay.

答:
Try this method. This will convert 24 hour time to 12 hour time.

```<code>getTime(String time) {
  TimeOfDay _startTime = TimeOfDay(
      hour: int.parse(time.split(":")[0]),
      minute: int.parse(time.split(":")[1]));
  return "${_startTime.hourOfPeriod}:${_startTime.minute} ${_startTime.period == DayPeriod.pm ? "P.M" : "A.M"}";
}
</code>```

Input = 15:48:00
output= 03:48 P.M

Body:
Try this method. This will convert 24 hour time to 12 hour time.

getTime(String time) {
  TimeOfDay _startTime = TimeOfDay(
      hour: int.parse(time.split(":")[0]),
      minute: int.parse(time.split(":")[1]));
  return "${_startTime.hourOfPeriod}:${_startTime.minute} ${_startTime.period == DayPeriod.pm ? "P.M" : "A.M"}";
}

Input = 15:48:00
output= 03:48 P.M


问:
how to display the value from store in vuex
I stored my data in Vuex store. Here how it looks like:

And basically, I want to show first_name in the view. So I returned the data like this:

```<code>data () {
        return {
            first_name: this.$store.state.user.attributes.first_name,
        }
    },
</code>```

Ans easily want to display it inside of the div:

```<code><div>{{first_name}}</div>
</code>```

But I am getting vue.esm.js:1906 TypeError: Cannot read properties of undefined (reading 'first_name')

答:
You need a computed property for that.

So instead of having the variable first_name in your data, set it as a computed property as follows:

computed: { first_name() { return this.$store.state.user.attributes.first_name } }

Body:
I stored my data in Vuex store. Here how it looks like:

And basically, I want to show first_name in the view. So I returned the data like this:

data () {
        return {
            first_name: this.$store.state.user.attributes.first_name,
        }
    },

Ans easily want to display it inside of the div:

{{first_name}}

But I am getting vue.esm.js:1906 TypeError: Cannot read properties of undefined (reading 'first_name')


问:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
I am trying to convert a timestamp of the format 2009-09-12 20:57:19 and turn it into something like 3 minutes ago with PHP.

I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

```<code>function _ago($tm,$rcs = 0) {
    $cur_tm = time();
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }
</code>```

I think on those first few lines the script is trying to do something that looks like this (different date format math):

```<code>$dif = 1252809479 - 2009-09-12 20:57:19;
</code>```

How would I go about converting my timestamp into that (unix?) format?

答:
I wanted to have dutch version that supported singles and plurals. Just adding an 's' at the end would not suffice, we use completely different words so I rewrote the top answer of this post.

This will result in:

2 jaren 1 maand 2 weken 1 dag 1 minuten 2 seconden

or

1 jaar 2 maanden 1 week 2 dagen 1 minuut 1 seconde

```<code>    public function getTimeAgo($full = false){

    $now = new \DateTime;
    $ago = new \DateTime($this->datetime());
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'jaren',
        'm' => 'maanden',
        'w' => 'weken',
        'd' => 'dagen',
        'h' => 'uren',
        'i' => 'minuten',
        's' => 'seconden',
    );
    $singleString = array(
        'y' => 'jaar',
        'm' => 'maand',
        'w' => 'week',
        'd' => 'dag',
        'h' => 'uur',
        'i' => 'minuut',
        's' => 'seconde',
    );
    // M.O. 2022-02-11 I rewrote this function to support dutch singles and plurals. Added some docs for next programmer to break his brain :)
    // For each possible notation, if corresponding value of current key is true (>1) otherwise remove its key/value from array
    // If the value from current key is 1, use value from $singleString array. Otherwise use value from $string array
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            if($diff->$k == 1){
                $v = $diff->$k . ' ' . $singleString[$k];
            } else {
                $v = $diff->$k . ' ' . $v;
            }
        } else {
            if($diff->$k == 1){
                unset($singleString[$k]);
            } else {
                unset($string[$k]);
            }
        }
    }

    // If $full = true, print all values.
    // Values have already been filtered with foreach removing keys that contain a 0 as value
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . '' : 'zojuist';
}
</code>```

You should probably test it first because I am not that good of a programmer :)

Body:
I am trying to convert a timestamp of the format 2009-09-12 20:57:19 and turn it into something like 3 minutes ago with PHP.

I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

function _ago($tm,$rcs = 0) {
    $cur_tm = time();
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }

I think on those first few lines the script is trying to do something that looks like this (different date format math):

$dif = 1252809479 - 2009-09-12 20:57:19;

How would I go about converting my timestamp into that (unix?) format?

Body:
I wanted to have dutch version that supported singles and plurals. Just adding an 's' at the end would not suffice, we use completely different words so I rewrote the top answer of this post.

This will result in:

2 jaren 1 maand 2 weken 1 dag 1 minuten 2 seconden

or

1 jaar 2 maanden 1 week 2 dagen 1 minuut 1 seconde

    public function getTimeAgo($full = false){

    $now = new \DateTime;
    $ago = new \DateTime($this->datetime());
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'jaren',
        'm' => 'maanden',
        'w' => 'weken',
        'd' => 'dagen',
        'h' => 'uren',
        'i' => 'minuten',
        's' => 'seconden',
    );
    $singleString = array(
        'y' => 'jaar',
        'm' => 'maand',
        'w' => 'week',
        'd' => 'dag',
        'h' => 'uur',
        'i' => 'minuut',
        's' => 'seconde',
    );
    // M.O. 2022-02-11 I rewrote this function to support dutch singles and plurals. Added some docs for next programmer to break his brain :)
    // For each possible notation, if corresponding value of current key is true (>1) otherwise remove its key/value from array
    // If the value from current key is 1, use value from $singleString array. Otherwise use value from $string array
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            if($diff->$k == 1){
                $v = $diff->$k . ' ' . $singleString[$k];
            } else {
                $v = $diff->$k . ' ' . $v;
            }
        } else {
            if($diff->$k == 1){
                unset($singleString[$k]);
            } else {
                unset($string[$k]);
            }
        }
    }

    // If $full = true, print all values.
    // Values have already been filtered with foreach removing keys that contain a 0 as value
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . '' : 'zojuist';
}

You should probably test it first because I am not that good of a programmer :)


问:
Responsive Typography in Material UI?
Designs commonly have smaller headline fonts for mobile designs.

Does Material UI have a mechanism for making the typography responsive?

I see that the default theme has the font sizes defined in rems - does that mean it's a matter of just reducing the base font-size? (That doesn't seem to work, what if you want to reduce the headline fonts at different rates).

答:
My approach with v5

```<code>import { createTheme } from "@mui/material";

let theme = createTheme({
  // ...
});

theme = createTheme(theme, {
  typography: {
    h1: {
      fontSize: 53,
      [theme.breakpoints.only("sm")]: {
        fontSize: 71,
      },
    },
  },
});
export default theme;

</code>```

Title: Responsive Typography in Material UI?

Body:
My approach with v5

import { createTheme } from "@mui/material";

let theme = createTheme({
  // ...
});

theme = createTheme(theme, {
  typography: {
    h1: {
      fontSize: 53,
      [theme.breakpoints.only("sm")]: {
        fontSize: 71,
      },
    },
  },
});
export default theme;


问:
Attaching files to comments?
Are there any guides/gems available that allow you to attach files to a comment.

I have already setup comments just need some way to add attachments to them.

Title: Attaching files to comments?

Body:
http://railscasts.com/episodes/134-paperclip

http://railscasts.com/episodes/253-carrierwave-file-uploads


问:
i need to pivot a table in sqlite
```<code>select team,medal,COUNT(*) AS no_of_medals from athletes where medal != 'NA' GROUP BY team,medal order by team,medal
</code>```

I need output in the following format

```<code>team gold silveR bronze
USA  3     4     6
</code>```

答:
Use TOTAL() aggregate function for each type of medal:

```<code>SELECT team,
       TOTAL(medal = 'Gold') gold,
       TOTAL(medal = 'Silver') silver,
       TOTAL(medal = 'Bronze') bronze
FROM athletes
GROUP BY team
ORDER BY team;
</code>```

Title: i need to pivot a table in sqlite

Body:
select team,medal,COUNT(*) AS no_of_medals from athletes where medal != 'NA' GROUP BY team,medal order by team,medal

I need output in the following format

team gold silveR bronze
USA  3     4     6

Body:
Use TOTAL() aggregate function for each type of medal:

SELECT team,
       TOTAL(medal = 'Gold') gold,
       TOTAL(medal = 'Silver') silver,
       TOTAL(medal = 'Bronze') bronze
FROM athletes
GROUP BY team
ORDER BY team;


问:
How to know which environmental variables that are used in spring?
Lets say I have a large multi module java spring project in IntelliJ and I would like to see which database it run towards. How would I do this easily?

More generally it would be nice with an intellij plugin or feature that could show all the environmental variables that are used when for example running a test. I would like to be able to see an overview about which beans are being used, which environmental variables and which settings in various application.* files are being used for this particular execution. Is there such a feature or plugin in IntelliJ or any other way to do it?

答: There is many way to do this, but I think the simplest is by adding Spring Actuator to your project. You'll be able to show all created beans and environments variables via exposed endpoints (/beans, /env,..).</p>


问:
Code to find cells that contain a constant preceded by = sign
Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.

I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:

```<code>Selection.SpecialCells(xlCellTypeConstants, 1).Select
</code>```

The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.

In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.

Any suggestions on how I can identify these cells?

答:
Exactly this "The problem is some users have a habit of inputing numbers preceded by an = sign" is your problem. Stop people having this habit!

First it is a stupid habit because it slows everything down because Excel has to evaluate those cells that contain something like =1000 to find out the value and

second those cells actually contain a formula and not a value. So there is no built in way to distinguish them.

Those people are just using Excel wrong.

There is only one workaround I can imagine and that is looping through all cells that contain a formula, remove the = sign and check if the rest of the "formula" is numeric IsNumeric(). If so replace the formula by its value.

So for example if the cell is =1000 then 1000 is numeric and it will replace it by the value 1000. If the cell is =1000*2 then 1000*2 is not numeric because it contains a * sign and it will keep the formula.

Note that this workaround is just fighting symptoms but not fixing the root cause. The root cause is those people using Excel wrong! And you should always fix the causes not fight the symptoms.

```<code>Option Explicit

Public Sub ReplaceFormluasWithValueIfNoCalculation()
    Dim AllCellsWithFormulas As Range
    On Error Resume Next  ' next line errors if no formulas are found, so hide errors
    Set AllCellsWithFormulas = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
    On Error GoTo 0  ' re-enable error reporting

    If Not AllCellsWithFormulas Is Nothing Then
        Dim Cell As Variant
        For Each Cell In AllCellsWithFormulas.Cells  ' loop through all formulas
            Dim ExtractedValue As String  ' extract formula right of the `=` sign
            ExtractedValue = Right$(Cell.Formula, Len(Cell.Formula) - 1)
            ' check if extracted formula is only a value, if so replace formula with value
            If IsNumeric(ExtractedValue) Then
                Cell.Value = ExtractedValue
            End If
        Next Cell
    End If
End Sub
</code>```

Even the above can be done, I recommend fixing the root cause.

Body:
Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.

I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:

Selection.SpecialCells(xlCellTypeConstants, 1).Select

The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.

In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.

Any suggestions on how I can identify these cells?

Body:
Exactly this "The problem is some users have a habit of inputing numbers preceded by an = sign" is your problem. Stop people having this habit!

First it is a stupid habit because it slows everything down because Excel has to evaluate those cells that contain something like =1000 to find out the value and

second those cells actually contain a formula and not a value. So there is no built in way to distinguish them.

Those people are just using Excel wrong.

There is only one workaround I can imagine and that is looping through all cells that contain a formula, remove the = sign and check if the rest of the "formula" is numeric IsNumeric(). If so replace the formula by its value.

So for example if the cell is =1000 then 1000 is numeric and it will replace it by the value 1000. If the cell is =1000*2 then 1000*2 is not numeric because it contains a * sign and it will keep the formula.

Note that this workaround is just fighting symptoms but not fixing the root cause. The root cause is those people using Excel wrong! And you should always fix the causes not fight the symptoms.

Option Explicit

Public Sub ReplaceFormluasWithValueIfNoCalculation()
    Dim AllCellsWithFormulas As Range
    On Error Resume Next  ' next line errors if no formulas are found, so hide errors
    Set AllCellsWithFormulas = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
    On Error GoTo 0  ' re-enable error reporting

    If Not AllCellsWithFormulas Is Nothing Then
        Dim Cell As Variant
        For Each Cell In AllCellsWithFormulas.Cells  ' loop through all formulas
            Dim ExtractedValue As String  ' extract formula right of the `=` sign
            ExtractedValue = Right$(Cell.Formula, Len(Cell.Formula) - 1)
            ' check if extracted formula is only a value, if so replace formula with value
            If IsNumeric(ExtractedValue) Then
                Cell.Value = ExtractedValue
            End If
        Next Cell
    End If
End Sub

Even the above can be done, I recommend fixing the root cause.


问:
How to get the K most-used words from a text file containing N words in O(N) time?
I need to print the K most-used words from a text file containing N words in O(N) time complexity.

I have tried it using HashMap by taking the word as key and number of occurrence as value and then sorting it by values. But sorting the HashMap by values takes O(NlogN) which is more than my requirement.

If K = 10 then I need to print the 10 most used words from a text file.

答:
You can't do sorting, because sorting is as O(NlogN), which apparently can not satisfy you.

Top k problem has the standard stereotype of solutions, which is O(N).

first, use a map to store the frequency. Iterate the list, calculate the frequency of words, then put them into the map.

Second, use a PriorityQueue to calculate the top k frequency, which has a volume of k. Iterate the map, put each entry into the PriorityQueue, if the
size of the PriorityQueue is larger than k, then do the poll().

finally, the ProioritiyQueue contains the result of the top K frequency words.


问:
How can i save or bookmark a cypher query in the Neo4J browser?
when i save my cypher scripts under saved scripts in the Neo4J browser, and log off for the day, when i return and sign back on, the scripts are gone and I cannot retrieve them.</p>

答: It is possible to favorite a cypher query, and then download it as a cypher file, and then later use it by dragging it to the browser in the new version 4.4 (but it was added before this version, not sure which one).</p>


问:
Changing tick frequency for x-axis in a two y-axis with imported data from .csv
Hello I'm importing my data from a .csv file and plotting it in a graph with two y-axis. The x-axis are Timestamps and I'd like to have less of them, since it looks really clutered (new here and can't post pictures yet).

I tried using plt.xticks(df.Time[::6], rotation=45), as I did before with a one y-axis plot, but it doesn't work. Can someone please give me options?

My data are 3 columns, basically like this:

```<code>
'Time':['00:09:00', '00:19:00','00:29:00', '00:39:00','00:49:00', '00:59:00',...'22:59:00'],
'Sensor1': [16,14,12,11,10,9,...27],
'Sensor2': [159.34,158.19,159.31,155.94,158.88,154.75,...897.25]

</code>```
```<code>import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('.../example.csv', delimiter=';')

#get data
x = df.Time
y1 = df.Sensor1
y2 = df.Sensor2

#create a figure
plt.figure(figsize=(20,10))

#plot axes
#plot y1
plt.plot(x,y1,color='red',label='Sensor1', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylim(0,40)
plt.ylabel('%')
plt.legend(loc='upper left')

plt.xlabel('Time')
plt.grid(True)
plt.xticks(df.Time[::6], rotation=45)

#plot y2
#create twin axes
ax2=plt.gca().twinx()

plt.plot(x,y2,color='blue',label='Sensor2', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylabel('ppb')
plt.legend(loc='upper right')

plt.show()

</code>```

答:
I managed to do what I wanted :D it appears it had something to do with the order in which I put the things. Now it looks like this:</p>
```<code>import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('.../example.csv', delimiter=';')

#get data
x = df.Time
y1 = df.Sensor1
y2 = df.Sensor2

#create a figure
plt.figure(figsize=(20,10))

#plot axes
#plot y1
plt.plot(x,y1,color='red',label='Sensor1', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylim(0,40)
plt.ylabel('%')
plt.legend(loc='upper left')

plt.xlabel('Time')
plt.grid(True)
plt.xticks(rotation=45)

#plot y2
#create twin axes
ax2=plt.gca().twinx()

plt.plot(x,y2,color='blue',label='Sensor2', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylabel('ppb')
plt.legend(loc='upper right')

plt.grid(True)
plt.xticks(voc_tt.Zeit[::6])

plt.show()
</code>```

Body:
Hello I'm importing my data from a .csv file and plotting it in a graph with two y-axis. The x-axis are Timestamps and I'd like to have less of them, since it looks really clutered (new here and can't post pictures yet).

I tried using plt.xticks(df.Time[::6], rotation=45), as I did before with a one y-axis plot, but it doesn't work. Can someone please give me options?

My data are 3 columns, basically like this:

'Time':['00:09:00', '00:19:00','00:29:00', '00:39:00','00:49:00', '00:59:00',...'22:59:00'],
'Sensor1': [16,14,12,11,10,9,...27],
'Sensor2': [159.34,158.19,159.31,155.94,158.88,154.75,...897.25]

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('.../example.csv', delimiter=';')

#get data
x = df.Time
y1 = df.Sensor1
y2 = df.Sensor2

#create a figure
plt.figure(figsize=(20,10))

#plot axes
#plot y1
plt.plot(x,y1,color='red',label='Sensor1', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylim(0,40)
plt.ylabel('%')
plt.legend(loc='upper left')

plt.xlabel('Time')
plt.grid(True)
plt.xticks(df.Time[::6], rotation=45)

#plot y2
#create twin axes
ax2=plt.gca().twinx()

plt.plot(x,y2,color='blue',label='Sensor2', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylabel('ppb')
plt.legend(loc='upper right')

plt.show()

Body:
I managed to do what I wanted :D it appears it had something to do with the order in which I put the things. Now it looks like this:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('.../example.csv', delimiter=';')

#get data
x = df.Time
y1 = df.Sensor1
y2 = df.Sensor2

#create a figure
plt.figure(figsize=(20,10))

#plot axes
#plot y1
plt.plot(x,y1,color='red',label='Sensor1', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylim(0,40)
plt.ylabel('%')
plt.legend(loc='upper left')

plt.xlabel('Time')
plt.grid(True)
plt.xticks(rotation=45)

#plot y2
#create twin axes
ax2=plt.gca().twinx()

plt.plot(x,y2,color='blue',label='Sensor2', linestyle='-', linewidth=0.8, marker='.', markersize=10)
plt.ylabel('ppb')
plt.legend(loc='upper right')

plt.grid(True)
plt.xticks(voc_tt.Zeit[::6])

plt.show()


问:
Validation form does not work and has a strange behavior
I'm learning to use forms and I have a javascript code that when I click submit the page shows an error but it does it in a microsecond so I cannot read it and the page refresh it self, I have no idea about what is wrong here.
Here is my html

```<code>    <body>
    <h3>Formulario</h3>
    <form name="formName" action="#" onsubmit="return validaciones()">
    <h4>Nombre:</h4>
    <input type="text" onkeypress="validateName(this)" name="campoNombre">
    <br>
    <br>
    <select id="opciones" name="opciones">
    <br>
    <br>
      <option value="1">Primer valor</option>
      <option value="2">Segundo valor</option>
      <option value="3">Tercer valor</option>
      <option value="4">Cuarto valor</option>
    </select>
    <br>
    <br>
    <input type="radio" value="si" name="pregunta" id="pregunta_si"/> SI
    <input type="radio" value="no" name="pregunta" id="pregunta_no"/> NO
    <input type="radio" value="nsnc" name="pregunta" id="pregunta_nsnc"/> NS/NC
    <br>
    <br>
    <input type="checkbox" value="condiciones" name="condiciones" id="condiciones"/> He leído
     y acepto las condiciones
    <input type="checkbox" value="privacidad" name="privacidad" id="privacidad"/> He leído la
    política de privacidad
    <br>
    <br>
    <textarea id="parrafo"></textarea>
    <br>
    <br>
    <input type="submit" value="submit">
    </form>
</code>```

Javascript code

```<code>    function validaciones() {
      let valorNombre = document.forms["formName"]["campoNombre"].value;
      if (valorNombre == "") {
      alert("Name must be filled out");
      console.log('Ingresaste tu nombre: ' + valorNombre)
      }

      var elementos = document.getElementsByName("pregunta");
      for(var i=0; i<elementos.length; i++) {
      console.log(" Elemento: " + elementos[i].value + "\n Seleccionado: " +
      elementos[i].checked)
      }
      return false
      };

      function validateName(item){
      value = item.value;
      console.log(value)
      };
</code>```

答:
If you submit a form, the page is reloaded by default. You will have to use something like the following:

document.forms["formname"].addEventListener("submit", (event) => {
  event.preventDefault();

  validaciones();
});
```

That prevents the browser from reloading the site, if the form is submitted.

Body:
I'm learning to use forms and I have a javascript code that when I click submit the page shows an error but it does it in a microsecond so I cannot read it and the page refresh it self, I have no idea about what is wrong here.
Here is my html

Formulario

    <form name="formName" action="#" onsubmit="return validaciones()">

Nombre:

    <input type="text" onkeypress="validateName(this)" name="campoNombre">

    <select id="opciones" name="opciones">

      <option value="1">Primer valor</option>
      <option value="2">Segundo valor</option>
      <option value="3">Tercer valor</option>
      <option value="4">Cuarto valor</option>
    </select>

    <input type="radio" value="si" name="pregunta" id="pregunta_si"/> SI
    <input type="radio" value="no" name="pregunta" id="pregunta_no"/> NO
    <input type="radio" value="nsnc" name="pregunta" id="pregunta_nsnc"/> NS/NC

    <input type="checkbox" value="condiciones" name="condiciones" id="condiciones"/> He leído
     y acepto las condiciones
    <input type="checkbox" value="privacidad" name="privacidad" id="privacidad"/> He leído la
    política de privacidad

    <textarea id="parrafo"></textarea>

    <input type="submit" value="submit">
    </form>

Javascript code

    function validaciones() {
      let valorNombre = document.forms["formName"]["campoNombre"].value;
      if (valorNombre == "") {
      alert("Name must be filled out");
      console.log('Ingresaste tu nombre: ' + valorNombre)
      }

      var elementos = document.getElementsByName("pregunta");
      for(var i=0; i<elementos.length; i++) {
      console.log(" Elemento: " + elementos[i].value + "\n Seleccionado: " +
      elementos[i].checked)
      }
      return false
      };

      function validateName(item){
      value = item.value;
      console.log(value)
      };

Body:
If you submit a form, the page is reloaded by default. You will have to use something like the following:

document.forms["formname"].addEventListener("submit", (event) => {
  event.preventDefault();

  validaciones();
});

That prevents the browser from reloading the site, if the form is submitted.


问:
How to use `null` to define an empty ref in Vue 3 & TypeScript?
I am using Vue 3 and TypeScript with the script setup tag (

答:
It's the other way around, your messageProp accepts only string or undefined due to the required: false, but you try to send it string or null.

The link I sent as comment VueJS Using Prop Type Validation With NULL and 'undefined' Values? does not seem to work with Vue3 and Volar/Typescript.

So to accept null you should change the prop type of messageProp as follows

```<code>defineProps({
  messageProp: {
    type: String as PropType<string|null>,
    required: false,
    default: '',
  },
});
</code>```

(note: I do not expect the default value ('') to be set for null, only undefined, so you'd probably need to handle the null value yourself)

(note2: you do not need to write ref<string | undefined>(undefined) you'd get the same Ref<string|undefined> object with ref<string>())

Body:
It's the other way around, your messageProp accepts only string or undefined due to the required: false, but you try to send it string or null.

The link I sent as comment VueJS Using Prop Type Validation With NULL and 'undefined' Values? does not seem to work with Vue3 and Volar/Typescript.

So to accept null you should change the prop type of messageProp as follows

defineProps({
  messageProp: {
    type: String as PropType<string|null>,
    required: false,
    default: '',
  },
});

(note: I do not expect the default value ('') to be set for null, only undefined, so you'd probably need to handle the null value yourself)

(note2: you do not need to write ref<string | undefined>(undefined) you'd get the same Ref<string|undefined> object with ref<string>())


问:
how to create C# web service for mpeg 4 streaming?
I want to create a C# web service for audio steaming (upload n download) to iPhone.

any help would be greatly appreciated.

答:
Your question is somewhat vague, But I'll assume that you're trying to stream multiple mp4 audio files.
Here are some possible solutions:

Use an already existing solution: like IceCast or ShoutCast. With that, you'll be able to stream easily. But it's not in "C#".

You can just serve directly the mp4 via a direct URL to the iPhone, and your service just tell the the URL where to get it. If you're making an iPhone application, you can ask the next song in queue to your service and be able to queue it. (pseudo streaming)

If you're into making a full fledged streamer, I would suggest you to look at the ".pls" format. It's not a simple task and may require a lot of time to achieve.


问:
install EXPORT problem for library with dependencies
I try to build two libraries (say A and B) from one project. I use add_subdirectory cmake command in root cmake file. B depends on A.

When I try to add

```<code>INSTALL (TARGETS B EXPORT B
    PUBLIC_HEADER DESTINATION "include/B"
    LIBRARY DESTINATION "lib"
    ARCHIVE DESTINATION "lib")

INSTALL (EXPORT B DESTINATION "./")
</code>```

CMake warns me about error in line with INSTALL (EXPORT .... It prints:

CMake Error: INSTALL (EXPORT "B" ...) includes target "B" which requires target "A" that is not in the export set.

答:
Aside from fixing

"A" that is not in the export set

part of the error message, one could consider to fix the part

target "B" which requires target "A"

by using PRIVATE linkage of B with A:

```<code>target_link_libraries(B PRIVATE A)
</code>```

Such linkage implies that A is needed only for building the library B, but is not needed for anyone who links with B.

It depends from the library B whether such linkage is sufficient.
But if it is, then this is a preferable way to overcome the error: If users of B doesn't need to link with A, then there is no reason to EXPORT A.

There are some easy signs when PRIVATE linkage is NOT an option:

Some public header of library B includes a header of library A.
In that case, if a user #include-s that header of B, then the header of A will be included too. And to find that header a compiler should be aware of include directories for A.

B is a STATIC library, and A is either STATIC or SHARED.
In that case, the binary file for B won't "embed" the binary file for A.
So, when link with B, one should explicitly link with A too.

However, if both A and B are SHARED libraries, then PRIVATE linkage could still be an option:

While binary file for shared B doesn't "embed" the binary file for shared A, the binary file for B contains reference to the binary file for A. So when a linker will find B binary in the command line, it will link with A binary too. If B is installed, then A should be installed too (otherwise the linker won't find A). But for being able to export B, the A needn't to be exported.

Body:
I try to build two libraries (say A and B) from one project. I use add_subdirectory cmake command in root cmake file. B depends on A.

When I try to add

INSTALL (TARGETS B EXPORT B
    PUBLIC_HEADER DESTINATION "include/B"
    LIBRARY DESTINATION "lib"
    ARCHIVE DESTINATION "lib")

INSTALL (EXPORT B DESTINATION "./")

CMake warns me about error in line with INSTALL (EXPORT .... It prints:

CMake Error: INSTALL (EXPORT "B" ...) includes target "B" which requires target "A" that is not in the export set.

Body:
Aside from fixing

"A" that is not in the export set

part of the error message, one could consider to fix the part

target "B" which requires target "A"

by using PRIVATE linkage of B with A:

target_link_libraries(B PRIVATE A)

Such linkage implies that A is needed only for building the library B, but is not needed for anyone who links with B.

It depends from the library B whether such linkage is sufficient.
But if it is, then this is a preferable way to overcome the error: If users of B doesn't need to link with A, then there is no reason to EXPORT A.

There are some easy signs when PRIVATE linkage is NOT an option:

Some public header of library B includes a header of library A.
In that case, if a user #include-s that header of B, then the header of A will be included too. And to find that header a compiler should be aware of include directories for A.

B is a STATIC library, and A is either STATIC or SHARED.
In that case, the binary file for B won't "embed" the binary file for A.
So, when link with B, one should explicitly link with A too.

However, if both A and B are SHARED libraries, then PRIVATE linkage could still be an option:

While binary file for shared B doesn't "embed" the binary file for shared A, the binary file for B contains reference to the binary file for A. So when a linker will find B binary in the command line, it will link with A binary too. If B is installed, then A should be installed too (otherwise the linker won't find A). But for being able to export B, the A needn't to be exported.


问:
Compare two variables from two breeds
I still haven't learned how to compare two attributes from two different breeds.

In my example, I want to ask the breeds (healthy shops and unhealthy shops) to compare their revenues. The type of shop with the least revenues will close and the other type of shop will open in his place. The command to "compare-revenue" is the one that doesn't work. I know I shouldn't use breed, but I don't know how to formulate it differently without getting the "tick" error.

Thanks!

```<code>breed[healthy-shops healthy-shop]
breed[unhealthy-shops unhealthy-shop]

healthy-shops-own[
  total-earnings-h
]

unhealthy-shops-own[
  total-earnings-nh
]

to setup
create-healthy-shops 50
create-unhealthy-shops 50
ask healthy-shop [set total-earnings-n 2000 + random 2000]
ask unhealthy-shop [set total-earnings-nn 2000 + random 2000]
end

to go

compare-revenue
end

;;;;;;;;;

to compare-revenue

 let minhealth one-of healthy-shops with-min [total-earnings-h]
 let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  ask breed [ifelse (total-earnings-nh < total-earnings-h
  [ask minunhealth [die hatch-healthy-shops 1]]
  [ask minhealth [die hatch-unhealthy-shops 1]]]
end
</code>```

Another version using the let command (not sure if it is right)

```<code>to compare-revenue

    let minhealth one-of healthy-shops with-min [total-earnings-h]
    let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  if minhealth > minunhealth [ask minunhealth [die hatch-healthy-shops 1]]
  if minhealth < minunhealth [ask minhealth [die hatch-unhealthy-shops 1]]

end
</code>```

答:
When you correct the typos: ask healthy-shops [set total-earnings-h 2000 + random 2000]  and ask unhealthy-shops [set total-earnings-nh 2000 + random 2000] I get an error "You can't use go in an observer context, because go is turtle/link-only".
That is because of the usage of minhealth/minunhealth without giving the respective shop. You can correct that by writing:

```<code>([total-earnings-nh] of minunhealth < [total-earnings-h] of minhealth)
</code>```

This will make the code run until there are no healty or unhealty shops left and then crash.

You can change that by using

```<code>if any? unhealthy-shops and any? healthy-shops
  [compare-revenue]
</code>```

Also, you have to change the order of die and hatch. Right now, no new shops are created, because the shop, it should hatch from is already deleted.

This would be the full code:

```<code>breed[healthy-shops healthy-shop]
breed[unhealthy-shops unhealthy-shop]

healthy-shops-own[
  total-earnings-h
]

unhealthy-shops-own[
  total-earnings-nh
]

to setup
  create-healthy-shops 50
  [
    setxy random-xcor random-ycor
    set total-earnings-h 2000 + random 2000
  ]
  create-unhealthy-shops 50
  [
    setxy random-xcor random-ycor
    set total-earnings-nh 2000 + random 2000
  ]

end

to go
if any? unhealthy-shops and any? healthy-shops
  [compare-revenue]
end

to compare-revenue

 let minhealth one-of healthy-shops with-min [total-earnings-h]
 let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  ifelse ([total-earnings-nh] of minunhealth < [total-earnings-h] of minhealth)
  [ask minunhealth [hatch-healthy-shops 1 die]]
  [ask minhealth [hatch-unhealthy-shops 1 die]]
end
</code>```

Title: Compare two variables from two breeds

Body:
I still haven't learned how to compare two attributes from two different breeds.

In my example, I want to ask the breeds (healthy shops and unhealthy shops) to compare their revenues. The type of shop with the least revenues will close and the other type of shop will open in his place. The command to "compare-revenue" is the one that doesn't work. I know I shouldn't use breed, but I don't know how to formulate it differently without getting the "tick" error.

Thanks!

breed[healthy-shops healthy-shop]
breed[unhealthy-shops unhealthy-shop]

healthy-shops-own[
  total-earnings-h
]

unhealthy-shops-own[
  total-earnings-nh
]

to setup
create-healthy-shops 50
create-unhealthy-shops 50
ask healthy-shop [set total-earnings-n 2000 + random 2000]
ask unhealthy-shop [set total-earnings-nn 2000 + random 2000]
end

to go

compare-revenue
end

;;;;;;;;;

to compare-revenue

 let minhealth one-of healthy-shops with-min [total-earnings-h]
 let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  ask breed [ifelse (total-earnings-nh < total-earnings-h
  [ask minunhealth [die hatch-healthy-shops 1]]
  [ask minhealth [die hatch-unhealthy-shops 1]]]
end

Another version using the let command (not sure if it is right)

to compare-revenue

    let minhealth one-of healthy-shops with-min [total-earnings-h]
    let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  if minhealth > minunhealth [ask minunhealth [die hatch-healthy-shops 1]]
  if minhealth < minunhealth [ask minhealth [die hatch-unhealthy-shops 1]]

end

Body:
When you correct the typos: ask healthy-shops [set total-earnings-h 2000 + random 2000]  and ask unhealthy-shops [set total-earnings-nh 2000 + random 2000] I get an error "You can't use go in an observer context, because go is turtle/link-only".
That is because of the usage of minhealth/minunhealth without giving the respective shop. You can correct that by writing:

([total-earnings-nh] of minunhealth < [total-earnings-h] of minhealth)

This will make the code run until there are no healty or unhealty shops left and then crash.

You can change that by using

if any? unhealthy-shops and any? healthy-shops
  [compare-revenue]

Also, you have to change the order of die and hatch. Right now, no new shops are created, because the shop, it should hatch from is already deleted.

This would be the full code:

breed[healthy-shops healthy-shop]
breed[unhealthy-shops unhealthy-shop]

healthy-shops-own[
  total-earnings-h
]

unhealthy-shops-own[
  total-earnings-nh
]

to setup
  create-healthy-shops 50
  [
    setxy random-xcor random-ycor
    set total-earnings-h 2000 + random 2000
  ]
  create-unhealthy-shops 50
  [
    setxy random-xcor random-ycor
    set total-earnings-nh 2000 + random 2000
  ]

end

to go
if any? unhealthy-shops and any? healthy-shops
  [compare-revenue]
end

to compare-revenue

 let minhealth one-of healthy-shops with-min [total-earnings-h]
 let minunhealth one-of unhealthy-shops with-min [total-earnings-nh]

  ifelse ([total-earnings-nh] of minunhealth < [total-earnings-h] of minhealth)
  [ask minunhealth [hatch-healthy-shops 1 die]]
  [ask minhealth [hatch-unhealthy-shops 1 die]]
end