问:
Changing ListView's ItemPanelTemplate Orientation
I have a ListView in a DataTemplate in my app page. I want to use it in two different places, 1. on top and then secondly on the side.
Now I have an ItemPanelTemplate in it so I can easily manage it how to display the View but I cant seem to change the Orientation in VisualStateManager. It simply doesn't work. It works if I change the Orientation directly in the StackPanel but it doesn't work like that.
The code I am trying is:

```<code>    <DataTemplate x:Name="SidePaneTemplate">
        <UserControl>
            <ListView SelectionChanged="TopListBox_SelectionChanged"
                      SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectionMode="Single"
                      Margin="0,10,0,0">
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel x:Name="TemplatePanel"
                                    >
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup>
                                    <VisualState x:Name="w_state">
                                        <VisualState.StateTriggers>
                                            <AdaptiveTrigger MinWindowHeight="550"
                                                             MinWindowWidth="451"/>
                                        </VisualState.StateTriggers>
                                        <VisualState.Setters>
                                            <Setter Target="TemplatePanel.Orientation"
                                                    Value="Vertical"/>
                                        </VisualState.Setters>
                                    </VisualState>
                                    <VisualState x:Name="n_state">
                                        <VisualState.StateTriggers>
                                            <AdaptiveTrigger MinWindowWidth="0"/>
                                        </VisualState.StateTriggers>
                                        <VisualState.Setters>
                                            <Setter Target="TemplatePanel.Orientation"
                                                    Value="Horizontal"/>
                                        </VisualState.Setters>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                        </StackPanel>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Movies"
                                   TextAlignment="Center"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="TV Shows"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Search"
                                   TextAlignment="DetectFromContent"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Settings"/>
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
            </ListView>
        </UserControl>
    </DataTemplate>
</code>```

If someone has any idea how can I do this please point me in the right direction. Thank you.

Update:
I tried both the answers below but unfortunately it's the same thing as it was before. Once the panel gets set at the start time whether it's Horizontal or Vertical it stays the same for me. It doesn't change the Orientation for some reason.

Here is the code for the whole page:

```<code><Page.Resources>
    <!--
    <DataTemplate x:Name="SidePaneTemplate">
        <UserControl>
            <UserControl.Resources>
                <ItemsPanelTemplate x:Name="SidePanelTemp">
                    <ItemsStackPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>

                <ItemsPanelTemplate x:Name="TopPanelTemp">
                    <ItemsStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </UserControl.Resources>
            <ListView SelectionChanged="TopListBox_SelectionChanged"
                      Name="List"
                      SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectionMode="Single"
                      Margin="0,10,0,0">
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState>
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowHeight="550"
                                                 MinWindowWidth="451"/>
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel"
                                        Value="{StaticResource SidePanelTemp}"/>
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState>
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0"
                                                 />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel"
                                        Value="{StaticResource TopPanelTemp}"/>
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Movies"
                                   TextAlignment="Center"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="TV Shows"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Search"
                                   TextAlignment="DetectFromContent"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Settings"/>
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
            </ListView>
        </UserControl>
    </DataTemplate>
    -->
        <DataTemplate x:Key="DoubleSidePaneTemplate">
        <UserControl>
            <UserControl.Resources>
                <ItemsPanelTemplate x:Key="HorizontalStackPanel">
                    <ItemsStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>

                <ItemsPanelTemplate x:Key="VerticalStackPanel">
                    <ItemsStackPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </UserControl.Resources>
            <ListView
                x:Name="rootview"
                Margin="0,10,0,0"
                SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                SelectionChanged="TopListBox_SelectionChanged"
                SelectionMode="Single">
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph=""/>
                            <TextBlock Text="Movies" TextAlignment="Center" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph=""/>
                            <TextBlock Text="TV Shows" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Search" TextAlignment="DetectFromContent" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Settings" />
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState x:Name="w_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger  MinWindowWidth="500" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="rootview.ItemsPanel" Value="{StaticResource VerticalStackPanel }" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="n_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="rootview.ItemsPanel" Value="{StaticResource  HorizontalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </ListView>
        </UserControl>
    </DataTemplate>

    <!--
    <DataTemplate x:Name="TopPaneTemplate">
        <UserControl>
            <ListView SelectionChanged="TopListBox_SelectionChanged"
                      ItemsPanel="{StaticResource TopPanelTemp}"
                      SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectionMode="Single"
                      Margin="0,10,0,0">
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Movies"
                                   TextAlignment="Center"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="TV Shows"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Search"
                                   TextAlignment="DetectFromContent"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Settings"/>
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
            </ListView>
        </UserControl>
    </DataTemplate>
-->
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="WideState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="550"
                                     MinWindowHeight="451"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MyUITheme.Edge"
                            Value="Left"/>
                    <Setter Target="IndexPane.IsPaneOpen"
                        Value="True"/>
                    <Setter Target="TopPane.Visibility"
                            Value="Collapsed"/>
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="NarrowState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MyUITheme.Edge"
                            Value="Top"/>
                    <Setter Target="IndexPane.IsPaneOpen"
                        Value="False"/>
                    <Setter Target="TopPane.Visibility"
                            Value="Visible"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Grid.Transitions>
        <TransitionCollection>
            <EdgeUIThemeTransition x:Name="MyUITheme"/>
        </TransitionCollection>
    </Grid.Transitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Viewbox x:Name="TopPane"
             MaxHeight="50">
        <ContentPresenter ContentTemplate="{StaticResource DoubleSidePaneTemplate}"/>
    </Viewbox>

    <SplitView Grid.Row="1"
               Grid.RowSpan="2"
               x:Name="IndexPane"
               OpenPaneLength="100"
               DisplayMode="Inline"
               PaneBackground="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <SplitView.Pane>
            <ContentPresenter ContentTemplate="{StaticResource DoubleSidePaneTemplate}"
                            VerticalAlignment="Stretch"/>
        </SplitView.Pane>
        <SplitView.Content>
            <Grid>
                <Frame x:Name="PaneContentFrame"/>
                <StackPanel HorizontalAlignment="Stretch"
                            VerticalAlignment="Bottom"
                            x:Name="InternetPanel"
                            Background="{StaticResource SystemControlBackgroundAccentBrush}"
                            MaxWidth="500">
                    <TextBlock Text="{Binding IsInternet, Mode=OneWay}"
                               HorizontalAlignment="Center"
                               Style="{StaticResource BaseTextBlockStyle}"
                               Margin="10">
                    </TextBlock>
                    <StackPanel.RenderTransform>
                        <TranslateTransform/>
                    </StackPanel.RenderTransform>
                </StackPanel>
                <Grid.Resources>
                    <Storyboard x:Name="LocalNotifStoryboard"
                                Completed="LocalNotifStoryboard_Completed">
                        <DoubleAnimation AutoReverse="True"
                                         FillBehavior="HoldEnd"
                                         Duration="0:0:3"
                                         From="0"
                                         To="1"
                                         Storyboard.TargetName="InternetPanel"
                                         Storyboard.TargetProperty="(InternetPanel.Opacity)"/>
                    </Storyboard>
                </Grid.Resources>
            </Grid>

        </SplitView.Content>
    </SplitView>
</Grid>
</code>```

