问:
Can not able to navigate to child screens
My initialRouteName is loginScreen.

After signin Second screen came with BottamTabNavigation. BottomTab contain 4 screens and one of the screen named GroupScreen go to TopTabScren. I am not able to navigate To this screen.

The flow is --> loginScreen --> BottomTabScreen --> TopTabScreen.

I am not able to navigate to TopTabScreen. It gives error

"undefined is not an
  object(evaluating'this.props.navigation.navigate' ".

TopTabScreen leades to further 4 Screens

But when I set InitailRoutName= "TobTabScreen" then all the four screen work with that.

For navigation screens i am using this .

```<code>onPress={() => this.props.navigation.navigate('screenName')}.
</code>```

答:
Get Botttom Tabbar Screen Navigation props

```<code>_getScreenProps = () => {
    return (
        {
            navigation: this.props.navigation,
        }
    )
}
</code>```

Render Tabbar

```<code>render() {
    return (
       <View style={{ flex: 1.0 }}>
            <Stack screenProps={this._getScreenProps()} />
        </View>
    )
}
</code>```

On Tab screen use navigation as follow

```<code>onPress={() => this.props.screenProps.navigation.navigate('screenName')}.
</code>```

Tabbar

```<code>const TabView = createBottomTabNavigator({
    Home: {
        screen: Home,
    },
    Contacts: {
        screen: Contacts,
    },
    Group: {
        screen: Group,
    },
    Task: {
        screen: Task,
    },
    Event: {
        screen: EventView
    }
},
    {
        defaultNavigationOptions: ({ navigation }) => ({
            defaultProps: navigation,
            tabBarIcon: ({ focused, horizontal, tintColor }) => {
                const { routeName } = navigation.state;
                let iconName;
                let title = ''
                if (routeName === 'Home') {
                    iconName = 'ic_home'
                    title = "HOME"
                } else if (routeName === 'Contacts') {
                    iconName = 'ic_user_home'
                    title = "CONTACTS"
                } else if (routeName === 'Group') {
                    iconName = 'ic_group'
                    title = "PROSPECTS"
                } else if (routeName === 'Task') {
                    iconName = 'ic_document'
                    title = "TASKS"
                } else if (routeName === 'Event') {
                    iconName = 'ic_calculator'
                    title = "EVENTS"
                }

                if (focused) {
                    return (
                        <LinearGradient style={{ flex: 1.0, width: '100%' }}
                            colors={[Constant.COLOR.grediantTop, Constant.COLOR.grediantBottom]}>
                            <View style={{ flex: 1.0, justifyContent: 'center' }}>
                                <Image
                                    style={{
                                        height: 25,
                                        width: 25,
                                        tintColor: 'white',
                                        alignSelf: 'center'
                                    }}
                                    tintColor='white'
                                    source={{ uri: iconName }}
                                    resizeMode='contain' />
                                <SPText
                                    style={{ alignSelf: 'center', marginTop: 2, textAlign: 'center' }}
                                    fontSize={8}
                                    textColor='white'
                                    text={title} />
                            </View>
                        </LinearGradient>
                    )
                }
                else {
                    return (
                        <View style={{ flex: 1.0, justifyContent: 'center' }}>
                            <Image
                                style={{
                                    height: 25,
                                    width: 25,
                                    alignSelf: 'center'
                                }}
                                source={{ uri: iconName }}
                                resizeMode='contain' />
                            <SPText
                                style={{ alignSelf: 'center', marginTop: 2 }}
                                fontSize={8}
                                textColor='gray'
                                text={title} />
                        </View>
                    )
                }

            },
            tabBarOnPress: () => {
                const { routeName } = navigation.state;
                navigation.navigate(routeName)
            },

        }),
        tabBarOptions: {
            showLabel: false,
            inactiveTintColor: 'gray',
            inactiveBackgroundColor: 'white',
        },
    })

const RootStack = createStackNavigator(
    {
        TabView: {
            screen: TabView,
        },
    },
    {
        mode: 'modal',
        headerMode: 'none',
    }
);

const Stack = createAppContainer(RootStack);
</code>```

Body:
My initialRouteName is loginScreen.

After signin Second screen came with BottamTabNavigation. BottomTab contain 4 screens and one of the screen named GroupScreen go to TopTabScren. I am not able to navigate To this screen.

The flow is --> loginScreen --> BottomTabScreen --> TopTabScreen.

I am not able to navigate to TopTabScreen. It gives error

"undefined is not an
  object(evaluating'this.props.navigation.navigate' ".

TopTabScreen leades to further 4 Screens

But when I set InitailRoutName= "TobTabScreen" then all the four screen work with that.

For navigation screens i am using this .

onPress={() => this.props.navigation.navigate('screenName')}.

Body:
Get Botttom Tabbar Screen Navigation props

_getScreenProps = () => {
    return (
        {
            navigation: this.props.navigation,
        }
    )
}

Render Tabbar

render() {
    return (
       <View style={{ flex: 1.0 }}>
            <Stack screenProps={this._getScreenProps()} />
        </View>
    )
}

On Tab screen use navigation as follow

onPress={() => this.props.screenProps.navigation.navigate('screenName')}.

Tabbar

const TabView = createBottomTabNavigator({
    Home: {
        screen: Home,
    },
    Contacts: {
        screen: Contacts,
    },
    Group: {
        screen: Group,
    },
    Task: {
        screen: Task,
    },
    Event: {
        screen: EventView
    }
},
    {
        defaultNavigationOptions: ({ navigation }) => ({
            defaultProps: navigation,
            tabBarIcon: ({ focused, horizontal, tintColor }) => {
                const { routeName } = navigation.state;
                let iconName;
                let title = ''
                if (routeName === 'Home') {
                    iconName = 'ic_home'
                    title = "HOME"
                } else if (routeName === 'Contacts') {
                    iconName = 'ic_user_home'
                    title = "CONTACTS"
                } else if (routeName === 'Group') {
                    iconName = 'ic_group'
                    title = "PROSPECTS"
                } else if (routeName === 'Task') {
                    iconName = 'ic_document'
                    title = "TASKS"
                } else if (routeName === 'Event') {
                    iconName = 'ic_calculator'
                    title = "EVENTS"
                }

                if (focused) {
                    return (
                        <LinearGradient style={{ flex: 1.0, width: '100%' }}
                            colors={[Constant.COLOR.grediantTop, Constant.COLOR.grediantBottom]}>
                            <View style={{ flex: 1.0, justifyContent: 'center' }}>
                                <Image
                                    style={{
                                        height: 25,
                                        width: 25,
                                        tintColor: 'white',
                                        alignSelf: 'center'
                                    }}
                                    tintColor='white'
                                    source={{ uri: iconName }}
                                    resizeMode='contain' />
                                <SPText
                                    style={{ alignSelf: 'center', marginTop: 2, textAlign: 'center' }}
                                    fontSize={8}
                                    textColor='white'
                                    text={title} />
                            </View>
                        </LinearGradient>
                    )
                }
                else {
                    return (
                        <View style={{ flex: 1.0, justifyContent: 'center' }}>
                            <Image
                                style={{
                                    height: 25,
                                    width: 25,
                                    alignSelf: 'center'
                                }}
                                source={{ uri: iconName }}
                                resizeMode='contain' />
                            <SPText
                                style={{ alignSelf: 'center', marginTop: 2 }}
                                fontSize={8}
                                textColor='gray'
                                text={title} />
                        </View>
                    )
                }

            },
            tabBarOnPress: () => {
                const { routeName } = navigation.state;
                navigation.navigate(routeName)
            },

        }),
        tabBarOptions: {
            showLabel: false,
            inactiveTintColor: 'gray',
            inactiveBackgroundColor: 'white',
        },
    })

const RootStack = createStackNavigator(
    {
        TabView: {
            screen: TabView,
        },
    },
    {
        mode: 'modal',
        headerMode: 'none',
    }
);

const Stack = createAppContainer(RootStack);


来源: stackexchange

问:
Parentheses change O(n) algorithm
If I have a n length string of open ( and close ) parentheses and I have to count the number of time I change the close ) parentheses to open ( every time when I have more close parentheses than the open one at the current moment while traversing from left to right in every substring of that string.

For e.g. : n = 3, s = ) ( ) :

all substring of s will be [ ), ) (, ) ( ), (, ( ), ) ]

