问:
How do I make a listbox clickable, and redirect to a new page in a Windows Phone project?
I have a Listbox in my Windows Phone page, that contains some text among other things. I want each grouped item to be clickable and taken to the same destination page, but passing a different parameter each time. This is the closest approximation to what I want right now:

```<code>        <ListBox Margin="0,0,-12,0" Name="MainListBox" ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Width="460" Height="220" ClickMode="Release" Click="Button_Click" Tag="{Binding Name1}" BorderThickness="0" >
                        <Button.Content>
                            <StackPanel Orientation="Horizontal" Margin="0,0,0,17" >
                                <Border Background="#FFE5001b" BorderBrush="Black" BorderThickness="2" Height="100" Width="100" Margin="12,0,9,0"  >
                                    <TextBlock Text="{Binding Name2, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-28,9,0" Style="{StaticResource PhoneTextSubtleStyle}" FontSize="40" Name="Name2" />
                                </Border>
                                <StackPanel Width="311">
                                    <TextBlock Text="{Binding Name1, Mode=TwoWay}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" />
                                    <TextBlock Text="{Binding Name3, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                    <TextBlock Text="{Binding Name4, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                    <TextBlock Text="{Binding Calories, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                </StackPanel>
                            </StackPanel>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</code>```

The problem is that the click is set to Release (if set to Press, I cannot scroll at all). Everytime I try to scroll up/down, I get the momentary white glow associated with the click of a button. How do I do this correctly? I don't mind not using the button, just want this to work :/

答:
Check this out.
In the selection changed event handler you can decide which page to navigate based on which item was selected.
And no need for the button inside the template.

Body:
I have a Listbox in my Windows Phone page, that contains some text among other things. I want each grouped item to be clickable and taken to the same destination page, but passing a different parameter each time. This is the closest approximation to what I want right now:

        <ListBox Margin="0,0,-12,0" Name="MainListBox" ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Width="460" Height="220" ClickMode="Release" Click="Button_Click" Tag="{Binding Name1}" BorderThickness="0" >
                        <Button.Content>
                            <StackPanel Orientation="Horizontal" Margin="0,0,0,17" >
                                <Border Background="#FFE5001b" BorderBrush="Black" BorderThickness="2" Height="100" Width="100" Margin="12,0,9,0"  >
                                    <TextBlock Text="{Binding Name2, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-28,9,0" Style="{StaticResource PhoneTextSubtleStyle}" FontSize="40" Name="Name2" />
                                </Border>
                                <StackPanel Width="311">
                                    <TextBlock Text="{Binding Name1, Mode=TwoWay}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" />
                                    <TextBlock Text="{Binding Name3, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                    <TextBlock Text="{Binding Name4, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                    <TextBlock Text="{Binding Calories, Mode=TwoWay}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                                </StackPanel>
                            </StackPanel>
                        </Button.Content>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

The problem is that the click is set to Release (if set to Press, I cannot scroll at all). Everytime I try to scroll up/down, I get the momentary white glow associated with the click of a button. How do I do this correctly? I don't mind not using the button, just want this to work :/


来源: stackexchange

问:
Trying to keep the same type after saving a dataframe in a csv file
When I try to get my dataframe out of the csv file the type of the data changed. Is there a way I can avoid this?

答:
CSVs are text files so don't inherently contain meta-data like datatypes.

When you're opening the CSV you've saved, Python/Pandas is interpreting what it thinks the datatypes are - presumably it's getting it slightly wrong compared to what you want (this is what's happening rather than your CSV being saved with the wrong datatypes).

Pandas 'read_csv' has a 'dtype' argument which will take a dictionary of column types. This should let you specify what data types you'd like. I'd suggest reading through the function documentation here.

ContentLicense: CC BY-SA 4.0


问:
RandomForestRegressor: questions about output, parameters and execution time
I have used the following code to run and evaluate a RandomForestRegressor model for my data:

My dataset is 36 features, 1 label with around 31 million rows. The features are continuous and the labels are binary.

I have the following questions:

When I use np.unique(Y_Pred) it tells me array([0. , 0.5, 1. ]). Why am I getting 0.5 as an output? Is there a parameter I can change in the model to fix it? I don't know whether to include it as a 1 or 0. For now I've included it as a 1 (hence Y_Pred > 0.45 in my code).

The documentation says the most important parameters to adjust are n_estimators and max_features. For n_estimators what is a reasonable number? I've started at 2 because of how slow it took to run on my TPU Google Colab session (43 minutes for each tree or 86 minutes total). Should I bother increasing trees to improve accuracy? Are there any other parameters I can change to improve speed? All of my features are reasonably important so I don't want to start dropping them.

Is there anything I am doing wrong that is making it slow, or anything I can do to make it faster?

Any help would be greatly appreciated.

答:
When your labels are binary, you should use the RandomForestClassifier so that you can get the 1 or 0 as the output directly from the model.

you could play around with the max_samples parameter to reduce the number of datapoints used for each tree in the random forest. Since you have 31 millions records, it make sense to subsample them for each tree.

max_depth has greatly help you to reduce the training time. You need to find the sweet spot the get a balance between computation time and model performance.


问:
Scrollbar creating overlaping chart div
I'm implementing a button to generate a report (plot some charts). Those charts are hidden() before pressing the button, since I'm using bootstrap scrollbar is also hidden. After pressing the button I call show() on divs that charts are defined and call chart render function, after divs are shown scrollbar is also created but chart.reflow() for some reason is getting inaccessible and it won't trigger, so exporting button and credits are getting cropped by scrollbar.

https://jsfiddle.net/bernardo0marques/m6jqa79r/24/

If you resize the window manually the .reflow() is called and it gets fixed. Any workaround or sugestion?

答:
Actually the issue which you are struggling to is not related to triggering the chart.reflow. In the provided demo you are trying to trigger chart.reflow before the chart has been initialized - check your dev console.

The true issue is related to your button position. You have used the style="float: left;" attribute for your button element, which sets the left position of the button in the window - which is also a container for the first chart and that creates the complication while calculating initial positions of some chart elements - here is a demo where is easier to see what I am talking about: https://jsfiddle.net/BlackLabel/L70xh95g/

So you will need to find the other CSS styles which wouldn't disturb the chart rendering. In regular block pattern everything works fine:

https://jsfiddle.net/BlackLabel/dwrje7f0/

I just deleted the style="float: left;"

Title: Scrollbar creating overlaping chart div


问:
Optimise permutation code in C to run within time limit
I am trying to solve this challenge:
https://www.hackerrank.com/challenges/permutations-of-strings/problem

The code is supposed to generate permutations of strings in a lexicographical order.

This is the algorithm I am trying to implement (taken from Wikipedia):

```<code>1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
2. Find the largest index l greater than k such that a[k] < a[l].
3. Swap the value of a[k] with that of a[l].
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].
</code>```