I am using ContentPresenter to show the Templates, can this be the reason for this not changing the Orientation? Thanks for trying to help.

答:
As @James Croft said that you could not place <VisualStateManager.VisualStateGroups> under the <ItemsPanelTemplate>.
And you could create some resources for <VisualState.Setters> and then move the visual states to the UserControl level.

I cannot create two different DataTemplates for this. Otherwise it would be the same thing that I am already doing. I want to be able to use one template for two different places and change the template properties during runtime.

For your scenario you just need to move resources from  <Page.Resources> to  <UserControl.Resources> base on James Croft's answer. And you can reference the follow code sample.

```<code><DataTemplate x:Key="SidePaneTemplate">
            <UserControl>
                <UserControl.Resources>
                    <ItemsPanelTemplate x:Key="HorizontalStackPanel">
                        <ItemsStackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>

                    <ItemsPanelTemplate x:Key="VerticalStackPanel">
                        <ItemsStackPanel Orientation="Vertical" />
                    </ItemsPanelTemplate>
                </UserControl.Resources>
                <ListView
                    x:Name="rootview"
                    Margin="0,10,0,0"
                    SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectionChanged="ListView_SelectionChanged"
                    SelectionMode="Single">
                    <ListView.Items>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph=""/>
                                <TextBlock Text="Movies" TextAlignment="Center" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph=""/>
                                <TextBlock Text="TV Shows" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="" />
                                <TextBlock Text="Search" TextAlignment="DetectFromContent" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="" />
                                <TextBlock Text="Favorites"/>
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="" />
                                <TextBlock Text="Settings" />
                            </StackPanel>
                        </ListViewItem>
                    </ListView.Items>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup>
                            <VisualState x:Name="w_state">
                                <VisualState.StateTriggers>
                                    <AdaptiveTrigger  MinWindowWidth="0" />
                                </VisualState.StateTriggers>
                                <VisualState.Setters>
                                    <Setter Target="rootview.ItemsPanel" Value="{StaticResource VerticalStackPanel }" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="n_state">
                                <VisualState.StateTriggers>
                                    <AdaptiveTrigger MinWindowWidth="700" />
                                </VisualState.StateTriggers>
                                <VisualState.Setters>
                                    <Setter Target="rootview.ItemsPanel" Value="{StaticResource  HorizontalStackPanel}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </ListView>
            </UserControl>
        </DataTemplate>
</code>```

And this is Datatemplate effect.

Body:
I have a ListView in a DataTemplate in my app page. I want to use it in two different places, 1. on top and then secondly on the side.
Now I have an ItemPanelTemplate in it so I can easily manage it how to display the View but I cant seem to change the Orientation in VisualStateManager. It simply doesn't work. It works if I change the Orientation directly in the StackPanel but it doesn't work like that.
The code I am trying is:

    <DataTemplate x:Name="SidePaneTemplate">
        <UserControl>
            <ListView SelectionChanged="TopListBox_SelectionChanged"
                      SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectionMode="Single"
                      Margin="0,10,0,0">
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel x:Name="TemplatePanel"
                                    >
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup>
                                    <VisualState x:Name="w_state">
                                        <VisualState.StateTriggers>
                                            <AdaptiveTrigger MinWindowHeight="550"
                                                             MinWindowWidth="451"/>
                                        </VisualState.StateTriggers>
                                        <VisualState.Setters>
                                            <Setter Target="TemplatePanel.Orientation"
                                                    Value="Vertical"/>
                                        </VisualState.Setters>
                                    </VisualState>
                                    <VisualState x:Name="n_state">
                                        <VisualState.StateTriggers>
                                            <AdaptiveTrigger MinWindowWidth="0"/>
                                        </VisualState.StateTriggers>
                                        <VisualState.Setters>
                                            <Setter Target="TemplatePanel.Orientation"
                                                    Value="Horizontal"/>
                                        </VisualState.Setters>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                        </StackPanel>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Movies"
                                   TextAlignment="Center"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="TV Shows"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Search"
                                   TextAlignment="DetectFromContent"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon FontFamily="Segoe MDL2 Assets"
                                  FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                  Glyph=""
                                  Margin="5"/>
                            <TextBlock Text="Settings"/>
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
            </ListView>
        </UserControl>
    </DataTemplate>

If someone has any idea how can I do this please point me in the right direction. Thank you.

Update:
I tried both the answers below but unfortunately it's the same thing as it was before. Once the panel gets set at the start time whether it's Horizontal or Vertical it stays the same for me. It doesn't change the Orientation for some reason.

Here is the code for the whole page:

<Page.Resources>

        <DataTemplate x:Key="DoubleSidePaneTemplate">
        <UserControl>
            <UserControl.Resources>
                <ItemsPanelTemplate x:Key="HorizontalStackPanel">
                    <ItemsStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>

                <ItemsPanelTemplate x:Key="VerticalStackPanel">
                    <ItemsStackPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </UserControl.Resources>
            <ListView
                x:Name="rootview"
                Margin="0,10,0,0"
                SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                SelectionChanged="TopListBox_SelectionChanged"
                SelectionMode="Single">
                <ListView.Items>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph=""/>
                            <TextBlock Text="Movies" TextAlignment="Center" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph=""/>
                            <TextBlock Text="TV Shows" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Search" TextAlignment="DetectFromContent" />
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Favorites"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem HorizontalContentAlignment="Center">
                        <StackPanel>
                            <FontIcon
                                Margin="5"
                                FontFamily="Segoe MDL2 Assets"
                                FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                Glyph="" />
                            <TextBlock Text="Settings" />
                        </StackPanel>
                    </ListViewItem>
                </ListView.Items>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState x:Name="w_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger  MinWindowWidth="500" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="rootview.ItemsPanel" Value="{StaticResource VerticalStackPanel }" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="n_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="rootview.ItemsPanel" Value="{StaticResource  HorizontalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </ListView>
        </UserControl>
    </DataTemplate>