we will have to count in all substring, like in ) ( ) we have close = 1 and open = 0, close > open hence count++. Now the currently processed string is ( ( ), and have no more change to do. Similarly, when we do this for all substring count will be 4.

I wrote a brute force code. I'm assuming is there any way to do this using stack or dynamic programming to do in O(n) or something?

My brute force is like :
1. Create every substring of the given string. O(n^2).
2. Iterating through one substring at a time to count the change. O(n)
Hence, total complexity is O(n^3)

答:
The problem can be solved in O(n^2) by doing some precomputation. Take two arrays left and right of size n(string length). left[index] will store no of left parentheis from s[0] to s[index], similarly right will store no of right parenthesis. So for your example s = ")()", left will be [0, 1, 1] and right will be [1, 1, 2]. This precomputation can be done in O(n). Now we need to figure out how many left parenthesis should have been added for each interval (i,j). So for each interval and sum them up. For each interval figure out this value using the precomputed array in O(1). To iterate each interval we need O(n^2). So the overall complexity is O(n^2).

```<code>int main(){
    vector<int>prefix_sum_left_parentheisis(1000, 0);
    vector<int>prefix_sum_right_parentheisis(1000, 0);
    string s = ")()";
    int count_left_parenthesis = 0;
    int count_right_parenthesis = 0;

    int index = 0;
    for(auto ch:s) {
        if(ch=='(')
            count_left_parenthesis++;
        else
            count_right_parenthesis++;

        prefix_sum_left_parentheisis[index] = count_left_parenthesis;
        prefix_sum_right_parentheisis[index] = count_right_parenthesis;
        index++;
    }

    auto total = 0;
    for(auto i = 0; i < s.size(); i++) {
        for(auto j = i; j < s.size(); j++) {
            if(i == 0) {
                total += max(0, prefix_sum_right_parentheisis[j] - prefix_sum_left_parentheisis[j]);
            }
            else {
                auto count_left_parenthesis_in_range = prefix_sum_left_parentheisis[j] - prefix_sum_left_parentheisis[i-1];
                auto count_right_parenthesis_in_range = prefix_sum_right_parentheisis[j] - prefix_sum_right_parentheisis[i-1];
                total += max(0,count_right_parenthesis_in_range - count_left_parenthesis_in_range);
            }
        }
    }
    cout << "answer is: " << total;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Parentheses change O(n) algorithm

Body:
The problem can be solved in O(n^2) by doing some precomputation. Take two arrays left and right of size n(string length). left[index] will store no of left parentheis from s[0] to s[index], similarly right will store no of right parenthesis. So for your example s = ")()", left will be [0, 1, 1] and right will be [1, 1, 2]. This precomputation can be done in O(n). Now we need to figure out how many left parenthesis should have been added for each interval (i,j). So for each interval and sum them up. For each interval figure out this value using the precomputed array in O(1). To iterate each interval we need O(n^2). So the overall complexity is O(n^2).

int main(){
    vector<int>prefix_sum_left_parentheisis(1000, 0);
    vector<int>prefix_sum_right_parentheisis(1000, 0);
    string s = ")()";
    int count_left_parenthesis = 0;
    int count_right_parenthesis = 0;

    int index = 0;
    for(auto ch:s) {
        if(ch=='(')
            count_left_parenthesis++;
        else
            count_right_parenthesis++;

        prefix_sum_left_parentheisis[index] = count_left_parenthesis;
        prefix_sum_right_parentheisis[index] = count_right_parenthesis;
        index++;
    }

    auto total = 0;
    for(auto i = 0; i < s.size(); i++) {
        for(auto j = i; j < s.size(); j++) {
            if(i == 0) {
                total += max(0, prefix_sum_right_parentheisis[j] - prefix_sum_left_parentheisis[j]);
            }
            else {
                auto count_left_parenthesis_in_range = prefix_sum_left_parentheisis[j] - prefix_sum_left_parentheisis[i-1];
                auto count_right_parenthesis_in_range = prefix_sum_right_parentheisis[j] - prefix_sum_right_parentheisis[i-1];
                total += max(0,count_right_parenthesis_in_range - count_left_parenthesis_in_range);
            }
        }
    }
    cout << "answer is: " << total;
}


问:
How to use loop to display looped information all at once? Functionality Issue
I am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.

I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.

The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].

I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.

Snippet of my code:

```<code>//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if ((rows == y) && (columns == x)) {
                cout << "|" << (i);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}
</code>```

Current Output:

As you can see there's a separate grid for each 'city coordinate'

答:
You need to track which cells already has been visited. That's why you need to take another array which stores the cells that are already visited and by which value.

```<code>int vis[n][n];
memset(vis, -1, sizeof vis);

for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;
    vis[x][y] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if (vis[rows][columns] != -1) {
                cout << "|" << (vis[rows][columns]);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}
</code>```

Output:

Body:
I am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.

I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.

The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].

I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.

Snippet of my code:

//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if ((rows == y) && (columns == x)) {
                cout << "|" << (i);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}

Current Output:

As you can see there's a separate grid for each 'city coordinate'

Body:
You need to track which cells already has been visited. That's why you need to take another array which stores the cells that are already visited and by which value.

int vis[n][n];
memset(vis, -1, sizeof vis);

for(i=0; i<k; i++) {
    //random select int coordinates (x,y) for each K(cities)
    x = rand() % n + 0;
    y = rand() % n + 0;
    arrCity[i] = i;
    vis[x][y] = i;

    //display coordinates for city 1..city2.. etc
    cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;

    //display cities on grid
    for (int rows=0; rows < n; rows++) {
        for (int columns=0; columns < n; columns++) {
            if (vis[rows][columns] != -1) {
                cout << "|" << (vis[rows][columns]);
            } else {
                cout << "|_";
            }

        }
        cout << "\n";
    }
    cout << "\n";
}

Output:


问:
Open base64 encoded pdf file using javascript. Issue with file size larger than 2 MB
I'm using below code to open base64 encoded pdf file using javascript. It works well with small pdf files below 1MB. But it doesn't work if the file size is greater than 2MB. Please let me know if you have a working code for similar scenario.</p>

```<code>var base64 = "base64 content";
let pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64, " + base64 + "'></iframe>");
</code>```

答:
There indeed seems to be a limit on both Chrome's pdf reader plugin and Mozilla's pdf.js (used by Firefox) as to the size of pdf documents loaded by a data-URI.

Note that this limit is not dictated by anything else than these plugin/scripts (pdf.js even just crash the tab), browsers do support far bigger dataURLs in many places like , <video>,  etc.

You can see a live repro here But beware if you are on Firefox, it may crash your browser, so toggle the checkbox at your own risk. (Outsourced because somehow Chrome can't load pdfs from StackSnippet's null origined iframes).

For a fix, convert your base64 data back to binary, packed in a Blob and then set your iframe's src to a blob-URI pointing to that Blob:

const blob = base64ToBlob( base64, 'application/pdf' );
const url = URL.createObjectURL( blob );
const pdfWindow = window.open("");
pdfWindow.document.write("");

function base64ToBlob( base64, type = "application/octet-stream" ) {
  const binStr = atob( base64 );
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[ i ] = binStr.charCodeAt( i );
  }
  return new Blob( [ arr ], { type: type } );
}
```

Once again Live Demo as an outsourced plnkr.

But note that it would be even more efficient if your API sent that pdf directly as a Blob, or even if you could make your  point directly to the resource's URL.

Body:
I'm using below code to open base64 encoded pdf file using javascript. It works well with small pdf files below 1MB. But it doesn't work if the file size is greater than 2MB. Please let me know if you have a working code for similar scenario.

var base64 = "base64 content";
let pdfWindow = window.open("");
pdfWindow.document.write("");

Body:
There indeed seems to be a limit on both Chrome's pdf reader plugin and Mozilla's pdf.js (used by Firefox) as to the size of pdf documents loaded by a data-URI.

Note that this limit is not dictated by anything else than these plugin/scripts (pdf.js even just crash the tab), browsers do support far bigger dataURLs in many places like <img>, <video>, <iframe> etc.

You can see a live repro here But beware if you are on Firefox, it may crash your browser, so toggle the checkbox at your own risk. (Outsourced because somehow Chrome can't load pdfs from StackSnippet's null origined iframes).

For a fix, convert your base64 data back to binary, packed in a Blob and then set your iframe's src to a blob-URI pointing to that Blob:

const blob = base64ToBlob( base64, 'application/pdf' );
const url = URL.createObjectURL( blob );
const pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='" + url + "'></iframe>");

function base64ToBlob( base64, type = "application/octet-stream" ) {
  const binStr = atob( base64 );
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[ i ] = binStr.charCodeAt( i );
  }
  return new Blob( [ arr ], { type: type } );
}

Once again Live Demo as an outsourced plnkr.

But note that it would be even more efficient if your API sent that pdf directly as a Blob, or even if you could make your <iframe> point directly to the resource's URL.


问:
SQL Select row between two conditional rows
```<code>id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0
</code>```

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

```<code>id  vehicle   speed
4   ABC-78     0
6   ABC-91     0
</code>```

