问:
WPF - GridSplitter not working between two grids
I have some issues with getting the grid splitter to work properly.

I have placed the GridSplitter between two grids but the problem is that the grid splitter attaches to left grid which is the only one I can move with the splitter. If I move the left grid towards the right grid, the right grid will get smaller but if I move it away from the right grid it will not expand more than its initial size.

How can I place the GridSplitter in such a way that it allows me to adjust the width of the right grid and then reducing the width of the left grid if it is dragged that way.

I did add a SharedSizeGroup to one of the child grids of the right grid but I'm not sure if that is relevant to my problem, removing it didn't solve anything.

I have also tried to play around with the ResizeBehavor of the GridSplitter also without luck.

I hope it makes sense.

XAML:

```<code><Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="3"></TextBlock>

            <Label Grid.Row="0" Grid.Column="0" VerticalContentAlignment="Center" Margin="5"/>
            <ComboBox Grid.Row="0" Grid.Column="1" MinWidth="200px"/>
            <Label Grid.Column="2" VerticalContentAlignment="Center" Margin="10 5 5 5"/>
            <ComboBox Grid.Row="0" Grid.Column="3" IsEditable="True" MinWidth="250px"/>
        </Grid>

        <!--Below grid only shown when errors are present. Not relevant for problem -->
        <Grid Grid.Row="1" Grid.ColumnSpan="2" Grid.RowSpan="2"  Grid.Column="0">
            <TextBlock/>
        </Grid>

        <!-- The "Left" Grid -->
        <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="0">
            <WebBrowser></WebBrowser>
        </Grid>

        <GridSplitter HorizontalAlignment="Stretch" ResizeDirection="Columns" Width="10" Grid.Row="1" Grid.Column="1" ResizeBehavior="PreviousAndNext"/>

        <!-- The "Right" Grid -->
        <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="2" Panel.ZIndex="2" MinWidth="200" HorizontalAlignment="Right">
            <Border BorderBrush="Blue"  BorderThickness="1" MinWidth="200" Background="#4C808080" >
                <GroupBox MinWidth="200">
                    <GroupBox.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="*"></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <TextBlock  Grid.Row="0" Grid.Column="1" Margin="5"/>
                            </Grid>
                        </DataTemplate>
                    </GroupBox.HeaderTemplate>
                    <Grid Grid.IsSharedSizeScope="True">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center" Grid.ColumnSpan="2"/>
                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5,7" VerticalAlignment="Center" IsReadOnly="True" />

                        <Label Grid.Column="0" Grid.Row="1" Margin="5" VerticalAlignment="Center" Grid.ColumnSpan="2"/>
                        <TextBox  Grid.Column="1" Grid.Row="1" Margin="5,7" VerticalAlignment="Center" IsReadOnly="True"/>

                        <ItemsControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>

                                        <Label Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center"/>
                                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5" VerticalAlignment="Center" IsReadOnly="True"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </Grid>
                </GroupBox>
            </Border>
        </Grid>
    </Grid>
</Grid>
</code>```

答:
Have a look at this

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Column="3"></TextBlock>

        <Label Grid.Row="0"
               Grid.Column="0"
               VerticalContentAlignment="Center"
               Margin="5" />
        <ComboBox Grid.Row="0"
                  Grid.Column="1"
                  MinWidth="200px" />
        <Label Grid.Column="2"
               VerticalContentAlignment="Center"
               Margin="10 5 5 5" />
        <ComboBox Grid.Row="0"
                  Grid.Column="3"
                  IsEditable="True"
                  MinWidth="250px" />
    </Grid>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <!-- The "Left" Grid -->
        <Grid Grid.Column="0"
              Background="Aqua">
        </Grid>

        <GridSplitter HorizontalAlignment="Stretch"
                      ResizeDirection="Columns"
                      Width="10"
                      Grid.Column="1"
                      ResizeBehavior="PreviousAndNext" />

        <!-- The "Right" Grid -->
        <Grid Grid.Column="2"
              Panel.ZIndex="2"
              MinWidth="200"
              Background="Yellow">
            <Border BorderBrush="Blue"
                    BorderThickness="1"
                    MinWidth="200"
                    Background="#4C808080">
                <GroupBox MinWidth="200">
                    <GroupBox.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="*"></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <TextBlock  Grid.Row="0"
                                            Grid.Column="1"
                                            Margin="5" />
                            </Grid>
                        </DataTemplate>
                    </GroupBox.HeaderTemplate>
                    <Grid Grid.IsSharedSizeScope="True">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"
                                              SharedSizeGroup="Label" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0"
                               Grid.Row="0"
                               Margin="5"
                               VerticalAlignment="Center"
                               Grid.ColumnSpan="2" />
                        <TextBox Grid.Column="1"
                                 Grid.Row="0"
                                 Margin="5,7"
                                 VerticalAlignment="Center"
                                 IsReadOnly="True" />

                        <Label Grid.Column="0"
                               Grid.Row="1"
                               Margin="5"
                               VerticalAlignment="Center"
                               Grid.ColumnSpan="2" />
                        <TextBox  Grid.Column="1"
                                  Grid.Row="1"
                                  Margin="5,7"
                                  VerticalAlignment="Center"
                                  IsReadOnly="True" />

                        <ItemsControl Grid.Row="2"
                                      Grid.Column="0"
                                      Grid.ColumnSpan="2">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto" />
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"
                                                              SharedSizeGroup="Label" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>

                                        <Label Grid.Column="0"
                                               Grid.Row="0"
                                               Margin="5"
                                               VerticalAlignment="Center" />
                                        <TextBox Grid.Column="1"
                                                 Grid.Row="0"
                                                 Margin="5"
                                                 VerticalAlignment="Center"
                                                 IsReadOnly="True" />
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </Grid>
                </GroupBox>
            </Border>
        </Grid>
    </Grid>

    <!--Below grid only shown when errors are present. Not relevant for problem -->
    <Grid Grid.Row="2">
        <TextBlock />
    </Grid>
</Grid>
</code>```

I changed the Grid "logic" a bit. As I understand you correct you want the GridSplitter for the middle part. Thats why I put the top and bottom part in extra rows to keep them away from the GridSplitter. I had to remove the HorizontalAlignment="Right" from your right Grid, too. Otherwise it would have not changed it's size.

Just to be sure the GridSplitter is working I removed the WebBrowser and added Background colors to the left and right Grid. You can replace that. Thought maybe it would be helpfull for you to see if it's working like expected.

/edit added width relation

```<code><Grid Grid.Row="1">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>

    <!-- The "Left" Grid -->