</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="WideState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="550"
                                     MinWindowHeight="451"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MyUITheme.Edge"
                            Value="Left"/>
                    <Setter Target="IndexPane.IsPaneOpen"
                        Value="True"/>
                    <Setter Target="TopPane.Visibility"
                            Value="Collapsed"/>
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="NarrowState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MyUITheme.Edge"
                            Value="Top"/>
                    <Setter Target="IndexPane.IsPaneOpen"
                        Value="False"/>
                    <Setter Target="TopPane.Visibility"
                            Value="Visible"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Grid.Transitions>
        <TransitionCollection>
            <EdgeUIThemeTransition x:Name="MyUITheme"/>
        </TransitionCollection>
    </Grid.Transitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Viewbox x:Name="TopPane"
             MaxHeight="50">
        <ContentPresenter ContentTemplate="{StaticResource DoubleSidePaneTemplate}"/>
    </Viewbox>

    <SplitView Grid.Row="1"
               Grid.RowSpan="2"
               x:Name="IndexPane"
               OpenPaneLength="100"
               DisplayMode="Inline"
               PaneBackground="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <SplitView.Pane>
            <ContentPresenter ContentTemplate="{StaticResource DoubleSidePaneTemplate}"
                            VerticalAlignment="Stretch"/>
        </SplitView.Pane>
        <SplitView.Content>
            <Grid>
                <Frame x:Name="PaneContentFrame"/>
                <StackPanel HorizontalAlignment="Stretch"
                            VerticalAlignment="Bottom"
                            x:Name="InternetPanel"
                            Background="{StaticResource SystemControlBackgroundAccentBrush}"
                            MaxWidth="500">
                    <TextBlock Text="{Binding IsInternet, Mode=OneWay}"
                               HorizontalAlignment="Center"
                               Style="{StaticResource BaseTextBlockStyle}"
                               Margin="10">
                    </TextBlock>
                    <StackPanel.RenderTransform>
                        <TranslateTransform/>
                    </StackPanel.RenderTransform>
                </StackPanel>
                <Grid.Resources>
                    <Storyboard x:Name="LocalNotifStoryboard"
                                Completed="LocalNotifStoryboard_Completed">
                        <DoubleAnimation AutoReverse="True"
                                         FillBehavior="HoldEnd"
                                         Duration="0:0:3"
                                         From="0"
                                         To="1"
                                         Storyboard.TargetName="InternetPanel"
                                         Storyboard.TargetProperty="(InternetPanel.Opacity)"/>
                    </Storyboard>
                </Grid.Resources>
            </Grid>

        </SplitView.Content>
    </SplitView>
</Grid>

I am using ContentPresenter to show the Templates, can this be the reason for this not changing the Orientation? Thanks for trying to help.

Body:
As @James Croft said that you could not place <VisualStateManager.VisualStateGroups> under the <ItemsPanelTemplate>.
And you could create some resources for <VisualState.Setters> and then move the visual states to the UserControl level.

I cannot create two different DataTemplates for this. Otherwise it would be the same thing that I am already doing. I want to be able to use one template for two different places and change the template properties during runtime.

For your scenario you just need to move resources from  <Page.Resources> to  <UserControl.Resources> base on James Croft's answer. And you can reference the follow code sample.

<DataTemplate x:Key="SidePaneTemplate">
            <UserControl>
                <UserControl.Resources>
                    <ItemsPanelTemplate x:Key="HorizontalStackPanel">
                        <ItemsStackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>

                    <ItemsPanelTemplate x:Key="VerticalStackPanel">
                        <ItemsStackPanel Orientation="Vertical" />
                    </ItemsPanelTemplate>
                </UserControl.Resources>
                <ListView
                    x:Name="rootview"
                    Margin="0,10,0,0"
                    SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectionChanged="ListView_SelectionChanged"
                    SelectionMode="Single">
                    <ListView.Items>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="&#xE8B2;"/>
                                <TextBlock Text="Movies" TextAlignment="Center" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="&#xE7F4;"/>
                                <TextBlock Text="TV Shows" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="&#xE721;" />
                                <TextBlock Text="Search" TextAlignment="DetectFromContent" />
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="&#xE728;" />
                                <TextBlock Text="Favorites"/>
                            </StackPanel>
                        </ListViewItem>
                        <ListViewItem HorizontalContentAlignment="Center">
                            <StackPanel>
                                <FontIcon
                                    Margin="5"
                                    FontFamily="Segoe MDL2 Assets"
                                    FontSize="{StaticResource ComboBoxArrowThemeFontSize}"
                                    Glyph="&#xE713;" />
                                <TextBlock Text="Settings" />
                            </StackPanel>
                        </ListViewItem>
                    </ListView.Items>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup>
                            <VisualState x:Name="w_state">
                                <VisualState.StateTriggers>
                                    <AdaptiveTrigger  MinWindowWidth="0" />
                                </VisualState.StateTriggers>
                                <VisualState.Setters>
                                    <Setter Target="rootview.ItemsPanel" Value="{StaticResource VerticalStackPanel }" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="n_state">
                                <VisualState.StateTriggers>
                                    <AdaptiveTrigger MinWindowWidth="700" />
                                </VisualState.StateTriggers>
                                <VisualState.Setters>
                                    <Setter Target="rootview.ItemsPanel" Value="{StaticResource  HorizontalStackPanel}" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </ListView>
            </UserControl>
        </DataTemplate>

And this is Datatemplate effect.


来源: stackexchange

问:
Union of unique words in two strings
Example of string to work with:

Given: "FORD EF FALCON SEDAN" and  "Ford sedan 4dr"

Needed: "FORD EF FALCON SEDAN 4dr"

Using javascript regex, the code below tries to remove the duplicate words "case insensitive" if such word happens to repeat again, thus keeping the first instance of the word and removing the subsequent repeat of the same word.

let myString = str1+' '+str2;
 myString.replace(/\b(\w+)\b.*\b\1\b/gi, "$1")

is giving "FORD sedan 4dr" which is wrong. How can I fix it? thx

答:
The best bet is to split the words and check the array.

You can use regex if you want to but it will remove only 1 duplicate

per replace.

You have to start from the beginning each time.