I am not sure it's possible or not

答:
```<code>select a.*
from table_name a, table_name b,table_name c
where a.speed = 0 and b.id = a.id - 1 and b.speed > 0 and c.id = a.id + 1 and c.speed > 0;
</code>```

Body:
id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

id  vehicle   speed
4   ABC-78     0
6   ABC-91     0

I am not sure it's possible or not


问:
How do you handle checks to see if a user changed something in a dialog
Talking .NET WinForms here:

If you have an application where someone can change items using some properties dialog for example, how do you determine if a user has changed something when he clicks on cancel (to decide whether to display a cancel confirmation message box, or not).

I can think of 2 methods:

Defining a dirty bit and handling all "changed" events to set this bit to true.

Clone the original object and write some comparison code to determine if the modified object really was modified compared with the original

Is there any more elegant and/or more generic way to do that?

答:
Actually, in a dialog, clicking cancel should just close the dialog. Clicking OK/Save should then save any changes.

So, both methods are slightly flawed in that they assume you are changing the model before the user clicks OK!

I would do following: Attach a pseudo-model object to the dialog. Let changes be reflected in this object, then scrap it on Cancel or pass it on to your DAL on Save. If you only create the pseudo-model on the first change, why then you have your bit for the cancel confirmation dialog.

OwnerDisplayName: Stefan Koell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Daren Thomas


问:
Unable to swap multiple elements in a list in python
I'm new to python and am trying to make a function that swaps multiple values in a list at once.

```<code>def swap(deck: List[int], start1: int, end1: int, start2: int, end2: int) -> None:

    start1 = start1 % len(deck)
    start2 = start2 % len(deck)

    end1 = end1 % len(deck)
    end2 = end2 % len(deck)

    if start1 < start2:
        deck[start1: end1], deck[start2: end2] = deck[start2: end2], deck[start1: end1]
    else:
        deck[start2: end2], deck[start1: end1] = deck[start1: end1], deck[start2: end2]
</code>```

when deck = [0,1,2,3,4,5,6,7,8,9,10]
swap(deck, -3, 11, 0, 2) should mutate the deck to be [8,9,2,3,4,5,6,7,0,1,10], but I get this instead [2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]

I have also tried it with the temp variable method

```<code>    temp = deck[start1: start1]

    deck[start1: start1] = deck[start2: end2]

    deck[start2: end2] = temp
</code>```

but I get the same result... An explanation of why this is happening and how I can fix it is greatly appreciated.

答:
Because your two ranges are not the same size, the deck list changes size after the first assignment, so the range where the temp content is assigned does not correspond to the original positions.

for example:

```<code>deck = [0,1,2,3,4,5,6,7,8,9,10]
temp = deck[0:2]         # temp is [0,1]
deck[0:2] = deck[-3:11]  # deck is now [8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
deck[-3:11] = temp       # [8,9] is replaced by [0,1]
                         # because -3 is now at position 9 instead of  8
</code>```

one way to fix this (assuming your ranges never overlap) is to form a concatenation of the 5 slices of the deck: [before range1]+[range2]+[between ranges]+[range1]+[after range2], or more specifically, assign the total subrange with the concatenation of the 3 middle parts

```<code>deck[start1:end2] = deck[start2:end2] + deck[end1:start2] + deck[start1:end1]
</code>```

Body:
I'm new to python and am trying to make a function that swaps multiple values in a list at once.

def swap(deck: List[int], start1: int, end1: int, start2: int, end2: int) -> None:

    start1 = start1 % len(deck)
    start2 = start2 % len(deck)

    end1 = end1 % len(deck)
    end2 = end2 % len(deck)

    if start1 < start2:
        deck[start1: end1], deck[start2: end2] = deck[start2: end2], deck[start1: end1]
    else:
        deck[start2: end2], deck[start1: end1] = deck[start1: end1], deck[start2: end2]

when deck = [0,1,2,3,4,5,6,7,8,9,10]
swap(deck, -3, 11, 0, 2) should mutate the deck to be [8,9,2,3,4,5,6,7,0,1,10], but I get this instead [2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]

I have also tried it with the temp variable method

    temp = deck[start1: start1]

    deck[start1: start1] = deck[start2: end2]

    deck[start2: end2] = temp

but I get the same result... An explanation of why this is happening and how I can fix it is greatly appreciated.

Body:
Because your two ranges are not the same size, the deck list changes size after the first assignment, so the range where the temp content is assigned does not correspond to the original positions.

for example:

deck = [0,1,2,3,4,5,6,7,8,9,10]
temp = deck[0:2]         # temp is [0,1]
deck[0:2] = deck[-3:11]  # deck is now [8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
deck[-3:11] = temp       # [8,9] is replaced by [0,1]
                         # because -3 is now at position 9 instead of  8

one way to fix this (assuming your ranges never overlap) is to form a concatenation of the 5 slices of the deck: [before range1]+[range2]+[between ranges]+[range1]+[after range2], or more specifically, assign the total subrange with the concatenation of the 3 middle parts

deck[start1:end2] = deck[start2:end2] + deck[end1:start2] + deck[start1:end1]


问:
Hide search bar when cancel button is pressed, and resize navbar
I have a search bar implemented using a UISearchController inside my navigation bar. There is also a table view whose top constraint is set to the bottom of the navigation bar.

Desired behaviour: When the cancel button is pressed, the search bar is hidden and the top constraint of the table view returns to what it was before the search bar was removed (see screenshot #1 at the end of this post)

Current behaviour: When the cancel button is pressed, the search bar is gone but the top constraint of the tableView does not change in response (see screenshot #3)

A possible solution to this problem would be to manually update constraints whenever the cancel button is clicked. However, I can't find a way to access the tableView's constraints from the UISearchBarDelegate method searchBarCancelButtonClicked

Code Snippet:

```<code>class ViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchBar.delegate = self

        /* Adding search button to the navbar */

        /* setting tableView constraints */

        /* tableView delegate/datasource methods, etc... */
    }

    @objc func searchButtonTapped(_ sender: UIBarButtonItem) {
        setup()
        navigationItem.searchController = searchController
    }

    func setup() {
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
    }
}

extension UISearchBarDelegate {
    public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

        navigationItem.searchController = nil

        /* Cannot access tableview constraints from here because extension is outside of the class */
    }
}
</code>```

Before the search button is pressed.

Before the cancel button is pressed.

After the cancel button is pressed.

答:
Try to update the view inside the navigation controller like this:</p>

```<code>func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
    navigationItem.searchController = nil // or searchController
    navigationController?.view.setNeedsLayout() // invalidate current layout
    navigationController?.view.layoutIfNeeded() // force update layout
}
</code>```

Body:
I have a search bar implemented using a UISearchController inside my navigation bar. There is also a table view whose top constraint is set to the bottom of the navigation bar.

Desired behaviour: When the cancel button is pressed, the search bar is hidden and the top constraint of the table view returns to what it was before the search bar was removed (see screenshot #1 at the end of this post)

Current behaviour: When the cancel button is pressed, the search bar is gone but the top constraint of the tableView does not change in response (see screenshot #3)

A possible solution to this problem would be to manually update constraints whenever the cancel button is clicked. However, I can't find a way to access the tableView's constraints from the UISearchBarDelegate method searchBarCancelButtonClicked

Code Snippet:

class ViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchBar.delegate = self

        /* Adding search button to the navbar */

        /* setting tableView constraints */

        /* tableView delegate/datasource methods, etc... */
    }

    @objc func searchButtonTapped(_ sender: UIBarButtonItem) {
        setup()
        navigationItem.searchController = searchController
    }

    func setup() {
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.sizeToFit()
    }
}

extension UISearchBarDelegate {
    public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

        navigationItem.searchController = nil

        /* Cannot access tableview constraints from here because extension is outside of the class */
    }
}

Before the search button is pressed.

Before the cancel button is pressed.

After the cancel button is pressed.

Body:
Try to update the view inside the navigation controller like this:

func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
    navigationItem.searchController = nil // or searchController
    navigationController?.view.setNeedsLayout() // invalidate current layout
    navigationController?.view.layoutIfNeeded() // force update layout
}