My code runs perfectly on all but one test cases, which is terminated due to a timeout. On my machine (locally) the code runs perfectly on that test case too.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // swaps two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s)
{
    /**
    * Complete this method
    * Return 0 when there is no next permutation and 1 otherwise
    * Modify array s to its next permutation
    */
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // step 1
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // step 2
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // step 3

    for(i = n - 1; i > (k + 1 + n - 1) / 2; i--) // step 4
        swap(&s[i], &s[n - 1 - i + k + 1]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}
</code>```

This is the test case on which it times out:

```<code>8
nrify
tsomld
ubvns
wmgyym
xdyqyfpec
xkpafs
xvd
ysboegsv
</code>```

The expected output is :
https://hr-testcases-us-east-1.s3.amazonaws.com/65303/output36.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1591006903&Signature=SL4ZoBvj2Zp84iAlmheZYs1LePs%3D&response-content-type=text%2Fplain

How can I optimise it to run within the time limit?

答:
Optimisation was required on step 4.

Instead of

```<code>for(i = n - 1; i > (k + 1 + n - 1) / 2; i--) // step 4
        swap(&s[i], &s[n - 1 - i + k + 1]);
</code>```

a better alternative would be

```<code>int inner = k + 1 + n - 1; // step 4
int cond = inner / 2;
for(i = n - 1; i > cond; i--)
    swap(&s[i], &s[inner - i]);
</code>```

Since in this version the condition as well as array index is not calculation expensive in each iteration.

Body:
I am trying to solve this challenge:
https://www.hackerrank.com/challenges/permutations-of-strings/problem

The code is supposed to generate permutations of strings in a lexicographical order.

This is the algorithm I am trying to implement (taken from Wikipedia):

1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
2. Find the largest index l greater than k such that a[k] < a[l].
3. Swap the value of a[k] with that of a[l].
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

My code runs perfectly on all but one test cases, which is terminated due to a timeout. On my machine (locally) the code runs perfectly on that test case too.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // swaps two strings
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
int next_permutation(int n, char **s)
{
    /**
    * Complete this method
    * Return 0 when there is no next permutation and 1 otherwise
    * Modify array s to its next permutation
    */
    int k, i, l;
    k = i = l = 0;

    for(i = n - 2; i >= 0; i--) // step 1
        if(strcmp(s[i], s[i + 1]) < 0) {
            k = i;
            break;
        }

    if(i == -1)
        return 0;

    for(i = n - 1; i >= k + 1; i--) // step 2
        if(strcmp(s[k], s[i]) < 0) {
            l = i;
            break;
        }

    swap(&s[k], &s[l]); // step 3

    for(i = n - 1; i > (k + 1 + n - 1) / 2; i--) // step 4
        swap(&s[i], &s[n - 1 - i + k + 1]);

    return 1;
}

int main() // locked code
{
    char **s;
    int n;
    scanf("%d", &n);
    s = calloc(n, sizeof(char*));
    for (int i = 0; i < n; i++)
    {
        s[i] = calloc(11, sizeof(char));
        scanf("%s", s[i]);
    }
    do
    {
        for (int i = 0; i < n; i++)
            printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
    } while (next_permutation(n, s));
    for (int i = 0; i < n; i++)
        free(s[i]);
    free(s);
    return 0;
}

This is the test case on which it times out:

8
nrify
tsomld
ubvns
wmgyym
xdyqyfpec
xkpafs
xvd
ysboegsv

The expected output is :
https://hr-testcases-us-east-1.s3.amazonaws.com/65303/output36.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1591006903&Signature=SL4ZoBvj2Zp84iAlmheZYs1LePs%3D&response-content-type=text%2Fplain

How can I optimise it to run within the time limit?

Body:
Optimisation was required on step 4.

Instead of

for(i = n - 1; i > (k + 1 + n - 1) / 2; i--) // step 4
        swap(&s[i], &s[n - 1 - i + k + 1]);

a better alternative would be

int inner = k + 1 + n - 1; // step 4
int cond = inner / 2;
for(i = n - 1; i > cond; i--)
    swap(&s[i], &s[inner - i]);

Since in this version the condition as well as array index is not calculation expensive in each iteration.


问:
Strange behavior when copying an array Java in static method
I have a problem with creating a copy of an array in Java.

I pass a copy of the received data to my custom sort method.
The problem is the original array changes too. I 've tried with .clone() and with some other methods which I found on the internet but the result always was the same: sorted array. I think it's specific for java behaviour and it's super easy to fix. Probably something with static keyword (?). Normally I'm programming in JS, Java is not for me :(

```<code>    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }
</code>```

How to create a true copy of the received data in mySort method?

All code:

```<code>package com.company;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String[] args) {

        Example examples[] = new Example[20];

        for (int i = 0; i < examples.length; i++) {
            int randomValue1 = ThreadLocalRandom.current().nextInt(1, 6);
            double randomValue2 = ThreadLocalRandom.current().nextDouble();
            examples[i] = new Example(randomValue1, randomValue2);
        }

        System.out.println("Beforesort: ");
        for (int i = 0; i < examples.length; i++) {
            System.out.println(i + ". " + examples[i]);
        }

        mySort(examples);
    }

    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }

// you can ignore this, it's just customSort
    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        int temp = copy[j].value1;
                        copy[j].value1 = copy[j + 1].value1;
                        copy[j + 1].value1 = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        double temp = copy[j].value2;
                        copy[j].value2 = copy[j + 1].value2;
                        copy[j + 1].value2 = temp;
                    }
                }

        }
        return copy;
    }

}

class Example {
    int value1;
    double value2;

    public Example(int value1, double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "Example{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}

</code>```

答:
The issue is that you are sorting by swapping the content of the Example instances. Imagine those instances with the corresponding values (just in an abstract way):

```<code>e1 = 3;
e2 = 1;
e3 = 2;
</code>```

You are swapping the values, not the positions of the instances.

```<code>e1 = 1;
e2 = 2;
e3 = 3;
</code>```

You can see that the values are sorted, but this hasn't affected the position of instances. Every array that references those instances will obviously see those changes as the values are changed, not the position in the sort array.

What you need is:

```<code>e2 = 1;
e3 = 2;
e1 = 3;
</code>```

As you can see, the order itself is changed, not whatever an instance contains. This will obviously only be visible in the one array, the one you swap the instances in.

Your sorting function has to be like so:

    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                }

        }
        return copy;
    }
```

<p>Again, your current version swaps <em>values</em> not <em>positions</em>. I hope that's clear now.</p>

<hr>

<p>Here's the whole thing:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String[] args) {

        Example examples[] = new Example[20];

        for (int i = 0; i < examples.length; i++) {
            int randomValue1 = ThreadLocalRandom.current().nextInt(1, 6);
            double randomValue2 = ThreadLocalRandom.current().nextDouble();
            examples[i] = new Example(randomValue1, randomValue2);
        }

        System.out.println("Beforesort: ");
        for (int i = 0; i < examples.length; i++) {
            System.out.println(i + ". " + examples[i]);
        }

        mySort(examples);
    }

    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(i + ". " + data[i]);
        }

        System.out.println("Sorted data: ");
        for (int i = 0; i < sortedArray.length; i++) {
            System.out.println(i + ". " + sortedArray[i]);
        }
    }

// you can ignore this, it's just customSort
    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                }

        }
        return copy;
    }

}

class Example {
    int value1;
    double value2;