I.e. while ( myString.replace(/\b((\w+)\b.*?)\b\2\b/i, "$1")

I'm not a JS person, so I assume replace() returns a value.

Use this regex /\b((\w+)\b.*?)\b\2\b/i

Explained

```<code> \b
 (                             # (1 start)
      ( \w+ )                       # (2)
      \b .*
 )                             # (1 end)
 \b \2 \b
</code>```

ContentLicense: CC BY-SA 3.0

Title: Union of unique words in two strings

Body:
The best bet is to split the words and check the array.

You can use regex if you want to but it will remove only 1 duplicate

per replace.

You have to start from the beginning each time.

I.e. while ( myString.replace(/\b((\w+)\b.*?)\b\2\b/i, "$1")

I'm not a JS person, so I assume replace() returns a value.

Use this regex /\b((\w+)\b.*?)\b\2\b/i

Explained

 \b
 (                             # (1 start)
      ( \w+ )                       # (2)
      \b .*
 )                             # (1 end)
 \b \2 \b


问:
How to check every 3rd element in a list and count the vowels in that string?
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

```<code>wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']
</code>```

答:
This may help you:</p>

```<code>wordlist = ['hat', 'bat', 'cat', 'dog', 'bird', 'bear', 'lion', 'tiger', 'frog', 'mouse']

if len(wordlist) < 10:
    print("Error. list length must be grater than 10")
    exit(-1)
found = False
for word in wordlist[::3]:
    count = sum(map(word.lower().count, "aeiou"))
    if count >= 3:
        print('Found string with 3 or more vowels!')
        found = True
        break
    print("The string %s contains %d vowel(s)" % (word, count))
if not found:
    print("Did not find suitable string.")
</code>```

Body:
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']

Body:
This may help you:

wordlist = ['hat', 'bat', 'cat', 'dog', 'bird', 'bear', 'lion', 'tiger', 'frog', 'mouse']

if len(wordlist) < 10:
    print("Error. list length must be grater than 10")
    exit(-1)
found = False
for word in wordlist[::3]:
    count = sum(map(word.lower().count, "aeiou"))
    if count >= 3:
        print('Found string with 3 or more vowels!')
        found = True
        break
    print("The string %s contains %d vowel(s)" % (word, count))
if not found:
    print("Did not find suitable string.")


答:
Don't use a regex for this. Here's a solution in plain javascript. It's even easier in later versions (where we get a Set type) or using a library like lodash.

// Input
var str1 = "FORD EF FALCON SEDAN";
var str2 = "Ford sedan 4dr";

// Make a case-insensitive map.
var key = function(s) {return s.toUpperCase()}
var map = {};

// All words, whitespace-separated, as an array.
var words = [str1, str2].join(' ').split(/\s+/);

// Unique words
var unique = [];

// Find unique words.
words.forEach(function (word) {
  if (!(key(word) in map)) {
    unique.push(word);
  }
  map[key(word)] = 1;
});

// Join back to a string.
var result = unique.join(' ');
console.log(result);```
</div>
</div>
</p>

<p>Incredibly easy in lodash =)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const strings = [
"FORD EF FALCON SEDAN",
"Ford sedan 4dr",
];

const result = _(strings)
  .map(s => _.split(s, ' '))
  .flatten()
  .uniqBy(_.toUpper)
  .join(' ')

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

```

Title: Union of unique words in two strings

Body:
Example of string to work with:

Given: "FORD EF FALCON SEDAN" and  "Ford sedan 4dr"

Needed: "FORD EF FALCON SEDAN 4dr"

Using javascript regex, the code below tries to remove the duplicate words "case insensitive" if such word happens to repeat again, thus keeping the first instance of the word and removing the subsequent repeat of the same word.

let myString = str1+' '+str2;
 myString.replace(/\b(\w+)\b.*\b\1\b/gi, "$1")

is giving "FORD sedan 4dr" which is wrong. How can I fix it? thx

Body:
Don't use a regex for this. Here's a solution in plain javascript. It's even easier in later versions (where we get a Set type) or using a library like lodash.

// Input
var str1 = "FORD EF FALCON SEDAN";
var str2 = "Ford sedan 4dr";

// Make a case-insensitive map.
var key = function(s) {return s.toUpperCase()}
var map = {};

// All words, whitespace-separated, as an array.
var words = [str1, str2].join(' ').split(/\s+/);

// Unique words
var unique = [];

// Find unique words.
words.forEach(function (word) {
  if (!(key(word) in map)) {
    unique.push(word);
  }
  map[key(word)] = 1;
});

// Join back to a string.
var result = unique.join(' ');
console.log(result);

Incredibly easy in lodash =)

const strings = [
"FORD EF FALCON SEDAN",
"Ford sedan 4dr",
];

const result = _(strings)
  .map(s => _.split(s, ' '))
  .flatten()
  .uniqBy(_.toUpper)
  .join(' ')

console.log(result);

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>


问:
Sorting array of objects by the ascending order of values related to another value
I am looking to sort a JSON array of objects by the ascending order of values related to another value. Sounds confusing because it is. I have properties 'column' and 'order' in each object in an array. I need the order to be like:
lowest number in column 1, lowest number in column 2, lowest number in column 3, second lowest number in column 1, second lowest number in column 2, second lowest number in column 3 and continue on. This is easy when 'order' has the exact same values, you can use a sort function like:

```<code>function sortCourses(a, b){
    if (a.order == b.order) {
        return (a.column - b.column);
    } else {
        return (a.order - b.order);
    }
}
</code>```

The problem is that I don't always have them setup like that. Here is an example array:

```<code>[
    {
        column: 2,
        order: 5
    },
    {
        column: 1,
        order: 1
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 4
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 1,
        order: 2
    }
]
</code>```

After sorting, I need this array to look like:

```<code>[
    {
        column: 1,
        order: 1
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 2
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 5
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 4
    }
]
</code>```

Any ideas on how I could accomplish this?

答:
A fairly long winded way, but all I do is just group each 'group' (columns) into an object, pushing their orders into an array. Then I just sort them and paste them in.

var array = [
    {
        column: 2,
        order: 5
    },
    {
        column: 1,
        order: 1
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 4
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 1,
        order: 2
    }
];

var new_array = {}

for (let item of array)
{
  if (item.column in new_array)
  {
    new_array[item.column].push(item.order);
  }
  else
  {
    new_array[item.column] = [item.order];
  }
}

let max = 0;
for (let key in new_array)
{
  max = (max < new_array[key].length) ? new_array[key].length : max;
  new_array[key].sort();
}

var final = [];

for (let i = 0; i < max; i++)
{
  for (let key in new_array)
  {
    if (i < new_array[key].length)
    {
      final.push({column: key, order: new_array[key][i]});
    }
  }
}

console.log(final);```

Body:
I am looking to sort a JSON array of objects by the ascending order of values related to another value. Sounds confusing because it is. I have properties 'column' and 'order' in each object in an array. I need the order to be like:
lowest number in column 1, lowest number in column 2, lowest number in column 3, second lowest number in column 1, second lowest number in column 2, second lowest number in column 3 and continue on. This is easy when 'order' has the exact same values, you can use a sort function like:

function sortCourses(a, b){
    if (a.order == b.order) {
        return (a.column - b.column);
    } else {
        return (a.order - b.order);
    }
}

The problem is that I don't always have them setup like that. Here is an example array:

[
    {
        column: 2,
        order: 5
    },
    {
        column: 1,
        order: 1
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 4
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 1,
        order: 2
    }
]

After sorting, I need this array to look like:

[
    {
        column: 1,
        order: 1
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 2
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 5
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 4
    }
]

Any ideas on how I could accomplish this?


问:
Timing Java Bubble Sort algorithm
I have to sort a various number of arrays of various sizes and time each sort. My timer is giving me very short times in nanoseconds but mostly zeros. I have changed the point to start and end timer trying to fix the problem but have been unsuccessful. Can someone please show me what my timer problem is?</p>

```<code>import java.util.Random;
import java.util.Scanner;

public class BubbleSort
{
   public static void main(String[] args) {
      Random rand = new Random();
      Scanner input = new Scanner(System.in);

  int m;
  int n = 0;
  int num_i = 0;
  long startTime = System.nanoTime();
  long running_time;
  int temp;
  System.out.print("Input array size: ");
  n = input.nextInt();
  System.out.print("Input number of arrays: ");
  num_i = input.nextInt();

  for(int j =  0; j < num_i; j++){

  }
  int array[] = new int [n];

  for(int i = 0; i < n; i++)
  {

      for( m = 0; m < array.length; m++){

      array[m] = (int)(Math.random()*100);
      }

     //int[] sorted = new int[n];
     for (int k = 0; k < array.length; k++) {

        for (int j = 1; j < (array.length - k); j++) {

          //System.out.println("Start Time: " + startTime);
              startTime =System.nanoTime();

           if (array[j - 1] > array[j]) {
              temp = array[j - 1];
              array[j - 1] = array[j];
              array[j] = temp;

           }
           long endTime = System.nanoTime();
           running_time = endTime - startTime;
         // System.out.println("End Time: " + endTime);
          System.out.println(running_time);
        }

     }

  }

   }
}
</code>```

答:
One  problem is the code is only testing the time it takes for the if and swap code, not the entire bubble sort. I made a simplified version that takes about a second to sort 30,000 numbers.

The frequency of the timer is not in nanoseconds on most systems, depending on the computer and the operating system. On my system, Intel 3770K 3.5 ghz, under Windows 7 64 bit mode, the timer runs at 3.410312 mhz, or about 293.2283 nano-seconds per "tick". Under Windows XP, the timer runs at about 3.5ghz, or about .2857 nano-seconds per "tick", but this is probably rare these days.

If the testing is resulting in zero elapsed times, test with larger arrays. You could repeat the test many times, but caching of the data from multiple runs will affect the results.

```<code>    public static void main (String args[])
    {
        Random rand = new Random();
        int m;
        long startTime;
        long endTime;
        long running_time;
        int temp;
        int n = 30000;     // set to value rather than input from user
        int array[] = new int [n];

        for( m = 0; m < array.length; m++){
            array[m] = (int)(Math.random()*100);
        }

        // benchmark sort time
        startTime =System.nanoTime();
        for (int k = 0; k < array.length; k++) {
            for (int j = 1; j < (array.length - k); j++) {
                if (array[j - 1] > array[j]) {
                    temp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temp;
                }
            }
        }
        endTime = System.nanoTime();
        running_time = endTime - startTime;
        System.out.println(running_time);
    }
}
</code>```

Title: Timing Java Bubble Sort algorithm

Body:
I have to sort a various number of arrays of various sizes and time each sort. My timer is giving me very short times in nanoseconds but mostly zeros. I have changed the point to start and end timer trying to fix the problem but have been unsuccessful. Can someone please show me what my timer problem is?

import java.util.Random;
import java.util.Scanner;

public class BubbleSort
{
   public static void main(String[] args) {
      Random rand = new Random();
      Scanner input = new Scanner(System.in);

  int m;
  int n = 0;
  int num_i = 0;
  long startTime = System.nanoTime();
  long running_time;
  int temp;
  System.out.print("Input array size: ");
  n = input.nextInt();
  System.out.print("Input number of arrays: ");
  num_i = input.nextInt();

  for(int j =  0; j < num_i; j++){

  }
  int array[] = new int [n];

  for(int i = 0; i < n; i++)
  {

      for( m = 0; m < array.length; m++){

      array[m] = (int)(Math.random()*100);
      }

     //int[] sorted = new int[n];
     for (int k = 0; k < array.length; k++) {

        for (int j = 1; j < (array.length - k); j++) {

          //System.out.println("Start Time: " + startTime);
              startTime =System.nanoTime();

           if (array[j - 1] > array[j]) {
              temp = array[j - 1];
              array[j - 1] = array[j];
              array[j] = temp;

           }
           long endTime = System.nanoTime();
           running_time = endTime - startTime;
         // System.out.println("End Time: " + endTime);
          System.out.println(running_time);
        }

     }

  }

   }
}

Body:
One  problem is the code is only testing the time it takes for the if and swap code, not the entire bubble sort. I made a simplified version that takes about a second to sort 30,000 numbers.

The frequency of the timer is not in nanoseconds on most systems, depending on the computer and the operating system. On my system, Intel 3770K 3.5 ghz, under Windows 7 64 bit mode, the timer runs at 3.410312 mhz, or about 293.2283 nano-seconds per "tick". Under Windows XP, the timer runs at about 3.5ghz, or about .2857 nano-seconds per "tick", but this is probably rare these days.

If the testing is resulting in zero elapsed times, test with larger arrays. You could repeat the test many times, but caching of the data from multiple runs will affect the results.

    public static void main (String args[])
    {
        Random rand = new Random();
        int m;
        long startTime;
        long endTime;
        long running_time;
        int temp;
        int n = 30000;     // set to value rather than input from user
        int array[] = new int [n];

        for( m = 0; m < array.length; m++){
            array[m] = (int)(Math.random()*100);
        }

        // benchmark sort time
        startTime =System.nanoTime();
        for (int k = 0; k < array.length; k++) {
            for (int j = 1; j < (array.length - k); j++) {
                if (array[j - 1] > array[j]) {
                    temp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temp;
                }
            }
        }
        endTime = System.nanoTime();
        running_time = endTime - startTime;
        System.out.println(running_time);
    }
}


问:
Replace Multiple If\Else with Design Pattern
Based on various threads on SO (ex. Replacing if else statement with pattern ) I understand that I can replace multiple if\else statements with the Command pattern.

My situation is a bit different.

I have a series of Commands and I need to execute each Command only if the previous command was unsuccessful.

For example, suppose I need to retrieve text from a hypothetical web page - I could scrape the text directly from the page using screen scraping or I could fetch the text from the API. I would only want to fetch the text from API if screen scraping was not successful. In other words I would only execute the "fetch" command if the "scrape" command didn't work.

In this case, I  would test if the scraped String is empty or equal to null and then execute the second Command. If the second command is also unsuccessful I would execute the third Command and so on.

The important point is that we only execute subsequent commands if a certain condition is true/false. The condition is always the same for each Command but the number of commands might grow in the future.

I cannot implement this via the typically suggested route (using a Map and Command interface) bec this would not execute the next Command if the first one failed (it would also be unable to check if a Command was successful or not)

What design pattern could be used to solve this problem?

答:
As others have said, use the Chain of Responsibility Pattern which can keep trying different implementations in serial until one succeeds.

Let's say your Command has this interface where a handled Request returns a Result object if it succeeds or null if it failed ( could also use a boolean or Optional or whatever you want)

```<code>public interface Command{

  Result handle( Request request);
}
</code>```

Then your chained Command could wrap several other Commands and try each one until something works.

```<code>public class ChainedCommand implements Command {
    //could also be set in a constructor instead
    List<Command> commandChain = Arrays.asList( new ScrapperCommand(),
                                            new ApiCommand());

    public Result handle( Request request){

         Result result = null;
         Iterator<Command> iter = commandChain.iterator();
         while( result ==null && iter.hasNext()){
              result = iter.next().handle(request);
         }

         return result;
    }
}
</code>```

Body:
As others have said, use the Chain of Responsibility Pattern which can keep trying different implementations in serial until one succeeds.

Let's say your Command has this interface where a handled Request returns a Result object if it succeeds or null if it failed ( could also use a boolean or Optional or whatever you want)

public interface Command{

  Result handle( Request request);
}

Then your chained Command could wrap several other Commands and try each one until something works.

public class ChainedCommand implements Command {
    //could also be set in a constructor instead
    List<Command> commandChain = Arrays.asList( new ScrapperCommand(),
                                            new ApiCommand());

    public Result handle( Request request){

         Result result = null;
         Iterator<Command> iter = commandChain.iterator();
         while( result ==null && iter.hasNext()){
              result = iter.next().handle(request);
         }

         return result;
    }
}


问:
HANA: How can I set the seed on the RAND() function?
I am trying to fix the pseudo random numbers generated by the RAND() function in HANA sqlscript.

I'm pretty sure it must be possible but the documentation is not very explicit.

Thank you.

答: There's no seeding option available for RAND() and neither for RAND_SECURE().


问:
How to explore the structure and dimensions of an object in Octave?
Im Matlab the properties function sounds like a possible valid equivalent to commands in R that acquaint you with a particular object in the working environment, providing information as to its structure (data.frame, matrix, list, vector) and type of variables (character, numeric) (for example, with the R command str()), dimensions (using perhaps the call dim()), and names of the variables (names()).

However, this function is not operational in Octave:

```<code>>> properties(data)
warning: the 'properties' function is not yet implemented in Octave
</code>```

I installed the package dataframe as suggested in a comment on the post linked above:

pkg install -forge dataframe and loaded it pkg load dataframe

But I can't find a way of getting a summary of the structure and dimensions of a datset data.mat in the workspace.

I believe it's a structure consisting of a 4 x 372,550 numerical matrix; two 4 x 46,568 numerical matrices, and a 256 x 1 character matrix. To get this info I had to scroll through many pages of the printout of data.

This info is not available on the Octave IDE, where I get:

```<code>Name      Class     Dimensions
data      struc     1 x 1
</code>```

a far cry from the complexity of the object data.

What is the smart way of getting some this information about an object in the workspace in Octave?

Following up on the first answer provided, here is what I get with whos:

```<code>>> whos
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  =====
        data        1x1                    7452040  struct