问:
Collect array with same id inside array and create new array with id, and name javascript
```<code>{
   "workRequestCompleted":[
      {
         "number":"4329502",
         "name":"Scheduled Outage Primary Feeder",
         "startDate":"2019-07-01",
         "endDate":"2019-07-10",
         "lastUpdate":"2019-12-01T05:00:00Z",
         "contractId":null,
         "status":"Scheduled"
      }
   ],
   "prerequisites":[
      {
         "preq_id":"M12345",
         "preq_type":"FLAG",
         "preq_date_time":"2019-10-02T03:28:00Z",
         "preq_last_update":"2018-12-03T13:30:00Z",
         "preq_crew_id_id":"W_FOD_013",
         "wr_number":"4329502",
         "preq_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ],
   "workComponents":[
      {
         "wc_number":"888-FOD-CO-950-609",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":null,
         "wc_end_date_time":null,
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":"2020-02-16T19:23:02.866019Z",
         "wc_scheduled_end_date_time":"2020-02-17T19:23:02.866028Z",
         "wc_actual_hours":0.0,
         "wc_status":"Scheduled",
         "wc_notes":null,
         "wc_number_pre":"888-FOD-CO-178-0",
         "wc_number_post":"",
         "delay_type":null,
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      },
      {
         "wc_number":"888-FOD-CO-178-0",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":"2019-12-02T04:28:00Z",
         "wc_end_date_time":"2019-12-03T13:30:00Z",
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":null,
         "wc_scheduled_end_date_time":null,
         "wc_actual_hours":10.0,
         "wc_status":"Pending\n",
         "wc_notes":"We noticed that VS5678 may require additional maintenance soon.",
         "wc_number_pre":"",
         "wc_number_post":"",
         "delay_type":"",
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ]
}
</code>```

I have that JSON that contain array, I want to combine facility array that have same facility id from Prerequisites and WorkComponents array and create new array that contain facility id and preq_type with wc_type separate by comma if it have a same facility id, how I can do in javascripts?, thanks

Expected Result :

```<code>[
        {
            "facility_id": "VS1234",
            "type": ["FLAG", "PSMECH", "PSMECH"]
        }
]
</code>```

答:
You can use multiple forEach loops and build one object.

const data = {
  workRequestCompleted: [
    {
      number: "4329502",
      name: "Scheduled Outage Primary Feeder",
      startDate: "2019-07-01",
      endDate: "2019-07-10",
      lastUpdate: "2019-12-01T05:00:00Z",
      contractId: null,
      status: "Scheduled"
    }
  ],
  prerequisites: [
    {
      preq_id: "M12345",
      preq_type: "FLAG",
      preq_date_time: "2019-10-02T03:28:00Z",
      preq_last_update: "2018-12-03T13:30:00Z",
      preq_crew_id_id: "W_FOD_013",
      wr_number: "4329502",
      preq_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ],
  workComponents: [
    {
      wc_number: "888-FOD-CO-950-609",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: null,
      wc_end_date_time: null,
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: "2020-02-16T19:23:02.866019Z",
      wc_scheduled_end_date_time: "2020-02-17T19:23:02.866028Z",
      wc_actual_hours: 0.0,
      wc_status: "Scheduled",
      wc_notes: null,
      wc_number_pre: "888-FOD-CO-178-0",
      wc_number_post: "",
      delay_type: null,
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    },
    {
      wc_number: "888-FOD-CO-178-0",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: "2019-12-02T04:28:00Z",
      wc_end_date_time: "2019-12-03T13:30:00Z",
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: null,
      wc_scheduled_end_date_time: null,
      wc_actual_hours: 10.0,
      wc_status: "Pending\n",
      wc_notes:
        "We noticed that VS5678 may require additional maintenance soon.",
      wc_number_pre: "",
      wc_number_post: "",
      delay_type: "",
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ]
};

const res = {};

data.prerequisites.forEach(pre => {
  pre.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, pre.preq_type]
          }
        : { facility_id: fac.facility_id, type: [pre.preq_type] };
  });
});

data.workComponents.forEach(work => {
  work.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, work.wc_type]
          }
        : { facility_id: fac.facility_id, type: [work.wc_type] };
  });
});

const required_data = Object.values(res);

console.log(required_data);```

Body:
{
   "workRequestCompleted":[
      {
         "number":"4329502",
         "name":"Scheduled Outage Primary Feeder",
         "startDate":"2019-07-01",
         "endDate":"2019-07-10",
         "lastUpdate":"2019-12-01T05:00:00Z",
         "contractId":null,
         "status":"Scheduled"
      }
   ],
   "prerequisites":[
      {
         "preq_id":"M12345",
         "preq_type":"FLAG",
         "preq_date_time":"2019-10-02T03:28:00Z",
         "preq_last_update":"2018-12-03T13:30:00Z",
         "preq_crew_id_id":"W_FOD_013",
         "wr_number":"4329502",
         "preq_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ],
   "workComponents":[
      {
         "wc_number":"888-FOD-CO-950-609",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":null,
         "wc_end_date_time":null,
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":"2020-02-16T19:23:02.866019Z",
         "wc_scheduled_end_date_time":"2020-02-17T19:23:02.866028Z",
         "wc_actual_hours":0.0,
         "wc_status":"Scheduled",
         "wc_notes":null,
         "wc_number_pre":"888-FOD-CO-178-0",
         "wc_number_post":"",
         "delay_type":null,
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      },
      {
         "wc_number":"888-FOD-CO-178-0",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":"2019-12-02T04:28:00Z",
         "wc_end_date_time":"2019-12-03T13:30:00Z",
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":null,
         "wc_scheduled_end_date_time":null,
         "wc_actual_hours":10.0,
         "wc_status":"Pending\n",
         "wc_notes":"We noticed that VS5678 may require additional maintenance soon.",
         "wc_number_pre":"",
         "wc_number_post":"",
         "delay_type":"",
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ]
}

I have that JSON that contain array, I want to combine facility array that have same facility id from Prerequisites and WorkComponents array and create new array that contain facility id and preq_type with wc_type separate by comma if it have a same facility id, how I can do in javascripts?, thanks

Expected Result :

[
        {
            "facility_id": "VS1234",
            "type": ["FLAG", "PSMECH", "PSMECH"]
        }
]


问:
Show 'P' instead of NULL values in PIVOT table
I am working on a PIVOT data and I am stuck at one point. This is my procedure:

```<code>ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, isnull(LeaveTypeName,'P') temp into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnName + '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END
</code>```

PROBLEM:

What I want is, I want to display 'P' for the LeaveTypeName if entry is null. That means, the employee is present at that day. When I am using isNull it showing NULL instead of P.

WHAT I TRIED:

Using COALESCE function to replace the LeaveTypeName with P, but that doesn't work either.

Using ISNULL, but no luck.

EDIT:
Here is my sample data:

```<code>BuddyId   Name  RoleName    DivisionName   01Jan2020     02Jan2020    ....
1          ABC  Developer    Dev              NULL      Casual Leave
2          DEF  Maintenance  Maintenance    Sick Leave   NULL
</code>```

WHAT I NEED:
Replace the Nulls with 'P'

Where I am going wrong?

答:
try this</p>

```<code>DECLARE @ColumnNameNOTnull AS NVARCHAR(MAX)