    public Example(int value1, double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "Example{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}
</code>```

Body:
I have a problem with creating a copy of an array in Java.

I pass a copy of the received data to my custom sort method.
The problem is the original array changes too. I 've tried with .clone() and with some other methods which I found on the internet but the result always was the same: sorted array. I think it's specific for java behaviour and it's super easy to fix. Probably something with static keyword (?). Normally I'm programming in JS, Java is not for me :(

    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }

How to create a true copy of the received data in mySort method?

All code:

package com.company;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String[] args) {

        Example examples[] = new Example[20];

        for (int i = 0; i < examples.length; i++) {
            int randomValue1 = ThreadLocalRandom.current().nextInt(1, 6);
            double randomValue2 = ThreadLocalRandom.current().nextDouble();
            examples[i] = new Example(randomValue1, randomValue2);
        }

        System.out.println("Beforesort: ");
        for (int i = 0; i < examples.length; i++) {
            System.out.println(i + ". " + examples[i]);
        }

        mySort(examples);
    }

    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }

// you can ignore this, it's just customSort
    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        int temp = copy[j].value1;
                        copy[j].value1 = copy[j + 1].value1;
                        copy[j + 1].value1 = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        double temp = copy[j].value2;
                        copy[j].value2 = copy[j + 1].value2;
                        copy[j + 1].value2 = temp;
                    }
                }

        }
        return copy;
    }

}

class Example {
    int value1;
    double value2;

    public Example(int value1, double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "Example{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}

Body:
The issue is that you are sorting by swapping the content of the Example instances. Imagine those instances with the corresponding values (just in an abstract way):

e1 = 3;
e2 = 1;
e3 = 2;

You are swapping the values, not the positions of the instances.

e1 = 1;
e2 = 2;
e3 = 3;

You can see that the values are sorted, but this hasn't affected the position of instances. Every array that references those instances will obviously see those changes as the values are changed, not the position in the sort array.

What you need is:

e2 = 1;
e3 = 2;
e1 = 3;

As you can see, the order itself is changed, not whatever an instance contains. This will obviously only be visible in the one array, the one you swap the instances in.

Your sorting function has to be like so:

    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                }

        }
        return copy;
    }

Again, your current version swaps values not positions. I hope that's clear now.

Here's the whole thing:

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void main(String[] args) {

        Example examples[] = new Example[20];

        for (int i = 0; i < examples.length; i++) {
            int randomValue1 = ThreadLocalRandom.current().nextInt(1, 6);
            double randomValue2 = ThreadLocalRandom.current().nextDouble();
            examples[i] = new Example(randomValue1, randomValue2);
        }

        System.out.println("Beforesort: ");
        for (int i = 0; i < examples.length; i++) {
            System.out.println(i + ". " + examples[i]);
        }

        mySort(examples);
    }

    public static void mySort(Example[] data) {
        Example[] copy = Arrays.copyOf(data, data.length);
        Example[] sortedArray= customSort(copy);
        System.out.println("Original data (should not be sorted): ");
        for (int i = 0; i < data.length; i++) {
            System.out.println(i + ". " + data[i]);
        }

        System.out.println("Sorted data: ");
        for (int i = 0; i < sortedArray.length; i++) {
            System.out.println(i + ". " + sortedArray[i]);
        }
    }

// you can ignore this, it's just customSort
    static Example[] customSort(Example[] copy) {

        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy.length - i - 1; j++)
                if (copy[j].value1 != copy[j + 1].value1) {
                    if (copy[j].value1 > copy[j + 1].value1) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                } else {
                    if (copy[j].value2 > copy[j + 1].value2) {
                        Example temp = copy[j];
                        copy[j] = copy[j + 1];
                        copy[j + 1] = temp;
                    }
                }

        }
        return copy;
    }

}

class Example {
    int value1;
    double value2;

    public Example(int value1, double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    @Override
    public String toString() {
        return "Example{" +
                "value1=" + value1 +
                ", value2=" + value2 +
                '}';
    }
}


问:
Access $errors inside Laravel Blade Component
I've got a "error message" component which I can use via

```<code>@component('error-messages')
    // Some slot stuff which is used for various things.
@endcomponent

</code>```

Then within this I try and access $errors - However the bag is empty, You can see below when i @dump($errors) outside the component, and then within the component.

When I use @include it works, but with @component it's empty

I know I could pass $errors into the component, but this would need to happen everywhere - which isn't ideal.

Has anybody got any idea how to solve this?

答:
Share it in main view by:

```<code>@php
  @View::share('errors', $errors);
@endphp
</code>```

or in controller

```<code>    $validator = Validator::make($request->all(), $this->rules());
    if ($validator->fails()) {
        View::share('item', $item);
        $view = view('admin.param_type.form')->withErrors($validator->errors());
        View::share('errors', $view->errors);
        return $view;
    }
</code>```

Body:
I've got a "error message" component which I can use via

@component('error-messages')
    // Some slot stuff which is used for various things.
@endcomponent

Then within this I try and access $errors - However the bag is empty, You can see below when i @dump($errors) outside the component, and then within the component.

When I use @include it works, but with @component it's empty

I know I could pass $errors into the component, but this would need to happen everywhere - which isn't ideal.

Has anybody got any idea how to solve this?

Body:
Share it in main view by:

@php
  @View::share('errors', $errors);
@endphp

or in controller

    $validator = Validator::make($request->all(), $this->rules());
    if ($validator->fails()) {
        View::share('item', $item);
        $view = view('admin.param_type.form')->withErrors($validator->errors());
        View::share('errors', $view->errors);
        return $view;
    }


问:
Eel python: Javascript error eel is not a function
I am using eel to communicate with python. I'm working in dir C:\Users\Desktop\Eel where I have app.py and inside the UI folder I have index.html, myjava.js, style.css, images but nothing called eel.js. I said this because in docs it says to include script called /eel.js.

index.html

```<code><head>
    <script type="text/javascript" language="JavaScript" src="./myjava.js"></script>
    <script type="text/javascript" src="/eel.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
</code>```

```<code><body>
<div class="container" onclick="runeel()">
</body>
</code>```

my Javascript is:

```<code>function runeel(){
    eel.runpy()
}
</code>```

app.py

```<code>import eel

eel.init('UI')
eel.start('index.html', size=(900, 550))

@eel.expose
def runpy():
     ....code which creates an excel file in desktop...
</code>```

When I run the py file, the index.html loads up and then when I click the div I get into the function and but it throws the error:

```<code>myjava.js:2 Uncaught TypeError: eel.runpy is not a function
</code>```

What am I missing?

答:
It seems that the init statement is written first.
What about writing the @eel.expose statement right after the import statement?

I'm not good at English, so I'm worried that it will make sense.
But I would be happy if I could help.

Body:
I am using eel to communicate with python. I'm working in dir C:\Users\Desktop\Eel where I have app.py and inside the UI folder I have index.html, myjava.js, style.css, images but nothing called eel.js. I said this because in docs it says to include script called /eel.js.

index.html

    <link rel="stylesheet" href="style.css">

my Javascript is:

function runeel(){
    eel.runpy()
}

app.py

import eel

eel.init('UI')
eel.start('index.html', size=(900, 550))

@eel.expose
def runpy():
     ....code which creates an excel file in desktop...

When I run the py file, the index.html loads up and then when I click the div I get into the function and but it throws the error:

myjava.js:2 Uncaught TypeError: eel.runpy is not a function

What am I missing?


问:
Regular expression to extract text between square brackets
Simple regex question. I have a string on the following format:

```<code>this is a [sample] string with [some] special words. [another one]
</code>```

What is the regular expression to extract the words within the square brackets, ie.

```<code>sample
some
another one
</code>```

Note: In my use case, brackets cannot be nested.

答:
To match a substring between the first [ and last ], you may use

```<code>\[.*\]            # Including open/close brackets
\[(.*)\]          # Excluding open/close brackets (using a capturing group)
(?<=\[).*(?=\])   # Excluding open/close brackets (using lookarounds)
</code>```

See a regex demo and a regex demo #2.

Use the following expressions to match strings between the closest square brackets:

Including the brackets:

\[[^][]*] - PCRE, Python re/regex, .NET, Golang, POSIX (grep, sed, bash)

\[[^\][]*] - ECMAScript (JavaScript, C++ std::regex, VBA RegExp)

\[[^\]\[]*] - Java, ICU regex

\[[^\]\[]*\] - Onigmo (Ruby, requires escaping of brackets everywhere)

Excluding the brackets:

(?<=\[)[^][]*(?=]) - PCRE, Python re/regex, .NET (C#, etc.), JGSoft Software

\[([^][]*)] - Bash, Golang - capture the contents between the square brackets with a pair of unescaped parentheses, also see below

\[([^\][]*)] - JavaScript, C++ std::regex, VBA RegExp

(?<=\[)[^\]\[]*(?=]) - Java regex, ICU (R stringr)

(?<=\[)[^\]\[]*(?=\]) - Onigmo (Ruby, requires escaping of brackets everywhere)

NOTE: * matches 0 or more characters, use + to match 1 or more to avoid empty string matches in the resulting list/array.

Whenever both lookaround support is available, the above solutions rely on them to exclude the leading/trailing open/close bracket. Otherwise, rely on capturing groups (links to most common solutions in some languages have been provided).

If you need to match nested parentheses, you may see the solutions in the Regular expression to match balanced parentheses thread and replace the round brackets with the square ones to get the necessary functionality. You should use capturing groups to access the contents with open/close bracket excluded:

\[((?:[^][]++|(?R))*)] - PHP PCRE

\[((?>[^][]+|(?<o>)\[|(?<-o>]))*)] - .NET demo

\[(?:[^\]\[]++|(\g<0>))*\] - Onigmo (Ruby) demo

ContentLicense: CC BY-SA 2.5

Body:
Simple regex question. I have a string on the following format:

this is a [sample] string with [some] special words. [another one]

What is the regular expression to extract the words within the square brackets, ie.

sample
some
another one

Note: In my use case, brackets cannot be nested.

Body:
To match a substring between the first [ and last ], you may use

\[.*\]            # Including open/close brackets
\[(.*)\]          # Excluding open/close brackets (using a capturing group)
(?<=\[).*(?=\])   # Excluding open/close brackets (using lookarounds)

See a regex demo and a regex demo #2.

Use the following expressions to match strings between the closest square brackets:

Including the brackets:

\[[^][]*] - PCRE, Python re/regex, .NET, Golang, POSIX (grep, sed, bash)

\[[^\][]*] - ECMAScript (JavaScript, C++ std::regex, VBA RegExp)

\[[^\]\[]*] - Java, ICU regex

\[[^\]\[]*\] - Onigmo (Ruby, requires escaping of brackets everywhere)

Excluding the brackets:

(?<=\[)[^][]*(?=]) - PCRE, Python re/regex, .NET (C#, etc.), JGSoft Software

\[([^][]*)] - Bash, Golang - capture the contents between the square brackets with a pair of unescaped parentheses, also see below

\[([^\][]*)] - JavaScript, C++ std::regex, VBA RegExp

(?<=\[)[^\]\[]*(?=]) - Java regex, ICU (R stringr)

(?<=\[)[^\]\[]*(?=\]) - Onigmo (Ruby, requires escaping of brackets everywhere)

NOTE: * matches 0 or more characters, use + to match 1 or more to avoid empty string matches in the resulting list/array.

Whenever both lookaround support is available, the above solutions rely on them to exclude the leading/trailing open/close bracket. Otherwise, rely on capturing groups (links to most common solutions in some languages have been provided).

If you need to match nested parentheses, you may see the solutions in the Regular expression to match balanced parentheses thread and replace the round brackets with the square ones to get the necessary functionality. You should use capturing groups to access the contents with open/close bracket excluded:

\[((?:[^][]++|(?R))*)] - PHP PCRE

\[((?>[^][]+|(?<o>)\[|(?<-o>]))*)] - .NET demo

\[(?:[^\]\[]++|(\g<0>))*\] - Onigmo (Ruby) demo


问:
How to convert a RGB image (3 channel) to grayscale (1 channel) and save it?
Working with a deep learning project and I have a lot of images, that don't need to have colors. I saved them doing:

```<code>import matplotlib.pyplot as plt

plt.imsave('image.png', image, format='png', cmap='gray')
</code>```

However later when I checked the shape of the image the result is:

```<code>import cv2
img_rgb = cv2.imread('image.png')
print(img_rgb.shape)
(196,256,3)
</code>```

So even though the image I view is in grayscale, I still have 3 color channels. I realized I had to do some algebric operations in order to convert those 3 channels into 1 single channel.

I have tried the methods described on the thread "How can I convert an RGB image into grayscale in Python?" but I'm confused.

For example, when to do the conversion using:

```<code>from skimage import color
from skimage import io
img_gray = color.rgb2gray(io.imread('image.png'))
plt.imsave('image_gray.png', img_gray, format='png')
</code>```

However when I load the new image and check its shape:

```<code>img_gr = cv2.imread('image_gray.png')
print(img_gr.shape)
(196,256,3)
</code>```

I tried the other methods on that thread but the results are the same. My goal is to have images with a (196,256,1) shape, given how much less computationally intensive it will be for a Convolutional Neural Network.

Any help would be appreciated.

答:
Try this method

```<code>import imageio
new_data = imageio.imread("file_path", as_gray =True)
imageio.imsave("file_path", new_data)
</code>```

The optional argument "as_gray = True" in line 2 of the code does the actual conversion.

Body:
Working with a deep learning project and I have a lot of images, that don't need to have colors. I saved them doing:

import matplotlib.pyplot as plt

plt.imsave('image.png', image, format='png', cmap='gray')

However later when I checked the shape of the image the result is:

import cv2
img_rgb = cv2.imread('image.png')
print(img_rgb.shape)
(196,256,3)

So even though the image I view is in grayscale, I still have 3 color channels. I realized I had to do some algebric operations in order to convert those 3 channels into 1 single channel.

I have tried the methods described on the thread "How can I convert an RGB image into grayscale in Python?" but I'm confused.

For example, when to do the conversion using:

from skimage import color
from skimage import io
img_gray = color.rgb2gray(io.imread('image.png'))
plt.imsave('image_gray.png', img_gray, format='png')

However when I load the new image and check its shape:

img_gr = cv2.imread('image_gray.png')
print(img_gr.shape)
(196,256,3)

I tried the other methods on that thread but the results are the same. My goal is to have images with a (196,256,1) shape, given how much less computationally intensive it will be for a Convolutional Neural Network.

Any help would be appreciated.

Body:
Try this method

import imageio
new_data = imageio.imread("file_path", as_gray =True)
imageio.imsave("file_path", new_data)

The optional argument "as_gray = True" in line 2 of the code does the actual conversion.


问:
_react.default.createContext is not a function when using react-redux
I have a problem when adding components to the entry point, this error immediately pops up here, how to fix it?
I also try add only Main component but anyway i take that error, in main.jsx just class with render method return "hello world"

```<code>_react.default.createContext is not a function
</code>```

// App.jsx

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';

import 'react-select/dist/react-select.css';

import configureStore from './Data/store/configureStore';
import Main from "./Templates/Main/Main";

const store = configureStore();
render(

        <Provider store={store}>
            <BrowserRouter>

            </BrowserRouter>
        </Provider>

,
    document.getElementById('app-root')
);```
</div>
</div>
</p>

<p>Webpack config</p>

```'use strict';

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  devtool: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.join(__dirname, 'src/app.jsx')
  ],
  resolve: {
    root: [
      path.resolve(__dirname, "src"),
    ],
    extensions: ['', '.js', '.jsx', '.css']
  },
  output: {
    path: path.join(__dirname, '/public/'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.tpl.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['es2015', 'react']
      }
    }, {
      test: /\.css$/,
      loader: 'style!css'
    }]
  }
};
```

<p>and dependencies</p>

```    "react": "^15.6.2",
    "react-addons-update": "^15.6.2",
    "react-bootstrap": "^1.0.0-beta.5",
    "react-dom": "^15.6.2",
    "react-helmet": "^5.2.0",
    "react-redux": "^6.0.0",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-select": "^1.0.0-beta13",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "sequelize": "^3.20.0",
    "sqlite3": "^4.0.6"
```

Google advises to upgrade to version 16 of the ract, but I do not think that this is the problem of the old version.

答:
Got the issue fixed by updating the react and react-dom

```<code>npm update react react-dom
</code>```

And ofcourse closing the server and restarting by npm start again.

Body:
I have a problem when adding components to the entry point, this error immediately pops up here, how to fix it?
I also try add only Main component but anyway i take that error, in main.jsx just class with render method return "hello world"

_react.default.createContext is not a function

// App.jsx

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';

import 'react-select/dist/react-select.css';

import configureStore from './Data/store/configureStore';
import Main from "./Templates/Main/Main";

const store = configureStore();
render(

        <Provider store={store}>
            <BrowserRouter>

            </BrowserRouter>
        </Provider>

,
    document.getElementById('app-root')
);

Webpack config

'use strict';

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  devtool: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.join(__dirname, 'src/app.jsx')
  ],
  resolve: {
    root: [
      path.resolve(__dirname, "src"),
    ],
    extensions: ['', '.js', '.jsx', '.css']
  },
  output: {
    path: path.join(__dirname, '/public/'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.tpl.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['es2015', 'react']
      }
    }, {
      test: /\.css$/,
      loader: 'style!css'
    }]
  }
};