</code>```

This means when you start the application the first column will take twice the size then the third.

Body:
I have some issues with getting the grid splitter to work properly.

I have placed the GridSplitter between two grids but the problem is that the grid splitter attaches to left grid which is the only one I can move with the splitter. If I move the left grid towards the right grid, the right grid will get smaller but if I move it away from the right grid it will not expand more than its initial size.

How can I place the GridSplitter in such a way that it allows me to adjust the width of the right grid and then reducing the width of the left grid if it is dragged that way.

I did add a SharedSizeGroup to one of the child grids of the right grid but I'm not sure if that is relevant to my problem, removing it didn't solve anything.

I have also tried to play around with the ResizeBehavor of the GridSplitter also without luck.

I hope it makes sense.

XAML:

<Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="3"></TextBlock>

            <ComboBox Grid.Row="0" Grid.Column="1" MinWidth="200px"/>

            <ComboBox Grid.Row="0" Grid.Column="3" IsEditable="True" MinWidth="250px"/>
        </Grid>

        <Grid Grid.Row="1" Grid.ColumnSpan="2" Grid.RowSpan="2"  Grid.Column="0">
            <TextBlock/>
        </Grid>

        <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="0">
            <WebBrowser></WebBrowser>
        </Grid>

        <GridSplitter HorizontalAlignment="Stretch" ResizeDirection="Columns" Width="10" Grid.Row="1" Grid.Column="1" ResizeBehavior="PreviousAndNext"/>

        <Grid Grid.Row="1" Grid.RowSpan="2" Grid.Column="2" Panel.ZIndex="2" MinWidth="200" HorizontalAlignment="Right">
            <Border BorderBrush="Blue"  BorderThickness="1" MinWidth="200" Background="#4C808080" >
                <GroupBox MinWidth="200">
                    <GroupBox.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="*"></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <TextBlock  Grid.Row="0" Grid.Column="1" Margin="5"/>
                            </Grid>
                        </DataTemplate>
                    </GroupBox.HeaderTemplate>
                    <Grid Grid.IsSharedSizeScope="True">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5,7" VerticalAlignment="Center" IsReadOnly="True" />

                        <TextBox  Grid.Column="1" Grid.Row="1" Margin="5,7" VerticalAlignment="Center" IsReadOnly="True"/>

                        <ItemsControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>

                                        <TextBox Grid.Column="1" Grid.Row="0" Margin="5" VerticalAlignment="Center" IsReadOnly="True"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </Grid>
                </GroupBox>
            </Border>
        </Grid>
    </Grid>
</Grid>

Body:
Have a look at this

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

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Column="3"></TextBlock>

        <Label Grid.Row="0"
               Grid.Column="0"
               VerticalContentAlignment="Center"
               Margin="5" />
        <ComboBox Grid.Row="0"
                  Grid.Column="1"
                  MinWidth="200px" />
        <Label Grid.Column="2"
               VerticalContentAlignment="Center"
               Margin="10 5 5 5" />
        <ComboBox Grid.Row="0"
                  Grid.Column="3"
                  IsEditable="True"
                  MinWidth="250px" />
    </Grid>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <!-- The "Left" Grid -->
        <Grid Grid.Column="0"
              Background="Aqua">
        </Grid>

        <GridSplitter HorizontalAlignment="Stretch"
                      ResizeDirection="Columns"
                      Width="10"
                      Grid.Column="1"
                      ResizeBehavior="PreviousAndNext" />

        <!-- The "Right" Grid -->
        <Grid Grid.Column="2"
              Panel.ZIndex="2"
              MinWidth="200"
              Background="Yellow">
            <Border BorderBrush="Blue"
                    BorderThickness="1"
                    MinWidth="200"
                    Background="#4C808080">
                <GroupBox MinWidth="200">
                    <GroupBox.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="*"></ColumnDefinition>
                                </Grid.ColumnDefinitions>
                                <TextBlock  Grid.Row="0"
                                            Grid.Column="1"
                                            Margin="5" />
                            </Grid>
                        </DataTemplate>
                    </GroupBox.HeaderTemplate>
                    <Grid Grid.IsSharedSizeScope="True">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"
                                              SharedSizeGroup="Label" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0"
                               Grid.Row="0"
                               Margin="5"
                               VerticalAlignment="Center"
                               Grid.ColumnSpan="2" />
                        <TextBox Grid.Column="1"
                                 Grid.Row="0"
                                 Margin="5,7"
                                 VerticalAlignment="Center"
                                 IsReadOnly="True" />

                        <Label Grid.Column="0"
                               Grid.Row="1"
                               Margin="5"
                               VerticalAlignment="Center"
                               Grid.ColumnSpan="2" />
                        <TextBox  Grid.Column="1"
                                  Grid.Row="1"
                                  Margin="5,7"
                                  VerticalAlignment="Center"
                                  IsReadOnly="True" />

                        <ItemsControl Grid.Row="2"
                                      Grid.Column="0"
                                      Grid.ColumnSpan="2">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto" />
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"
                                                              SharedSizeGroup="Label" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>

                                        <Label Grid.Column="0"
                                               Grid.Row="0"
                                               Margin="5"
                                               VerticalAlignment="Center" />
                                        <TextBox Grid.Column="1"
                                                 Grid.Row="0"
                                                 Margin="5"
                                                 VerticalAlignment="Center"
                                                 IsReadOnly="True" />
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </Grid>
                </GroupBox>
            </Border>
        </Grid>
    </Grid>

    <!--Below grid only shown when errors are present. Not relevant for problem -->
    <Grid Grid.Row="2">
        <TextBlock />
    </Grid>
</Grid>

I changed the Grid "logic" a bit. As I understand you correct you want the GridSplitter for the middle part. Thats why I put the top and bottom part in extra rows to keep them away from the GridSplitter. I had to remove the HorizontalAlignment="Right" from your right Grid, too. Otherwise it would have not changed it's size.

Just to be sure the GridSplitter is working I removed the WebBrowser and added Background colors to the left and right Grid. You can replace that. Thought maybe it would be helpfull for you to see if it's working like expected.

/edit added width relation

<Grid Grid.Row="1">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>

    <!-- The "Left" Grid -->

This means when you start the application the first column will take twice the size then the third.


来源: stackexchange

问:
Converting number to words in Crystal Reports
How can you convert a number to its written-equivalent in a formula?

For example, 10000 is converted to Ten Thousand.

答: If you need in proper Indian formats like **Four lakhs Twenty Three Thousand...**etc, then follow the link https://archive.sap.com/discussions/thread/2030967. Refer comment by Balakumar Viswanathan. It worked for me.</p>

ContentLicense: CC BY-SA 3.0


问:
Boolean != false
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?

答: As Boolean will give you an object, you must always check for NULL before working on the object</p>

ContentLicense: CC BY-SA 2.5

Title: Boolean != false


问:
Excel VBA: Maintaining number formatting with digits and letters
I am writing a code where basically I need to follow the sequence in logic. I am going through all the lines

```<code>Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & o - 1
End If
Next i
</code>```

So this the last line (there are more than 50 in original code) returns me a value of the cell C5 (20170331) & AB & the o minus 1 (because I have started at 2 (1st line header)). So this is giving 20170331AB1, but it should give 20170331AB01 (zero before the 0). This sequence works like a charm after 10, but before ten when I need to add a zero - I got stuck.

Any ideas? Thank you.

答:
you can do it in one shot with exploiting AutoFilter() method's operator xlFilterValues value

```<code>Sub main()
    Dim rep As Worksheet

    Dim criteriaArr As Variant
    With Worksheets("Work_report") '<--| reference "Work_report" sheet
        criteriaArr = Application.Transpose(.Range("E2", .Cells(.Rows.Count, "E").End(xlUp)).Value) '<--| store its column E cells content from row 2 down to last not empty one
    End With

    Set rep = Sheets("Details")
    With Worksheets("Work") '<--| reference "Work" sheet
        With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)) '<--| reference its column A cells from row 1 (header) down to last not empty one
            .AutoFilter Field:=1, Criteria1:=criteriaArr, Operator:=xlFilterValues '<--| filter it with "Work_report" sheet column E content
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any filtered cells other then headers
                With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping header
                    rep.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count).Value = "FT_EXCEL" '<--| write 'rep' sheet column A corresponding cells content
                    With rep.Range("B" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count)
                        .Formula = "=CONCATENATE(Start!$C$5,""AB"",TEXT(ROW(),""00""))" '<--| '<--| write 'rep' sheet column B corresponding cells content
                        .Value = .Value
                    End With
                End With
            End If
        End With
        .AutoFilterMode = False
    End With
End Sub
</code>```

Body:
I am writing a code where basically I need to follow the sequence in logic. I am going through all the lines

Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & o - 1
End If
Next i

So this the last line (there are more than 50 in original code) returns me a value of the cell C5 (20170331) & AB & the o minus 1 (because I have started at 2 (1st line header)). So this is giving 20170331AB1, but it should give 20170331AB01 (zero before the 0). This sequence works like a charm after 10, but before ten when I need to add a zero - I got stuck.

Any ideas? Thank you.

Body:
you can do it in one shot with exploiting AutoFilter() method's operator xlFilterValues value

Sub main()
    Dim rep As Worksheet

    Dim criteriaArr As Variant
    With Worksheets("Work_report") '<--| reference "Work_report" sheet
        criteriaArr = Application.Transpose(.Range("E2", .Cells(.Rows.Count, "E").End(xlUp)).Value) '<--| store its column E cells content from row 2 down to last not empty one
    End With

    Set rep = Sheets("Details")
    With Worksheets("Work") '<--| reference "Work" sheet
        With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)) '<--| reference its column A cells from row 1 (header) down to last not empty one
            .AutoFilter Field:=1, Criteria1:=criteriaArr, Operator:=xlFilterValues '<--| filter it with "Work_report" sheet column E content
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any filtered cells other then headers
                With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| reference filtered cells skipping header
                    rep.Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count).Value = "FT_EXCEL" '<--| write 'rep' sheet column A corresponding cells content
                    With rep.Range("B" & Rows.Count).End(xlUp).Offset(1).Resize(.Rows.Count)
                        .Formula = "=CONCATENATE(Start!$C$5,""AB"",TEXT(ROW(),""00""))" '<--| '<--| write 'rep' sheet column B corresponding cells content
                        .Value = .Value
                    End With
                End With
            End If
        End With
        .AutoFilterMode = False
    End With
End Sub


问:
Why does this sort in Java not work?
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?</p>

```<code>public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}
</code>```

答:
Here:

```<code>array[i+1] = array[i];
array[i] = array[i+1];
</code>```

You must store the value in a temporary variable, as in the second line you get the same value.

Try with this

```<code>int tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
</code>```

Title: Why does this sort in Java not work?

Body:
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?

public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}

Body:
Here:

array[i+1] = array[i];
array[i] = array[i+1];

You must store the value in a temporary variable, as in the second line you get the same value.

Try with this

int tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;


问:
How to log Client Side exceptions in StackExchange.Exceptional?
I am working on a web project and implemented StackExchange.Exceptional for server exceptions logging. I am just wondering if I could log my client side exceptions as well through StackExchange.Exceptional.

Is there any way to use this library for client-side exceptions logging?

答:
As far as client side logging is concerned there is no mechanism as per my knowledge.
Because the developer never maintain any database of stuff on client side. Even if you save exception in client side storage that wont be a centralized approach and how will you be getting back again?

What you can do
By client side you can log javascript's specific scenarios/Exceptions via Ajax Calls to your server in the same error logging module that you are using for server error logs and saving those exception you want to log in your database to have their centralized record.


问:
C++ File Type changing,etc bank.in.out and cant just change it to bank.in
I want to change its type to bank.in but its name changed but not the type how to do it, I created this bank.in by copying the out file

答:
I think you are looking for rename. Example:

```<code>#include <iostream>
#include <stdio.h>