SELECT @ColumnNameNOTnull =
            STUFF(
            (
                SELECT ', ISNULL(' + QUOTENAME([DateFrom]) + ', ''P'') AS ' + QUOTENAME([DateFrom])
                FROM (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) tempTBL
                ORDER BY [DateFrom]
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
            ,1 , 1, '')

 SET @DynamicPivotQuery =
        N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnNameNOTnull + '
        FROM #PivotLeaveData
        PIVOT(Max( [LeaveTypeName]   )
              FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'
</code>```

Body:
I am working on a PIVOT data and I am stuck at one point. This is my procedure:

ALTER PROCEDURE [dbo].[usp_GetLeaveReportOrg]
@startDate date,
@endDate date

AS
BEGIN
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @leaveReport TABLE (
    BuddyId bigint,
    Name nvarchar(300),
    RoleName nvarchar(150),
    DivisionName nvarchar(200),
    LeaveTypeName nvarchar(max),
    DateFrom date,
    DateTo date
 )

 insert into @leaveReport
 select tbl_Lm.BuddyId, tbl_Bm.Name,tbl_Rm.RoleName, tbl_Dm.DivisionName,tbl_Lt.LeaveTypeName,tbl_Lm.DateFrom, tbl_Lm.DateTo from tbl_LeaveMaster as tbl_Lm
inner join tbl_BuddyMaster as tbl_Bm on tbl_Bm.id= tbl_Lm.BuddyId inner join tbl_DivisionMaster as tbl_Dm on tbl_Dm.Id = tbl_Bm.Divisionid
inner join tbl_LeaveType as tbl_Lt on  tbl_Lt.Id = tbl_Lm.LeaveTypeId inner join tbl_RoleMaster as tbl_Rm on tbl_Lt.Id = tbl_Rm.Id

select BuddyId,Name,  RoleName , DivisionName,DateFrom, isnull(LeaveTypeName,'P') temp into #PivotLeaveData from @leaveReport where
CAST (DateFrom as date) >= cast(@startDate as date) and
cast(DateTo as date) <= cast(@endDate as date)
order by DateFrom  ASC

SELECT @ColumnName =COALESCE (@ColumnName + ',[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']',
           '[' + CONVERT(NVARCHAR, [DateFrom], 106) + ']')
           FROM    (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) PV
           ORDER BY [DateFrom]

 SET @DynamicPivotQuery =
N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnName + '
FROM #PivotLeaveData
PIVOT(Max( [LeaveTypeName]   )
      FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'

EXEC(@DynamicPivotQuery)

END

PROBLEM:

What I want is, I want to display 'P' for the LeaveTypeName if entry is null. That means, the employee is present at that day. When I am using isNull it showing NULL instead of P.

WHAT I TRIED:

Using COALESCE function to replace the LeaveTypeName with P, but that doesn't work either.

Using ISNULL, but no luck.

EDIT:
Here is my sample data:

BuddyId   Name  RoleName    DivisionName   01Jan2020     02Jan2020    ....
1          ABC  Developer    Dev              NULL      Casual Leave
2          DEF  Maintenance  Maintenance    Sick Leave   NULL

WHAT I NEED:
Replace the Nulls with 'P'

Where I am going wrong?

Body:
try this

DECLARE @ColumnNameNOTnull AS NVARCHAR(MAX)

SELECT @ColumnNameNOTnull =
            STUFF(
            (
                SELECT ', ISNULL(' + QUOTENAME([DateFrom]) + ', ''P'') AS ' + QUOTENAME([DateFrom])
                FROM (SELECT DISTINCT [DateFrom] FROM #PivotLeaveData) tempTBL
                ORDER BY [DateFrom]
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
            ,1 , 1, '')

 SET @DynamicPivotQuery =
        N'SELECT BuddyId,Name,RoleName,DivisionName, ' + @ColumnNameNOTnull + '
        FROM #PivotLeaveData
        PIVOT(Max( [LeaveTypeName]   )
              FOR [DateFrom] IN (' + @ColumnName + ')) AS PVTTable'


问:
Uniform EditText size
I'm trying to get all edit text views to be the same size without using a hard definition like px or dp, but rather to use a wrap_content and get them all to be the same size. This is what I have, but it doesn't work:

```<code>    enterAge = (EditText) findViewById(R.id.enterAge);
    enterAge.addTextChangedListener(new TextWatcher1());

    enterWeight = (EditText) findViewById(R.id.enterWeight);
    enterWeight.addTextChangedListener(new TextWatcher2());
    enterWeight.setWidth(enterAge.getWidth());

    enterHeight = (EditText) findViewById(R.id.enterHeight);
    enterHeight.addTextChangedListener(new TextWatcher3());
    enterHeight.setWidth(enterAge.getWidth());

    enterMealFrequency = (EditText) findViewById(R.id.enterMealFrequency);
    enterMealFrequency.addTextChangedListener(new TextWatcher4());
    enterMealFrequency.setWidth(enterAge.getWidth());
</code>```

Any suggestions on why this isn't working the way I want it to?

答:
It depends entirely on when you are executing this code.  The values for the width and height of a View will not return valid data in Java code until layout is complete (this happens sometime later than when the layout is inflated from XML).  If you are doing this in onCreate() or even onResume(), this is too early and getWidth() will likely return zero.

You need to work with the layout system to determine when you will have valid view sizes to work with.

Hope that Helps!

ContentLicense: CC BY-SA 3.0

Title: Uniform EditText size

Body:
I'm trying to get all edit text views to be the same size without using a hard definition like px or dp, but rather to use a wrap_content and get them all to be the same size. This is what I have, but it doesn't work:

    enterAge = (EditText) findViewById(R.id.enterAge);
    enterAge.addTextChangedListener(new TextWatcher1());

    enterWeight = (EditText) findViewById(R.id.enterWeight);
    enterWeight.addTextChangedListener(new TextWatcher2());
    enterWeight.setWidth(enterAge.getWidth());

    enterHeight = (EditText) findViewById(R.id.enterHeight);
    enterHeight.addTextChangedListener(new TextWatcher3());
    enterHeight.setWidth(enterAge.getWidth());

    enterMealFrequency = (EditText) findViewById(R.id.enterMealFrequency);
    enterMealFrequency.addTextChangedListener(new TextWatcher4());
    enterMealFrequency.setWidth(enterAge.getWidth());

Any suggestions on why this isn't working the way I want it to?


问:
Read Pandas DataFrame object like a flatfile
I have an custom Python library function that takes a csv flat file as input that is read using data = open('file.csv', 'r').read(). But currently I've the data processed in Python as a Pandas DataFrame. How can I pass this DataFrame as a flat file object that my custom library function accepts?

As a work around I'm writing the DataFrame to disk and reading it back using the read function which is causing adding a second or two for each iteration. I want to avoid using this process.

答: In the to_csv method of pandas DataFrame, if you don't provide any argument you get the CSV output returned as a string. So you can use the to_csv method on your DataFrame, that produces the same output as you are getting by storing and reading the DataFrame again. </p>


问:
How to get a node's path from root Angular mat-tree
I need to get the path from given node to root in a Angular nested Mat-Tree.

Preferably starting from root until I get to my chosen node. Note that the chosen node can be repeated in the multiple leaves of the tree (with the same node name).

The answer might look like a 2D array in which the first dimension is an array of paths and seconds dimension is the array containing the nodes in the path.

I 'm not really comfortable with recursive functions can someone please help me figure this one out?

An example of the tree structure from Angular.io can be found on stackblitz. Just imagine that the fruit or vegetables in this example could be repeated in multiple categories.

EDIT1: Clarification, more context, added example link

答:
If you are using nested tree, you might want to have a look at an example given in the mat-tree section in the docs. Which is:
Tree with checkboxes from the examples

Now moving to your query, You can use angular map structure as used in above link. Flatmap or NestedMap which can help you to get parent node from child or vice versa. The code given is rather complex but worth to experiment with.

Example:

```<code>// This gets the level of node.
_getLevel = (node: ItemFlatNode) => node.level;
</code>```

If you want to get the parent node:

```<code>  /**
   * Gets Parent node in form of ItemFlatNode
   */
  getParentNode(node: ItemFlatNode): ItemFlatNode | null {
    const currentLevel = this.
    _getLevel (node);

    if (currentLevel < 1) {
      return null;
    }

    const startIndex = this.treeControl.dataNodes.indexOf(node) - 1;

    for (let i = startIndex; i >= 0; i--) {
      const currentNode = this.treeControl.dataNodes[i];

      if (this._getLevel (currentNode) < currentLevel) {
        return currentNode;
      }
    }
    return null;
  }
</code>```

There are some built-in functions already given. But you might have to modify them as per your requirements. Hope this helps.

Body:
If you are using nested tree, you might want to have a look at an example given in the mat-tree section in the docs. Which is:
Tree with checkboxes from the examples

Now moving to your query, You can use angular map structure as used in above link. Flatmap or NestedMap which can help you to get parent node from child or vice versa. The code given is rather complex but worth to experiment with.

Example:

// This gets the level of node.
_getLevel = (node: ItemFlatNode) => node.level;

If you want to get the parent node:

  /**
   * Gets Parent node in form of ItemFlatNode
   */
  getParentNode(node: ItemFlatNode): ItemFlatNode | null {
    const currentLevel = this.
    _getLevel (node);

    if (currentLevel < 1) {
      return null;
    }

    const startIndex = this.treeControl.dataNodes.indexOf(node) - 1;

    for (let i = startIndex; i >= 0; i--) {
      const currentNode = this.treeControl.dataNodes[i];

      if (this._getLevel (currentNode) < currentLevel) {
        return currentNode;
      }
    }
    return null;
  }

There are some built-in functions already given. But you might have to modify them as per your requirements. Hope this helps.


问:
Failure to get a positive integer
Here is the code that I've written:

number = int(input('Enter a nonnegative integer: '))

product=1
for i in range(number):
    product = product * (i+1)
    print(product)
```

<p>The result is:</p>

<pre class="lang-py prettyprint-override"><code>1
2
6
24...
5040
</code>```

But I only need the resulted nonnegative integer when the input is 7, which is 5040. How do I get that?

答:
Unindent the print statement so it's not in the for loop. Then it will only print the result.

number = int(input('Enter a nonnegative integer: '))

product=1
for i in range(number):
    product = product * (i+1)
print(product)
```

Title: Failure to get a positive integer

Body:
Here is the code that I've written:

number = int(input('Enter a nonnegative integer: '))

product=1
for i in range(number):
    product = product * (i+1)
    print(product)

The result is:

1
2
6
24...
5040

But I only need the resulted nonnegative integer when the input is 7, which is 5040. How do I get that?


问:
Handling AWS credentials within an Angular app
I have an Angular application that makes use of the following AWS credentials:

```<code>  awsAccessKeyId
  awssecretAccessKey
  awsBucket
  awsEndpointUrl
  awsRegion
  awsKey
</code>```

I wanted to store them in the environment.ts file of my application but have been told that it is a bad idea. Where else can I store them? I was thinking Firebase, but only allowing the document to be read with an authenticated user with a particular UID via an API call.

答:
Storing such credentials in the environment file is discouraged because generally, environment files are committed into the git.

1. If it repository is public, then all of your credentials are available for public (mis)use.

2. If the repository is private, then also there may come such a situation where multiple people are working on same project but only very few people will need these credentials and not everyone.

3. In your case, if you get the AWS credentials in the front end, then anyone can get those credentials from the network tab (easiest way) and will be able to (mis)use it.

How / Where you should store such credentials depends upon your use case. There cannot be an answer which would fit everyone's need. Though there are few good approaches for it:

1. Keep the environment file out of the repository, and distributed it to developers as they need it.

2. Like you mentioned, storing it in a separate place and fetching them during runtime.

3. If you have a backend, then instead of fetching the credentials on the front end and then accessing the cloud service, store the credentials on the backend, and access the cloud service through the backend. (recommended)

There can be many other ways also to tackle this problem but they would also depend upon those projects.

Body:
I have an Angular application that makes use of the following AWS credentials:

  awsAccessKeyId
  awssecretAccessKey
  awsBucket
  awsEndpointUrl
  awsRegion
  awsKey

I wanted to store them in the environment.ts file of my application but have been told that it is a bad idea. Where else can I store them? I was thinking Firebase, but only allowing the document to be read with an authenticated user with a particular UID via an API call.


问:
How to declare a variable in a template in Angular
I have the following template :

```<code><div>
  <span>{{aVariable}}</span>
</div>
</code>```

and would like to end up with :

```<code><div "let a = aVariable">
  <span>{{a}}</span>
</div>
</code>```

Is there a way to do it ?

答:
If you need autocomplete support from within in your templates from the Angular Language Service:

Synchronous:

```<code>myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">
  {{var.hello}}
</ng-container>
</code>```

Using async pipe:

```<code>myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">
  {{var.hello}}
</ng-container>
</code>```

Body:
I have the following template :

  {{aVariable}}

and would like to end up with :

  {{a}}

Is there a way to do it ?

Body:
If you need autocomplete support from within in your templates from the Angular Language Service:

Synchronous:

myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">
  {{var.hello}}
</ng-container>

Using async pipe:

myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">
  {{var.hello}}
</ng-container>


问:
Change image of button when pressed - Python 3.7 Tkinter
This may seem like a dumb question but couldn't find an answer on stackoverflow and I needed this for a project. Hope somebody can help.

Now, I am creating cross platform screen recorder. I have attached the current UI below. In the below UI, I want the pause button to change into a play button (swapping of images) or vice versa if again pressed. I am attaching the whole GUI code here. please help me out regarding this. I am working python 3.7 on Ubuntu OS but it should be applicable on all platforms.

Along with this, I wanted to also know how to set background for the whole window, I tried canvas but didn't seem to work. I also wanted to place a Logo beside the Label showing "Screen Videographer", is that possible if so may I know how to align it.

Here is the code below:-

```<code>from tkinter import *
from tkinter.ttk import *
from detect_screen_size import detect_screen_size
from PIL import Image, ImageTk
import tkinter as tk

paused= True

LOGO_PNG_PATH="pic/logo.png"
LOGO_PATH="pic/logo.ico"
BG_PATH = 'pic/bg_1.jpg'
LOGO_LINUX_PATH="@pic/logo_1.xbm"

def play():
    global paused,image2
    print("start of function",paused)
    if paused:
        image2=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/play.png")
        paused=False
        print("inside if function",paused)
    else:
        image2 = PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
        paused=True
        print("inside if function", paused)

def pause():
    print("button hit")
def stop():
    print("button stop")
def record():
    print("button rec")
WIDTH, HEIGHT = 350, 100

root = Tk()
#root.geometry('{}x{}'.format(WIDTH, HEIGHT))
root.resizable(0, 0)
root.style = Style()
#('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
root.style.theme_use("clam")
if detect_screen_size().detect_os()=="Linux":
    root.iconbitmap(LOGO_LINUX_PATH)
else:
    root.iconbitmap(default=LOGO_PATH)
root.title("Screenvideographer")

frame_display = tk.Frame(relief=FLAT)
label = tk.Label(master=frame_display, text="Screen Videographer")
label.pack()
canvas = Canvas(root, width = 50, height = 50)
canvas.pack(side=LEFT)
img = PhotoImage(file=LOGO_PNG_PATH)
canvas.create_image(50,50, anchor=NW, image=img)

frame_display.pack()
frame_controls = tk.Frame(relief=FLAT)

image1=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/record.png")
image2=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
image3=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/stop.png")

Button(master=frame_controls,width=35,image=image1,command=record).pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=image2,command=play).pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=image3,command=stop).pack(side=RIGHT,padx=7,pady=4)

frame_controls.pack()

root.mainloop()
</code>```

Thank you!!

答:
1) you should load the 4 images on program start:

```<code>img_record=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/record.png")
img_pause=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
img_stop=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/stop.png")
img_play=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/play.png")
</code>```

2) you need to separate the Button(...) and pack(...) statements for the play/pause button:

```<code>Button(master=frame_controls,width=35,image=img_record,command=record).pack(side=LEFT,padx=7,pady=4)
play_btn = Button(master=frame_controls,width=35,image=img_play,command=play)
play_btn.pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=img_stop,command=stop).pack(side=RIGHT,padx=7,pady=4)
</code>```

3) change the button image based on the current play state:

```<code>def play():
    global paused
    print("start of function", paused)
    if paused:
        play_btn.config(image=img_pause)
        paused = False
        print("inside if function", paused)
    else:
        play_btn.config(image=img_play)
        paused = True
        print("inside if function", paused)
</code>```

4) edit stop() function to change back to play image:

```<code>def stop():
    global paused
    print("button stop")
    if not paused:
        play_btn.config(image=img_play)
        paused = True
</code>```

5) if you want to show an image beside the Screen Videographer label, just use image and compound options of the label:

```<code># logo = PhotoImage(file="/path/to/logo/image")
label = tk.Label(master=frame_display, image=logo, text="Screen Videographer", compound="left")
</code>```

6) if you want to change the background color of the whole window, you need to change the background options of root window, frames inside root window and labels inside frames.

Body:
This may seem like a dumb question but couldn't find an answer on stackoverflow and I needed this for a project. Hope somebody can help.

Now, I am creating cross platform screen recorder. I have attached the current UI below. In the below UI, I want the pause button to change into a play button (swapping of images) or vice versa if again pressed. I am attaching the whole GUI code here. please help me out regarding this. I am working python 3.7 on Ubuntu OS but it should be applicable on all platforms.

Along with this, I wanted to also know how to set background for the whole window, I tried canvas but didn't seem to work. I also wanted to place a Logo beside the Label showing "Screen Videographer", is that possible if so may I know how to align it.

Here is the code below:-

from tkinter import *
from tkinter.ttk import *
from detect_screen_size import detect_screen_size
from PIL import Image, ImageTk
import tkinter as tk

paused= True

LOGO_PNG_PATH="pic/logo.png"
LOGO_PATH="pic/logo.ico"
BG_PATH = 'pic/bg_1.jpg'
LOGO_LINUX_PATH="@pic/logo_1.xbm"

def play():
    global paused,image2
    print("start of function",paused)
    if paused:
        image2=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/play.png")
        paused=False
        print("inside if function",paused)
    else:
        image2 = PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
        paused=True
        print("inside if function", paused)

def pause():
    print("button hit")
def stop():
    print("button stop")
def record():
    print("button rec")
WIDTH, HEIGHT = 350, 100

root = Tk()
#root.geometry('{}x{}'.format(WIDTH, HEIGHT))
root.resizable(0, 0)
root.style = Style()
#('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
root.style.theme_use("clam")
if detect_screen_size().detect_os()=="Linux":
    root.iconbitmap(LOGO_LINUX_PATH)
else:
    root.iconbitmap(default=LOGO_PATH)
root.title("Screenvideographer")

frame_display = tk.Frame(relief=FLAT)
label = tk.Label(master=frame_display, text="Screen Videographer")
label.pack()
canvas = Canvas(root, width = 50, height = 50)
canvas.pack(side=LEFT)
img = PhotoImage(file=LOGO_PNG_PATH)
canvas.create_image(50,50, anchor=NW, image=img)