Total is 1 element using 7452040 bytes
</code>```

This is not particularly informative about what data really contains. In fact, I just found out a way to extract the names inside data:

```<code>>> fieldnames(data)
ans =
{
  [1,1] = testData
  [2,1] = trainData
  [3,1] = validData
  [4,1] = vocab
}
</code>```

Now if I call

```<code>>> size(data)
ans =

   1   1
</code>```

the output is not very useful. On the other hand, knowing the names of the matrices within data I can do

```<code>>> size(data.trainData)
ans =

        4   372550
</code>```

which is indeed informative.

答:
If you type the name of the variable, you'll see information about it. In your case it's a struct, so it'll tell you the field names. Relevant functions are: size, ndims, class, fieldnames, etc.

```<code>size(var)
class(var)
</code>```

etc.

You refer to .mat. Maybe you have a MAT-file, which you can load with load filename. Once loaded you can examine and use the variables in the file.

```<code>whos
</code>```

prints simple information on the variables in memory, most useful to see what variables exist.

Following up on your edited question. This works in Octave:

```<code>for s=fieldnames(data)'
   s=s{1};
   tmp=data.(s);
   disp([s,' - ',class(tmp),' - ',mat2str(size(tmp))])
end
</code>```

It prints basic information of each of the members of the struct. It does assume that data is a 1x1 struct array. Note that a struct can be an array:

```<code>data(2).testData = [];
</code>```

Causes your data struct to be a 2x1 array. This is why size(data) is relevant. class is also important (it's shown in the output of whos. Variables can be of type double (normal arrays), and other numeric types, logical, struct, cell (an array of arrays), or a custom class that you can write yourself.

I highly recommend reading an introductory text on MATLAB/Octave, as it works very differently from R. It's not just a different flavor of language, it's a whole different world.

Body:
Im Matlab the properties function sounds like a possible valid equivalent to commands in R that acquaint you with a particular object in the working environment, providing information as to its structure (data.frame, matrix, list, vector) and type of variables (character, numeric) (for example, with the R command str()), dimensions (using perhaps the call dim()), and names of the variables (names()).

However, this function is not operational in Octave:

>> properties(data)
warning: the 'properties' function is not yet implemented in Octave

I installed the package dataframe as suggested in a comment on the post linked above:

pkg install -forge dataframe and loaded it pkg load dataframe

But I can't find a way of getting a summary of the structure and dimensions of a datset data.mat in the workspace.

I believe it's a structure consisting of a 4 x 372,550 numerical matrix; two 4 x 46,568 numerical matrices, and a 256 x 1 character matrix. To get this info I had to scroll through many pages of the printout of data.

This info is not available on the Octave IDE, where I get:

Name      Class     Dimensions
data      struc     1 x 1

a far cry from the complexity of the object data.

What is the smart way of getting some this information about an object in the workspace in Octave?

Following up on the first answer provided, here is what I get with whos:

>> whos
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  =====
        data        1x1                    7452040  struct

Total is 1 element using 7452040 bytes

This is not particularly informative about what data really contains. In fact, I just found out a way to extract the names inside data:

>> fieldnames(data)
ans =
{
  [1,1] = testData
  [2,1] = trainData
  [3,1] = validData
  [4,1] = vocab
}

Now if I call

>> size(data)
ans =

   1   1

the output is not very useful. On the other hand, knowing the names of the matrices within data I can do

>> size(data.trainData)
ans =

        4   372550

which is indeed informative.

Body:
If you type the name of the variable, you'll see information about it. In your case it's a struct, so it'll tell you the field names. Relevant functions are: size, ndims, class, fieldnames, etc.

size(var)
class(var)

etc.

You refer to .mat. Maybe you have a MAT-file, which you can load with load filename. Once loaded you can examine and use the variables in the file.

whos

prints simple information on the variables in memory, most useful to see what variables exist.

Following up on your edited question. This works in Octave:

for s=fieldnames(data)'
   s=s{1};
   tmp=data.(s);
   disp([s,' - ',class(tmp),' - ',mat2str(size(tmp))])
end

It prints basic information of each of the members of the struct. It does assume that data is a 1x1 struct array. Note that a struct can be an array:

data(2).testData = [];

Causes your data struct to be a 2x1 array. This is why size(data) is relevant. class is also important (it's shown in the output of whos. Variables can be of type double (normal arrays), and other numeric types, logical, struct, cell (an array of arrays), or a custom class that you can write yourself.

I highly recommend reading an introductory text on MATLAB/Octave, as it works very differently from R. It's not just a different flavor of language, it's a whole different world.


问:
create spooledFile from jtopen
I try to create a spooledfile with the library jt400.

I have done the program which list the spool in a outqueue without problem but when i want to create the SpooledFile object, my as400 return me an error

com.ibm.as400.access.ServerStartupException: Not able to pass
  connection to server job.  Server job timed out.

I don't understand why. Is there something to do on os400 about the security.
Thanks to help me.

答: It would be helpful to see the stack trace. JT400 may require PRINT host service for spooled file operations. On IBM i, check if QNPSERVD job is present (wrkjob QNPSERVD) if not use STRHOSTSVR *netprt to start. Also check that the print server port (default is 8474 for plain connection and 9474 for encrypted) is accessible from your Java server.

Title: create spooledFile from jtopen


问:
Twisted + Gtk - shutdown not working properly
Using Python 2.6, Twisted 10.1, and GTK+ 2.22, with latest pygtk installed, I'm having problems on shutdown. When I close my application and shut down the reactor (using the gtk2reactor of course), the application simply freezes.

I've poked around the twisted source and added debug messages. What ends up happening is, the 'shutdown' event fires, PortableGtkReactor.crash is called, which calls gtk.main_quit. The event gets processed at the end of ReactorBase.runUntilCurrent. When the function returns, control goes to ReactorBase.iterate, which returns control to PortableGtkReactor.simulate, which goes back to... the gtk.main() call. It looks like gtk just doesn't quit.

Unfortunately, when I put together a very simple example with twisted and the gtk "Hello World" sample, everything shut down correctly. It must be something my application is doing. Until I can figure it out further, though...

What might be causing this? Like what could an app do that causes gtk to not quit? The app worked fine on Gtk 2.12, with Python 2.5 and Twisted 8.1, if that helps at all.

答: Threads, perhaps?  The Twisted reactor joins all threads on shutdown, and if you're doing something in a callInThread that hangs, your loop may be unable to stop.  (I'm not sure what the behavior would be if you're starting your own threads, either.)

ContentLicense: CC BY-SA 2.5


问:
How to redirect npgsql log output to a log4net logger?
Is it possible to redirect the npgsql log output to go to a log4net logger? From the npgsql source code, it looks like it logs directly to stdout/stderr or a specified file (using the static properties on NpgsqlEventLog). Is there a way to route that logging into log4net?

答:
This is how I have done it and it seems to work reasonably well. Note that I am splitting the command logging out to a separate appender because it gets pretty verbose...

First, add this before you make any other calls to Npgsql:

NpgsqlLogManager.Provider = new Log4NetNpgsqlLoggingProvider("NpgsqlDefaultLogger")
{
    CommandLoggerName = "NpgsqlCommandLogger"
};
```
<p>Now you need to add in the logging provider class:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using Npgsql.Logging;