int main()
{
    int result = rename("bank.in.out","bank.in");
    if(result == 0)
        std::cout << "successfully renamed the file" << std::endl;
    return 0;
}
</code>```

if you post the actual code we could look for a problem there.

Body:
I think you are looking for rename. Example:

#include <iostream>
#include <stdio.h>

int main()
{
    int result = rename("bank.in.out","bank.in");
    if(result == 0)
        std::cout << "successfully renamed the file" << std::endl;
    return 0;
}

if you post the actual code we could look for a problem there.


问:
Xamarin Form: Animate using absolute layout bounds
I have a grid in my app:-

```<code>   <Grid x:Name="BookPagerContainer" IsVisible="false" ColumnSpacing="0" RowSpacing="0" AbsoluteLayout.LayoutBounds="0,1,1,AutoSize" AbsoluteLayout.LayoutFlags="XProportional,YProportional,WidthProportional">
        <BoxView Color="{DynamicResource HeaderColor}" Opacity="0.5"></BoxView>
        <Grid x:Name="BookPager" ColumnSpacing="0" RowSpacing="0" HorizontalOptions="Center" Padding="0,5,0,5">
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
        </Grid>
      </Grid>
</code>```

I want hide/show this grid with animation like going up and down.
 I tried something like this:

```<code>var animation = new Animation(v => BookPagerContainer.HeightRequest = v,1, AutoSize);
    animation.Commit(this, "SimpleAnimation", 500, 500, Easing.Linear, (v, c) => {
       BookPagerContainer.HeightRequest = AutoSize;
    }, () => false);
</code>```

But it didn't worked.

答:
If you want to move your grid, you can use the TranslateTo extension method.

For example :

```<code>await _BookPagerContainer.TranslateTo(0, _BookPagerContainer.Height);
</code>```

Body:
I have a grid in my app:-

   <Grid x:Name="BookPagerContainer" IsVisible="false" ColumnSpacing="0" RowSpacing="0" AbsoluteLayout.LayoutBounds="0,1,1,AutoSize" AbsoluteLayout.LayoutFlags="XProportional,YProportional,WidthProportional">
        <BoxView Color="{DynamicResource HeaderColor}" Opacity="0.5"></BoxView>
        <Grid x:Name="BookPager" ColumnSpacing="0" RowSpacing="0" HorizontalOptions="Center" Padding="0,5,0,5">
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
        </Grid>
      </Grid>

I want hide/show this grid with animation like going up and down.
 I tried something like this:

var animation = new Animation(v => BookPagerContainer.HeightRequest = v,1, AutoSize);
    animation.Commit(this, "SimpleAnimation", 500, 500, Easing.Linear, (v, c) => {
       BookPagerContainer.HeightRequest = AutoSize;
    }, () => false);

But it didn't worked.

Body:
If you want to move your grid, you can use the TranslateTo extension method.

For example :

await _BookPagerContainer.TranslateTo(0, _BookPagerContainer.Height);


问:
wants javascript countdown to continue from where it was even after refresh
I am designing a javaScript countdown for 3 hours using the below code

```<code><div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
count = count - 1;
if (count == -1) {
    clearInterval(counter);
    return;
}

var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;

document.getElementById("timer").innerHTML = hours +  "hours "  + minutes +  "minutes and "   + seconds +  "  seconds left to complete this transaction"; // watch for spelling
}
</script>
</code>```

but the only issue I am having here is whenever I refresh the page the countdown starts all over again. I want it to resume from where it stopped.

答:
You need to store the data into some persistent storage method, such as cookies, the browsers localStorage, or write data out to an external data source (such as a database through an API). Otherwise the session data is lost between browser refreshes.

For example, if you wanted to use localStorage:

```<code><script type="text/javascript">
  // properties
  var count = 0;
  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 1000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours +  "hours "  + minutes +  "minutes and "   + seconds +  "  seconds left to complete this transaction"; // watch for spelling
  }
 </script>
 <div id="timer"></div>
</code>```

You can try it out here: https://jsfiddle.net/rcg4mt9x/

Body:
I am designing a javaScript countdown for 3 hours using the below code

but the only issue I am having here is whenever I refresh the page the countdown starts all over again. I want it to resume from where it stopped.

Body:
You need to store the data into some persistent storage method, such as cookies, the browsers localStorage, or write data out to an external data source (such as a database through an API). Otherwise the session data is lost between browser refreshes.

For example, if you wanted to use localStorage:

<script type="text/javascript">
  // properties
  var count = 0;
  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 1000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours +  "hours "  + minutes +  "minutes and "   + seconds +  "  seconds left to complete this transaction"; // watch for spelling
  }
 </script>
 <div id="timer"></div>

You can try it out here: https://jsfiddle.net/rcg4mt9x/


问:
new-webapplication command fails when a TFS Release definition runs at the same time in multiple environments, getting null exception
I am trying to run a release definition for multiple environments at the same time. as part of this definition, I run a powershell script executing the new-webapplication command with certain parameters. I have 9 different environments. As part of the steps I am running a powershell script that doesn't fail when I run the release definition in sequence, I mean, running each release environment if the previous one was successful, then I don't get any errors. But If I pretend to run the same release definition for all my environments at the same time. Then it fails.

These are just a small example of my environments for this release

This is the error I am getting

```<code>    ##[error]Object reference not set to an instance of an object.
    + CategoryInfo          : NotSpecified: (:) [New-Item], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.NewItemCommandBut this just happens when I run the script with release agents in parallel, not in sequence as you can see on this configuration where all them have this option **Automated:After release creation**
</code>```

And this is the script code on powershell that runs in every environment as the powershell task

```<code>Param
(
  [string]$remoteserver,
  [string]$directory_path,
  [string]$website_name,
  [string]$app_n
)
$ScriptBlockContent =
{
$eventlog = $args[0]
$num = $args[1]
$app_name = $args[2]

$targetdir= $eventlog+'\'+$num+'\'+$app_name
 write-host $targetdir
 write-host 'THE PATH ' $targetdir ' NOT EXIST'
 write-host 'CREATING ' $app_name' DIRECTORY'
 new-item -itemtype directory -path $targetdir -force
write-host 'CREATING ' $app_name' APPLICATION'
new-webapplication -name $app_name -force -site $num -physicalpath $targetdir
}

Invoke-Command -Computer $remoteserver -ScriptBlock $ScriptBlockContent -ArgumentList $directory_path, $website_name, $app_n
</code>```

After printing each command with the -Verbose parameter, I realize that the new-webapplication command is failing with this null reference exception.
Is the IIS not capable to manage the requests of this command at the same time from multiple threads?
Is there anyways to rewrite myscript?

```<code>while(iis-is-failing)
   //re-run new-webapplication ...
</code>```

答:
First please double check your Queuing policies. Queuing policies are defined in the Options section of the Deployment conditions tab.

Maek sure you didn't select after successful deployment on another environment in the trigger and select allow multiple releases to be deployed at the same time.  For the detail info of each settings please refer Deployment conditions

When you create a new environment, the default is checking the trigger.

Also pay attention to the license just like Daniel Mann mentioned in this question Release Management TFS 2015 - No Parallel Tasks

Body:
I am trying to run a release definition for multiple environments at the same time. as part of this definition, I run a powershell script executing the new-webapplication command with certain parameters. I have 9 different environments. As part of the steps I am running a powershell script that doesn't fail when I run the release definition in sequence, I mean, running each release environment if the previous one was successful, then I don't get any errors. But If I pretend to run the same release definition for all my environments at the same time. Then it fails.

These are just a small example of my environments for this release

This is the error I am getting

    ##[error]Object reference not set to an instance of an object.
    + CategoryInfo          : NotSpecified: (:) [New-Item], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.NewItemCommandBut this just happens when I run the script with release agents in parallel, not in sequence as you can see on this configuration where all them have this option **Automated:After release creation**

And this is the script code on powershell that runs in every environment as the powershell task

Param
(
  [string]$remoteserver,
  [string]$directory_path,
  [string]$website_name,
  [string]$app_n
)
$ScriptBlockContent =
{
$eventlog = $args[0]
$num = $args[1]
$app_name = $args[2]

$targetdir= $eventlog+'\'+$num+'\'+$app_name
 write-host $targetdir
 write-host 'THE PATH ' $targetdir ' NOT EXIST'
 write-host 'CREATING ' $app_name' DIRECTORY'
 new-item -itemtype directory -path $targetdir -force
write-host 'CREATING ' $app_name' APPLICATION'
new-webapplication -name $app_name -force -site $num -physicalpath $targetdir
}

Invoke-Command -Computer $remoteserver -ScriptBlock $ScriptBlockContent -ArgumentList $directory_path, $website_name, $app_n

After printing each command with the -Verbose parameter, I realize that the new-webapplication command is failing with this null reference exception.
Is the IIS not capable to manage the requests of this command at the same time from multiple threads?
Is there anyways to rewrite myscript?

while(iis-is-failing)
   //re-run new-webapplication ...


问:
Change returned value in SQL query
I am working with real time viewing program that makes SQL queries (and let me edit bit of the code)

At the moment code is:

```<code>SELECT
    [LogonName] AS [Logon name],
    [LogonExtension] AS [Logon extension],
    [VoiceReady] AS [Ready for Voice],
    [CallState] AS [Call state]