frame_display.pack()
frame_controls = tk.Frame(relief=FLAT)

image1=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/record.png")
image2=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
image3=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/stop.png")

Button(master=frame_controls,width=35,image=image1,command=record).pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=image2,command=play).pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=image3,command=stop).pack(side=RIGHT,padx=7,pady=4)

frame_controls.pack()

root.mainloop()

Thank you!!

Body:
1) you should load the 4 images on program start:

img_record=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/record.png")
img_pause=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/symbol.png")
img_stop=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/stop.png")
img_play=PhotoImage(file="/media/admin_ash/New Volume/proj/screen rec/pic/gui_controls/play.png")

2) you need to separate the Button(...) and pack(...) statements for the play/pause button:

Button(master=frame_controls,width=35,image=img_record,command=record).pack(side=LEFT,padx=7,pady=4)
play_btn = Button(master=frame_controls,width=35,image=img_play,command=play)
play_btn.pack(side=LEFT,padx=7,pady=4)
Button(master=frame_controls,width=35,image=img_stop,command=stop).pack(side=RIGHT,padx=7,pady=4)

3) change the button image based on the current play state:

def play():
    global paused
    print("start of function", paused)
    if paused:
        play_btn.config(image=img_pause)
        paused = False
        print("inside if function", paused)
    else:
        play_btn.config(image=img_play)
        paused = True
        print("inside if function", paused)

4) edit stop() function to change back to play image:

def stop():
    global paused
    print("button stop")
    if not paused:
        play_btn.config(image=img_play)
        paused = True

5) if you want to show an image beside the Screen Videographer label, just use image and compound options of the label:

# logo = PhotoImage(file="/path/to/logo/image")
label = tk.Label(master=frame_display, image=logo, text="Screen Videographer", compound="left")

6) if you want to change the background color of the whole window, you need to change the background options of root window, frames inside root window and labels inside frames.


问:
Using WMI and PYWIN32 to change IPV4 settings on Ethernet card
Im trying to change the IPV4 adress on the Ethernet-card.
But when i run the script only the subnetmask changes and the IPV4 settings
remain on "obtain an IP address automaticly".
Any clue?

Info: The var_ip, var_mask, var_gateway comes from entry widgets.

```<code>import wmi

def set_ip():

nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
nic = nic_configs[0]
ip = var_ip.get()
subnetmask = var_mask.get()
gateway = var_gateway.get()

# Set IP address, subnet mask and default gateway
a = nic.EnableStatic(IPAddress=[ip], SubnetMask=[subnetmask])
b = nic.SetGateways(DefaultIPGateway=[gateway])
</code>```

答:
In one of my projects I also tried to do this using WMI, finally changed this to using netsh program. You can use CreateProcess and pass required parameters to netsh.
For example, assuming that Etnernet adapter name is eth1, command-line utility netsh can be used by the following way:

```<code>netsh interface ipv4 set address "eth1" dhcp

netsh interface ipv4 set address "eth1" static 192.168.0.1 255.255.255.0
</code>```

See also: https://www.howtogeek.com/103190/change-your-ip-address-from-the-command-prompt/

Body:
Im trying to change the IPV4 adress on the Ethernet-card.
But when i run the script only the subnetmask changes and the IPV4 settings
remain on "obtain an IP address automaticly".
Any clue?

Info: The var_ip, var_mask, var_gateway comes from entry widgets.

import wmi

def set_ip():

nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
nic = nic_configs[0]
ip = var_ip.get()
subnetmask = var_mask.get()
gateway = var_gateway.get()

# Set IP address, subnet mask and default gateway
a = nic.EnableStatic(IPAddress=[ip], SubnetMask=[subnetmask])
b = nic.SetGateways(DefaultIPGateway=[gateway])

Body:
In one of my projects I also tried to do this using WMI, finally changed this to using netsh program. You can use CreateProcess and pass required parameters to netsh.
For example, assuming that Etnernet adapter name is eth1, command-line utility netsh can be used by the following way:

netsh interface ipv4 set address "eth1" dhcp

netsh interface ipv4 set address "eth1" static 192.168.0.1 255.255.255.0

See also: https://www.howtogeek.com/103190/change-your-ip-address-from-the-command-prompt/


问:
Automatically insert a data to database in certain cases in laravel
I am new to laravel. I want to know is there any particular better option to use in the following case in laravel. For an example I have a table called product and another table called productlog. While a product is created / updated / deleted in those cases I have to insert a log in productlog table. I know, I can insert these data directly in the controller while these actions happening. Except this laravel has any better feature to use in this case?</p>

答:
You want to perform some action while your Eloquent model is processing. Laravel’s Eloquent provide a convenient way to add your own action while the model is completing or has completed some action.

This is the list of all of the events, eloquent model fired that we can hook into:

retrieved : after a record has been retrieved.

creating : before a record has been created.

created : after a record has been created.

updating : before a record is updated.

updated : after a record has been updated.

saving : before a record is saved (either created or updated).

saved : after a record has been saved (either created or updated).

deleting : before a record is deleted or soft-deleted.

deleted : after a record has been deleted or soft-deleted.

restoring : before a soft-deleted record is going to be restored.

restored : after a soft-deleted record has been restored.

For more details check the Laravel documentation here.
Observers/ Model Events


问:
how to get discord.js to pick a random image from file
I'm in another pickle I've realized over the past week that my images are not loading due to the fact the links have expired so I wanna find out how to go about using a file directory in the code.

Here's what I've tried:

```<code>});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readdirSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});
</code>```

and

```<code>});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
const path = 'C:\Users\nevbw\Desktop\games\FBIBot\images\hugs';
const fs = require('fs');

fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random() * file.length);
message.channel.sendFile(ranfile);
})
}
});
</code>```

答:
Happy to help.

You're using FS the wrong way. This Is What It Should Look Like :D Also Here Is Some Documentation on It ( https://nodejs.org/dist/latest-v13.x/docs/api/fs.html ).

-- Code --

Also Just As A Tip! I See You Are Using Full Directories, That's Quite Innificeng (E.g if You Change Your Username, Drive ID, etc.) so in fs provided the image is in the same folder you can just do ./(ImageName), or if it is in the same folder but under another say /FBIBot/Images you can do ./Images/(ImageName). ^^

--

What The Error Was: (I Unfortunately Cannot Test it But I Am Like 99% Sure).

You Were Using fs.readdirSync(path).forEach(file => { When You Were Meant To Be Using fs.readfilesync(path).forEach(file => {.

-- First Code --

});

```<code>client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readfileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});
</code>```

-- Second Code --

```<code>});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readFileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});
</code>```

^^

Body:
I'm in another pickle I've realized over the past week that my images are not loading due to the fact the links have expired so I wanna find out how to go about using a file directory in the code.

Here's what I've tried:

});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readdirSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});

and

});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
const path = 'C:\Users\nevbw\Desktop\games\FBIBot\images\hugs';
const fs = require('fs');

fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random() * file.length);
message.channel.sendFile(ranfile);
})
}
});

Body:
Happy to help.

You're using FS the wrong way. This Is What It Should Look Like :D Also Here Is Some Documentation on It ( https://nodejs.org/dist/latest-v13.x/docs/api/fs.html ).

-- Code --

Also Just As A Tip! I See You Are Using Full Directories, That's Quite Innificeng (E.g if You Change Your Username, Drive ID, etc.) so in fs provided the image is in the same folder you can just do ./(ImageName), or if it is in the same folder but under another say /FBIBot/Images you can do ./Images/(ImageName). ^^

--

What The Error Was: (I Unfortunately Cannot Test it But I Am Like 99% Sure).

You Were Using fs.readdirSync(path).forEach(file => { When You Were Meant To Be Using fs.readfilesync(path).forEach(file => {.

-- First Code --

});

client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readfileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});

-- Second Code --

});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readFileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
    }
});

^^


问:
AngularDart: How to configure routerProviders / routerProvidersHash for development and production environments?
There is one SO question about same problem. But I can't find production-ready code example how to use routerProviders / routerProvidersHash in real application.

As I understand we need to define two injectors and use one of them depending on compile time environment variable, like shown below.

// File: web/main.dart