and dependencies

    "react": "^15.6.2",
    "react-addons-update": "^15.6.2",
    "react-bootstrap": "^1.0.0-beta.5",
    "react-dom": "^15.6.2",
    "react-helmet": "^5.2.0",
    "react-redux": "^6.0.0",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-select": "^1.0.0-beta13",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "sequelize": "^3.20.0",
    "sqlite3": "^4.0.6"

Google advises to upgrade to version 16 of the ract, but I do not think that this is the problem of the old version.

Body:
Got the issue fixed by updating the react and react-dom

npm update react react-dom

And ofcourse closing the server and restarting by npm start again.


问:
GTag event for Sign Up with reference to Ad (Utm Variables?)
I created a Facebook ad with a link to a page on my website:

```<code>https://www.example.net/signup?utm_source=facebook&utm_medium=cpc&utm_campaign=launch
</code>```

With the UTM variables I can track which campaigns the user came from.

I also need to know how many users really signed up so I am trying to use GTag to create an event:

```<code>gtag('event', 'sign_up', {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});
</code>```

How to relate this event with the Facebook campaign defined in the UTM variables?

答:
If the user lands on the website from that link with the UTM parameters and completes the desired action (sign_up), Google Analytics will be able to understand for itself if that action is associated with that campaign.

If you set a goal in the view so that it activates when an event has action sign_up, you will conveniently see in the channel report the number of goals associated with that specific source / medium.

Body:
I created a Facebook ad with a link to a page on my website:

https://www.example.net/signup?utm_source=facebook&utm_medium=cpc&utm_campaign=launch

With the UTM variables I can track which campaigns the user came from.

I also need to know how many users really signed up so I am trying to use GTag to create an event:

gtag('event', 'sign_up', {
  'event_category': <category>,
  'event_label': ,
  'value': <value>
});

How to relate this event with the Facebook campaign defined in the UTM variables?


问:
Flutter, how to have release and debug app on the same device?
I'm working with flutter on an application (only android for now) which can be downloaded from Google Play.
I have installed the released app on my phone. However, whenever I launch the debug on my device with android studio, it is deleting the released version.
What I would want is having both apps at the same time, like "App" and "App_debug" on my device.

How can I set up my project so there is no conflict between the debug and the release app ?

Thank you.

答:
I managed to found a solution (only for android).

To not delete the "released App" download from Google Play, I add these lines in the file android/app/build.gradle:

```<code>android {
    buildTypes {
        // ------ Start Changes -----
        debug {
            applicationIdSuffix ".debug"
        }
        // ----- End Changes -----
    }
}
</code>```

In that way the package will be com.example.app for a release app and com.example.app.debug for my debug app and there is no conflict anymore.

However I also wanted a different app name so I can differenciate both apps.
To do so I followed this comment:

In the file android/app/src/main/AndroidManifest.xml I made this change:

<manifest ...>
    <application
        // before : android:label="App"
        android:label="@string/app_name"    // <- After my changes
    >
    </application>
</manifest>
```

<p>Then to set up the name for the release app, create or modify the file <code>android/app/src/main/res/values/string.xml</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">App</string>
</resources>
</code>```

And for the debug version, create or modify the file android/app/src/debug/res/values/string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">App Debug</string>
</resources>
```

Body:
I managed to found a solution (only for android).

To not delete the "released App" download from Google Play, I add these lines in the file android/app/build.gradle:

android {
    buildTypes {
        // ------ Start Changes -----
        debug {
            applicationIdSuffix ".debug"
        }
        // ----- End Changes -----
    }
}

In that way the package will be com.example.app for a release app and com.example.app.debug for my debug app and there is no conflict anymore.

However I also wanted a different app name so I can differenciate both apps.
To do so I followed this comment:

In the file android/app/src/main/AndroidManifest.xml I made this change:

<manifest ...>
    <application
        // before : android:label="App"
        android:label="@string/app_name"    // <- After my changes
    >
    </application>
</manifest>

Then to set up the name for the release app, create or modify the file android/app/src/main/res/values/string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">App</string>
</resources>

And for the debug version, create or modify the file android/app/src/debug/res/values/string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">App Debug</string>
</resources>


问:
Question about the difference between Integer triple pointer and float triple pointer
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

```<code>    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