FROM
    [AgentPerformance]
WHERE
    (AgentID IN (1, 2, 3))
</code>```

This returns:

Now my question is that is there any way to change the returned "call state" values to let's say busy, free, handling etc... (there are 3 different values).

I have tried for example:

```<code>SELECT
    [LogonName] AS [Logon name],
    [LogonExtension] AS [Logon extension],
    [VoiceReady] AS [Ready for Voice],
    [CallState] AS [Call state]
FROM
    [AgentPerformance]
WHERE
    (AgentID IN (1, 2, 3))

SELECT
    CASE
       WHEN CallState = 0 THEN 'No'
       WHEN CallState = 1 THEN 'Yes
       ELSE 'Maybe'
    END AS kakaduu
FROM
    AgentPerformance
</code>```

But this didn't work for me.

答:
Your CASE expression need to be in SELECT list along with another columns. second SELECT was incorrect syntax in your example.

So, try this:

```<code>SELECT [LogonName] AS [Logon name], [LogonExtension] AS [Logon extension], [VoiceReady] AS [Ready for Voice], [CallState] AS [Call state],
CASE
    WHEN CallState = 0 then 'No'
    WHEN CallState = 1 then 'Yes'
    ELSE 'Maybe'
END
AS kakaduu
FROM [AgentPerformance]
WHERE   AgentID IN (1, 2, 3)
</code>```

Title: Change returned value in SQL query

Body:
I am working with real time viewing program that makes SQL queries (and let me edit bit of the code)

At the moment code is:

SELECT
    [LogonName] AS [Logon name],
    [LogonExtension] AS [Logon extension],
    [VoiceReady] AS [Ready for Voice],
    [CallState] AS [Call state]
FROM
    [AgentPerformance]
WHERE
    (AgentID IN (1, 2, 3))

This returns:

Now my question is that is there any way to change the returned "call state" values to let's say busy, free, handling etc... (there are 3 different values).

I have tried for example:

SELECT
    [LogonName] AS [Logon name],
    [LogonExtension] AS [Logon extension],
    [VoiceReady] AS [Ready for Voice],
    [CallState] AS [Call state]
FROM
    [AgentPerformance]
WHERE
    (AgentID IN (1, 2, 3))

SELECT
    CASE
       WHEN CallState = 0 THEN 'No'
       WHEN CallState = 1 THEN 'Yes
       ELSE 'Maybe'
    END AS kakaduu
FROM
    AgentPerformance

But this didn't work for me.

Body:
Your CASE expression need to be in SELECT list along with another columns. second SELECT was incorrect syntax in your example.

So, try this:

SELECT [LogonName] AS [Logon name], [LogonExtension] AS [Logon extension], [VoiceReady] AS [Ready for Voice], [CallState] AS [Call state],
CASE
    WHEN CallState = 0 then 'No'
    WHEN CallState = 1 then 'Yes'
    ELSE 'Maybe'
END
AS kakaduu
FROM [AgentPerformance]
WHERE   AgentID IN (1, 2, 3)


问:
ios app containers sync with icloud
I am building an app that contains its own iCloud container. The capabilities configuration is attached below.

Below is the key entry in Info.plist.

```<code><key>iCloud.com.dearle.Ascert</key>
<dict>
  <key>NSUbiquitousContainerIsDocumentScopePublic</key>
  <true/>
  <key>NSUbiquitousContainerSupportedFolderLevels</key>
  <string>Any</string>
  <key>NSUbiquitousContainerName</key>
  <string>Ascert</string>
</dict>
</code>```

It is my understanding that anything I put into my app container should show up in the iCloud drive under a folder named Ascert and that I should be able to open the document in my app from the iCloud drive.

I have tried everything I can think of, unfortunately I am not very experienced with xCode so am unsure of where I am going wrong.

Any help would be appreciated.

答: I faced the same issue as well, the setup you have done is correct. Try increasing the build number and version number before you run your code for the iCloud functionality. This worked for me. Apparently as long as these values are not increased the iCloud setup is not picked up</p>

Title: ios app containers sync with icloud

Body:
I am building an app that contains its own iCloud container. The capabilities configuration is attached below.

Below is the key entry in Info.plist.

<key>iCloud.com.dearle.Ascert</key>
<dict>
  <key>NSUbiquitousContainerIsDocumentScopePublic</key>
  <true/>
  <key>NSUbiquitousContainerSupportedFolderLevels</key>
  <string>Any</string>
  <key>NSUbiquitousContainerName</key>
  <string>Ascert</string>
</dict>

It is my understanding that anything I put into my app container should show up in the iCloud drive under a folder named Ascert and that I should be able to open the document in my app from the iCloud drive.

I have tried everything I can think of, unfortunately I am not very experienced with xCode so am unsure of where I am going wrong.

Any help would be appreciated.


问:
pragma comment(lib) not working
Given this library:

lib1.h:

```<code>#pragma once

#include <windows.h>

void foo();
</code>```

lib1.cpp

```<code>#include "lib1.h"

void foo() {
    MessageBox(NULL, "XXX", "YYY1", MB_OK);
}
</code>```

Created in the command line with the next commands:

```<code>cl /c lib1.cpp
lib lib1.obj
</code>```

And then this little test:

```<code>#pragma comment(lib, "lib1")

#include "lib1.h"

void start() {
    foo();
}
</code>```

I've tried to run it on a windows vs2015 project setting:

/NODEFAULTLIB

entry:start

optimization disabled (/Od)

(security check disabled) /GS-

But I'm facing a linker error such as:

```<code>main.obj : error LNK2019: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ) referenced in function "void __cdecl start(void)" (?start@@YAXXZ)
</code>```

I've tried changing the pragma comment to #pragma comment(lib, "lib1.lib"), #pragma comment(lib, ".\\lib1.lib"), #pragma comment(lib, "./lib1.lib") and none of them worked.

I've also tried to include in the linker additional paths the path of lib1.lib and then using either #pragma comment(lib, "lib1.lib") or ``#pragma comment(lib, "lib1.lib")`, no luck.

In fact, the funny thing is, when turning on the /VERBOSE in the linker I don't see any linker's attempt to use the #pragma directive. Of course, If i added lib1.cpp or lib1.lib to the project it'd work but I'm trying to figure out how to use the pragma directive... So, anyone could explain what's going on here and how to solve this issue?

答:
Don't use /NODEFAULTLIB, it basically instructs the linker to ignore the lib #pragma. Explanation from here for instance:

When you use #pragma comment(linker) or #pragma comment(lib) you get a
  special entry in the object file (it's a special COFF section usually
  named ".drectve" with the directive bit set). Once the linker sees
  this entry it treats it as if the switch was given on the linker
  command line.

So:

```<code>t.cpp:
#pragma comment(lib,"advapi32.lib")
...

cl t.cpp
</code>```

is equivalent to

```<code>t.cpp:
...

cl t.cpp /link /DEFAULTLIB:advapi32.lib
</code>```

and when you add /NODEFAULTLIB to that last comment it will ignore whatever is specified as /DEFAULTLIB

Title: pragma comment(lib) not working

Body:
Given this library:

lib1.h:

#pragma once

#include <windows.h>

void foo();

lib1.cpp

#include "lib1.h"

void foo() {
    MessageBox(NULL, "XXX", "YYY1", MB_OK);
}

Created in the command line with the next commands:

cl /c lib1.cpp
lib lib1.obj

And then this little test:

#pragma comment(lib, "lib1")

#include "lib1.h"

void start() {
    foo();
}

I've tried to run it on a windows vs2015 project setting:

/NODEFAULTLIB

entry:start

optimization disabled (/Od)

(security check disabled) /GS-

But I'm facing a linker error such as:

main.obj : error LNK2019: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ) referenced in function "void __cdecl start(void)" (?start@@YAXXZ)

I've tried changing the pragma comment to #pragma comment(lib, "lib1.lib"), #pragma comment(lib, ".\\lib1.lib"), #pragma comment(lib, "./lib1.lib") and none of them worked.

I've also tried to include in the linker additional paths the path of lib1.lib and then using either #pragma comment(lib, "lib1.lib") or ``#pragma comment(lib, "lib1.lib")`, no luck.

In fact, the funny thing is, when turning on the /VERBOSE in the linker I don't see any linker's attempt to use the #pragma directive. Of course, If i added lib1.cpp or lib1.lib to the project it'd work but I'm trying to figure out how to use the pragma directive... So, anyone could explain what's going on here and how to solve this issue?

Body:
Don't use /NODEFAULTLIB, it basically instructs the linker to ignore the lib #pragma. Explanation from here for instance:

When you use #pragma comment(linker) or #pragma comment(lib) you get a
  special entry in the object file (it's a special COFF section usually
  named ".drectve" with the directive bit set). Once the linker sees
  this entry it treats it as if the switch was given on the linker
  command line.

So:

t.cpp:
#pragma comment(lib,"advapi32.lib")
...

cl t.cpp

is equivalent to

t.cpp:
...

cl t.cpp /link /DEFAULTLIB:advapi32.lib

and when you add /NODEFAULTLIB to that last comment it will ignore whatever is specified as /DEFAULTLIB


问:
Ordering array of strings in bash scripting
I am fairly new to bash scripting. I have a list of files in my directory and I'd like to store them into an array and then sort them inside the array. I've stored the list of files into my array; however, I'm unable to order them.

```<code>  for file in test_file*.txt;
  do
    TEST_FILE="${file##*/}"
    arrayname[index]=$TEST_FILE
    index=$(expr $index + 1)
  done
</code>```

That stores all the files starting with test_file and ending with .txt into my array. The part that I find tricky is sorting it. I've done a bit of digging around, but I could not find the solution.

Also if I was so run compile a python code later, would I do a loop and call

```<code>python3 test.py "$arrayname[n]"
</code>```

and increment n?

My current directory has these files and it is stored in the array "arrayname[]" in the form:

```<code> test_file0.txt, test_file12.txt, test_file11.txt, test_file10.txt,
</code>```

I am trying to sort it and store it into another array, so the new array has the following order:

```<code> test_file0.txt, test_file10.txt, test_file11.txt, test_file12.txt
</code>```

答:
If your sort knows the -V (GNU sort):

```<code>readarray -t files < <(printf "%s\n" test_file* | sort -V)
printf "%s\n" "${files[@]}"

#bash 4.4+
readarray -t -d '' files1 < <(find . -maxdepth 1 -name test_file\* -print0 | sort -zV)
printf "%s\n" "${files1[@]}"
</code>```

Body:
I am fairly new to bash scripting. I have a list of files in my directory and I'd like to store them into an array and then sort them inside the array. I've stored the list of files into my array; however, I'm unable to order them.

  for file in test_file*.txt;
  do
    TEST_FILE="${file##*/}"
    arrayname[index]=$TEST_FILE
    index=$(expr $index + 1)
  done

That stores all the files starting with test_file and ending with .txt into my array. The part that I find tricky is sorting it. I've done a bit of digging around, but I could not find the solution.

Also if I was so run compile a python code later, would I do a loop and call

python3 test.py "$arrayname[n]"

and increment n?

My current directory has these files and it is stored in the array "arrayname[]" in the form:

 test_file0.txt, test_file12.txt, test_file11.txt, test_file10.txt,

I am trying to sort it and store it into another array, so the new array has the following order:

 test_file0.txt, test_file10.txt, test_file11.txt, test_file12.txt

Body:
If your sort knows the -V (GNU sort):

readarray -t files < <(printf "%s\n" test_file* | sort -V)
printf "%s\n" "${files[@]}"

#bash 4.4+
readarray -t -d '' files1 < <(find . -maxdepth 1 -name test_file\* -print0 | sort -zV)
printf "%s\n" "${files1[@]}"


问:
Using SDL, OpenGL and Qt together
For a while I've been using SDL to write my 3D engine,and have recently been implementing an editor that can export an optimized format for the type of engine Im building. Right now the editor is fairly simple, objects can just be moved around and their textures and models can be changed. As of right now, I'm using SDL with OpenGL to render everything, but I want to use Qt for the GUI part of the editor, that way it looks native on every platform. I've got it working great so far, I'm running a QApplication inside of the SDL application, so it basically just opens 2 windows, one that uses SDL and OpenGL, and the other using Qt. Doing a bit of research, I've found that you can manually update a QApplication, which totally removes any threading problems, and everything works. Just in case you're having a hard time visualizing this, heres a picture:

What my goal is to merge these windows into one, because on smaller screens (like my laptop's) it makes it really hard to keep track of all the different windows that I would eventually have. I know theres a way to render to Qt with OpenGL, but can this be integrated with SDL? Am I going to need to move away from using an SDL window and use a QT one if the editor is enabled? Just to clarify, when the engine isn't in editor mode, it won't use and Qt, just SDL, so optimally I wouldn't need to do this.

答:
You can keep your game and editor separate processes and still make them part of the same app.

Just spawn the window where you want the game to run as part of Qt, and at least in windows, you can then pass the window handle to your game, and make sure when your game is setting up, instead of creating the window yourself in SDL and binding the opengl context to it, you can actually bind to the existing handle.

There are some gotchas with this technique to watch out for such as input focus I believe (I tested with directX, but it might be similar with SDL). The problem is that the foreground mode does some dumb checks on the "root" window which for me was not the window that owned the opengl context, so it failed to initialize. However background mode worked. I think that was for a joystick now that I think about it, but anyway, that's how you can merge everything together.

Title: Using SDL, OpenGL and Qt together


问:
Getting single PID from pgrep
When I execute the following command on shell it returns the expected PID of e.g. 4676:

```<code>pgrep -f konakart
</code>```

But when using that line on a script it returns two IDs (the expected one, and I guess the other one from itself):

```<code># vim test.sh
#!/bin/ksh
echo $(pgrep -f $1)

# ./test.sh konakart
4676 17847
</code>```

What is wrong on these lines?

答:
You have not considered your command that you entered at the command line.

When submitted at the command line, you are correct that there is only a single command running with the word konakart in its full description.

Now you are calling a script ... how??

```<code>./test.sh konakart
</code>```

So now how many commands have the word konakart in their full listing?

the answer is 2, the one you think you are looking for and the one you just submitted where you put the word on the command line to call your script ;)

Title: Getting single PID from pgrep

Body:
When I execute the following command on shell it returns the expected PID of e.g. 4676:

pgrep -f konakart

But when using that line on a script it returns two IDs (the expected one, and I guess the other one from itself):

# vim test.sh
#!/bin/ksh
echo $(pgrep -f $1)

# ./test.sh konakart
4676 17847

What is wrong on these lines?

Body:
You have not considered your command that you entered at the command line.

When submitted at the command line, you are correct that there is only a single command running with the word konakart in its full description.

Now you are calling a script ... how??

./test.sh konakart

So now how many commands have the word konakart in their full listing?

the answer is 2, the one you think you are looking for and the one you just submitted where you put the word on the command line to call your script ;)


问:
Best Solution For the Train Composition
Recently I answered My Online Interview test Wherein I was asked Following question

A TrainComposition is built by attaching and detaching wagons from the left and the right sides.

For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13. Implement a TrainComposition that models this problem.

I used doubly linked list to solve the issue

```<code>class Node

{
    protected int data;
    protected Node next, prev;
    /* Constructor */
    public Node()
    {
        next = null;
        prev = null;
        data = 0;
    }

    /* Constructor */

    public Node(int d, Node n, Node p)
    {
        data = d;
        next = n;
        prev = p;
    }

    /* Function to set link to next node */
    public void setLinkNext(Node n) {
        next = n;
    }
    /* Function to set link to previous node */
    public void setLinkPrev(Node p) {
        prev = p;
    }

    /* Funtion to get link to next node */

    public Node getLinkNext() {
        return next;
    }

    /* Function to get link to previous node */

    public Node getLinkPrev() {
        return prev;
    }

    /* Function to set data to node */
    public void setData(int d) {
        data = d;
    }

    /* Function to get data from node */

    public int getData() {
        return data;
    }
}

public class SortedSearch {
    protected Node start;
    protected Node end;
    public int size;
    /* Constructor */
    public SortedSearch()
    {
        start = null;
        end = null;
        size = 0;
    }
    public boolean isEmpty()
    {
        return start == null;
    }

    public int getSize()
    {
        return size;
    }

    public void attachWagonFromLeft(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            start.setLinkPrev(nptr);
            nptr.setLinkNext(start);
            start = nptr;
        }
        size++;
    }
    public void attachWagonFromRight(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            nptr.setLinkPrev(end);
            end.setLinkNext(nptr);
            end = nptr;
        }
        size++;
    }
    public int detachWagonFromLeft() {
        int value=0;
        if (size == 1)
        {
            value = start.getData();
            start = null;
            end = null;
            size = 0;
            return value;

        }
        value = start.getData();
        start = start.getLinkNext();
        start.setLinkPrev(null);
        size--;
        return value;
    }

    public int detachWagonFromRight() {
        int value=0;
            value = end.getData();
            end = end.getLinkPrev();
            end.setLinkNext(null);
            size-- ;
            return value;
    }

    public static void main(String[] args) {
        SortedSearch tree = new SortedSearch();
        tree.attachWagonFromLeft(7);
        tree.attachWagonFromLeft(13);
        tree.attachWagonFromLeft(12);
        tree.attachWagonFromLeft(10);
        tree.attachWagonFromLeft(6);
        tree.attachWagonFromLeft(4);
        tree.attachWagonFromLeft(3);
        tree.attachWagonFromLeft(2);
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13

    }
}
</code>```

And tested it accordingly. But when submitted it said failed internal test cases, and the answer was marked wrong.
Can you please tell which is the best solution for this problem.