namespace Util.Npgsql
{
    public class Log4NetNpgsqlLoggingProvider : INpgsqlLoggingProvider
    {
        public string DefaultLoggerName { get; }
        public string CommandLoggerName { get; set; }

        public Log4NetNpgsqlLoggingProvider(string defaultLoggerName)
        {
            if (defaultLoggerName == null) throw new ArgumentNullException(nameof(defaultLoggerName));
            DefaultLoggerName = defaultLoggerName;
        }

        public NpgsqlLogger CreateLogger(string name)
        {
            switch (name)
            {
                case "Npgsql.NpgsqlCommand":
                    return new Log4NetNpgsqlLogger(CommandLoggerName ?? DefaultLoggerName);
                default:
                    return new Log4NetNpgsqlLogger(DefaultLoggerName);
            }
        }
    }
}
</code>```

And you also need the actual logger class:

using System;
using log4net;
using log4net.Core;
using Npgsql.Logging;

namespace Util.Npgsql
{
    public class Log4NetNpgsqlLogger : NpgsqlLogger
    {
        private readonly ILog _log;

        public Log4NetNpgsqlLogger(string name)
        {
            _log = LogManager.GetLogger(name);
        }

        public override bool IsEnabled(NpgsqlLogLevel level)
        {
            return _log.Logger.IsEnabledFor(GetLog4NetLevelFromNpgsqlLogLevel(level));
        }

        public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null)
        {
            _log.Logger.Log(typeof(NpgsqlLogger), GetLog4NetLevelFromNpgsqlLogLevel(level), connectorId + ": " + msg, exception);
        }

        protected Level GetLog4NetLevelFromNpgsqlLogLevel(NpgsqlLogLevel level)
        {
            switch (level)
            {
                case NpgsqlLogLevel.Trace:
                case NpgsqlLogLevel.Debug:
                    return Level.Debug;
                case NpgsqlLogLevel.Info:
                    return Level.Info;
                case NpgsqlLogLevel.Warn:
                    return Level.Warn;
                case NpgsqlLogLevel.Error:
                    return Level.Error;
                case NpgsqlLogLevel.Fatal:
                    return Level.Fatal;
                default:
                    throw new Exception("Unknown Npgsql Log Level: " + level);
            }
        }
    }
}
```