</code>```

enter image description here

答:
Did you see the warning when you compile your code:

warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int **’ [-Wformat=]

  assignment from incompatible pointer type [-Wincompatible-pointer-types]

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘float **’ [-Wformat=]

You can do something like:

```<code>ptr3 = malloc(sizeof(int**)); // allocate the memory for storing one double pointer
*ptr3 = malloc(sizeof(int*)); // allocate the memory for storing one single pointer
**ptr3 = Matrix[0]; // point to first row of the matrix

// it's similar to float pointer type
ptr3_f = malloc(sizeof(float**));
*ptr3_f = malloc(sizeof(float*));
**ptr3_f = Matrix_f[0];
</code>```

Then when you want to print:

```<code>for (i = 0; i < 9; i++) {printf("%d ", (**ptr3)[i]);}
for (i = 0; i < 9; i++) {printf("%.1f ", (**ptr3_f)[i]);}
</code>```

Body:
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

enter image description here

Body:
Did you see the warning when you compile your code:

warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int **’ [-Wformat=]

  assignment from incompatible pointer type [-Wincompatible-pointer-types]

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘float **’ [-Wformat=]

You can do something like:

ptr3 = malloc(sizeof(int**)); // allocate the memory for storing one double pointer
*ptr3 = malloc(sizeof(int*)); // allocate the memory for storing one single pointer
**ptr3 = Matrix[0]; // point to first row of the matrix

// it's similar to float pointer type
ptr3_f = malloc(sizeof(float**));
*ptr3_f = malloc(sizeof(float*));
**ptr3_f = Matrix_f[0];

Then when you want to print:

for (i = 0; i < 9; i++) {printf("%d ", (**ptr3)[i]);}
for (i = 0; i < 9; i++) {printf("%.1f ", (**ptr3_f)[i]);}


问:
Getting Error "Vaadin Designer requires Node to be installed" with Intellij IDEA
I recently started learning Vaadin, I installed the Vaadin Designer plugin in IntelliJ IDEA. When I open JS files I'm getting an error like below:

I'm using nvm for installing node js in my mac. What are the things that I required to configure to get rid of this error?

答: Add export NVM_SYMLINK_CURRENT=true to your .bashrc before NVM-stuff. Then do nvm use default - symlink is created. Then add $HOME/.nvm/current/bin to your PATH in .profile.


问:
What is the difference between signed and unsigned variables?
I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>

答:
Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so they can store larger numbers in the same space, but only nonnegative numbers, e.g. 0 and higher.

For more: Unsigned and Signed Integers

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Chris Hynes

LastEditorDisplayName: Chris Hynes


问:
How to get the focus on a textbox on a key press
We have a page which requires user to enter some input and post submission (e.g. by hitting Enter key or Submit button). The answer is shown to the end user and we provide a link which says 'Press any key to continue'.

The focus on the input box is automatically shown, either after pressing any key or by clicking on the link. Can someone provide some sample code to do this?

答:
try this too...     </p>

```<code> $('#link').click(function() {
        $('#inputbox').focus();
    });
</code>```

Body:
try this too...

 $('#link').click(function() {
        $('#inputbox').focus();
    });


问:
Large json, store two fields in an array
I have a large json file that needs to have to "fields" merged in to an array in order to store to firestore.

Here a screenshot to show what I mean. What i have:

What I need:

As you can see GRP1D and GRP2D where merged in to an array. The json has 15000 entries so doing it manually is not an option

答:
You can write a script using NodeJS to edit this huge file similar to the following:

const largeJson = require('./largeJson.json');

// I am assuming here that the large JSON file is an array of objects
const mergedJson = largeJson.map(obj => {
    const objEditted = { ...obj, GRP1D: [ obj.GRP1D, obj.GRP2D ] };
    delete objEditted.GRP2D;

    return objEditted;
});

// mergedJson now holds an array of objects which merge the fields
// GRP1D and GRP2D as you described in the example
```


问:
Using multiple mapped types for objects key/values. Need only one value from union?
Having some trouble trying to get the type to work correctly here.

I want to specify in an object that each top-level key is one of the strings from a union, and the value is a nested object that has keys of one of the strings from another union, and its value can be the string from the first union (kind of like a state-machine).

Eg:

```<code>type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

const app = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_fail: 'error',
  },
  error: {
    search: 'loading'
  }
  view: {
    search: 'loading'
  }
}
</code>```

My attempts to type this have been:

```<code>type States = { [key in Status]: { [key in Actions]: Status } };
</code>```

Though this doesn't work. Could somebody explain how I could make use of some utility types possibly to allow the nested object key to not require ALL values from the Actions type?

Thanks!

答:
I simplified your code a bit.

This definition

```<code>type Status = 'idle' | 'loading'
type State = { [key in Status]: any}
</code>```

is equivalent to

```<code>type State = {
  idle: any;
  loading: any;
}
</code>```

Therefor, the following code is invalid

```<code>const foo: State = {
  idle: true
}
</code>```

because it's missing the prop loading.

A solution - make the props optional

```<code>type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

type States = { [key in Status]?: { [key in Actions]?: Status } };

const app: States = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_failure: 'error',
  },
  error: {
    search: 'loading'
  },
  view: {
    search: 'loading'
  }
}
</code>```

playground

Body:
Having some trouble trying to get the type to work correctly here.

I want to specify in an object that each top-level key is one of the strings from a union, and the value is a nested object that has keys of one of the strings from another union, and its value can be the string from the first union (kind of like a state-machine).

Eg:

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

const app = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_fail: 'error',
  },
  error: {
    search: 'loading'
  }
  view: {
    search: 'loading'
  }
}

My attempts to type this have been:

type States = { [key in Status]: { [key in Actions]: Status } };

Though this doesn't work. Could somebody explain how I could make use of some utility types possibly to allow the nested object key to not require ALL values from the Actions type?

Thanks!

Body:
I simplified your code a bit.

This definition

type Status = 'idle' | 'loading'
type State = { [key in Status]: any}

is equivalent to

type State = {
  idle: any;
  loading: any;
}

Therefor, the following code is invalid

const foo: State = {
  idle: true
}

because it's missing the prop loading.

A solution - make the props optional

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

type States = { [key in Status]?: { [key in Actions]?: Status } };

const app: States = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_failure: 'error',
  },
  error: {
    search: 'loading'
  },
  view: {
    search: 'loading'
  }
}

playground


问:
Moq async DbSet Setup IDbAsyncQueryProvider
I have this Moq setup:

```<code>_mockContext.Setup(x => x.CarSections).Returns(new List<CarSection> { _carSection }.ToDbSet());
</code>```

Which basically assigns the List to the entity of DbContext.CarSections.

One of the methods is an async method. Something like:

```<code>public async Task<CarSection> GetSectionAsync(int sectionId)
    {
        return await _context
            .CarSections
            .FirstOrDefaultAsync(s => s.CarSectionId == sectionId && s.StatusCode == 4);
    }
</code>```

When it goes through that method I'm getting the error:

The provider for the source IQueryable doesn't implement
  IDbAsyncQueryProvider. Only providers that implement
  IDbAsyncQueryProvider can be used for Entity Framework asynchronous
  operations.