// >>> Have to use 2 injectors:
@GenerateInjector([
  routerProvidersHash,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorDev = self.injectorDev$Injector;

@GenerateInjector([
  routerProviders,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorProd = self.injectorProd$Injector;
// <<<

void main() {
  final env = ServerEnvironment();
  if (env.isProduction) {
    runApp(ng.AppComponentNgFactory, createInjector: injectorProd);
  } else {
    runApp(ng.AppComponentNgFactory, createInjector: injectorDev);
  }
}
```

<pre class="lang-dart prettyprint-override"><code>// File: lib/server_environment.dart

enum ServerEnvironmentId { development, production }

class ServerEnvironment {

  ServerEnvironmentId id;

  static final ServerEnvironment _instance = ServerEnvironment._internal();
  factory ServerEnvironment() => _instance;

  ServerEnvironment._internal() {
    const compileTimeEnvironment = String.fromEnvironment('MC_ENVIRONMENT', defaultValue: 'development');
    if (compileTimeEnvironment != 'development') {
      id = ServerEnvironmentId.production;
    } else {
      id = ServerEnvironmentId.development;
    }
  }

  bool get isProduction {
    return id == ServerEnvironmentId.production;
  }

}
</code>```

```<code>File: build.production.yaml

targets:
  $default:
    builders:
      build_web_compilers|entrypoint:
        generate_for:
          - web/main.dart
        options:
          compiler: dart2js
          # List any dart2js specific args here, or omit it.
          dart2js_args:
          - -DMC_ENVIRONMENT=production
          - --fast-startup
          - --minify
          - --trust-primitives

</code>```

# Build execution

pub run build_runner build --config production --release -o web:build
```

Is the assumption of having two injectors is the right way to do?

Thank you in advance!

答:
What I would do is make a different main.dart file for your different injector setup.  You shouldn't have too much stuff in main.dart it should just serve as a mechanism to start your app.  The branching should occur in build.production.yaml as specifying a different main for production (i.e. web/main_production.dart) and this file is the one with the non-hash route provider.  This would remove the need for a "ServerEnvironment" and a if/else with a potentially confusing double injector setup in one file.

```<code>// File: web/main.dart

@GenerateInjector([
  routerProvidersHash,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: injector);
}
</code>```

and

```<code>// File: web/main_production.dart

@GenerateInjector([
  routerProviders,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: injector);
}
</code>```

with

```<code>File: build.production.yaml

targets:
  $default:
    builders:
      build_web_compilers|entrypoint:
        generate_for:
          - web/main_production.dart
        options:
          compiler: dart2js
          # List any dart2js specific args here, or omit it.
          dart2js_args:
          - --fast-startup
          - --minify
          - --trust-primitives
</code>```

Ran as

```<code># Build execution

pub run build_runner build --config production --release -o web:build
</code>```

Body:
There is one SO question about same problem. But I can't find production-ready code example how to use routerProviders / routerProvidersHash in real application.

As I understand we need to define two injectors and use one of them depending on compile time environment variable, like shown below.

// File: web/main.dart

// >>> Have to use 2 injectors:
@GenerateInjector([
  routerProvidersHash,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorDev = self.injectorDev$Injector;

@GenerateInjector([
  routerProviders,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorProd = self.injectorProd$Injector;
// <<<

void main() {
  final env = ServerEnvironment();
  if (env.isProduction) {
    runApp(ng.AppComponentNgFactory, createInjector: injectorProd);
  } else {
    runApp(ng.AppComponentNgFactory, createInjector: injectorDev);
  }
}

// File: lib/server_environment.dart

enum ServerEnvironmentId { development, production }

class ServerEnvironment {

  ServerEnvironmentId id;

  static final ServerEnvironment _instance = ServerEnvironment._internal();
  factory ServerEnvironment() => _instance;

  ServerEnvironment._internal() {
    const compileTimeEnvironment = String.fromEnvironment('MC_ENVIRONMENT', defaultValue: 'development');
    if (compileTimeEnvironment != 'development') {
      id = ServerEnvironmentId.production;
    } else {
      id = ServerEnvironmentId.development;
    }
  }

  bool get isProduction {
    return id == ServerEnvironmentId.production;
  }

}

File: build.production.yaml

targets:
  $default:
    builders:
      build_web_compilers|entrypoint:
        generate_for:
          - web/main.dart
        options:
          compiler: dart2js
          # List any dart2js specific args here, or omit it.
          dart2js_args:
          - -DMC_ENVIRONMENT=production
          - --fast-startup
          - --minify
          - --trust-primitives

# Build execution

pub run build_runner build --config production --release -o web:build

Is the assumption of having two injectors is the right way to do?

Thank you in advance!

Body:
What I would do is make a different main.dart file for your different injector setup.  You shouldn't have too much stuff in main.dart it should just serve as a mechanism to start your app.  The branching should occur in build.production.yaml as specifying a different main for production (i.e. web/main_production.dart) and this file is the one with the non-hash route provider.  This would remove the need for a "ServerEnvironment" and a if/else with a potentially confusing double injector setup in one file.

// File: web/main.dart

@GenerateInjector([
  routerProvidersHash,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: injector);
}

and

// File: web/main_production.dart

@GenerateInjector([
  routerProviders,
  ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;

void main() {
  runApp(ng.AppComponentNgFactory, createInjector: injector);
}

with

File: build.production.yaml

targets:
  $default:
    builders:
      build_web_compilers|entrypoint:
        generate_for:
          - web/main_production.dart
        options:
          compiler: dart2js
          # List any dart2js specific args here, or omit it.
          dart2js_args:
          - --fast-startup
          - --minify
          - --trust-primitives

Ran as

# Build execution

pub run build_runner build --config production --release -o web:build


问:
Whats wrong with setprecision in my compiler?
I've been having trouble with my compiler, NetBeans. It seems that using setprecision is not doing anything. Here is the code needed to see what's happening. This  part of the program check to see if a triangle it possible given three sides.

```<code>#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(){
   double SideA,SideB,SideC,p,a,longest;

   cout<<"Enter the length of each side of your triangle. Press enter after each number."<<endl;

   cin>>SideA>>SideB>>SideC;

   cout<<fixed<<setprecision(3);
   if(SideA+SideB<=SideC||SideA+SideC<=SideB||SideB+SideC<=SideA||SideA<=0||SideB<=0||SideC<=0)
   {
        cout<<"The length of the first side is "<<SideA<<"."<<endl;
        cout<<"The length of the second side is "<<SideB<<"."<<endl;
        cout<<"The length of the third side is "<<SideC<<"."<<endl;
        cout<<"This triangle is impossible."<<endl;
    }

    return 0;
}
</code>```

My problem is that I want the side length to be rounded to the nearest thousandths when shown on the screen. It does not do this with my NetBeans compiler. I've put this into online compilers, and it works there.

Here's my C++ configuration in NetBeans:

The sample input data is: 6.6666666, 5.4444444, 1

The expected output is: 6.667, 5.443, 1.000

The actual output is: 6.66667, 5.44444, 1

答:
Your code is behaving correctly. You are using cout to display the values of double variables, and by default it will use a precision of 6:

A double value will be printed using a general format that usually
  works fine to represent a number in a small amount of space. The basic
  amount of space used is determined by the precision. The default
  precision is 6, which means up to 6 significant digits are used to
  represent the number. This counts digits both to the left and the
  right of the decimal point. Fewer digits are printed if the result is
  accurate; e.g. trailing zeros at the right of the decimal point are
  not printed. As shown in the example below, as the number increases in
  size, places to the right of the decimal point will be dropped, and
  the result rounded off as needed to stay within 6 digits.

The text in bold font explains the output you obtained for your sample input: 6.66667, 5.44444, and 1.

You can limit the precision to obtain the results you want by using cout.precision() or setprecision(). This is also detailed in the linked article.

Finally, note that this is issue has nothing to do with NetBeans. You can confirm this by using g++ to compile your code from the command line. When you run it you will get the same results, even though you are not using NetBeans.

Body:
I've been having trouble with my compiler, NetBeans. It seems that using setprecision is not doing anything. Here is the code needed to see what's happening. This  part of the program check to see if a triangle it possible given three sides.

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(){
   double SideA,SideB,SideC,p,a,longest;

   cout<<"Enter the length of each side of your triangle. Press enter after each number."<<endl;

   cin>>SideA>>SideB>>SideC;

   cout<<fixed<<setprecision(3);
   if(SideA+SideB<=SideC||SideA+SideC<=SideB||SideB+SideC<=SideA||SideA<=0||SideB<=0||SideC<=0)
   {
        cout<<"The length of the first side is "<<SideA<<"."<<endl;
        cout<<"The length of the second side is "<<SideB<<"."<<endl;
        cout<<"The length of the third side is "<<SideC<<"."<<endl;
        cout<<"This triangle is impossible."<<endl;
    }

    return 0;
}

My problem is that I want the side length to be rounded to the nearest thousandths when shown on the screen. It does not do this with my NetBeans compiler. I've put this into online compilers, and it works there.

Here's my C++ configuration in NetBeans:

The sample input data is: 6.6666666, 5.4444444, 1

The expected output is: 6.667, 5.443, 1.000

The actual output is: 6.66667, 5.44444, 1