答:
It seems that the detachWagonFromRight lacks the check that detachWagonFromLeft has:

```<code>public int detachWagonFromLeft() {
    int value=0;
    if (size == 1)
    {
        value = start.getData();
        start = null;
        end = null;
        size = 0;
        return value;

    }
    value = start.getData();
    start = start.getLinkNext();
    start.setLinkPrev(null);
    size--;
    return value;
}

public int detachWagonFromRight() {
    int value=0;
        value = end.getData();
        end = end.getLinkPrev();
        end.setLinkNext(null);
        size-- ;
        return value;
}
</code>```

So the case when you are removing the last wagon from the right side, start still points to it

Title: Best Solution For the Train Composition

Body:
Recently I answered My Online Interview test Wherein I was asked Following question

A TrainComposition is built by attaching and detaching wagons from the left and the right sides.

For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13. Implement a TrainComposition that models this problem.

I used doubly linked list to solve the issue

class Node

{
    protected int data;
    protected Node next, prev;
    /* Constructor */
    public Node()
    {
        next = null;
        prev = null;
        data = 0;
    }

    /* Constructor */

    public Node(int d, Node n, Node p)
    {
        data = d;
        next = n;
        prev = p;
    }

    /* Function to set link to next node */
    public void setLinkNext(Node n) {
        next = n;
    }
    /* Function to set link to previous node */
    public void setLinkPrev(Node p) {
        prev = p;
    }

    /* Funtion to get link to next node */

    public Node getLinkNext() {
        return next;
    }

    /* Function to get link to previous node */

    public Node getLinkPrev() {
        return prev;
    }

    /* Function to set data to node */
    public void setData(int d) {
        data = d;
    }

    /* Function to get data from node */

    public int getData() {
        return data;
    }
}

public class SortedSearch {
    protected Node start;
    protected Node end;
    public int size;
    /* Constructor */
    public SortedSearch()
    {
        start = null;
        end = null;
        size = 0;
    }
    public boolean isEmpty()
    {
        return start == null;
    }

    public int getSize()
    {
        return size;
    }

    public void attachWagonFromLeft(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            start.setLinkPrev(nptr);
            nptr.setLinkNext(start);
            start = nptr;
        }
        size++;
    }
    public void attachWagonFromRight(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            nptr.setLinkPrev(end);
            end.setLinkNext(nptr);
            end = nptr;
        }
        size++;
    }
    public int detachWagonFromLeft() {
        int value=0;
        if (size == 1)
        {
            value = start.getData();
            start = null;
            end = null;
            size = 0;
            return value;

        }
        value = start.getData();
        start = start.getLinkNext();
        start.setLinkPrev(null);
        size--;
        return value;
    }

    public int detachWagonFromRight() {
        int value=0;
            value = end.getData();
            end = end.getLinkPrev();
            end.setLinkNext(null);
            size-- ;
            return value;
    }

    public static void main(String[] args) {
        SortedSearch tree = new SortedSearch();
        tree.attachWagonFromLeft(7);
        tree.attachWagonFromLeft(13);
        tree.attachWagonFromLeft(12);
        tree.attachWagonFromLeft(10);
        tree.attachWagonFromLeft(6);
        tree.attachWagonFromLeft(4);
        tree.attachWagonFromLeft(3);
        tree.attachWagonFromLeft(2);
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13

    }
}

And tested it accordingly. But when submitted it said failed internal test cases, and the answer was marked wrong.
Can you please tell which is the best solution for this problem.

Body:
It seems that the detachWagonFromRight lacks the check that detachWagonFromLeft has:

public int detachWagonFromLeft() {
    int value=0;
    if (size == 1)
    {
        value = start.getData();
        start = null;
        end = null;
        size = 0;
        return value;

    }
    value = start.getData();
    start = start.getLinkNext();
    start.setLinkPrev(null);
    size--;
    return value;
}

public int detachWagonFromRight() {
    int value=0;
        value = end.getData();
        end = end.getLinkPrev();
        end.setLinkNext(null);
        size-- ;
        return value;
}

So the case when you are removing the last wagon from the right side, start still points to it


问:
Python ARIMA exogenous variable out of sample
I am trying to predict a time series in python statsmodels ARIMA package with the inclusion of an exogenous variable, but cannot figure out the correct way to insert the exogenous variable in the predict step. See here for docs.

```<code>import numpy as np
from scipy import stats
import pandas as pd

import statsmodels.api as sm

vals = np.random.rand(13)
ts = pd.TimeSeries(vals)
df = pd.DataFrame(ts, columns=["test"])
df.index = pd.Index(pd.date_range("2011/01/01", periods = len(vals), freq = 'Q'))

fit1 = sm.tsa.ARIMA(df, (1,0,0)).fit()
#this works fine:
pred1 = fit1.predict(start=12, end = 16)
print(pred1)

Out[32]:
2014-03-31    0.589121
2014-06-30    0.747575
2014-09-30    0.631322
2014-12-31    0.654858
2015-03-31    0.650093
Freq: Q-DEC, dtype: float64
</code>```

now add in a trend exogenous variable

```<code>exogx = np.array(range(1,14))
#to make this easy, let's look at the ols of the trend (arima(0,0,0))
fit2 = sm.tsa.ARIMA(df, (0,0,0),exog = exogx).fit()
print(fit2.params)

const    0.555226
x1       0.013132
dtype: float64

print(fit2.fittedvalues)

2011-03-31    0.568358
2011-06-30    0.581490
2011-09-30    0.594622
2011-12-31    0.607754
2012-03-31    0.620886
2012-06-30    0.634018
2012-09-30    0.647150
2012-12-31    0.660282
2013-03-31    0.673414
2013-06-30    0.686546
2013-09-30    0.699678
2013-12-31    0.712810
2014-03-31    0.725942
Freq: Q-DEC, dtype: float64
</code>```

Notice, as we would expect, this is a trend line, increasing 0.013132 with each increase tick in time (of course this is random data, so if you run it the values will be different, but the positive or negative trend story will be the same). So, the next value (for time = 14) should be 0.555226 + 0.013132*14 = 0.739074.

```<code>#out of sample exog should be (14,15,16)
pred2 = fit2.predict(start = 12, end = 16, exog = np.array(range(13,17)))
print(pred2)
2014-03-31    0.725942
2014-06-30    0.568358
2014-09-30    0.581490
2014-12-31    0.594622
2015-03-31    0.765338
Freq: Q-DEC, dtype: float64
</code>```

So, 2014-03-31 predicts (the last insample) correctly, but 2014-06-30 starts back at the beginning (t = 1), but notice 2015-03-31 (actually, always the last observation of the forecast, regardless of horizon) picks up t = 16 (that is, (value - intercept)/beta = (0.765338 - 0.555226)/0.013132).

To make this more clear, notice what happens when I inflate the values of of the x mat

```<code>fit2.predict(start = 12, end = 16, exog = np.array(range(13,17))*10000)
Out[41]:
2014-03-31       0.725942
2014-06-30       0.568358
2014-09-30       0.581490
2014-12-31       0.594622
2015-03-31    2101.680532
Freq: Q-DEC, dtype: float64
</code>```

See that 2015-03-31 exploded, but none of the other xmat values were considered? What am I doing wrong here???

I have tried playing around with every way that I know how for passing in the exog variable (changing dimension, making the exog a matrix, making the exog as long as input plus the horizon, etc, etc, etc). Any suggestions would be really appreciated.

I am using 2.7 from Anaconda2.1
numpy 1.8.1
scipy 0.14.0
pandas 0.14.0
statsmodels 0.5.0

and have verified the issue on windows 7 64 bit, and centos 64 bit.

Also, a few things. I am using ARIMA for the ARIMA functionality and the above is just for illustration (that is, I cannot "just use OLS...", as I imagine will be suggested). I also cannot "just use R" due to the restrictions of the project (and more generally, the lack of support of R in base Spark).

Here are the interesting parts of the code all together in case you want to try it yourself

```<code>import numpy as np
from scipy import stats
import pandas as pd
import statsmodels.api as sm

vals = np.random.rand(13)
ts = pd.TimeSeries(vals)
df = pd.DataFrame(ts, columns=["test"])
df.index = pd.Index(pd.date_range("2011/01/01", periods = len(vals), freq = 'Q'))

exogx = np.array(range(1,14))
fit2 = sm.tsa.ARIMA(df, (0,0,0),exog = exogx).fit()
print(fit2.fittedvalues)
pred2 = fit2.predict(start = 12, end = 16, exog = np.array(range(13,17))*10000)
print(pred2)
</code>```

答:
If anyone is using the .forecast() method, this worked for me for one-step prediction.

history is training array

exog is external variable array

Y_exog_test is out-of-sample corresponding external variable.

Change it to .SARIMAX() and it should work