Body:
This is how I have done it and it seems to work reasonably well. Note that I am splitting the command logging out to a separate appender because it gets pretty verbose...

First, add this before you make any other calls to Npgsql:

NpgsqlLogManager.Provider = new Log4NetNpgsqlLoggingProvider("NpgsqlDefaultLogger")
{
    CommandLoggerName = "NpgsqlCommandLogger"
};

Now you need to add in the logging provider class:

using System;
using Npgsql.Logging;

namespace Util.Npgsql
{
    public class Log4NetNpgsqlLoggingProvider : INpgsqlLoggingProvider
    {
        public string DefaultLoggerName { get; }
        public string CommandLoggerName { get; set; }

        public Log4NetNpgsqlLoggingProvider(string defaultLoggerName)
        {
            if (defaultLoggerName == null) throw new ArgumentNullException(nameof(defaultLoggerName));
            DefaultLoggerName = defaultLoggerName;
        }

        public NpgsqlLogger CreateLogger(string name)
        {
            switch (name)
            {
                case "Npgsql.NpgsqlCommand":
                    return new Log4NetNpgsqlLogger(CommandLoggerName ?? DefaultLoggerName);
                default:
                    return new Log4NetNpgsqlLogger(DefaultLoggerName);
            }
        }
    }
}

And you also need the actual logger class:

using System;
using log4net;
using log4net.Core;
using Npgsql.Logging;

namespace Util.Npgsql
{
    public class Log4NetNpgsqlLogger : NpgsqlLogger
    {
        private readonly ILog _log;

        public Log4NetNpgsqlLogger(string name)
        {
            _log = LogManager.GetLogger(name);
        }

        public override bool IsEnabled(NpgsqlLogLevel level)
        {
            return _log.Logger.IsEnabledFor(GetLog4NetLevelFromNpgsqlLogLevel(level));
        }

        public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null)
        {
            _log.Logger.Log(typeof(NpgsqlLogger), GetLog4NetLevelFromNpgsqlLogLevel(level), connectorId + ": " + msg, exception);
        }