Which I believe is because of the .ToDbSet(). Already tried with Task.FromResult(new List<CarSection>{ _carSection } but the .Returns expects a "DbSet" and not a "Task".

Any ideas on how to workaround this?

答:
It would seem that the .ToDbSet() extension (what package is this extension from?) doesn't setup the IQueryable<T>.Provider property with a provider that implements IDbAsyncQueryProvider.

How would I resolve this?

Look for a mocking library that will do this for you. I moved to EFCore a fair while ago and so I am not sure what the landscape currently looks like for EF, possibly Effort?

If you want to roll your own check out the doco from MS which provides a ready to go copy/paste Moq implementation. There's a bit of scaffolding involved but MS has done the hard work for you. You'll end up creating your own implementation of IDbAsyncQueryProvider and using that as the provider for your DbSet<T>.

Body:
I have this Moq setup:

_mockContext.Setup(x => x.CarSections).Returns(new List<CarSection> { _carSection }.ToDbSet());

Which basically assigns the List to the entity of DbContext.CarSections.

One of the methods is an async method. Something like:

public async Task<CarSection> GetSectionAsync(int sectionId)
    {
        return await _context
            .CarSections
            .FirstOrDefaultAsync(s => s.CarSectionId == sectionId && s.StatusCode == 4);
    }

When it goes through that method I'm getting the error:

The provider for the source IQueryable doesn't implement
  IDbAsyncQueryProvider. Only providers that implement
  IDbAsyncQueryProvider can be used for Entity Framework asynchronous
  operations.

Which I believe is because of the .ToDbSet(). Already tried with Task.FromResult(new List<CarSection>{ _carSection } but the .Returns expects a "DbSet" and not a "Task".

Any ideas on how to workaround this?


问:
I want to switch over to Java, but have 0% of an idea
I have no idea how to install or open Java! Could someone please send me a link and instruct me through this process! Basically I've been using C# for 1 month now and want to try out Java, however I have 0% of an idea on how to open or even download Java, I know you have to download something on your PC and run the console or whatever, however, I don't know the website or have any idea on how to even open the console!</p>

答:
You could also use the Chocolatey package manager (https://chocolatey.org/install) to install OpenJDK (which is nice as the package manager is a central place to handle updates and you don't have to deal with installers).

Java 11 is a good choice for now as it is a so-called LTS version, which means you are not forced to switch to a new version too quickly.

If you're aiming to develop web apps or APIs, Spring (https://spring.io - with Spring Boot being the starting point for most of us) might be interesting for you.

In the Java world, dependency management is mostly handled with Maven or Gradle, with the latter being newer, sometimes faster and having a few nice features.

In terms of IDEs: IntelliJ is very hyped right now and is super convenient and powerful. But Eclipse is also working fine. Even Visual Studio Code might be enough for you, it just lacks some of the nicer Java-specific features.

It maybe is an overkill to mention here, but I really came to love Lombok (https://projectlombok.org), which auto-generates simple getters and setters for me and keeps my code as brief as possible. Definitely worth having a look at.


问:
`flip` function implementation in JavaScript?
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

```<code>const funcName = (arg1) => (arg2) => (arg3) => { ... }
</code>```

I want it turns to:

```<code>const funcName = (arg2) => (arg1) => (arg3) => { ... }
</code>```

And like this:

```<code>const funcName = (arg3) => (arg2) => (arg1) => { ... }
</code>```

答:
flip notoriously takes a function of two arguments a and b, and gives you back a different function with the arguments flipped.

if you want to keep the curried version, this is a way of implementing flip

// f :: a -> b -> c
// flip f :: b -> a -> c

const flip = f => b => a => f(a)(b)
const f = a => b => ({ [a]: b });

console.log(
  f('name')('Alex'),       // { name: 'Alex' }
  flip(f)('Alex')('name'), // { name: 'Alex' }
)
```

Extending it to functions of more than two arguments is relatively simple, as flip can be composed quite easily.

Body:
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

const funcName = (arg1) => (arg2) => (arg3) => { ... }

I want it turns to:

const funcName = (arg2) => (arg1) => (arg3) => { ... }

And like this:

const funcName = (arg3) => (arg2) => (arg1) => { ... }

Body:
flip notoriously takes a function of two arguments a and b, and gives you back a different function with the arguments flipped.

if you want to keep the curried version, this is a way of implementing flip

// f :: a -> b -> c
// flip f :: b -> a -> c

const flip = f => b => a => f(a)(b)
const f = a => b => ({ [a]: b });

console.log(
  f('name')('Alex'),       // { name: 'Alex' }
  flip(f)('Alex')('name'), // { name: 'Alex' }
)

Extending it to functions of more than two arguments is relatively simple, as flip can be composed quite easily.


问:
SQL query for overlapping time
I have this data:

I'm looking for a query which can return the results of combination of Type (Phone and Memory) based on overlapping of startdate and enddate as below:

Thanks

答:
Probably something like this:</p>

```<code>SELECT *
FROM
   table p
   INNER JOIN
   table m
   ON
     NOT(m.startdate > p.enddate OR m.enddate < p.startdate)
WHERE
  p.Type = 'Phone' AND
  m.Type = 'Memory'
</code>```

Title: SQL query for overlapping time

Body:
Probably something like this:

SELECT *
FROM
   table p
   INNER JOIN
   table m
   ON
     NOT(m.startdate > p.enddate OR m.enddate < p.startdate)
WHERE
  p.Type = 'Phone' AND
  m.Type = 'Memory'


问:
how to change TextPainter on Flutter?
Is it possible to change text paint like the below image? I need to add two lines and without rotating.

```<code>Container(
foregroundDecoration: const BadgeDecoration(
   badgeColor: Colors.green,
   badgeSize: 50,
   textSpan: TextSpan(
   text: '42',
   style: TextStyle(color: Colors.black, fontSize: 10),
   ),
   ),
),
</code>```

Decoration

```<code>import 'package:flutter/material.dart';
import 'dart:math' as math;

class BadgeDecoration extends Decoration {
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  const BadgeDecoration({@required this.badgeColor, @required this.badgeSize, @required this.textSpan});

  @override
  BoxPainter createBoxPainter([onChanged]) => _BadgePainter(badgeColor, badgeSize, textSpan);
}

class _BadgePainter extends BoxPainter {
  static const double BASELINE_SHIFT = 1;
  static const double CORNER_RADIUS = 4;
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  _BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    canvas.save();
    canvas.translate(offset.dx + configuration.size.width - badgeSize, offset.dy);
    canvas.drawPath(buildBadgePath(), getBadgePaint());
    // draw text
    final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter.layout(minWidth: hyp, maxWidth: hyp);
    final halfHeight = textPainter.size.height / 2;
    final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) + BASELINE_SHIFT;
    canvas.translate(v, -v);
    canvas.rotate(0.785398); // 45 degrees
    textPainter.paint(canvas, Offset.zero);
    canvas.restore();
  }

  Paint getBadgePaint() => Paint()
    ..isAntiAlias = true
    ..color = badgeColor;

  Path buildBadgePath() => Path.combine(
      PathOperation.difference,
      Path()..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize, topRight: Radius.circular(CORNER_RADIUS))),
      Path()
        ..lineTo(0, badgeSize)
        ..lineTo(badgeSize, badgeSize)
        ..close());
}
</code>```

答:
You can copy paste run full code below

You can paint before rotate and provide offset

code snippet

```<code>TextSpan span = new TextSpan(style: new TextStyle(color: Colors.black, fontSize: 10), text: "Point");
final textPainter1 = TextPainter(text: span, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
textPainter1.layout(minWidth: hyp, maxWidth: hyp);

textPainter1.paint(canvas, Offset(0.0, 5.0));
textPainter.paint(canvas, Offset(3.0, 17.0));
canvas.translate(v, -v);
canvas.rotate(0.785398);
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'dart:math' as math;

class BadgeDecoration extends Decoration {
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  const BadgeDecoration({@required this.badgeColor, @required this.badgeSize, @required this.textSpan});

  @override
  BoxPainter createBoxPainter([onChanged]) => _BadgePainter(badgeColor, badgeSize, textSpan);
}

class _BadgePainter extends BoxPainter {
  static const double BASELINE_SHIFT = 1;
  static const double CORNER_RADIUS = 4;
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  _BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    canvas.save();
    canvas.translate(offset.dx + configuration.size.width - badgeSize, offset.dy);
    canvas.drawPath(buildBadgePath(), getBadgePaint());
    // draw text
    final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter.layout(minWidth: hyp, maxWidth: hyp);
    final halfHeight = textPainter.size.height / 2;
    final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) + BASELINE_SHIFT;

    TextSpan span = new TextSpan(style: new TextStyle(color: Colors.black, fontSize: 10), text: "Point");
    final textPainter1 = TextPainter(text: span, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter1.layout(minWidth: hyp, maxWidth: hyp);

    textPainter1.paint(canvas, Offset(0.0, 5.0));
    textPainter.paint(canvas, Offset(3.0, 17.0));
    canvas.translate(v, -v);
    canvas.rotate(0.785398);
    canvas.restore();
  }

  Paint getBadgePaint() => Paint()
    ..isAntiAlias = true
    ..color = badgeColor;

  Path buildBadgePath() => Path.combine(
      PathOperation.difference,
      Path()..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize, topRight: Radius.circular(CORNER_RADIUS))),
      Path()
        ..lineTo(0, badgeSize)
        ..lineTo(badgeSize, badgeSize)
        ..close());
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              foregroundDecoration: const BadgeDecoration(
                badgeColor: Colors.green,
                badgeSize: 50,
                textSpan: TextSpan(
                  text: '42',
                  style: TextStyle(color: Colors.black, fontSize: 10),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Title: how to change TextPainter on Flutter?

Body:
Is it possible to change text paint like the below image? I need to add two lines and without rotating.

Container(
foregroundDecoration: const BadgeDecoration(
   badgeColor: Colors.green,
   badgeSize: 50,
   textSpan: TextSpan(
   text: '42',
   style: TextStyle(color: Colors.black, fontSize: 10),
   ),
   ),
),

Decoration

import 'package:flutter/material.dart';
import 'dart:math' as math;

class BadgeDecoration extends Decoration {
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  const BadgeDecoration({@required this.badgeColor, @required this.badgeSize, @required this.textSpan});

  @override
  BoxPainter createBoxPainter([onChanged]) => _BadgePainter(badgeColor, badgeSize, textSpan);
}

class _BadgePainter extends BoxPainter {
  static const double BASELINE_SHIFT = 1;
  static const double CORNER_RADIUS = 4;
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  _BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    canvas.save();
    canvas.translate(offset.dx + configuration.size.width - badgeSize, offset.dy);
    canvas.drawPath(buildBadgePath(), getBadgePaint());
    // draw text
    final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter.layout(minWidth: hyp, maxWidth: hyp);
    final halfHeight = textPainter.size.height / 2;
    final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) + BASELINE_SHIFT;
    canvas.translate(v, -v);
    canvas.rotate(0.785398); // 45 degrees
    textPainter.paint(canvas, Offset.zero);
    canvas.restore();
  }

  Paint getBadgePaint() => Paint()
    ..isAntiAlias = true
    ..color = badgeColor;

  Path buildBadgePath() => Path.combine(
      PathOperation.difference,
      Path()..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize, topRight: Radius.circular(CORNER_RADIUS))),
      Path()
        ..lineTo(0, badgeSize)
        ..lineTo(badgeSize, badgeSize)
        ..close());
}