model = sm.tsa.statespace.ARIMA(history, trend='c', order=(1,1,1),seasonal_order=(0,1,0,24),exog=yexog)
model_fit = model.fit()
predicted = model_fit.forecast(step=1,exog=[[Y_exog_test]], dynamic=True)
```

Body:
I am trying to predict a time series in python statsmodels ARIMA package with the inclusion of an exogenous variable, but cannot figure out the correct way to insert the exogenous variable in the predict step. See here for docs.

import numpy as np
from scipy import stats
import pandas as pd

import statsmodels.api as sm

vals = np.random.rand(13)
ts = pd.TimeSeries(vals)
df = pd.DataFrame(ts, columns=["test"])
df.index = pd.Index(pd.date_range("2011/01/01", periods = len(vals), freq = 'Q'))

fit1 = sm.tsa.ARIMA(df, (1,0,0)).fit()
#this works fine:
pred1 = fit1.predict(start=12, end = 16)
print(pred1)

Out[32]:
2014-03-31    0.589121
2014-06-30    0.747575
2014-09-30    0.631322
2014-12-31    0.654858
2015-03-31    0.650093
Freq: Q-DEC, dtype: float64

now add in a trend exogenous variable

exogx = np.array(range(1,14))
#to make this easy, let's look at the ols of the trend (arima(0,0,0))
fit2 = sm.tsa.ARIMA(df, (0,0,0),exog = exogx).fit()
print(fit2.params)

const    0.555226
x1       0.013132
dtype: float64

print(fit2.fittedvalues)

2011-03-31    0.568358
2011-06-30    0.581490
2011-09-30    0.594622
2011-12-31    0.607754
2012-03-31    0.620886
2012-06-30    0.634018
2012-09-30    0.647150
2012-12-31    0.660282
2013-03-31    0.673414
2013-06-30    0.686546
2013-09-30    0.699678
2013-12-31    0.712810
2014-03-31    0.725942
Freq: Q-DEC, dtype: float64

Notice, as we would expect, this is a trend line, increasing 0.013132 with each increase tick in time (of course this is random data, so if you run it the values will be different, but the positive or negative trend story will be the same). So, the next value (for time = 14) should be 0.555226 + 0.013132*14 = 0.739074.

#out of sample exog should be (14,15,16)
pred2 = fit2.predict(start = 12, end = 16, exog = np.array(range(13,17)))
print(pred2)
2014-03-31    0.725942
2014-06-30    0.568358
2014-09-30    0.581490
2014-12-31    0.594622
2015-03-31    0.765338
Freq: Q-DEC, dtype: float64

So, 2014-03-31 predicts (the last insample) correctly, but 2014-06-30 starts back at the beginning (t = 1), but notice 2015-03-31 (actually, always the last observation of the forecast, regardless of horizon) picks up t = 16 (that is, (value - intercept)/beta = (0.765338 - 0.555226)/0.013132).

To make this more clear, notice what happens when I inflate the values of of the x mat

fit2.predict(start = 12, end = 16, exog = np.array(range(13,17))*10000)
Out[41]:
2014-03-31       0.725942
2014-06-30       0.568358
2014-09-30       0.581490
2014-12-31       0.594622
2015-03-31    2101.680532
Freq: Q-DEC, dtype: float64

See that 2015-03-31 exploded, but none of the other xmat values were considered? What am I doing wrong here???

I have tried playing around with every way that I know how for passing in the exog variable (changing dimension, making the exog a matrix, making the exog as long as input plus the horizon, etc, etc, etc). Any suggestions would be really appreciated.

I am using 2.7 from Anaconda2.1
numpy 1.8.1
scipy 0.14.0
pandas 0.14.0
statsmodels 0.5.0

and have verified the issue on windows 7 64 bit, and centos 64 bit.

Also, a few things. I am using ARIMA for the ARIMA functionality and the above is just for illustration (that is, I cannot "just use OLS...", as I imagine will be suggested). I also cannot "just use R" due to the restrictions of the project (and more generally, the lack of support of R in base Spark).

Here are the interesting parts of the code all together in case you want to try it yourself

import numpy as np
from scipy import stats
import pandas as pd
import statsmodels.api as sm

vals = np.random.rand(13)
ts = pd.TimeSeries(vals)
df = pd.DataFrame(ts, columns=["test"])
df.index = pd.Index(pd.date_range("2011/01/01", periods = len(vals), freq = 'Q'))

exogx = np.array(range(1,14))
fit2 = sm.tsa.ARIMA(df, (0,0,0),exog = exogx).fit()
print(fit2.fittedvalues)
pred2 = fit2.predict(start = 12, end = 16, exog = np.array(range(13,17))*10000)
print(pred2)

ContentLicense: CC BY-SA 4.0


问:
AngularJS don't trigger outer click event (nested ng-click)
```<code><ul>
    <li ng-init="hide1={state1:true}" ng-repeat="(id,name) in tree_root_list" ng-click="click_e_s_0(id,hide1)">
        {$ name[1] $}
        <ul ng-hide=hide1.state1>
            <li ng-init="hide2={state2:true}" ng-repeat="id in e_s_1" ng-click="click_e_s_1(hide2)">
                 {$ id $}
            </li>
        </ul>
    </li>