        protected Level GetLog4NetLevelFromNpgsqlLogLevel(NpgsqlLogLevel level)
        {
            switch (level)
            {
                case NpgsqlLogLevel.Trace:
                case NpgsqlLogLevel.Debug:
                    return Level.Debug;
                case NpgsqlLogLevel.Info:
                    return Level.Info;
                case NpgsqlLogLevel.Warn:
                    return Level.Warn;
                case NpgsqlLogLevel.Error:
                    return Level.Error;
                case NpgsqlLogLevel.Fatal:
                    return Level.Fatal;
                default:
                    throw new Exception("Unknown Npgsql Log Level: " + level);
            }
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to ORDER BY one query only in a UNION ALL without subquery
I'm creating a list from unrelated data using UNION ALL in order to be saved to Excel in SQL Server 2008. Only one of the SELECT statements will have an ORDER BY and that is where my issue arises with the following error message

```<code>'The multi-part identifier "p.Category" could not be bound.'
</code>```

This is a simplified working code example that I prefer to the second one below but breaks when uncommenting the first SELECT query:

```<code>CREATE TABLE #People(Category varchar(50), [Name] varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

-- Unrelated data SELECT query
--SELECT 'Best Employee' AS Matrix
--     , 'Alan' AS [Name]
--UNION ALL

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category;

DROP TABLE #People;
</code>```

After some research I found that I could rewrite the query in the following way, which would give me the desired result in this small example but not something that I would consider ideal in my real case. Is there a way to give me the correct result without resorting to sub queries like in the working example below?

```<code>CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT *
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category

    UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category
    FROM #People p
) x
ORDER BY x.Category;

DROP TABLE #People;
</code>```

答:
If your issue is that your ordering is causing the 2 tables from being mixed up, you could add a column so that the 1st select result set would be displayed first always.</p>

```<code>CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT Matrix, Name, Category
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category
         , 1 as Ord

UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category,
         2 as Ord
    FROM #People p
) x
ORDER BY x.Ord --,Additional Order by columns
</code>```

Body:
I'm creating a list from unrelated data using UNION ALL in order to be saved to Excel in SQL Server 2008. Only one of the SELECT statements will have an ORDER BY and that is where my issue arises with the following error message

'The multi-part identifier "p.Category" could not be bound.'

This is a simplified working code example that I prefer to the second one below but breaks when uncommenting the first SELECT query:

CREATE TABLE #People(Category varchar(50), [Name] varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

-- Unrelated data SELECT query
--SELECT 'Best Employee' AS Matrix
--     , 'Alan' AS [Name]
--UNION ALL

SELECT CASE
           WHEN p.Category = 1
           THEN 'Very Active'
           WHEN p.Category = 2
           THEN 'Active '
           ELSE 'Departed'
       END AS Matrix
     , p.name AS [Name]
FROM #People p
ORDER BY p.Category;

DROP TABLE #People;

After some research I found that I could rewrite the query in the following way, which would give me the desired result in this small example but not something that I would consider ideal in my real case. Is there a way to give me the correct result without resorting to sub queries like in the working example below?

CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT *
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category

    UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category
    FROM #People p
) x
ORDER BY x.Category;

DROP TABLE #People;

Body:
If your issue is that your ordering is causing the 2 tables from being mixed up, you could add a column so that the 1st select result set would be displayed first always.

CREATE TABLE #People(Category varchar(50), [Name]  varchar(50));

INSERT INTO #People VALUES(1, 'Steve');
INSERT INTO #People VALUES(99, 'Anna');
INSERT INTO #People VALUES(2, 'Sarah');

SELECT Matrix, Name, Category
FROM
(
    -- Unrelated data SELECT query
    SELECT 'Best Employee' AS Matrix
         , 'Alan' AS [Name]
         , '' AS Category
         , 1 as Ord

UNION ALL

    SELECT CASE
               WHEN p.Category = 1
               THEN 'Very Active'
               WHEN p.Category = 2
               THEN 'Active '
               ELSE 'Departed'
           END Matrix
         , p.name AS [Name]
         , p.Category Category,
         2 as Ord
    FROM #People p
) x
ORDER BY x.Ord --,Additional Order by columns


问:
Integrate third party page to my wordpress website
I am new in WordPress. I have purchased some sms from a company. Login link is: isms.sslwireless.com.

I want to integrate this application to my own page with removing header and footer information. I want to hide actual provider and his information. Could anyone help me? Is there have suitable plugin to do the same?

答:
You Can do by use of css.

for eg:-

```<code>#footer
{
 display:none;
}
</code>```

Body:
You Can do by use of css.

for eg:-

#footer
{
 display:none;
}


问:
Return Custom HTTP Status Code from WebAPI?
You can return the http status code along with the response object using:

```<code> return Ok(responseObject);
 return BadRequest(responseObject);
 return NotFound(responseObject);
</code>```

But what about you want to return your own custom http status code? 402, 429, 500, 501 etc

答:
```<code>return StatusCode(402, responseObject);
return StatusCode(500, responseObject);
</code>```

Body:
You can return the http status code along with the response object using:

 return Ok(responseObject);
 return BadRequest(responseObject);
 return NotFound(responseObject);

But what about you want to return your own custom http status code? 402, 429, 500, 501 etc


问:
How to apply css style for HTML element using Mootools
How can we hide all list element from first form in following html structure using mootools</p>

```<code><form method="post" action="/signup" class="global_form" enctype="application/x-www-form-urlencoded">
<div>
    <div>
        <ul class="form-errors">
            <li>First Name
                <ul class="errors">
                    <li>Please provide a valid answer for this field.</li>
                </ul>
            </li>
            <li>Last name
                <ul class="errors">
                    <li>Please provide a valid answer for this field.</li>
                </ul>
            </li>
        </ul>
    </div>
</div>
</form>

 <form method="post" id="user_form_login" action="/login" class="global_form" enctype="application/x-www-form-urlencoded">
<div>
    <div>
        <ul class="form-errors">
            <li>Uername
                <ul class="errors">
                    <li>Please provide a valid answer for this field.</li>
                </ul>
            </li>
            <li>Password
                <ul class="errors">
                    <li>Please provide a valid answer for this field.</li>
                </ul>
            </li>
        </ul>
    </div>
</div>
</form>
</code>```

答:
This is completely untested and I switched to jQuery a while ago so there might be a cleaner way to do this, but this should give you a basic idea.

If you are trying to select multiple elements use the mootools dollars method.

If you were to append an id to the first form you could do something like this...

$$('#form1 li').setStyle('display', 'none');

OR

If you do not want to add an id tag this might work.

```<code>var firstForm = $$("form").getFirst(),
listElements = firstForm.getChildren('li');

listelements.setStyle('display', 'none');
</code>```

Body:
How can we hide all list element from first form in following html structure using mootools

<form method="post" action="/signup" class="global_form" enctype="application/x-www-form-urlencoded">

First Name

Please provide a valid answer for this field.

Last name

Please provide a valid answer for this field.

</form>

 <form method="post" id="user_form_login" action="/login" class="global_form" enctype="application/x-www-form-urlencoded">

Uername

Please provide a valid answer for this field.

Password

Please provide a valid answer for this field.

</form>

Body:
This is completely untested and I switched to jQuery a while ago so there might be a cleaner way to do this, but this should give you a basic idea.

If you are trying to select multiple elements use the mootools dollars method.

If you were to append an id to the first form you could do something like this...

$$('#form1 li').setStyle('display', 'none');

OR

If you do not want to add an id tag this might work.

var firstForm = $$("form").getFirst(),
listElements = firstForm.getChildren('li');

listelements.setStyle('display', 'none');


问:
Java - Rest Endpoint returning Image if available and JSON if not available
I'm working on integrating a mobile front-end using the Ionic Framework and the $cordovaFileTransfer plugin.  The use case is the fetching/uploading of a person's Profile Photo.  I've got the uploading working.  It's just the fetching that's giving me some trouble.

Internally, the Cordove File Transfer plugin handles the fetching and creating of the JPG/PNG that's returned from a REST API.  In the event that an image is not available, the backend responds with an HTTP 200 OK + JSON response.  Is this the best practice?  I was thinking that the API should respond with NULL if the image is not available.  That way, I could check to see if the file size is 0 and decide on whether or not to show a default image.

答:
Your backend should respond with status code 404 if the image is not available. In the response body you can put whatever data you deem necessary.

From RFC7231 (HTTP 1.1 Semantics and Content):

The 404 (Not Found) status code indicates that the origin server did

not find a current representation for the target resource or is not

willing to disclose that one exists.