问:
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.

答:
Unfortunately, you can't do this at the level you're attempting to do it at.

You will need to create ItemsPanelTemplate resources for the orientations you're supporting and then move the visual states to the Grid which contains the ListView. The reason for wrapping the ListView in a Grid is that the visual states will not always guarantee firing if they are at the root UserControl level.

Here's an example of how you would do this:

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

                <ItemsPanelTemplate x:Key="VerticalStackPanel">
                    <StackPanel />
                </ItemsPanelTemplate>
            </UserControl.Resources>

            <Grid>
                <ListView
                    x:Name="List"
                    Margin="0,10,0,0"
                    SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectionChanged="TopListBox_SelectionChanged"
                    SelectionMode="Single">
                    <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
                                    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>
                </ListView>

                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState x:Name="w_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowHeight="550" MinWindowWidth="451" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel" Value="{StaticResource VerticalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="n_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel" Value="{StaticResource HorizontalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Grid>
        </UserControl>
    </DataTemplate>
</code>```

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:
Unfortunately, you can't do this at the level you're attempting to do it at.

You will need to create ItemsPanelTemplate resources for the orientations you're supporting and then move the visual states to the Grid which contains the ListView. The reason for wrapping the ListView in a Grid is that the visual states will not always guarantee firing if they are at the root UserControl level.

Here's an example of how you would do this:

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

                <ItemsPanelTemplate x:Key="VerticalStackPanel">
                    <StackPanel />
                </ItemsPanelTemplate>
            </UserControl.Resources>

            <Grid>
                <ListView
                    x:Name="List"
                    Margin="0,10,0,0"
                    SelectedIndex="{Binding CurrentSelectedPage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectionChanged="TopListBox_SelectionChanged"
                    SelectionMode="Single">
                    <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
                                    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>
                </ListView>

                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState x:Name="w_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowHeight="550" MinWindowWidth="451" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel" Value="{StaticResource VerticalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="n_state">
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="List.ItemsPanel" Value="{StaticResource HorizontalStackPanel}" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Grid>
        </UserControl>
    </DataTemplate>


来源: stackexchange

问:
ASP.NET Core and EF Core 1.1 - Display data using Stored Procedure
I have problem with my query. I want to display the result on a view.

```<code>[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index()
{
    return View(await _Context.Employee
                              .FromSql("EXEC sp_GetLoanDetails")
                              .ToArrayAsync());
}
</code>```

Here is my list of items I want to view:

```<code>public class StoredProcRow
{
    [Key]
    public int empID { get; set; }
    public string empFullName { get; set; }
    public double EducationalLoan { get; set; }
    public double PettyCash { get; set; }
    public double BusinessLoan { get; set; }
    public double ApplianceLoan { get; set; }
    public double EmergencyLoan { get; set; }
    public double AllPurposeLoan { get; set; }
    public double KAPUSOIILoan { get; set; }
    public double FiestaLoan { get; set; }
    public double SalaryLoan { get; set; }
    public double Pledge { get; set; }
    public double PagIbigLoan { get; set; }
    public double SSSLoan { get; set; }
    public double AllAroundLoan { get; set; }
    public double Total { get; set; }
}
</code>```

Note: These entities name are the same as entities on column name in sp_GetLoanDetails

Is this achievable right now on EF Core 1.1? Or do I need to go back to manual ADO.NET code?

Thanks!

答:
While support for stored procedures isn’t completely there with Entity Framework Core yet, you still can use FromSql to consume stored procedures with it.

In order to do that, the database context needs to know the entity you are mapping to from the stored procedure. Unfortunately, the only way to do that  right now is to actually define it as an entity in the database context:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<StoredProcRow>(entity =>
    {
        // …
    });
}
</code>```

Then, you can consume the stored procedure by running the FromSql method on a set for that entity:

```<code>public virtual IQueryable<StoredProcRow> GetLoanDetails()
{
    return Set<StoredProcRow>().FromSql("[sp_GetLoanDetails]").AsNoTracking();
}
</code>```

Note that I’m using a AsNoTracking here to avoid the data context to track changes to entities that come from the stored procedure (since you don’t have a way to update them anyway). Also I’m using Set<T>() inside the method to avoid having to expose the type as a member on the database context since you cannot use the set without the stored procedure anyway.

Btw. you don’t need (not sure if that even works) EXEC in the sql statement you pass to FromSql. Just pass the stored procedure name and any arguments to it, e.g.:

```<code>Set<MyEntity>().FromSql("[SomeStoredProcedure]");
Set<MyEntity>().FromSql("[SProcWithOneArgument] @Arg = {0}");
Set<MyEntity>().FromSql("[SProcWithTwoArguments] @Arg1 = {0}, Arg2 = {1}");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have problem with my query. I want to display the result on a view.

[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index()
{
    return View(await _Context.Employee
                              .FromSql("EXEC sp_GetLoanDetails")
                              .ToArrayAsync());
}

Here is my list of items I want to view:

public class StoredProcRow
{
    [Key]
    public int empID { get; set; }
    public string empFullName { get; set; }
    public double EducationalLoan { get; set; }
    public double PettyCash { get; set; }
    public double BusinessLoan { get; set; }
    public double ApplianceLoan { get; set; }
    public double EmergencyLoan { get; set; }
    public double AllPurposeLoan { get; set; }
    public double KAPUSOIILoan { get; set; }
    public double FiestaLoan { get; set; }
    public double SalaryLoan { get; set; }
    public double Pledge { get; set; }
    public double PagIbigLoan { get; set; }
    public double SSSLoan { get; set; }
    public double AllAroundLoan { get; set; }
    public double Total { get; set; }
}

Note: These entities name are the same as entities on column name in sp_GetLoanDetails

Is this achievable right now on EF Core 1.1? Or do I need to go back to manual ADO.NET code?

Thanks!

Body:
While support for stored procedures isn’t completely there with Entity Framework Core yet, you still can use FromSql to consume stored procedures with it.

In order to do that, the database context needs to know the entity you are mapping to from the stored procedure. Unfortunately, the only way to do that  right now is to actually define it as an entity in the database context:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<StoredProcRow>(entity =>
    {
        // …
    });
}

Then, you can consume the stored procedure by running the FromSql method on a set for that entity:

public virtual IQueryable<StoredProcRow> GetLoanDetails()
{
    return Set<StoredProcRow>().FromSql("[sp_GetLoanDetails]").AsNoTracking();
}

Note that I’m using a AsNoTracking here to avoid the data context to track changes to entities that come from the stored procedure (since you don’t have a way to update them anyway). Also I’m using Set<T>() inside the method to avoid having to expose the type as a member on the database context since you cannot use the set without the stored procedure anyway.

Btw. you don’t need (not sure if that even works) EXEC in the sql statement you pass to FromSql. Just pass the stored procedure name and any arguments to it, e.g.:

Set<MyEntity>().FromSql("[SomeStoredProcedure]");
Set<MyEntity>().FromSql("[SProcWithOneArgument] @Arg = {0}");
Set<MyEntity>().FromSql("[SProcWithTwoArguments] @Arg1 = {0}, Arg2 = {1}");

ContentLicense: CC BY-SA 3.0


问:
Run a kernel thread on an isolated cpu core
I boot my kernel

```<code>with isolcpus=3-7
</code>```

and I want to run a thread on one of those isolated CPU cores.

Based on this idea, I do:

```<code>ctx->workq = create_singlethread_workqueue("my_work");
struct workqueue_attrs *attr = alloc_workqueue_attrs(GFP_KERNEL);
alloc_cpumask_var(&attr->cpumask, GFP_KERNEL);
cpumask_clear(attr->cpumask);
cpumask_set_cpu(5, attr->cpumask);
apply_workqueue_attrs(ctx->workq, attr);
INIT_WORK(&ctx->work, my_work);
</code>```

But it's not working. The following code reports 0:

```<code>static void my_work(struct work_struct *w) {
    printk("CPU is: %d\n", get_cpu());
    put_cpu();
</code>```

How can I run this workqueue thread on a specific core (if possible an isolated one)?

答:
There is already one API schedule_work_on in the mainline kernel which you can use to run your workqueue thread on a specific core.

Few years ago I have used same API for the same purpose.
Have a look in the sample code.

```<code>static void
 myworkmod_work_handler(struct work_struct *w)
{
    printk(KERN_ERR "CPU is: %d\n", get_cpu());
    pr_info("work %u jiffies\n", (unsigned)onesec);
    put_cpu();
 }

 static int myworkmod_init(void)
 {
    onesec = msecs_to_jiffies(1000);
    pr_info("module loaded: %u jiffies\n", (unsigned)onesec);

    if (!wq)
            wq = create_singlethread_workqueue("myworkmod");
    if (wq)
            queue_delayed_work_on(2,wq, &myworkmod_work, onesec); //2 CPU no

    return 0;
  }
</code>```

In your case I think you are using the schedule_work API which always hold the default CPU number. That is why you are getting the CPU 0. So you have to try the below one:

```<code>schedule_work_on(cpu_nr, &ctx->work);  //cpu_nr will the CPU no to be used.
</code>```

Body:
I boot my kernel

with isolcpus=3-7

and I want to run a thread on one of those isolated CPU cores.

Based on this idea, I do:

ctx->workq = create_singlethread_workqueue("my_work");
struct workqueue_attrs *attr = alloc_workqueue_attrs(GFP_KERNEL);
alloc_cpumask_var(&attr->cpumask, GFP_KERNEL);
cpumask_clear(attr->cpumask);
cpumask_set_cpu(5, attr->cpumask);
apply_workqueue_attrs(ctx->workq, attr);
INIT_WORK(&ctx->work, my_work);

But it's not working. The following code reports 0:

static void my_work(struct work_struct *w) {
    printk("CPU is: %d\n", get_cpu());
    put_cpu();

How can I run this workqueue thread on a specific core (if possible an isolated one)?

Body:
There is already one API schedule_work_on in the mainline kernel which you can use to run your workqueue thread on a specific core.

Few years ago I have used same API for the same purpose.
Have a look in the sample code.

static void
 myworkmod_work_handler(struct work_struct *w)
{
    printk(KERN_ERR "CPU is: %d\n", get_cpu());
    pr_info("work %u jiffies\n", (unsigned)onesec);
    put_cpu();
 }

 static int myworkmod_init(void)
 {
    onesec = msecs_to_jiffies(1000);
    pr_info("module loaded: %u jiffies\n", (unsigned)onesec);

    if (!wq)
            wq = create_singlethread_workqueue("myworkmod");
    if (wq)
            queue_delayed_work_on(2,wq, &myworkmod_work, onesec); //2 CPU no

    return 0;
  }

In your case I think you are using the schedule_work API which always hold the default CPU number. That is why you are getting the CPU 0. So you have to try the below one:

schedule_work_on(cpu_nr, &ctx->work);  //cpu_nr will the CPU no to be used.


问:
select data header join detail last doc_num header is promotion?
I have two tables, named t_header and t_detail.

this data header

```<code>ID | doc_num | promotion
1     0001      0
2     0002      1
</code>```

this data detail

```<code>ID | doc_num | item | price
1     0001      2      100
2     0001      3      170
3     0001      4      102
4     0001      5      105
5     0002      3      120
6     0002      4       99
7     0002      7      165
</code>```

if promo = 1, then the price in detail would take detailed data promo price, for the table above if the item = 3 then will take the price = 120 because the item with doc_num 002 promo = 1, if no promo it will take prices docnum 001, 001 num doc standard prices, and group by item

output

```<code>ID | doc_num | item | price | promotion
1     0001      2      100    0
5     0002      3      120    1
6     0002      4      99     1
4     0001      5      105    0
7     0002      7      165    0
</code>```

答:
I guess you need to select promo price if it's available otherwise you need normal price. So you should select columns using IF statement after LEFT JOIN.
this query may help : </p>

```<code>SELECT
if(td_prom.ID, td_prom.ID, td_norm.ID) as ID,
th.doc_num,
if(td_prom.price, td_prom.price, td_norm.price) as price,
if(td_prom.item, td_prom.item, td_norm.item) as item,
th.promo
FROM
t_header th
LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0
LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1
GROUP BY item
</code>```

Body:
I have two tables, named t_header and t_detail.

this data header

ID | doc_num | promotion
1     0001      0
2     0002      1

this data detail

ID | doc_num | item | price
1     0001      2      100
2     0001      3      170
3     0001      4      102
4     0001      5      105
5     0002      3      120
6     0002      4       99
7     0002      7      165

if promo = 1, then the price in detail would take detailed data promo price, for the table above if the item = 3 then will take the price = 120 because the item with doc_num 002 promo = 1, if no promo it will take prices docnum 001, 001 num doc standard prices, and group by item

output

ID | doc_num | item | price | promotion
1     0001      2      100    0
5     0002      3      120    1
6     0002      4      99     1
4     0001      5      105    0
7     0002      7      165    0

Body:
I guess you need to select promo price if it's available otherwise you need normal price. So you should select columns using IF statement after LEFT JOIN.
this query may help :

SELECT
if(td_prom.ID, td_prom.ID, td_norm.ID) as ID,
th.doc_num,
if(td_prom.price, td_prom.price, td_norm.price) as price,
if(td_prom.item, td_prom.item, td_norm.item) as item,
th.promo
FROM
t_header th
LEFT JOIN t_detail as td_norm ON th.doc_num = td_norm.doc_num AND th.promo = 0
LEFT JOIN t_detail as td_prom ON th.doc_num = td_prom.doc_num AND th.promo = 1
GROUP BY item


问:
Table-Valued Parameter versus multiple Insert rows performance question for inserting into SQL Server 2008
If all I'm doing is inserting multiple rows of data into a single table in SQL Server 2008, which is faster?

A Table-Valued Parameter or a single insert statement with multiple values?

Where in this simple scenario would you prefer one over the other?

答:
If I understand the question correctly, I'd go with the Table-Valued Parameter. Otherwise I'd think the list of parameters would quickly become unmanageable. You wouldn't want to end up with something like:</p>

```<code>insert into YourTable
    (col1, col2, ..., colN)
    values
    (@Row1Col1, @Row1Col2, ..., @Row1ColN),
    (@Row2Col1, @Row2Col2, ..., @Row2ColN),
    ...
    (@RowMCol1, @RowMCol2, ..., @RowMColN)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If I understand the question correctly, I'd go with the Table-Valued Parameter. Otherwise I'd think the list of parameters would quickly become unmanageable. You wouldn't want to end up with something like:

insert into YourTable
    (col1, col2, ..., colN)
    values
    (@Row1Col1, @Row1Col2, ..., @Row1ColN),
    (@Row2Col1, @Row2Col2, ..., @Row2ColN),
    ...
    (@RowMCol1, @RowMCol2, ..., @RowMColN)


问:
How to get list of current AJAX Calls in the WebPage and how to track programatically, if there are finished
I have an interesting testing issue.

My requirement is to do performance test on a web site.

Issue here to get the REAL time taking to load the web page (i am testing). The word REAL time i refer here as the total time taken to finished all the (initial) AJAX calls (with some response). I thought of using Page Load Event.

But this approach does not give the REAL time.

Any suggestions how to do it any reference to the information is also great!

My environment: Java and WedDriver.

答:
As everyone said, WebDriver is not meant for Performance. However, see the following method that I use sometimes.

Following code will work if you can capture the performance against some particular webelement, can be a div or a span block.

1 Use any stopwatch. I am using apache stopwatch.

```<code>import org.apache.commons.lang3.time.StopWatch;
</code>```

2 Initialize the variable

```<code>StopWatch timer = new StopWatch();
</code>```

3 Start the timer and in next line navigate to your page. I prefer driver.navigate().to() than driver.get() as I feel it reduces other processing time to invoke a fresh URL.

```<code>timer.start();
driver.navigate().to(URL);
</code>```

4 Wait for a particular element that can specify page loading finished. Once it appear, in next line stop the timer.

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions. presenceOfElementLocated(By.className("demoClass")));
timer.stop();
System.out.println("timer.getTime() + " milliseconds");
</code>```

Additional Note: If you want to know the loading time of Network calls of any particular webapge load, use webkit like phantomJS or thing like browsermobproxy. It will return network calls in HAR/JSON file. Parse those files and you may get your time.

Hope this helps.

Body:
As everyone said, WebDriver is not meant for Performance. However, see the following method that I use sometimes.

Following code will work if you can capture the performance against some particular webelement, can be a div or a span block.

1 Use any stopwatch. I am using apache stopwatch.

import org.apache.commons.lang3.time.StopWatch;

2 Initialize the variable

StopWatch timer = new StopWatch();

3 Start the timer and in next line navigate to your page. I prefer driver.navigate().to() than driver.get() as I feel it reduces other processing time to invoke a fresh URL.

timer.start();
driver.navigate().to(URL);

4 Wait for a particular element that can specify page loading finished. Once it appear, in next line stop the timer.

new WebDriverWait(driver, 10).until(ExpectedConditions. presenceOfElementLocated(By.className("demoClass")));
timer.stop();
System.out.println("timer.getTime() + " milliseconds");

Additional Note: If you want to know the loading time of Network calls of any particular webapge load, use webkit like phantomJS or thing like browsermobproxy. It will return network calls in HAR/JSON file. Parse those files and you may get your time.

Hope this helps.


问:
Working with pointers: program that sorts an integer array, segmentation fault
I am trying to make a program with the following properties: Program with the prototype int*max_sorted(int array[], int laenge, int max), which orders the integers in the array. Create an integer array of the size max+1 on the heap and fill all positions with zero. Then the array which is given to the function is read. If a integer x is read, the value of the array on the heap at position x is incremented by one. Then array is overriden: if the value n at postion i of the array on the heap is read, i is written n times in the array (current position).  The code below gives segmentation fault:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int *max_sorted(int array[],int laenge, int max){
  int k,l;
  int *ptr;

  ptr= malloc((max+1)*sizeof(int)); /*allocates memory for new array*/
  if(ptr==NULL || max<0){
    return NULL;   /*error*/
  }
  for(k=0; k<max+1; k++){      /*sets all values of ptr array to 0*/
    ptr[k]=0;
  }

  for(k=0;k<laenge;k++){
    ptr[array[k]]++;
   }

  for(k=0;k<max+1;k++){
    if(ptr[k]!=0){
    array[k-l]=k*ptr[k];
    }
    else{
      l++;
    }
  }

  free(ptr);
  return array;
}

int main(void){

  int array[3]={2,1,3};
  int laenge=3;
  int max=3;
  int k;
  int*ptr;
  ptr=max_sorted(array,laenge,max);
   for(k=0;k<laenge;k++){
    printf("%d",ptr[k]);
   }

    return 0;
}
</code>```

EDIT: The corrected version which now just works fine can be viewed below:

```<code>int *max_sorted(int array[],int laenge, int max){
  int k;
  int l=0;
  int *ptr;
  int i=0;

  ptr= malloc((max+1)*sizeof(int)); /*allocates memory for new array*/
  if(ptr==NULL || max<0){
    return NULL;   /*error*/
  }
  for(k=0; k<max+1; k++){      /*sets all values of ptr array to 0*/
    ptr[k]=0;
  }

  for(k=0;k<laenge;k++){
    ptr[array[k]]++;
   }

  for(k=0;k<max+1;k++){
    l=ptr[k];
    while(l>0){
      array[i]=k;
      i++;
      l--;
    }

  }

  free(ptr);
  return array;
}
</code>```

答:
the EDITED posted code is still not correct.

Here is a version of the code that

cleanly compiles

performs the desired function

still depends on the contents of the array to avoid undefined behavior

and now the code

```<code>#include <stdio.h>   // printf()
#include <stdlib.h>  // calloc(), free(), exit(), EXIT_FAILURE

int *max_sorted(int array[],
                size_t laenge,
                size_t numElementsInArray);

int main( void )
{
    int array[] = { 2,1,3 };
    size_t laenge=3;

    size_t k;
    int*ptr;

    ptr=max_sorted( array, laenge, sizeof( array )/sizeof(int) );

    for( k=0; k<(sizeof( array )/sizeof(int)); k++)
    {
        printf( "%d ", ptr[k] );  //<-- note space in format string
    }

    return 0;         // <-- in modern C, when main returns 0, this line not needed
} // end function: main

int *max_sorted( int array[],      // array to be sorted
                 size_t laenge,    // largest value in array
                 size_t numElementsInArray )
{
    int *ptr = calloc( numElementsInArray+1, sizeof(int) ); /*allocates memory for new array*/
    if(!ptr)
    { // then calloc failed
        perror( "calloc for temporary array failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    for( size_t i=0; i<laenge; i++ )
    {
        ptr[ array[i] ]++;      // <-- this will have undefined behavior
                                //     when array[i] > 3
    }

    size_t index2 = 1;
    for( size_t index1=1; index1<(numElementsInArray+1); index1++ )
    {
        if( ptr[index1] )
        {
            array[index1-index2] = (int)index1 * ptr[index1];
        }

        else
        {
            index2++;
        }
    }

    free(ptr);
    return array;
} // end function: max_sorted
</code>```

The output from the above code is:

```<code>1 2 3
</code>```

Body:
I am trying to make a program with the following properties: Program with the prototype int*max_sorted(int array[], int laenge, int max), which orders the integers in the array. Create an integer array of the size max+1 on the heap and fill all positions with zero. Then the array which is given to the function is read. If a integer x is read, the value of the array on the heap at position x is incremented by one. Then array is overriden: if the value n at postion i of the array on the heap is read, i is written n times in the array (current position).  The code below gives segmentation fault:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int *max_sorted(int array[],int laenge, int max){
  int k,l;
  int *ptr;

  ptr= malloc((max+1)*sizeof(int)); /*allocates memory for new array*/
  if(ptr==NULL || max<0){
    return NULL;   /*error*/
  }
  for(k=0; k<max+1; k++){      /*sets all values of ptr array to 0*/
    ptr[k]=0;
  }

  for(k=0;k<laenge;k++){
    ptr[array[k]]++;
   }

  for(k=0;k<max+1;k++){
    if(ptr[k]!=0){
    array[k-l]=k*ptr[k];
    }
    else{
      l++;
    }
  }

  free(ptr);
  return array;
}

int main(void){

  int array[3]={2,1,3};
  int laenge=3;
  int max=3;
  int k;
  int*ptr;
  ptr=max_sorted(array,laenge,max);
   for(k=0;k<laenge;k++){
    printf("%d",ptr[k]);
   }

    return 0;
}

EDIT: The corrected version which now just works fine can be viewed below:

int *max_sorted(int array[],int laenge, int max){
  int k;
  int l=0;
  int *ptr;
  int i=0;

  ptr= malloc((max+1)*sizeof(int)); /*allocates memory for new array*/
  if(ptr==NULL || max<0){
    return NULL;   /*error*/
  }
  for(k=0; k<max+1; k++){      /*sets all values of ptr array to 0*/
    ptr[k]=0;
  }

  for(k=0;k<laenge;k++){
    ptr[array[k]]++;
   }

  for(k=0;k<max+1;k++){
    l=ptr[k];
    while(l>0){
      array[i]=k;
      i++;
      l--;
    }

  }

  free(ptr);
  return array;
}

Body:
the EDITED posted code is still not correct.

Here is a version of the code that

cleanly compiles

performs the desired function

still depends on the contents of the array to avoid undefined behavior

and now the code

#include <stdio.h>   // printf()
#include <stdlib.h>  // calloc(), free(), exit(), EXIT_FAILURE

int *max_sorted(int array[],
                size_t laenge,
                size_t numElementsInArray);

int main( void )
{
    int array[] = { 2,1,3 };
    size_t laenge=3;

    size_t k;
    int*ptr;

    ptr=max_sorted( array, laenge, sizeof( array )/sizeof(int) );

    for( k=0; k<(sizeof( array )/sizeof(int)); k++)
    {
        printf( "%d ", ptr[k] );  //<-- note space in format string
    }

    return 0;         // <-- in modern C, when main returns 0, this line not needed
} // end function: main

int *max_sorted( int array[],      // array to be sorted
                 size_t laenge,    // largest value in array
                 size_t numElementsInArray )
{
    int *ptr = calloc( numElementsInArray+1, sizeof(int) ); /*allocates memory for new array*/
    if(!ptr)
    { // then calloc failed
        perror( "calloc for temporary array failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    for( size_t i=0; i<laenge; i++ )
    {
        ptr[ array[i] ]++;      // <-- this will have undefined behavior
                                //     when array[i] > 3
    }

    size_t index2 = 1;
    for( size_t index1=1; index1<(numElementsInArray+1); index1++ )
    {
        if( ptr[index1] )
        {
            array[index1-index2] = (int)index1 * ptr[index1];
        }

        else
        {
            index2++;
        }
    }

    free(ptr);
    return array;
} // end function: max_sorted

The output from the above code is:

1 2 3


问:
MVVM Displayer OberservableCollection<ViewModel> with unknown UserControl
im a little bit stuck with my current project and hope someone can help me out of this.

My application works with plugins so that the user is able to add additional functionality to the application. Now i would like to have the configuration window in the same style (Maybe a plugin need some kind of configurations).

The configuration window loads all plugins and get the configuration ViewModel from the plugins. All the ViewModels are stored in an ObservableCollection. These ViewModels should be displayed in a TabControl (one tab per ViewModel)

But i dont know the type of UserControl the plugin is using, because the plugin come up with its own UserControl for configuration purposes.
Otherwise i would create a TabControl, bind its ItemsSource to the ObservableCollection and specify the UserControl in the Resources (DataTemplates).

But how to do it in case the UserControls are unknown to compile time?

I thought about using a ObservableCollection instead of ViewModels, but im not realy happy with that and even dont know if this will work.

Do you have some idea how to deal with that?

Kind regards,

SyLuS

答:
You could use a ContentControl to achieve this.

It's used to show views depending on their viewmodel.
In your xaml you can specifiy which view should be shown. Based on the viewmodel which is the current DataContext.

```<code><ContentControl>
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type vm:MyViewModel}">
            <v:MyView/>
        </DataTemplate>
    </<ContentControl.Resources>
</ContentControl>
</code>```

But when you say you are using a plugin system, maybe something like PRISM, you have to setup the datatemplates automatically. Never done this before. But maybe I gave you a point where you can start.

Body:
You could use a ContentControl to achieve this.

It's used to show views depending on their viewmodel.
In your xaml you can specifiy which view should be shown. Based on the viewmodel which is the current DataContext.

<ContentControl>
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type vm:MyViewModel}">
            <v:MyView/>
        </DataTemplate>
    </<ContentControl.Resources>
</ContentControl>

But when you say you are using a plugin system, maybe something like PRISM, you have to setup the datatemplates automatically. Never done this before. But maybe I gave you a point where you can start.


问:
How to Deal double quotes and commas within csv string?
I am dealing with csv file and i am converting it to DataTable.
But it contains strings as follows.

"Pull PEG Kit, 24" , Ref:P-PEG-24, Exp: 2019/03"

Above phrase is one word. i have used following Regular expression to obtain values within double quotes.

```<code>"\".*?\""
</code>```

But in this scenario it break the word as

"Pull PEG Kit, 24"

Ref:P-PEG-24

Exp: 2019/03"

but i need the word

Pull PEG Kit, 24" , Ref:P-PEG-24, Exp: 2019/03

how can i solve this using c#?
please help me to solve this

Thanks in advance.

答:
I might be missing something out here, but the most basic solution yields the reuslt you need:

```<code>var regex = new Regex("(.*)");
var str = "Pull PEG Kit, 24\", Ref:P - PEG - 24, Exp: 2019 / 03";
var result = regex.Match(str);

Console.WriteLine(result.Value);
</code>```

Output:

```<code>Pull PEG Kit, 24", Ref:P - PEG - 24, Exp: 2019 / 03
</code>```

If the surrounding double quotes are part of the source string:

```<code>var regex = new Regex("(.*)");
var str = "\"Pull PEG Kit, 24\", Ref:P - PEG - 24, Exp: 2019 / 03\"";
var result = regex.Match(str);

Console.WriteLine(result.Value);
Console.WriteLine(result.Value.Trim('\"'));
</code>```

Just trim them out.

Body:
I am dealing with csv file and i am converting it to DataTable.
But it contains strings as follows.

"Pull PEG Kit, 24" , Ref:P-PEG-24, Exp: 2019/03"

Above phrase is one word. i have used following Regular expression to obtain values within double quotes.

"\".*?\""

But in this scenario it break the word as

"Pull PEG Kit, 24"

Ref:P-PEG-24

Exp: 2019/03"

but i need the word

Pull PEG Kit, 24" , Ref:P-PEG-24, Exp: 2019/03

how can i solve this using c#?
please help me to solve this

Thanks in advance.

Body:
I might be missing something out here, but the most basic solution yields the reuslt you need:

var regex = new Regex("(.*)");
var str = "Pull PEG Kit, 24\", Ref:P - PEG - 24, Exp: 2019 / 03";
var result = regex.Match(str);

Console.WriteLine(result.Value);

Output:

Pull PEG Kit, 24", Ref:P - PEG - 24, Exp: 2019 / 03

If the surrounding double quotes are part of the source string:

var regex = new Regex("(.*)");
var str = "\"Pull PEG Kit, 24\", Ref:P - PEG - 24, Exp: 2019 / 03\"";
var result = regex.Match(str);

Console.WriteLine(result.Value);
Console.WriteLine(result.Value.Trim('\"'));

Just trim them out.


问:
OpenCV - PCA analysis on BW image - area vs shape - is there already an implementation?
The shape of an object is detected on a bw image. The object is a black continuous shape, the background is white.
We use PCA (http://docs.opencv.org/3.1.0/d1/dee/tutorial_introduction_to_pca.html) to get the object direction and align the object. Currently the shape itself (the points on the contour) is the input to the opencv PCA implementation. This usually works very well. But from time to time there is small dirt on the object border, causing the shape to pass around the dirt. This causes more points and more weight on one side, slightly turning the object.

Idea: Instead of the contour, we use the area of the object as input for our PCA analysis. The issue there, to check all points on if they are inside the contour and then use them for PCA slows the application down. This part will be about 52352 times slower.

New Approach: We take random points in the image, check if they are inside the shape and if so, use them for our PCA. We have to see if we can get the consistent quality needed from this approach.

Is there already a similar implementation in opencv which is using the area instead of the shape?
Another approach would be to put a mesh over the object and use the mesh points inside the object for PCA.
Is there already something similar available one can just use or does one quickly need to implement something like this?

Going for straight lines around the object isn't an option.

答:
Given that we have received very limited information about your problem (posting images would help a lot) and you do not seem to know the probability density function of the noise, your best bet is to consider the noise to be Gaussian.

As such, and following your intuition, my suggested approach is to take a few (by a few I mean statistically relevant but not raising the computation time that much) random points that lie inside the object and compute the PCA.

Repeat this procedure in an iterative loop and store somewhere the resulting rotation angles you get from the application of the PCA to the object shape.

Stop once you have enough point, compute the mean of the rotation angles: this is a decent estimate of the true angle. Compute also the standard deviation to get a measure of the quality of your estimation. By "enough points" you can consider that ~30 points is usually considered to be "enough" for being representative of the underlying population according to the central limit theorem.

If you want, you can improve on this approach in many ways, for example doing robust estimation of the true angle once you have collected enough points. It all depends on the data you have at hand...take my suggestion just as a starting point.


问:
yii2: how to creating a back link button
I'm new in Yii2 and I'm not able to find something to do a back button in Yii2,
I found the solution in Yii1 is:

```<code>echo CHtml::link('Back',Yii::app()->request->urlReferrer);
</code>```

but I'm not able to find a solution in Yii2,
can you help me?

答:
Yii2 provides remember URLs functionality:

```<code>// Remember current URL
Url::remember();

// Remember URL specified. See Url::to() for argument format.
Url::remember(['product/view', 'id' => 42]);

// Remember URL specified with a name given
Url::remember(['product/view', 'id' => 42], 'product');
</code>```

In the next request we can get URL remembered in the following way:

```<code>$url = Url::previous();
$productUrl = Url::previous('product');
</code>```

Body:
I'm new in Yii2 and I'm not able to find something to do a back button in Yii2,
I found the solution in Yii1 is:

echo CHtml::link('Back',Yii::app()->request->urlReferrer);

but I'm not able to find a solution in Yii2,
can you help me?

Body:
Yii2 provides remember URLs functionality:

// Remember current URL
Url::remember();

// Remember URL specified. See Url::to() for argument format.
Url::remember(['product/view', 'id' => 42]);

// Remember URL specified with a name given
Url::remember(['product/view', 'id' => 42], 'product');

In the next request we can get URL remembered in the following way:

$url = Url::previous();
$productUrl = Url::previous('product');


问:
using sed or awk to remove a "checkbox" character
I have a script that has a variable that might contain some weird characters:  ✔. I need to remove them but, honestly, I don't even know where to begin to match those characters. I can't copy and paste them into my script, they just show up as ?? ?. How can a match those characters with sed or awk? I don't have the ability to use perl or php or anything much beyond sed or awk due to system availability.

答:
Try this - (file contain some control M and the character that you have mentioned in the question and I am trying to print only the alphanumeric character)

```<code>$cat f

hello vipin
street1
pin 12345

 ✔
</code>```

```<code>$awk '/[[:alnum:]]/ {print }' f
hello vipin
street1
pin 12345
</code>```

Looks like control M character is getting disappeared after saving the input file on SO.

Body:
Try this - (file contain some control M and the character that you have mentioned in the question and I am trying to print only the alphanumeric character)

$cat f

hello vipin
street1
pin 12345

 ✔

$awk '/[[:alnum:]]/ {print }' f
hello vipin
street1
pin 12345

Looks like control M character is getting disappeared after saving the input file on SO.


问:
Having trouble with select statements in a stored function
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

```<code>Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end
</code>```

答:
You can change your code to below, I think it will give you what you're looking for:

```<code>create function GetValue3 (@ID int)
returns nvarchar(350)
as
begin
    declare @result nvarchar(350)

    select
        @result = p.Full_Name + ',' + c.Phone + ',' + c.Email + ',' + c.CityID
    from d_People p
        , d_Contacts c
    where c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @result
end
</code>```

The reason you're getting errors is because in a SELECT statement you can either assign a value to variables or return data, you can't mix both together.

Also, the value of @fullName and @phoneNumber etc. is not being set separately at the top of the SELECT and then "moves down" so that at @results = @fullname, @phonenumber, @email, @city they are visible.

Body:
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end

Body:
You can change your code to below, I think it will give you what you're looking for:

create function GetValue3 (@ID int)
returns nvarchar(350)
as
begin
    declare @result nvarchar(350)

    select
        @result = p.Full_Name + ',' + c.Phone + ',' + c.Email + ',' + c.CityID
    from d_People p
        , d_Contacts c
    where c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @result
end

The reason you're getting errors is because in a SELECT statement you can either assign a value to variables or return data, you can't mix both together.

Also, the value of @fullName and @phoneNumber etc. is not being set separately at the top of the SELECT and then "moves down" so that at @results = @fullname, @phonenumber, @email, @city they are visible.


问:
How to efficiently concatenate strings in go
In Go, a string is a primitive type, which means it is read-only, and every manipulation of it will create a new string.

So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?

The naive way would be:

```<code>var s string
for i := 0; i < 1000; i++ {
    s += getShortStringFromSomewhere()
}
return s
</code>```

but that does not seem very efficient.

答:
This is actual version of benchmark provided by @cd1 (Go 1.8, linux x86_64) with the fixes of bugs mentioned by @icza and @PickBoy.

Bytes.Buffer is only 7 times faster than direct string concatenation via + operator.

```<code>package performance_test

import (
    "bytes"
    "fmt"
    "testing"
)

const (
    concatSteps = 100
)

func BenchmarkConcat(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var str string
        for i := 0; i < concatSteps; i++ {
            str += "x"
        }
    }
}

func BenchmarkBuffer(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var buffer bytes.Buffer
        for i := 0; i < concatSteps; i++ {
            buffer.WriteString("x")
        }
    }
}
</code>```

Timings:

```<code>BenchmarkConcat-4                             300000          6869 ns/op
BenchmarkBuffer-4                            1000000          1186 ns/op
</code>```

Body:
In Go, a string is a primitive type, which means it is read-only, and every manipulation of it will create a new string.

So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?

The naive way would be:

var s string
for i := 0; i < 1000; i++ {
    s += getShortStringFromSomewhere()
}
return s

but that does not seem very efficient.

Body:
This is actual version of benchmark provided by @cd1 (Go 1.8, linux x86_64) with the fixes of bugs mentioned by @icza and @PickBoy.

Bytes.Buffer is only 7 times faster than direct string concatenation via + operator.

package performance_test

import (
    "bytes"
    "fmt"
    "testing"
)

const (
    concatSteps = 100
)

func BenchmarkConcat(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var str string
        for i := 0; i < concatSteps; i++ {
            str += "x"
        }
    }
}

func BenchmarkBuffer(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var buffer bytes.Buffer
        for i := 0; i < concatSteps; i++ {
            buffer.WriteString("x")
        }
    }
}

Timings:

BenchmarkConcat-4                             300000          6869 ns/op
BenchmarkBuffer-4                            1000000          1186 ns/op


问:
Postprocess input field after submit
I'am building an application with Meteor. I use autoform, but I want to postprocess some inputfields after submit: add leading zeros to a number when converting to a string ( 20 -> "00020" ), change currency values to integers ( $ 20 -> 2000 or $ 21.34 -> 2134 ). I do not see how to do that. Can anybody help me with this? My issue is with triggering the postprocessing. Some examples would be great.
Regards, Roel</p>

答:
add a before hook to your form

From: https://github.com/aldeed/meteor-autoform#callbackshooks:

The before hooks are called after the form is deemed valid but before
  the submission operation happens. (The submission operation depends on
  the form type.) These hooks are passed the document or modifier as
  gathered from the form fields. If necessary they can modify the
  document or modifier.

somewhere in your client code where it will be loaded only once, add:

```<code>AutoForm.hooks({
  myFormId: {
     before: {
       // Replace `formType` with the form `type` attribute to which this hook applies
       formType: function(doc) {
       // Potentially alter the doc
       doc.foo = 'bar';

       // Then return it or pass it to this.result()
       //return doc; (synchronous)
       //return false; (synchronous, cancel)
       //this.result(doc); (asynchronous)
       //this.result(false); (asynchronous, cancel)
     }
  }
});
</code>```

Title: Postprocess input field after submit

Body:
add a before hook to your form

From: https://github.com/aldeed/meteor-autoform#callbackshooks:

The before hooks are called after the form is deemed valid but before
  the submission operation happens. (The submission operation depends on
  the form type.) These hooks are passed the document or modifier as
  gathered from the form fields. If necessary they can modify the
  document or modifier.

somewhere in your client code where it will be loaded only once, add:

AutoForm.hooks({
  myFormId: {
     before: {
       // Replace `formType` with the form `type` attribute to which this hook applies
       formType: function(doc) {
       // Potentially alter the doc
       doc.foo = 'bar';

       // Then return it or pass it to this.result()
       //return doc; (synchronous)
       //return false; (synchronous, cancel)
       //this.result(doc); (asynchronous)
       //this.result(false); (asynchronous, cancel)
     }
  }
});


问:
"Splitting" the output of a RLE (groupby) depending on a defined value ( the "character" to split the RLE on )
Consider the "string" ( treat it as an array of digits )

```<code>0 0 1 8 8 8 1 0
</code>```

The RLE ( "groupby" ) is:

```<code>[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
</code>```

We then enrich the above RLE with the sum of the run lengths of the previous elements.

Hence, the enriched version of the above becomes:

```<code>[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]
</code>```

The "string" split on 1:

```<code>0 0 , 8 8 8 , 0
</code>```

RLE split on 1

```<code>[(0,2)] , [(8,3)] , [(0, 1)]
</code>```

The "string" split on 8:

```<code>0 0 1 , , , 1 0
</code>```

RLE split on 8

```<code>[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]
</code>```

Note : In my examples, I have cited the "RLE split on Z" lists without enriching them. This would not be so. I left them out to reduce clutter. For example, the "RLE split on 1" should really be treated as:

```<code>[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]
</code>```

How can I achieve this "RLE split" on Z ( = 1, 8; in this case )

It's fine to leave out empty arrays ( after split ).

Perhaps a clever list comp.? ( it seems a little easier to solve with a for loop with an append nested within )

答:
Just for show the way how, I strongly advise you not to use this

"elegant" ugly way:

```<code>>>> data
[0, 0, 1, 8, 8, 8, 4, 4, 1, 0]
>>> def fromDataToSplitRLE(dat,n):
    RLE=[(k,len(tuple(g))) for k,g in itertools.groupby(dat)]
    tmp=tuple(zip(*RLE))
    return [list(g) for k,g in itertools.groupby((zip((sum(tmp[1][:i]) for i in range(len(tmp[1]))) ,(zip(*tmp)))),lambda x:x[1][0]!=n) if k]

>>> fromDataToSplitRLE(data,1)
[[(0, (0, 2))], [(3, (8, 3)), (6, (4, 2))], [(9, (0, 1))]]
</code>```

Body:
Consider the "string" ( treat it as an array of digits )

0 0 1 8 8 8 1 0

The RLE ( "groupby" ) is:

[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]

We then enrich the above RLE with the sum of the run lengths of the previous elements.

Hence, the enriched version of the above becomes:

[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]

The "string" split on 1:

0 0 , 8 8 8 , 0

RLE split on 1

[(0,2)] , [(8,3)] , [(0, 1)]

The "string" split on 8:

0 0 1 , , , 1 0

RLE split on 8

[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]

Note : In my examples, I have cited the "RLE split on Z" lists without enriching them. This would not be so. I left them out to reduce clutter. For example, the "RLE split on 1" should really be treated as:

[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]

How can I achieve this "RLE split" on Z ( = 1, 8; in this case )

It's fine to leave out empty arrays ( after split ).

Perhaps a clever list comp.? ( it seems a little easier to solve with a for loop with an append nested within )

Body:
Just for show the way how, I strongly advise you not to use this

"elegant" ugly way:

>>> data
[0, 0, 1, 8, 8, 8, 4, 4, 1, 0]
>>> def fromDataToSplitRLE(dat,n):
    RLE=[(k,len(tuple(g))) for k,g in itertools.groupby(dat)]
    tmp=tuple(zip(*RLE))
    return [list(g) for k,g in itertools.groupby((zip((sum(tmp[1][:i]) for i in range(len(tmp[1]))) ,(zip(*tmp)))),lambda x:x[1][0]!=n) if k]

>>> fromDataToSplitRLE(data,1)
[[(0, (0, 2))], [(3, (8, 3)), (6, (4, 2))], [(9, (0, 1))]]