</ul>
</code>```

When I trigger the click_e_s_1(hide2) event, Angular calls the click_e_s_0(id,hide1) event.

Actually I don't want to trigger click_e_s_0(id,hide1) event.

答:
Use </p>

```<code>ng-click="click_e_s_1(hide2, $event)"
</code>```

<p>and in the click_e_s_1 function, use </p>

```<code>$event.stopPropagation();
</code>```

Body:
        {$ name[1] $}

                 {$ id $}

When I trigger the click_e_s_1(hide2) event, Angular calls the click_e_s_0(id,hide1) event.

Actually I don't want to trigger click_e_s_0(id,hide1) event.

Body:
Use

ng-click="click_e_s_1(hide2, $event)"

and in the click_e_s_1 function, use

$event.stopPropagation();


问:
no provider for BarcodeScanner
The code is as follows:

```

    import { Component } from '@angular/core';
    import { NavController, Platform } from 'ionic-angular';
    import { TranslateService } from '@ngx-translate/core';
    import { BarcodeScanner } from '@ionic-native/barcode-scanner';

    @Component({
        selector: 'page-home',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor(public navCtrl: NavController, private translate: TranslateService, private barcodeScanner: BarcodeScanner) {

        }
        //Switch language
       changelanguage() {
            let browserLang = this.translate.currentLang;
            this.translate.use(browserLang.match(/en/) ? 'zh' : 'en');
        }
        //Scan test
        ScanCode() {
            this.barcodeScanner.scan()
                .then((result) => {
                    console.log(result);
                })
                .catch((error) => {
                    alert(error);
                });
        }
    }

```

Error Picture:

Reference：https://ionicframework.com/docs/native/barcode-scanner/

new questions arose:

According to Suraj recommendations, the prompt "plugin_not_installed"

Error Picture:

development environment:
Visual Studio 2017

答:
You need to set the scanner as provider in app.module.ts

```<code>import { BarcodeScanner } from '@ionic-native/barcode-scanner';

@NgModule({
  ...

  providers: [
    ...
    BarcodeScanner
    ...
  ]
  ...
})
export class AppModule { }
</code>```

Reference: Add Plugins to Your App's Module here

UPDATE:
From your package.json it looks like you have installed older ionic-native - 2.4.1.Remove it and do:

```<code>npm install --save @ionic-native/core
</code>```

Title: no provider for BarcodeScanner

Body:
The code is as follows:

    import { Component } from '@angular/core';
    import { NavController, Platform } from 'ionic-angular';
    import { TranslateService } from '@ngx-translate/core';
    import { BarcodeScanner } from '@ionic-native/barcode-scanner';

    @Component({
        selector: 'page-home',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor(public navCtrl: NavController, private translate: TranslateService, private barcodeScanner: BarcodeScanner) {

        }
        //Switch language
       changelanguage() {
            let browserLang = this.translate.currentLang;
            this.translate.use(browserLang.match(/en/) ? 'zh' : 'en');
        }
        //Scan test
        ScanCode() {
            this.barcodeScanner.scan()
                .then((result) => {
                    console.log(result);
                })
                .catch((error) => {
                    alert(error);
                });
        }
    }

Error Picture:

Reference：https://ionicframework.com/docs/native/barcode-scanner/

new questions arose:

According to Suraj recommendations, the prompt "plugin_not_installed"

Error Picture:

development environment:
Visual Studio 2017

Body:
You need to set the scanner as provider in app.module.ts

import { BarcodeScanner } from '@ionic-native/barcode-scanner';

@NgModule({
  ...

  providers: [
    ...
    BarcodeScanner
    ...
  ]
  ...
})
export class AppModule { }

Reference: Add Plugins to Your App's Module here

UPDATE:
From your package.json it looks like you have installed older ionic-native - 2.4.1.Remove it and do:

npm install --save @ionic-native/core


问:
Prime NG Data Table Underscore Issue
I am utilising the PrimeNG DataTable UIcomponent on one of my websites. I am making use of the row grouping functionality http://www.primefaces.org/primeng/#/datatable/rowgroup

On the whole everything is working well except for that a rouge underscore (_) is getting placed in front of each of the group headings. E.g using the examples they provide in the link above, rather than the grouping on brand been Audi, BMW etc it is _Audi, _BMW.

I have even tried copying their examples like for like and I still get an underscore placed in front of the grouping text. So for example:

```<code><p-dataTable [value]="cars1" sortField="brand" rowGroupMode="subheader" groupField="brand" expandableRowGroups="true"
        [sortableRowGroup]="false">
    <p-header>Toggleable Row Groups with Footers</p-header>
    <template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</template>
    <p-column field="color" header="Color"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="price" header="Price">
        <template let-col let-car="rowData" pTemplate="body">
            <span>{{car[col.field] | currency:'USD':true:'.0-0'}}</span>
        </template>
    </p-column>
    <template pTemplate="rowgroupfooter" let-car>
        <td colspan="3" style="text-align:right">Total Price</td>
        <td>{{calculateGroupTotal(car['brand']) | currency:'USD':true:'.0-0' }}</td>
    </template>
</p-dataTable>
</code>```

And the data: -

```<code>cars1 = [
{ "brand": "VW", "year": 2012, "color": "White", "vin": "dsad231ff" },
{ "brand": "Audi", "year": 2011, "color": "Black", "vin": "gwregre345" },
{ "brand": "Renault", "year": 2005, "color": "Gray", "vin": "h354htr" },
{ "brand": "BMW", "year": 2003, "color": "Blue", "vin": "j6w54qgh" },
{ "brand": "Mercedes", "year": 1995, "color": "White", "vin": "hrtwy34" },
{ "brand": "Volvo", "year": 2005, "color": "Black", "vin": "jejtyj" },
{ "brand": "Honda", "year": 2012, "color": "Yellow", "vin": "g43gr" },
{ "brand": "Jaguar", "year": 2013, "color": "White", "vin": "greg34" },
{ "brand": "Ford", "year": 2000, "color": "Black", "vin": "h54hw5" },
{ "brand": "Fiat", "year": 2013, "color": "Red", "vin": "245t2s" }
</code>```

];

Displays

Any ideas why this might be happening?

答:
Optimus gave a solutión in his forum

You need to add this CSS:

```<code>.ui-datatable a { text-decoration: none !important;}
</code>```

Title: Prime NG Data Table Underscore Issue

Body:
I am utilising the PrimeNG DataTable UIcomponent on one of my websites. I am making use of the row grouping functionality http://www.primefaces.org/primeng/#/datatable/rowgroup

On the whole everything is working well except for that a rouge underscore (_) is getting placed in front of each of the group headings. E.g using the examples they provide in the link above, rather than the grouping on brand been Audi, BMW etc it is _Audi, _BMW.

I have even tried copying their examples like for like and I still get an underscore placed in front of the grouping text. So for example:

Toggleable Row Groups with Footers

    <template pTemplate="rowgroupheader" let-rowData>{{rowData['brand']}}</template>

        <template let-col let-car="rowData" pTemplate="body">
            {{car[col.field] | currency:'USD':true:'.0-0'}}
        </template>

    <template pTemplate="rowgroupfooter" let-car>
        Total Price
        {{calculateGroupTotal(car['brand']) | currency:'USD':true:'.0-0' }}
    </template>

And the data: -

cars1 = [
{ "brand": "VW", "year": 2012, "color": "White", "vin": "dsad231ff" },
{ "brand": "Audi", "year": 2011, "color": "Black", "vin": "gwregre345" },
{ "brand": "Renault", "year": 2005, "color": "Gray", "vin": "h354htr" },
{ "brand": "BMW", "year": 2003, "color": "Blue", "vin": "j6w54qgh" },
{ "brand": "Mercedes", "year": 1995, "color": "White", "vin": "hrtwy34" },
{ "brand": "Volvo", "year": 2005, "color": "Black", "vin": "jejtyj" },
{ "brand": "Honda", "year": 2012, "color": "Yellow", "vin": "g43gr" },
{ "brand": "Jaguar", "year": 2013, "color": "White", "vin": "greg34" },
{ "brand": "Ford", "year": 2000, "color": "Black", "vin": "h54hw5" },
{ "brand": "Fiat", "year": 2013, "color": "Red", "vin": "245t2s" }

];

Displays

Any ideas why this might be happening?

Body:
Optimus gave a solutión in his forum

You need to add this CSS:

.ui-datatable a { text-decoration: none !important;}


问:
Exception in Collection.php line 1527: Property [id] does not exist on this collection instance
i m getting error
Exception in Collection.php line 1527: Property [id] does not exist on this collection instance.</p>

```<code>public function index()
    {
        $response=array();
        $data = MyList::all();
        $response['id']=$data->id;
        $response['name']=$data->name;
        $response['password']=$data->password;
        $response['city']=$data->city;
        return ResponseClass::prepareResponse(
                    $response,
                    'success',
                    ''
                );
    }
</code>```

答:
A collection doesn't have an ID, objects in this collection have IDs. So, you need to use foreach to iterate over the data. But in this case it's redundant, just do something like this:

```<code>public function index()
{
    return ResponseClass::prepareResponse(MyList::all(), 'success');
}
</code>```

Body:
i m getting error
Exception in Collection.php line 1527: Property [id] does not exist on this collection instance.

public function index()
    {
        $response=array();
        $data = MyList::all();
        $response['id']=$data->id;
        $response['name']=$data->name;
        $response['password']=$data->password;
        $response['city']=$data->city;
        return ResponseClass::prepareResponse(
                    $response,
                    'success',
                    ''
                );
    }

Body:
A collection doesn't have an ID, objects in this collection have IDs. So, you need to use foreach to iterate over the data. But in this case it's redundant, just do something like this:

public function index()
{
    return ResponseClass::prepareResponse(MyList::all(), 'success');
}


问:
Jagged and choppy Google webfonts in Chrome and Firefox on Windows
I am using google webfonts and have come accross an issue with jagged and choppy font rendering in FF and chrome (IE11 renders them better).

Example can be found here: http://jsfiddle.net/PNYfR/

```<code><link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,700&subset=latin">
<p style="font-family: 'Exo', serif; font-weight: 400; font-style:normal; font-size:31px; color:white; background-color: #0085B2; line-heigth:1.42857; padding:100px">
Open Sans is a humanist sans serif typeface designed by Steve Matteson, Type Director of Ascender Corp. This version contains the complete 897
</p>
</code>```

I've read related questions, but any of them don't offer simple solutions for quick projects:

Google webfonts render choppy in Chrome on Windows

Well rendered webfont solution

Google webfonts and windows xp

To complicate a bit more, our designer is using Mac, which renders fonts correctly.

Questions:

Is there a list of google webfonts which render OK?

Or is there a quick step by step solution on how to get fonts render correctly?

And last, is there an alternative free webfont provider, which serves fonts OK?

答:
Just go reset all flags in Chrome. Type in chrome://flags in the URL address bar and click on the Reset All Flags to default button. That should be on the right hand side of the settings page. It worked for me. If it does not for you, you may try enabling the Aero visual settings of your computer (only if disabled) then reset the flags. If resolved, you may then switch off the aero visuals.

To access the aero visual settings in Win7, go to My Computer properties > Advanced system settings > System Properties > Advanced tab > Performance (Settings). From there, toggle the current setting back to 'Adjust for best appearance (it should check all boxes under it). After resetting all flags and the fonts are back to normal, you may choose to toggle it back to Adjust for best performance. That essentially unchecks all visual options.

Thanks,

Dong

Body:
I am using google webfonts and have come accross an issue with jagged and choppy font rendering in FF and chrome (IE11 renders them better).

Example can be found here: http://jsfiddle.net/PNYfR/

<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,700&subset=latin">

Open Sans is a humanist sans serif typeface designed by Steve Matteson, Type Director of Ascender Corp. This version contains the complete 897

I've read related questions, but any of them don't offer simple solutions for quick projects:

Google webfonts render choppy in Chrome on Windows

Well rendered webfont solution

Google webfonts and windows xp

To complicate a bit more, our designer is using Mac, which renders fonts correctly.

Questions:

Is there a list of google webfonts which render OK?

Or is there a quick step by step solution on how to get fonts render correctly?

And last, is there an alternative free webfont provider, which serves fonts OK?


问:
Remove number from large string in specific position [PHP RegEx]
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

```<code>$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}
</code>```

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!

答:
```<code>$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';
$lDelim = ' sjdhfklsjaf<?kjnsdfh';
$rDelim = 'uihrfkjsn+%5Bmlknsadlfjncas ';
$start = strpos($sTestData, $lDelim) + strlen($lDelim);
$length = strpos($sTestData, $rDelim) - $start;
$number = substr($sTestData, $start, $length);
</code>```

Body:
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!


问:
How to extract numerator from fraction in SQL server?
I have a fraction like 15/3 stored in varchar. I want to extract numerator(15) in sql server. How can i do it?

答:
Try this:

```<code>declare @str varchar(max) = '15/3'

select left(@str, charindex('/', @str)-1)
</code>```

CHARINDEX locates the index of / character, LEFT uses this index in order to extract the numerator.

Demo here

Body:
Try this:

declare @str varchar(max) = '15/3'

select left(@str, charindex('/', @str)-1)

CHARINDEX locates the index of / character, LEFT uses this index in order to extract the numerator.

Demo here