Body:
You can copy paste run full code below

You can paint before rotate and provide offset

code snippet

TextSpan span = new TextSpan(style: new TextStyle(color: Colors.black, fontSize: 10), text: "Point");
final textPainter1 = TextPainter(text: span, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
textPainter1.layout(minWidth: hyp, maxWidth: hyp);

textPainter1.paint(canvas, Offset(0.0, 5.0));
textPainter.paint(canvas, Offset(3.0, 17.0));
canvas.translate(v, -v);
canvas.rotate(0.785398);

working demo

full code

import 'package:flutter/material.dart';
import 'dart:math' as math;

class BadgeDecoration extends Decoration {
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  const BadgeDecoration({@required this.badgeColor, @required this.badgeSize, @required this.textSpan});

  @override
  BoxPainter createBoxPainter([onChanged]) => _BadgePainter(badgeColor, badgeSize, textSpan);
}

class _BadgePainter extends BoxPainter {
  static const double BASELINE_SHIFT = 1;
  static const double CORNER_RADIUS = 4;
  final Color badgeColor;
  final double badgeSize;
  final TextSpan textSpan;

  _BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    canvas.save();
    canvas.translate(offset.dx + configuration.size.width - badgeSize, offset.dy);
    canvas.drawPath(buildBadgePath(), getBadgePaint());
    // draw text
    final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter.layout(minWidth: hyp, maxWidth: hyp);
    final halfHeight = textPainter.size.height / 2;
    final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) + BASELINE_SHIFT;

    TextSpan span = new TextSpan(style: new TextStyle(color: Colors.black, fontSize: 10), text: "Point");
    final textPainter1 = TextPainter(text: span, textDirection: TextDirection.ltr, textAlign: TextAlign.center);
    textPainter1.layout(minWidth: hyp, maxWidth: hyp);

    textPainter1.paint(canvas, Offset(0.0, 5.0));
    textPainter.paint(canvas, Offset(3.0, 17.0));
    canvas.translate(v, -v);
    canvas.rotate(0.785398);
    canvas.restore();
  }

  Paint getBadgePaint() => Paint()
    ..isAntiAlias = true
    ..color = badgeColor;

  Path buildBadgePath() => Path.combine(
      PathOperation.difference,
      Path()..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize, topRight: Radius.circular(CORNER_RADIUS))),
      Path()
        ..lineTo(0, badgeSize)
        ..lineTo(badgeSize, badgeSize)
        ..close());
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              foregroundDecoration: const BadgeDecoration(
                badgeColor: Colors.green,
                badgeSize: 50,
                textSpan: TextSpan(
                  text: '42',
                  style: TextStyle(color: Colors.black, fontSize: 10),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
Python, detect letters with “in”
I’m learning python and got stuck on the “in” keyword.
I want to write a simple code which detects the Turkish letters, for example ı,ş,ö,ç,ğ,ü. But my code never find those letters. It always prints ok. What can I do?

usern = input("username:")
if usern in ("ş", "ı", "ö", "ç", "ü", "ğ"):
    print("turkish letter detected")
else:
    print("ok.")
```

答:
Try this:

```<code>usern = input("username:")
chars_list = ["ş", "ı", "ö", "ç", "ü", "ğ"]
print ", ".join([letter for letter in list(usern) if letter in chars_list]])
</code>```

With list(usern) you convert string to list

Then you check each letter if it's in the defined list of accepted letters.

At the end you print out the found letters.

Better to assign the list/tuple of valid characters in another variable so as to be ale to adjust/handle it easily when needed.

Title: Python, detect letters with “in”

Body:
Try this:

usern = input("username:")
chars_list = ["ş", "ı", "ö", "ç", "ü", "ğ"]
print ", ".join([letter for letter in list(usern) if letter in chars_list]])

With list(usern) you convert string to list

Then you check each letter if it's in the defined list of accepted letters.

At the end you print out the found letters.

Better to assign the list/tuple of valid characters in another variable so as to be ale to adjust/handle it easily when needed.


问:
loading UTf8 from bytes doesn't work as expected in C#
When I load as bytes, and then convert it to utf8, i get a length of 438, if i just load it as utf8 directly, or just write textOut.lengt, i get 437 characters.
The string looks the same for the eyes in debug, but the first character it say is different. Does anyone know the reason for this</p>

```<code>var textOut = JsonConvert.SerializeObject(th);

File.WriteAllText(@"C:\Users\rooh\Music\jag_heter_roland.edit2", textOut, Encoding.UTF8);

var bytes = File.ReadAllBytes(@"C:\Users\rooh\Music\jag_heter_roland.edit2");
var str = System.Text.Encoding.UTF8.GetString(bytes);
Console.WriteLine(textOut.Length);
Console.WriteLine(str.Length);
</code>```

答:
Presumably the first 3 bytes are 0xEFBBBF - the UTF-8 BOM.

When using ReadAllText, I suspect it will detect this and remove it; if you're doing the decode manually (GetString) it will preserve it as codepoint U+FEFF as the first character.

Body:
When I load as bytes, and then convert it to utf8, i get a length of 438, if i just load it as utf8 directly, or just write textOut.lengt, i get 437 characters.
The string looks the same for the eyes in debug, but the first character it say is different. Does anyone know the reason for this

var textOut = JsonConvert.SerializeObject(th);

File.WriteAllText(@"C:\Users\rooh\Music\jag_heter_roland.edit2", textOut, Encoding.UTF8);

var bytes = File.ReadAllBytes(@"C:\Users\rooh\Music\jag_heter_roland.edit2");
var str = System.Text.Encoding.UTF8.GetString(bytes);
Console.WriteLine(textOut.Length);
Console.WriteLine(str.Length);


问:
how to widen the Visual Studio Code's Terminal window from left end of screen to right end of screen?
In Visual Studio Code, Terminal window is some inconvenient because of the width.
I want to widen the width from the end of screen to the end of screen.
Is it possible?

enter image description here

答:
As far as I'm aware, no, this isn't possible to some extent, but perhaps there are some extensions you could search around to see if they can do something similar.
Remember that using your PC's command terminal is also an option.

However, I've found that minimizing the left sidebar by dragging it to the left is an option, which increases the terminal width to the entire screen if this is what you're looking for:

Note doing that disables you from accessing that entire sidebar unless you drag it out again.


问:
Looking for a way to check all possible combinations of four dice in python
I have a single list (or iterable, I'm quite new to Python so I don't know what the difference is) that contains four integer elements, each element ranging from 1 to 6, including 6. My program is essentially a dice game that checks for a lot of different conditions and I'm not entirely sure if all of them work correctly.

I want to check for every possible combination of dice in order to debug the program.

Example: first loop [1, 1, 1, 1] -> second loop [1, 1, 1, 2] ---> seventh loop [1, 1, 2, 1]

答:
```<code>from itertools import product
for l in product(range(1,7), repeat=4):
   # do something with l, for example print(l)
</code>```


问:
CompletableFuture : Invoke a void function asynchronusly
I am trying to implement a database query with retry strategy on certain database exceptions. The code for retry strategy is not very relevant, so I did not include it. As you can see in the code below - I have written a retryCallable which takes the retry strategy and the Callable in populateData().

In getDataFromDB, I get the data from DB and put the data in a global hashmap which serves as a cache at an application level.

This code is working as expected. I would like to invoke populateData from a different class. However, this would be a blocking call. Since this is Database and has retry strategy, this could be slow. I want to call populateData asynchronously.

How can I use CompletableFuture or FutureTask to achieve this?
CompletableFuture.runAsync expects a runnable. CompletableFuture.supplyAsync expects a supplier. I have not implemented these things before. So any advice on best practices would be helpful.

```<code>Class TestCallableRetry {

public void populateData() {
        final Callable<Set<String>> retryCallable = new RetryingCallable<>(retryStrategyToRetryOnDBException(), getDataFromDB());
        Set<String> data = new HashSet<>();

        data = retryCallable.call();

        if (data != null && !data.isEmpty()) {
            // store data in a global hash map
        }
    }

    private Callable<Set<Building>> getDataFromDB() {
        return new Callable<Set<String>>() {
            @Override
            public Set<String> call() {
                // returns data from database
            }
        };
    }
}

Class InvokeCallableAsynchronously {
    public void putDataInGlobalMap {
      // call populateData asynchronously
    }
}
</code>```

答:
its very simple since java8 simply use
CompletableFuture.runAsync(() -> object.func());

Body:
I am trying to implement a database query with retry strategy on certain database exceptions. The code for retry strategy is not very relevant, so I did not include it. As you can see in the code below - I have written a retryCallable which takes the retry strategy and the Callable in populateData().

In getDataFromDB, I get the data from DB and put the data in a global hashmap which serves as a cache at an application level.

This code is working as expected. I would like to invoke populateData from a different class. However, this would be a blocking call. Since this is Database and has retry strategy, this could be slow. I want to call populateData asynchronously.

How can I use CompletableFuture or FutureTask to achieve this?
CompletableFuture.runAsync expects a runnable. CompletableFuture.supplyAsync expects a supplier. I have not implemented these things before. So any advice on best practices would be helpful.

Class TestCallableRetry {

public void populateData() {
        final Callable<Set<String>> retryCallable = new RetryingCallable<>(retryStrategyToRetryOnDBException(), getDataFromDB());
        Set<String> data = new HashSet<>();

        data = retryCallable.call();

        if (data != null && !data.isEmpty()) {
            // store data in a global hash map
        }
    }

    private Callable<Set<Building>> getDataFromDB() {
        return new Callable<Set<String>>() {
            @Override
            public Set<String> call() {
                // returns data from database
            }
        };
    }
}

Class InvokeCallableAsynchronously {
    public void putDataInGlobalMap {
      // call populateData asynchronously
    }
}


问:
How to extract UK postcodes from an address column in a pandas DataFrame?
I have a DataFrame that contains information, in particular addresses like the DataFrame below:

```<code>    col1   col2
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE
</code>```

These are all different formats, with some having commas and others not, and there are also examples of addresses from other countries. I was wondering how would I extract the addresses from here as I want to merge them with location data.

This could mean a merge on substring or just extracting the

I have tried:

```<code>df["postcodes"] = df["address"].str.extract(r'^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$')
</code>```

to extract the postcodes but this doesn't seem to work coming up with the error of 9 arguments given where 1 should be taken.

I have also attempted:

```<code>rhs = (df1.address
          .apply(lambda x: df2[df2.Postcode.str.find(x).ge(0)]['location'])
          .bfill(axis=1)
          .iloc[:, 0])

(pd.concat([df1.app_nbr, rhs], axis=1, ignore_index=True)
 .rename(columns={0: 'app_nbr', 1: 'location'}))
</code>```

from here: How to merge pandas on string contains? but it is taking a long time to run on my machine given there are 1.7million postcodes in the second dataframe to match on.

The expected output would be either:

```<code>    col1   col2                                                  col3
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY   CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       CD7 9HE
</code>```

Or (matching with the second dataframe based on postcode):

```<code>    col1   col2                                              col3 (coords)
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   50.00, 1.00
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       51.23, 1.05
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            54.65, 1.07
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY    51.23, 0.95
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               54.6,  2.23
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       49.25, 1.23
</code>```

Any help would be appreciated or to be pointed in the right direction.

Thank you

*addresses have been altered so are not real but the format is the same

答:
Try to use postal: https://github.com/openvenues/pypostal

It's an open-source library for parsing addresses

In [1]: from postal.parser import parse_address

In [2]: parse_address("Coller Crescent Runcorn,Cheshire WP6 4TY")
Out[2]:
[('coller crescent', 'road'),
 ('runcorn', 'city'),
 ('cheshire', 'state_district'),
 ('wp6 4ty', 'postcode')]

In [3]: parse_address("Yellow Gardens,Tunbridge Wells, Kent TN5 4NP")
Out[3]:
[('yellow gardens', 'road'),
 ('tunbridge wells', 'city'),
 ('kent', 'state_district'),
 ('tn5 4np', 'postcode')]
```

Also I think it will work better with real data.

Body:
I have a DataFrame that contains information, in particular addresses like the DataFrame below:

    col1   col2
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE

These are all different formats, with some having commas and others not, and there are also examples of addresses from other countries. I was wondering how would I extract the addresses from here as I want to merge them with location data.

This could mean a merge on substring or just extracting the

I have tried:

df["postcodes"] = df["address"].str.extract(r'^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$')

to extract the postcodes but this doesn't seem to work coming up with the error of 9 arguments given where 1 should be taken.

I have also attempted:

rhs = (df1.address
          .apply(lambda x: df2[df2.Postcode.str.find(x).ge(0)]['location'])
          .bfill(axis=1)
          .iloc[:, 0])

(pd.concat([df1.app_nbr, rhs], axis=1, ignore_index=True)
 .rename(columns={0: 'app_nbr', 1: 'location'}))

from here: How to merge pandas on string contains? but it is taking a long time to run on my machine given there are 1.7million postcodes in the second dataframe to match on.

The expected output would be either:

    col1   col2                                                  col3
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   TN5 4NP
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       WP6 4TY
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            SF6 9VT
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY   CM52 0QY
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               PT7 6WA
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       CD7 9HE

Or (matching with the second dataframe based on postcode):

    col1   col2                                              col3 (coords)
0   1303   674 Yellow Gardens,Tunbridge Wells, Kent TN5 4NP   50.00, 1.00
1   1205   154 Coller Crescent Runcorn,Cheshire WP6 4TY       51.23, 1.05
2   1504   122 Uphill Road,Rayleigh, Essex SF6 9VT            54.65, 1.07
3   1678   67 Lampoon Crescent,Billericay, Essex, CM52 0QY    51.23, 0.95
4   1897   32 Dovelane,Benfleet, Essex, PT7 6WA               54.6,  2.23
5   1654   46, The Clewter,Great Durham, Essex, CD7 9HE       49.25, 1.23

Any help would be appreciated or to be pointed in the right direction.

Thank you

*addresses have been altered so are not real but the format is the same

Body:
Try to use postal: https://github.com/openvenues/pypostal

It's an open-source library for parsing addresses

In [1]: from postal.parser import parse_address

In [2]: parse_address("Coller Crescent Runcorn,Cheshire WP6 4TY")
Out[2]:
[('coller crescent', 'road'),
 ('runcorn', 'city'),
 ('cheshire', 'state_district'),
 ('wp6 4ty', 'postcode')]

In [3]: parse_address("Yellow Gardens,Tunbridge Wells, Kent TN5 4NP")
Out[3]:
[('yellow gardens', 'road'),
 ('tunbridge wells', 'city'),
 ('kent', 'state_district'),
 ('tn5 4np', 'postcode')]

Also I think it will work better with real data.


问:
Hide keyboard in applicationDidEnterBackground: - screenshot problem
When the home button gets pressed I want to hide the keyboard and restore my view to a sane state, so that when the app is started/foregrounded again, there is no textfield selected and the keyboard is hidden.

My app delegate has this implementation of the method:

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application {
    [tabBarController.view endEditing:YES];
}
</code>```

The keyboard does indeed get removed, but what I don't get is this: Apple's docs say that a snapshot of the app is taken after the method returns. However this poses a problem with the keyboard slide-down animation. Sometimes when the app is started again for a short moment it shows the keyboard half-way down. I assume the screenshot is taken before the animation was finished.

What would I do to solve this, introduce a short timer in the applicationDidEnterBackground: method? I wonder if there is a "cleaner" solution.

答:
I've not tried this but what about turning animations off just before you resign the keyboard:

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application {
    [UIView setAnimationsEnabled:NO];
     [tabBarController.view endEditing:YES];
}
</code>```

If this works you need to turn them back on in applicationWillEnterForeground

Body:
When the home button gets pressed I want to hide the keyboard and restore my view to a sane state, so that when the app is started/foregrounded again, there is no textfield selected and the keyboard is hidden.

My app delegate has this implementation of the method:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [tabBarController.view endEditing:YES];
}

The keyboard does indeed get removed, but what I don't get is this: Apple's docs say that a snapshot of the app is taken after the method returns. However this poses a problem with the keyboard slide-down animation. Sometimes when the app is started again for a short moment it shows the keyboard half-way down. I assume the screenshot is taken before the animation was finished.

What would I do to solve this, introduce a short timer in the applicationDidEnterBackground: method? I wonder if there is a "cleaner" solution.

Body:
I've not tried this but what about turning animations off just before you resign the keyboard:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [UIView setAnimationsEnabled:NO];
     [tabBarController.view endEditing:YES];
}

If this works you need to turn them back on in applicationWillEnterForeground