问:
Different Base64 String of same image in JS and Java
I´m working on a webapp running on Apache Tomcat. This webapp creates an image from camera and sends it base64 encoded to a Servlet. The servlet then should save that image. Everything works fine, except the fact that the image shows up incomplete when I open it. I have compared the base64 String and noticed, that there are differences between the string sent and the string which is printed by Java. Do you have any idea where these differences might come from?

The differences are as follows:
- The Java String is longer
- The first ~7610 bytes are equal
- After the ~7610th byte, the Strings differ

```<code>private Path saveAsFile(InputStream stream) throws IOException {
    byte[] bytes = new byte[1024];
    String base64String = "";
    while (stream.read(bytes) != -1) {
        String tmp = new String(bytes, StandardCharsets.UTF_8);
        base64String += tmp;
    }
    //this prints out a longer base64 String than the Javascript part
    System.out.println(base64String);
    String replaced = base64String.replaceFirst("data:image/png;base64,", "");

    byte[] replacedbytes = Base64.decodeBase64(replaced);

    Path temp = Files.createTempFile("photo", ".png");
    FileOutputStream fos = new FileOutputStream(temp.toFile());
    fos.write(replacedbytes);
    return temp;
}
</code>```

Thanks in advance!

答:
This :

```<code>byte[] bytes = new byte[1024];
String base64String = "";
while (stream.read(bytes) != -1) {
    String tmp = new String(bytes, StandardCharsets.UTF_8);
    base64String += tmp;
}
</code>```

Is not a valid way to read a stream in java. (Basically, you must take into account the value returned by stream.read() as the number of bytes that are actually valid in the buffer, and use new String(bytes, 0, theAboveValue, charset) as the string constructor.

On top of this, you do not properly close the FileOutputStream.

But even so, there are other issues here (decoding the charset before concatenating stream is probably a bug waiting to happen here - but that will work because base64 is actually pure ASCII and no multi-bytes characters will cause a bug here. Pure luck).

Cleaning the IO part of the code, it should rather look like :

```<code>private Path saveAsFile(InputStream stream) throws IOException {
byte[] bytes = new byte[1024];
int readBytes = 0;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((readBytes = stream.read(bytes)) != -1) {
    buffer.write(bytes, 0, readBytes);
}

//this prints out a longer base64 String than the Javascript part
String base64String = new String(buffer.getBytes, "US-ASCII");
String replaced = base64String.replaceFirst("data:image/png;base64,", "");
byte[] replacedbytes = Base64.decodeBase64(replaced);

Path temp = Files.createTempFile("photo", ".png");
FileOutputStream fos = new FileOutputStream(temp.toFile());
fos.write(replacedbytes);
fos.close();// You should not miss that too! And put it in a "finally" step not to leak file descriptors.
return temp;
</code>```

}

This probably works better, but is inneficient as far as memory consumption goes (transforming bytes to String back to bytes, copying at each step!).

There is a better way !
You'd probably be even better of using libraries to do such copying. Apache Commons IO and Commons Codec have nice Base64InputStream and IOUtils.copy classes that could be of help here.

In which case, it could read :

```<code>private Path saveAsFile(InputStream stream) throws IOException {
    // Maybe you should advance the stream to skip the "data/image stuff"...
   //stream.skip(theActualNumberOfBytesToSkip);
    try (Base64InputStream decoded = new Base64InputStream(stream); FileOutputStream file = /*whatever*/) {
        IOUtils.copy(decoded, file);
    }
}
</code>```

Body:
I´m working on a webapp running on Apache Tomcat. This webapp creates an image from camera and sends it base64 encoded to a Servlet. The servlet then should save that image. Everything works fine, except the fact that the image shows up incomplete when I open it. I have compared the base64 String and noticed, that there are differences between the string sent and the string which is printed by Java. Do you have any idea where these differences might come from?

The differences are as follows:
- The Java String is longer
- The first ~7610 bytes are equal
- After the ~7610th byte, the Strings differ

private Path saveAsFile(InputStream stream) throws IOException {
    byte[] bytes = new byte[1024];
    String base64String = "";
    while (stream.read(bytes) != -1) {
        String tmp = new String(bytes, StandardCharsets.UTF_8);
        base64String += tmp;
    }
    //this prints out a longer base64 String than the Javascript part
    System.out.println(base64String);
    String replaced = base64String.replaceFirst("data:image/png;base64,", "");

    byte[] replacedbytes = Base64.decodeBase64(replaced);

    Path temp = Files.createTempFile("photo", ".png");
    FileOutputStream fos = new FileOutputStream(temp.toFile());
    fos.write(replacedbytes);
    return temp;
}

Thanks in advance!

Body:
This :

byte[] bytes = new byte[1024];
String base64String = "";
while (stream.read(bytes) != -1) {
    String tmp = new String(bytes, StandardCharsets.UTF_8);
    base64String += tmp;
}

Is not a valid way to read a stream in java. (Basically, you must take into account the value returned by stream.read() as the number of bytes that are actually valid in the buffer, and use new String(bytes, 0, theAboveValue, charset) as the string constructor.

On top of this, you do not properly close the FileOutputStream.

But even so, there are other issues here (decoding the charset before concatenating stream is probably a bug waiting to happen here - but that will work because base64 is actually pure ASCII and no multi-bytes characters will cause a bug here. Pure luck).

Cleaning the IO part of the code, it should rather look like :

private Path saveAsFile(InputStream stream) throws IOException {
byte[] bytes = new byte[1024];
int readBytes = 0;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((readBytes = stream.read(bytes)) != -1) {
    buffer.write(bytes, 0, readBytes);
}

//this prints out a longer base64 String than the Javascript part
String base64String = new String(buffer.getBytes, "US-ASCII");
String replaced = base64String.replaceFirst("data:image/png;base64,", "");
byte[] replacedbytes = Base64.decodeBase64(replaced);

Path temp = Files.createTempFile("photo", ".png");
FileOutputStream fos = new FileOutputStream(temp.toFile());
fos.write(replacedbytes);
fos.close();// You should not miss that too! And put it in a "finally" step not to leak file descriptors.
return temp;

}

This probably works better, but is inneficient as far as memory consumption goes (transforming bytes to String back to bytes, copying at each step!).

There is a better way !
You'd probably be even better of using libraries to do such copying. Apache Commons IO and Commons Codec have nice Base64InputStream and IOUtils.copy classes that could be of help here.

In which case, it could read :

private Path saveAsFile(InputStream stream) throws IOException {
    // Maybe you should advance the stream to skip the "data/image stuff"...
   //stream.skip(theActualNumberOfBytesToSkip);
    try (Base64InputStream decoded = new Base64InputStream(stream); FileOutputStream file = /*whatever*/) {
        IOUtils.copy(decoded, file);
    }
}


来源: stackexchange

问:
Listbox selection produces Cannot Animate Immutable Object error
I have a WPF 4 application. It contains 2 listboxes.

The first has a list of available matches. when a match is selected the selection is used as the DataContext for a details grid displaying details of the match. Additionally a storyboard is played and the 2nd Listbox comes into view displaying the available markets.

This all works fine.

Problem is when a market is selected from the 2nd listbox the app crashes and I get :

InvalidOperationException was
unhandled

Cannot animate '(0).(1)' on
an immutable object instance

I don't know why this is happening since the Markets Listbox doesn't try to play any animation. Could it be interfering with the selection from the match list??
I tried resetting the details datacontext when a selection is made in the MarketsList but that didnt work.

Here's the xaml for the two ListBoxes

```<code>       <StackPanel x:Name="Connected" Grid.Column="1" Grid.Row="1" Visibility="Collapsed">
            <ListBox x:Name="ListBoxMatches" HorizontalAlignment="Left" VerticalAlignment="Center" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}" ItemTemplate="{DynamicResource MatchesDataTemplate}" SelectionChanged="ListBoxMatches_SelectionChanged" />
        </StackPanel>

        <Border x:Name="border1" BorderBrush="White" BorderThickness="1" Grid.Row="1" CornerRadius="20" Padding="15" Margin="-400,0,400,0">
            <StackPanel x:Name="Markets">
                <ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" />
            </StackPanel>
        </Border>
</code>```

This is the code for the SelectionChanged event for the ListBoxMatches:

```<code> private void ListBoxMatches_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListBoxMatches.SelectedIndex != -1)
            {
                var selectedMatch = (Match)ListBoxMatches.SelectedItem;
                if (MatchData.DataContext == null)
                {
                    MatchData.DataContext = selectedMatch;
                    Storyboard PlayMatch = (Storyboard)FindResource("MatchSelected");
                    BeginStoryboard(PlayMatch);
                }
                else if (MatchData.DataContext != selectedMatch)
                {
                    MatchData.DataContext = selectedMatch;
                }
            }
        }
</code>```

If you need anymore code(like the storyboard xaml) please let me know.

If anyone knows why and whats going on please help.

Thanks

UPDATE

I made the change recommended by Daniel but I must have done something wrong as it's not working.
This is the code just where I set the items source:

```<code> List<Market> TestList = new List<Market>();
                Market market = new Market { ID = 0, MarketName = "CorrectScore" };
                TestList.Add(market);
                market = new Market { ID = 1, MarketName = "Match Odds" };
                TestList.Add(market);
                ListBoxCurrentMarkets.ItemsSource = TestList;
</code>```

This is the xaml for the listbox

```<code><ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock x:Name="Market" Foreground="Black" TextWrapping="Wrap" Text="{Binding MarketName, Converter={x:Static local:MyCloneConverter.Instance}}" />
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
</code>```

and this is the CloneConverter:

```<code>public class MyCloneConverter : IValueConverter
    {
        public static MyCloneConverter Instance = new MyCloneConverter();

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Freezable)
            {
                value = (value as Freezable).Clone();
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

    }
</code>```

Please take a look and tell me what you think? I put a breakpoint in the valueconverter and it's not getting hit. Also the item's in the listbox are showing up it's only when a selection is made that the error occurs.
Thanks

UPDATE

This is the xaml for the animation. The animation moves 2 negatively margined borders into positive margin(ie from out of screen into screen). There is a border which contains MatchDetails(textblocks databound to a Match), the one in question is a Border which contains the available markets ListBox.

```<code><Storyboard x:Key="MatchSelected">
            <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="borderMatchData">
                <EasingThicknessKeyFrame KeyTime="0" Value="0,-400,0,400"/>
                <EasingThicknessKeyFrame KeyTime="0:0:1" Value="0"/>
            </ThicknessAnimationUsingKeyFrames>
            <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="borderMarkets">
                <EasingThicknessKeyFrame KeyTime="0" Value="-400,0,400,0"/>
                <EasingThicknessKeyFrame KeyTime="0:0:1" Value="0"/>
            </ThicknessAnimationUsingKeyFrames>
        </Storyboard>
</code>```

This is the code for playing the storyboard from the selectionchanged event for the MatchesListBox:

```<code>MatchData.DataContext = selectedMatch;
                    Storyboard PlayMatch = (Storyboard)FindResource("MatchSelected");
                    BeginStoryboard(PlayMatch);
</code>```

This is the xaml for the BorderMArkets:

```<code><Border x:Name="borderMarkets" BorderBrush="White" BorderThickness="1" Grid.Row="1" CornerRadius="20" Padding="15" Margin="-400,0,400,0">
            <StackPanel x:Name="Markets">
                <ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock x:Name="Market" Foreground="Black" TextWrapping="Wrap" Text="{Binding MarketName, Converter={StaticResource CloneConverter}}" />
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </Border>
</code>```

UPDATE

This is the template that was causing all the problems(I think)

```<code><ControlTemplate x:Key="ListBoxItemControlTemplate1" TargetType="{x:Type ListBoxItem}">
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" Background="#FF807F7F">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal"/>
                    <VisualState x:Name="MouseOver">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FF3D3B3B"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="Disabled"/>
                </VisualStateGroup>
                <VisualStateGroup x:Name="SelectionStates">
                    <VisualState x:Name="Unselected"/>
                    <VisualState x:Name="Selected">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFA71616"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="SelectedUnfocused">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFA71616"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                </VisualStateGroup>
                <VisualStateGroup x:Name="FocusStates">
                    <VisualState x:Name="Unfocused"/>
                    <VisualState x:Name="Focused">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FF18E526"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsSelected" Value="true">
                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsSelected" Value="true"/>
                    <Condition Property="Selector.IsSelectionActive" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            </MultiTrigger>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</code>```

答:
See http://blogs.msdn.com/b/mikehillberg/archive/2006/09/26/cannotanimateimmutableobjectinstance.aspx

Basically, this happens if you animate a databound property.

ContentLicense: CC BY-SA 3.0

Body:
I have a WPF 4 application. It contains 2 listboxes.

The first has a list of available matches. when a match is selected the selection is used as the DataContext for a details grid displaying details of the match. Additionally a storyboard is played and the 2nd Listbox comes into view displaying the available markets.

This all works fine.

Problem is when a market is selected from the 2nd listbox the app crashes and I get :

InvalidOperationException was
unhandled

Cannot animate '(0).(1)' on
an immutable object instance

I don't know why this is happening since the Markets Listbox doesn't try to play any animation. Could it be interfering with the selection from the match list??
I tried resetting the details datacontext when a selection is made in the MarketsList but that didnt work.

Here's the xaml for the two ListBoxes

       <StackPanel x:Name="Connected" Grid.Column="1" Grid.Row="1" Visibility="Collapsed">
            <ListBox x:Name="ListBoxMatches" HorizontalAlignment="Left" VerticalAlignment="Center" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}" ItemTemplate="{DynamicResource MatchesDataTemplate}" SelectionChanged="ListBoxMatches_SelectionChanged" />
        </StackPanel>

        <Border x:Name="border1" BorderBrush="White" BorderThickness="1" Grid.Row="1" CornerRadius="20" Padding="15" Margin="-400,0,400,0">
            <StackPanel x:Name="Markets">
                <ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" />
            </StackPanel>
        </Border>

This is the code for the SelectionChanged event for the ListBoxMatches:

 private void ListBoxMatches_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListBoxMatches.SelectedIndex != -1)
            {
                var selectedMatch = (Match)ListBoxMatches.SelectedItem;
                if (MatchData.DataContext == null)
                {
                    MatchData.DataContext = selectedMatch;
                    Storyboard PlayMatch = (Storyboard)FindResource("MatchSelected");
                    BeginStoryboard(PlayMatch);
                }
                else if (MatchData.DataContext != selectedMatch)
                {
                    MatchData.DataContext = selectedMatch;
                }
            }
        }

If you need anymore code(like the storyboard xaml) please let me know.

If anyone knows why and whats going on please help.

Thanks

UPDATE

I made the change recommended by Daniel but I must have done something wrong as it's not working.
This is the code just where I set the items source:

 List<Market> TestList = new List<Market>();
                Market market = new Market { ID = 0, MarketName = "CorrectScore" };
                TestList.Add(market);
                market = new Market { ID = 1, MarketName = "Match Odds" };
                TestList.Add(market);
                ListBoxCurrentMarkets.ItemsSource = TestList;

This is the xaml for the listbox

<ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock x:Name="Market" Foreground="Black" TextWrapping="Wrap" Text="{Binding MarketName, Converter={x:Static local:MyCloneConverter.Instance}}" />
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

and this is the CloneConverter:

public class MyCloneConverter : IValueConverter
    {
        public static MyCloneConverter Instance = new MyCloneConverter();

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Freezable)
            {
                value = (value as Freezable).Clone();
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

    }

Please take a look and tell me what you think? I put a breakpoint in the valueconverter and it's not getting hit. Also the item's in the listbox are showing up it's only when a selection is made that the error occurs.
Thanks

UPDATE

This is the xaml for the animation. The animation moves 2 negatively margined borders into positive margin(ie from out of screen into screen). There is a border which contains MatchDetails(textblocks databound to a Match), the one in question is a Border which contains the available markets ListBox.

<Storyboard x:Key="MatchSelected">
            <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="borderMatchData">
                <EasingThicknessKeyFrame KeyTime="0" Value="0,-400,0,400"/>
                <EasingThicknessKeyFrame KeyTime="0:0:1" Value="0"/>
            </ThicknessAnimationUsingKeyFrames>
            <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="borderMarkets">
                <EasingThicknessKeyFrame KeyTime="0" Value="-400,0,400,0"/>
                <EasingThicknessKeyFrame KeyTime="0:0:1" Value="0"/>
            </ThicknessAnimationUsingKeyFrames>
        </Storyboard>

This is the code for playing the storyboard from the selectionchanged event for the MatchesListBox:

MatchData.DataContext = selectedMatch;
                    Storyboard PlayMatch = (Storyboard)FindResource("MatchSelected");
                    BeginStoryboard(PlayMatch);

This is the xaml for the BorderMArkets:

<Border x:Name="borderMarkets" BorderBrush="White" BorderThickness="1" Grid.Row="1" CornerRadius="20" Padding="15" Margin="-400,0,400,0">
            <StackPanel x:Name="Markets">
                <ListBox x:Name="ListBoxCurrentMarkets" SelectionChanged="ListBoxCurrentMarkets_SelectionChanged" ItemContainerStyle="{DynamicResource ListBoxItemContainerStyle1}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock x:Name="Market" Foreground="Black" TextWrapping="Wrap" Text="{Binding MarketName, Converter={StaticResource CloneConverter}}" />
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </Border>

UPDATE

This is the template that was causing all the problems(I think)

<ControlTemplate x:Key="ListBoxItemControlTemplate1" TargetType="{x:Type ListBoxItem}">
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" Background="#FF807F7F">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal"/>
                    <VisualState x:Name="MouseOver">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FF3D3B3B"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="Disabled"/>
                </VisualStateGroup>
                <VisualStateGroup x:Name="SelectionStates">
                    <VisualState x:Name="Unselected"/>
                    <VisualState x:Name="Selected">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFA71616"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="SelectedUnfocused">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FFA71616"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                </VisualStateGroup>
                <VisualStateGroup x:Name="FocusStates">
                    <VisualState x:Name="Unfocused"/>
                    <VisualState x:Name="Focused">
                        <Storyboard>
                            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                <EasingColorKeyFrame KeyTime="0" Value="#FF18E526"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsSelected" Value="true">
                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsSelected" Value="true"/>
                    <Condition Property="Selector.IsSelectionActive" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            </MultiTrigger>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

ContentLicense: CC BY-SA 2.5


问:
Play youtube video without controls in WPF
I need to play a youtube video inside WPF as a ScreenSaver. That is why I have to disable all controls and auto-play it.

additionally need an information when the video have ended.

Any help ? :)

答:
You can use that code and follow the tutorial at this link. (Sadly not in english, you can use a translator.)</p>

```<code>private void YouTube_Load(object sender, EventArgs e)
{
   axShockwaveFlash1.Movie = "http://www.youtube.com/v/xYRSt-bJggc";
}
</code>```

Body:
You can use that code and follow the tutorial at this link. (Sadly not in english, you can use a translator.)

private void YouTube_Load(object sender, EventArgs e)
{
   axShockwaveFlash1.Movie = "http://www.youtube.com/v/xYRSt-bJggc";
}


问:
Comparing two PorterDuffColorFilter objects
I am in need of comparing two PorterDuffColorFilter objects to check if a ProgressBar is displaying the correct color in an Espresso Test

I have tried comparing the two objects directly, but the following method always returns false:

```<code>// Creating a PorterDuffColorFilter Object
weakOrNonePasswordColorFilter =
            new PorterDuffColorFilter(ContextCompat.getColor(mActivityRule.getActivity(), R.color.red), PorterDuff.Mode.SRC_IN);
...

// Retrieving the ProgressBar ColorFilter and compare
public boolean matchesSafely(ProgressBar progressBar, PorterDuffColorFilter colorFilter) {
  LayerDrawable drawable = (LayerDrawable) progressBar.getProgressDrawable();
  Drawable progressDrawable = drawable.getDrawable(1);
  progressDrawable.setColorFilter(colorFilter);
  return ((PorterDuffColorFilter)progressDrawable.getColorFilter()).equals(colorFilter);
}
</code>```

Looking into the PorterDuffColorFilter there is a

```<code>public int getColor() {
    return mColor;
}
</code>```

Method that should solve my problem. However, I cannot access this method. Android Studio only displays the "Object" methods, and if I try to compile the app with the .getColor() an error message is displayed stating that the method could not be found.

Is this problem occurring due to the fact that this class is in android.graphics package, making it inaccessible?

If so, how can I retrieve the color of the ProgressBar bar and compare it with a Color?

答:
PorterDuffColorFilter overrides equals so you should be able to use: filterA.equals(filterB)

```<code>// From PorterDuffColorFilter.java

@Override
public boolean equals(Object object) {
    if (this == object) {
        return true;
    }
    if (object == null || getClass() != object.getClass()) {
        return false;
    }
    final PorterDuffColorFilter other = (PorterDuffColorFilter) object;
    return (mColor == other.mColor && mMode.nativeInt == other.mMode.nativeInt);
}
</code>```

Body:
I am in need of comparing two PorterDuffColorFilter objects to check if a ProgressBar is displaying the correct color in an Espresso Test

I have tried comparing the two objects directly, but the following method always returns false:

// Creating a PorterDuffColorFilter Object
weakOrNonePasswordColorFilter =
            new PorterDuffColorFilter(ContextCompat.getColor(mActivityRule.getActivity(), R.color.red), PorterDuff.Mode.SRC_IN);
...

// Retrieving the ProgressBar ColorFilter and compare
public boolean matchesSafely(ProgressBar progressBar, PorterDuffColorFilter colorFilter) {
  LayerDrawable drawable = (LayerDrawable) progressBar.getProgressDrawable();
  Drawable progressDrawable = drawable.getDrawable(1);
  progressDrawable.setColorFilter(colorFilter);
  return ((PorterDuffColorFilter)progressDrawable.getColorFilter()).equals(colorFilter);
}

Looking into the PorterDuffColorFilter there is a

public int getColor() {
    return mColor;
}

Method that should solve my problem. However, I cannot access this method. Android Studio only displays the "Object" methods, and if I try to compile the app with the .getColor() an error message is displayed stating that the method could not be found.

Is this problem occurring due to the fact that this class is in android.graphics package, making it inaccessible?

If so, how can I retrieve the color of the ProgressBar bar and compare it with a Color?

Body:
PorterDuffColorFilter overrides equals so you should be able to use: filterA.equals(filterB)

// From PorterDuffColorFilter.java

@Override
public boolean equals(Object object) {
    if (this == object) {
        return true;
    }
    if (object == null || getClass() != object.getClass()) {
        return false;
    }
    final PorterDuffColorFilter other = (PorterDuffColorFilter) object;
    return (mColor == other.mColor && mMode.nativeInt == other.mMode.nativeInt);
}


问:
java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()
I faced with a problem, was google it for a half of this day. Nothing could help me. It was working. But after that something has happened and i didn't capture that.

Here are TomCat Catalina Log

```<code>31-Jan-2016 00:35:27.278 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000412: Hibernate Core {5.0.7.Final}
31-Jan-2016 00:35:27.282 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=update}
31-Jan-2016 00:35:27.283 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000021: Bytecode provider name : javassist
31-Jan-2016 00:35:27.376 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
31-Jan-2016 00:35:28.170 INFO [RMI TCP Connection(2)-127.0.0.1] <unknown>.<unknown> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31-Jan-2016 00:35:29.632 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000228: Running hbm2ddl schema update
31-Jan-2016 00:35:30.331 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
31-Jan-2016 00:35:30.349 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
**31-Jan-2016 00:35:30.377 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [ROOT] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.**
31-Jan-2016 00:35:32.709 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager
31-Jan-2016 00:35:32.907 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager has finished in 197 ms
</code>```

Localhost Log

```<code> java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()V
    at org.springframework.context.support.AbstractApplicationContext.resetCommonCaches(AbstractApplicationContext.java:879)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:563)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1648)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$254(TCPTransport.java:683)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/2146013565.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

My DatabaseConfig

```<code>@Configuration
@EnableJpaRepositories("cards.server.repository")
@EnableTransactionManagement
@ComponentScan(value = "cards.server")
@PropertySource({
        "classpath:database.properties",
        "classpath:hibernate.properties"}
)
public class DatabaseConfig extends IOException {

    @Autowired
    private Environment env;

    @Bean(name = "entityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setJpaProperties(getHibernateProperties());
        return em;
    }

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(env.getRequiredProperty("db.url"));
        ds.setDriverClassName(env.getRequiredProperty("db.driver"));
        ds.setUsername(env.getRequiredProperty("db.username"));
        ds.setPassword(env.getRequiredProperty("db.password"));
        ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
        ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
        ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
        ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMillis")));
        ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMillis")));
        ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
        ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
        return ds;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager platformTransactionManager() {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(entityManagerFactory().getObject());
        return manager;
    }

    public Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.getProperty(env.getProperty("hibernate.dialect"));
        properties.getProperty(env.getProperty("hibernate.show_sql"));
        properties.getProperty(env.getProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cards.server</groupId>
    <artifactId>cards.server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <!-- cmd + alt + v -->
    <properties>
        <spring-core.version>4.2.2.RELEASE</spring-core.version>
        <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
        <spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
        <hibernate-entitymanager.version>5.0.7.Final</hibernate-entitymanager.version>
        <mysql-connector-java.version>5.1.38</mysql-connector-java.version>
        <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
        <jta.version>1.1</jta.version>
        <postgresql.version>9.1-901-1.jdbc4</postgresql.version>
        <junit.version>4.12</junit.version>
        <spring-webmvc.version>4.2.4.RELEASE</spring-webmvc.version>
        <spring-test.version>4.1.6.RELEASE</spring-test.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-core.version}</version>
        </dependency>
        <!-- Web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-core.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-webmvc.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet-api.version}</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>jstl</groupId>-->
            <!--<artifactId>jstl</artifactId>-->
            <!--<version>1.2</version>-->
        <!--</dependency>-->
        <!-- Database -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring-data-jpa.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate-entitymanager.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${commons-dbcp2.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>${jta.version}</version>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>postgresql</groupId>-->
            <!--<artifactId>postgresql</artifactId>-->
            <!--<version>${postgresql.version}</version>-->
        <!--</dependency>-->

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-test.version}</version>
        </dependency>

    </dependencies>

</project>
</code>```

Hoping for your help,
Thank you.

答:
I also suffered from this problem.
But,When I  changed version of spring and  JDK Version then this problem was solved.
So,it may to work out for you</p>

Body:
I faced with a problem, was google it for a half of this day. Nothing could help me. It was working. But after that something has happened and i didn't capture that.

Here are TomCat Catalina Log

31-Jan-2016 00:35:27.278 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000412: Hibernate Core {5.0.7.Final}
31-Jan-2016 00:35:27.282 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.MySQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.hbm2ddl.auto=update}
31-Jan-2016 00:35:27.283 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000021: Bytecode provider name : javassist
31-Jan-2016 00:35:27.376 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
31-Jan-2016 00:35:28.170 INFO [RMI TCP Connection(2)-127.0.0.1] <unknown>.<unknown> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31-Jan-2016 00:35:29.632 INFO [RMI TCP Connection(2)-127.0.0.1] null.null HHH000228: Running hbm2ddl schema update
31-Jan-2016 00:35:30.331 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
31-Jan-2016 00:35:30.349 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
**31-Jan-2016 00:35:30.377 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [ROOT] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.**
31-Jan-2016 00:35:32.709 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager
31-Jan-2016 00:35:32.907 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/apache-tomcat-8.0.24/webapps/manager has finished in 197 ms

Localhost Log

 java.lang.NoSuchMethodError: org.springframework.util.ReflectionUtils.clearCache()V
    at org.springframework.context.support.AbstractApplicationContext.resetCommonCaches(AbstractApplicationContext.java:879)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:563)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1648)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$254(TCPTransport.java:683)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/2146013565.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

My DatabaseConfig

@Configuration
@EnableJpaRepositories("cards.server.repository")
@EnableTransactionManagement
@ComponentScan(value = "cards.server")
@PropertySource({
        "classpath:database.properties",
        "classpath:hibernate.properties"}
)
public class DatabaseConfig extends IOException {

    @Autowired
    private Environment env;

    @Bean(name = "entityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        em.setJpaProperties(getHibernateProperties());
        return em;
    }

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(env.getRequiredProperty("db.url"));
        ds.setDriverClassName(env.getRequiredProperty("db.driver"));
        ds.setUsername(env.getRequiredProperty("db.username"));
        ds.setPassword(env.getRequiredProperty("db.password"));
        ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
        ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
        ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
        ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMillis")));
        ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMillis")));
        ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
        ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
        return ds;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager platformTransactionManager() {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(entityManagerFactory().getObject());
        return manager;
    }

    public Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.getProperty(env.getProperty("hibernate.dialect"));
        properties.getProperty(env.getProperty("hibernate.show_sql"));
        properties.getProperty(env.getProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cards.server</groupId>
    <artifactId>cards.server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring-core.version>4.2.2.RELEASE</spring-core.version>
        <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
        <spring-data-jpa.version>1.9.2.RELEASE</spring-data-jpa.version>
        <hibernate-entitymanager.version>5.0.7.Final</hibernate-entitymanager.version>
        <mysql-connector-java.version>5.1.38</mysql-connector-java.version>
        <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
        <jta.version>1.1</jta.version>
        <postgresql.version>9.1-901-1.jdbc4</postgresql.version>
        <junit.version>4.12</junit.version>
        <spring-webmvc.version>4.2.4.RELEASE</spring-webmvc.version>
        <spring-test.version>4.1.6.RELEASE</spring-test.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-core.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-core.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-webmvc.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet-api.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring-data-jpa.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate-entitymanager.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${commons-dbcp2.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>${jta.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-test.version}</version>
        </dependency>

    </dependencies>

</project>

Hoping for your help,
Thank you.


问:
How can I store an unknown number of inputs in different addresses in LMC (little-man-computer)?
I want to create a code that ask the user to input a number n, then ask for n inputs and store them all in different addresses so they can be read as instructions to be executed.

However, I'm stuck, because I don't know how to store n inputs in n different adresses. So far I am able to ask for an input n and then ask for n inputs, but they are all stored in the same address.

Here is my code:

```<code>    IN
    STO     N

loopTop
    IN
    STO NBS
    LDA N
    SUB ONE
    STO N
    BRZ done
    BR  loopTop

done

    OUT
    HLT

ONE
    DAT 001
N
    DAT 000
NBS
    DAT 000
</code>```

答:
With LMC you need to use self modifying code to update the STO instruction so that it points to a different memory address each time. We will add one to the memory location so that each time through the values stored will be in a location one higher than the previous loop.

```<code>        IN         ; Accumulator = number of values to read (N)
LOOP    BRZ PRG    ; If Accumulator (N) is 0 we are finished - execute program at PRG
        SUB ONE
        STO N      ; N=N-1
        IN         ; Get value
ST      STO PRG    ; Store it in the program starting at PRG (this changes every loop)
        LDA ST     ; Get current store command (ST)
        ADD ONE    ; add one to store command to increment memory location
        STO ST     ; Update store command (ST)
        LDA N      ; Put current value of N in accumulator
        BRA LOOP   ; Continue loop
N       DAT 0      ; Number of values to read
ONE     DAT 1      ; Value 1
PRG     DAT 0      ; We will store all of the values from this point onward
</code>```

Body:
I want to create a code that ask the user to input a number n, then ask for n inputs and store them all in different addresses so they can be read as instructions to be executed.

However, I'm stuck, because I don't know how to store n inputs in n different adresses. So far I am able to ask for an input n and then ask for n inputs, but they are all stored in the same address.

Here is my code:

    IN
    STO     N

loopTop
    IN
    STO NBS
    LDA N
    SUB ONE
    STO N
    BRZ done
    BR  loopTop

done

    OUT
    HLT

ONE
    DAT 001
N
    DAT 000
NBS
    DAT 000

Body:
With LMC you need to use self modifying code to update the STO instruction so that it points to a different memory address each time. We will add one to the memory location so that each time through the values stored will be in a location one higher than the previous loop.

        IN         ; Accumulator = number of values to read (N)
LOOP    BRZ PRG    ; If Accumulator (N) is 0 we are finished - execute program at PRG
        SUB ONE
        STO N      ; N=N-1
        IN         ; Get value
ST      STO PRG    ; Store it in the program starting at PRG (this changes every loop)
        LDA ST     ; Get current store command (ST)
        ADD ONE    ; add one to store command to increment memory location
        STO ST     ; Update store command (ST)
        LDA N      ; Put current value of N in accumulator
        BRA LOOP   ; Continue loop
N       DAT 0      ; Number of values to read
ONE     DAT 1      ; Value 1
PRG     DAT 0      ; We will store all of the values from this point onward


问:
C# Cannot access a disposed object when adding rows asynchronously to a winform datagridview
I am loading docs in a datagridview from a parallel thread using the code below:
inside a block Task.Run(() => {});

When I close the form I get ObjectDisposedException Cannot access a disposed object. Looks like the if (IsDisposed || Disposing) fails and the code attempts to add a row and in the meantime Disposing has became true.

I could catch this exception but it is dirty.

Adding a flag enabled when closing the form to check if the form has been closed does not work as well. It seems to behave the same way as this.Disposing

Adding a Thread.Sleep(5); before if (this.IsDisposed || this.Disposing) seems enough to avoid the exception to be raised though I am not sure if it could be raised if unlucky enough.

What would probably be the best practice to avoid this issue ?

```<code>  foreach (var doc in docList)
  {
     if (this.InvokeRequired)
     {
         if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing) return;
         this.Invoke(new MethodInvoker(() => { dgv.Rows.Add(doc.Name); }));
     }
  }
</code>```

答:
Have you tried adding conditions inside Invoke:</p>

```<code>if (this.InvokeRequired)
{
    this.Invoke(new MethodInvoker(() =>
    {
        foreach (var doc in docList)
        {
            if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing)  return;
            dgv.Rows.Add(doc.Name);
        }));
    }
}
</code>```

Body:
I am loading docs in a datagridview from a parallel thread using the code below:
inside a block Task.Run(() => {});

When I close the form I get ObjectDisposedException Cannot access a disposed object. Looks like the if (IsDisposed || Disposing) fails and the code attempts to add a row and in the meantime Disposing has became true.

I could catch this exception but it is dirty.

Adding a flag enabled when closing the form to check if the form has been closed does not work as well. It seems to behave the same way as this.Disposing

Adding a Thread.Sleep(5); before if (this.IsDisposed || this.Disposing) seems enough to avoid the exception to be raised though I am not sure if it could be raised if unlucky enough.

What would probably be the best practice to avoid this issue ?

  foreach (var doc in docList)
  {
     if (this.InvokeRequired)
     {
         if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing) return;
         this.Invoke(new MethodInvoker(() => { dgv.Rows.Add(doc.Name); }));
     }
  }

Body:
Have you tried adding conditions inside Invoke:

if (this.InvokeRequired)
{
    this.Invoke(new MethodInvoker(() =>
    {
        foreach (var doc in docList)
        {
            if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing)  return;
            dgv.Rows.Add(doc.Name);
        }));
    }
}


问:
How to retrieve columns data which are distinct
I need to retrieve columns of data which are having distinct values

For Ex:

```<code>Location FoodType Gender Alive
India    Veg      M      Y
India    NonVeg   M      N
</code>```

I need a query to list rows of data which are having distinct values
Expected Output Is:

```<code>FoodType Alive
Veg      Y
NonVeg   N
</code>```

Distinct and Unique may not work as i dont know what column will have distinct values.

答:
This is too long for a comment.

A SQL query has a fixed set of columns.  You cannot specify a query that has a variable number -- although you can do so using dynamic SQL.

You could get a list of distinct values within columns:

```<code>select count(distinct Location),
       count(distinct FoodType),
       count(distinct Gender),
       count(distinct Alive)
from t;
</code>```

However, this doesn't return the values in the columns.

Body:
I need to retrieve columns of data which are having distinct values

For Ex:

Location FoodType Gender Alive
India    Veg      M      Y
India    NonVeg   M      N

I need a query to list rows of data which are having distinct values
Expected Output Is:

FoodType Alive
Veg      Y
NonVeg   N

Distinct and Unique may not work as i dont know what column will have distinct values.

Body:
This is too long for a comment.

A SQL query has a fixed set of columns.  You cannot specify a query that has a variable number -- although you can do so using dynamic SQL.

You could get a list of distinct values within columns:

select count(distinct Location),
       count(distinct FoodType),
       count(distinct Gender),
       count(distinct Alive)
from t;

However, this doesn't return the values in the columns.


问:
What is the proper way of combining time series data with metadata in pandas?
I have two csv files:

customer.csv:

```<code>id  name     birthday
1   Martin   28.04.1990
2   Twain    30.11.1835
....
</code>```

and purchases.csv:

```<code>purchase_id    customer_id    item                            price
1              1              About the ugly German language  3.14
2              1              Food                            15.92
3              1              Book                            65.35
4              2              Stone                           89.79
</code>```

I can load both dataframes as

```<code>df_customers = pd.read_csv('customers.csv')
df_purchases = pd.read_csv('purchases.csv')
</code>```

but how can I combine those two, such that I can easily answer the following questions:

How many items did each customer buy?

What is the average price of items for each customer?

答:
Use merge with right join:

```<code>df = pd.merge(df_customers, df_purchases, left_on='id', right_on='customer_id', how='right')
print (df)
   purchase_id  customer_id                            item  price
0            1            1  About the ugly German language   3.14
1            2            1                            Food  15.92
2            3            1                            Book  65.35
3            4            2                           Stone  89.79
   id    name    birthday  purchase_id  customer_id  \
0   1  Martin  28.04.1990            1            1
1   1  Martin  28.04.1990            2            1
2   1  Martin  28.04.1990            3            1
3   2   Twain  30.11.1835            4            2

                             item  price
0  About the ugly German language   3.14
1                            Food  15.92
2                            Book  65.35
3                           Stone  89.79
</code>```

Body:
I have two csv files:

customer.csv:

id  name     birthday
1   Martin   28.04.1990
2   Twain    30.11.1835
....

and purchases.csv:

purchase_id    customer_id    item                            price
1              1              About the ugly German language  3.14
2              1              Food                            15.92
3              1              Book                            65.35
4              2              Stone                           89.79

I can load both dataframes as

df_customers = pd.read_csv('customers.csv')
df_purchases = pd.read_csv('purchases.csv')

but how can I combine those two, such that I can easily answer the following questions:

How many items did each customer buy?

What is the average price of items for each customer?

Body:
Use merge with right join:

df = pd.merge(df_customers, df_purchases, left_on='id', right_on='customer_id', how='right')
print (df)
   purchase_id  customer_id                            item  price
0            1            1  About the ugly German language   3.14
1            2            1                            Food  15.92
2            3            1                            Book  65.35
3            4            2                           Stone  89.79
   id    name    birthday  purchase_id  customer_id  \
0   1  Martin  28.04.1990            1            1
1   1  Martin  28.04.1990            2            1
2   1  Martin  28.04.1990            3            1
3   2   Twain  30.11.1835            4            2

                             item  price
0  About the ugly German language   3.14
1                            Food  15.92
2                            Book  65.35
3                           Stone  89.79


问:
Permissions for truncating a table
What permission do I need to GRANT a user, in MSSQL, in order to be able to truncate a table?

I'm trying to grant the minimal set of permissions, but I can't use DELETE, because the table is very large, and I want the operation to be quick.

答:
You need the ALTER permission: see the Permissions section here.

Note that you can also use a stored procedure with EXECUTE AS, so that the user running the stored procedure does not need to even be granted the ALTER permission.

Title: Permissions for truncating a table


问:
Prevent line break in header
I have an h1 with line breaks. On mobile devices, there should be no line breaks.

This code works on Chrome and iPhone but not on Firefox. So I am afraid it might not work on all devices/browsers.

(The code snippet seems to ignore the media query).

h1 {
  text-align: right;
}

@media screen and (max-width: 839px) {
 h1 {
  br {
   content: "";
   &:after {
    content: " ";
   }
  }
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This is a<br>header<br>with line breaks</h1></code>```

Note the spaces which get inserted by CSS when the header is on 1 line. And also the header should be able to align to right.
How could I make this cross-browser compatible?

答:
I ended up following the advice of Tim Medora (thanks!).
Pseudo elements on br are not crossbrowser, for example FF and iE will not respond.

I adjusted my CMS (I built a PHP viewHelper in TYPO3) which converts linebreaks to spans.

```<code>$textBreakParts = explode("\n", $text);
$convertedText = "<span>".implode('</span> <span>', $textBreakParts)."</span>";
</code>```

In SASS:

```<code>h1 span {display: block}

@media screen and (max-width: 839px) {
    h1 {
        span {
            display: inline;
        }
    }
}
</code>```

Title: Prevent line break in header

Body:
I have an h1 with line breaks. On mobile devices, there should be no line breaks.

This code works on Chrome and iPhone but not on Firefox. So I am afraid it might not work on all devices/browsers.

(The code snippet seems to ignore the media query).

h1 {
  text-align: right;
}

@media screen and (max-width: 839px) {
 h1 {
  br {
   content: "";
   &:after {
    content: " ";
   }
  }
 }
}

This is a
header
with line breaks

Note the spaces which get inserted by CSS when the header is on 1 line. And also the header should be able to align to right.
How could I make this cross-browser compatible?

Body:
I ended up following the advice of Tim Medora (thanks!).
Pseudo elements on br are not crossbrowser, for example FF and iE will not respond.

I adjusted my CMS (I built a PHP viewHelper in TYPO3) which converts linebreaks to spans.

$textBreakParts = explode("\n", $text);
$convertedText = "<span>".implode('</span> <span>', $textBreakParts)."</span>";

In SASS:

h1 span {display: block}

@media screen and (max-width: 839px) {
    h1 {
        span {
            display: inline;
        }
    }
}


问:
Sending logs to Graylog and in Gelf format
I would like to use graylog as central logging server and currently I am just using slf4j Logger "slf4j-api" as Java logging framework for logging in my java application. Can i use SLF4J to send logging to Graylog? or Which additional libraries do i need to send these logs to Graylog?</p>

答:
SLF4J is just a facade for other logging libraries.

You have to use a GELF appender for the specific logging framework (Log4j, Logback, java.util.logging, etc.) you're using in your application.

Check out the Graylog Marketplace for existing GELF appenders for Java logging frameworks:

https://marketplace.graylog.org/addons?tag=java


问:
Is there any way to react on a click on a <select> element before the menu is opened?
I have added a scrolling behaviour to a formular with Javascript: As soon as I click a form element, the page is scrolled to this element.

It works almost fine... by processing this JQuery on click of the formular elements:

```<code>$('html, body').animate({scrollTop: $(formularElement).offset().top - window.innerHeight/2 }, 500);
</code>```

When I click the select element, first the menu is shown and then the page scrolls while the select menu stays where it is.

Is there any way to process some code before the menu is shown?

Or could I maybe prevent opening the menu, then scroll and open it by code after the page scrolling has been processed?

Or is there a way to move the window the browser opens for the select element?

答:
I have included both onclick and onselect to help u distinguish; If it doesnt help u, I will remove;

document.getElementById('drop_down').onchange = changed;
document.getElementById('drop_down').onclick = clicked;

function changed() {
alert('on changed')
document.getElementById('drop_down').click();
}

function clicked(e) {
e.preventDefault();
alert('on clicked')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" id="drop_down" >
<option value="choose">Please choose</option>
<option value="option 1">option 1</option>
<option value="option 2">option 2</option>
<option value="option 3">option 3</option>
<option value="option 4">option 4</option>
</select></code>```

Body:
I have added a scrolling behaviour to a formular with Javascript: As soon as I click a form element, the page is scrolled to this element.

It works almost fine... by processing this JQuery on click of the formular elements:

$('html, body').animate({scrollTop: $(formularElement).offset().top - window.innerHeight/2 }, 500);

When I click the select element, first the menu is shown and then the page scrolls while the select menu stays where it is.

Is there any way to process some code before the menu is shown?

Or could I maybe prevent opening the menu, then scroll and open it by code after the page scrolling has been processed?

Or is there a way to move the window the browser opens for the select element?

Body:
I have included both onclick and onselect to help u distinguish; If it doesnt help u, I will remove;

document.getElementById('drop_down').onchange = changed;
document.getElementById('drop_down').onclick = clicked;

function changed() {
alert('on changed')
document.getElementById('drop_down').click();
}

function clicked(e) {
e.preventDefault();
alert('on clicked')
}

<select name="" id="drop_down" >
<option value="choose">Please choose</option>
<option value="option 1">option 1</option>
<option value="option 2">option 2</option>
<option value="option 3">option 3</option>
<option value="option 4">option 4</option>
</select>


问:
Is Web API 2 Controller thread safe? (datatables editor plugin)
I am wondering if this code is thread safe,
This is taken from datatable editor c# API
https://editor.datatables.net/manual/net/webapi

```<code>public class StaffController : ApiController
{
    [Route("api/staff")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult Staff()
    {
        var request = HttpContext.Current.Request;
        var settings = Properties.Settings.Default;

        using (var db = new Database(settings.DbType, settings.DbConnection))
        {
            var response = new Editor(Db, "staff")
                .Model<StaffModel>()
                .Process(request)
                .Data();

            return Json(response);
        }
    }
}
</code>```

What happen if few threads are entering Staff() method with an update? how it will affect the database?

EDIT
I am working with SQL database, the database should hold vital shared data and I am concern that it will break in the middle (like dead lock when 2 thread are updating the same data, is it even possible?)

答: Yes, this is thread safe, framework handles multiple concurrent requests by enqueuing them. For every request, a new instance of controller is created. By the way, you are only reading data, so no worries :)</p>

Body:
I am wondering if this code is thread safe,
This is taken from datatable editor c# API
https://editor.datatables.net/manual/net/webapi

public class StaffController : ApiController
{
    [Route("api/staff")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult Staff()
    {
        var request = HttpContext.Current.Request;
        var settings = Properties.Settings.Default;

        using (var db = new Database(settings.DbType, settings.DbConnection))
        {
            var response = new Editor(Db, "staff")
                .Model<StaffModel>()
                .Process(request)
                .Data();

            return Json(response);
        }
    }
}

What happen if few threads are entering Staff() method with an update? how it will affect the database?

EDIT
I am working with SQL database, the database should hold vital shared data and I am concern that it will break in the middle (like dead lock when 2 thread are updating the same data, is it even possible?)

ContentLicense: CC BY-SA 4.0


问:
jQuery - button disabled but can't be enabled again
This is my HTML Form and jQuery code, if password and confirm password do not match then a message is shown and along with that the submit button is getting disabled. But when the password matches, the error message disappears but button is not getting enabled. Kindly help.

$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else
    $('#message').html('Not Matching').css('color', 'red');
  $('#regbtn').prop('disabled', true);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="emailus" class="" method="post" action="session.php">
  <div class="signupform">
    <div>
      <input class="inputbox" type="text" name="Name" placeholder="Name" required>
    </div>
    <div>
      <input class="inputbox" type="email" name="Email" placeholder="Email" required>
    </div>
    <div>
      <input class="inputbox" type="Number" name="Mobile" placeholder="Mobile" required>
    </div>
    <div>
      <input class="inputbox" type="password" id="password" name="password" placeholder="password" required>
    </div>
    <div>
      <input class="inputbox" type="password" id="confirm_password" name="txtConfirmPassword" placeholder="Confirm password" required><span id='message'></span>
    </div>
    <div>
      <textarea class="inputbox" name="Company" placeholder="Company" required></textarea>
    </div>
    <div>
      <textarea class="inputbox" name="Designation" placeholder="Designation" required></textarea>
    </div>
    <div>
      <input class="inputbox submiit" type="submit" id="regbtn" name="Submit" value="Submit" class="modal fade">
    </div>
  </div>
</form></code>```

答:
You are missing brackets {} in your else statement if you add these it works.

```<code>$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else {
    $('#message').html('Not Matching').css('color', 'red');
    $('#regbtn').prop('disabled', true);
  }
});
</code>```

demo

$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else {
    $('#message').html('Not Matching').css('color', 'red');
    $('#regbtn').prop('disabled', true);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="emailus" class="" method="post" action="session.php">
  <div class="signupform">

    <div><input class="inputbox" type="text" name="Name" placeholder="Name" required></div>
    <div><input class="inputbox" type="email" name="Email" placeholder="Email" required></div>
    <div><input class="inputbox" type="Number" name="Mobile" placeholder="Mobile" required></div>
    <div><input class="inputbox" type="password" id="password" name="password" placeholder="password" required></div>
    <div><input class="inputbox" type="password" id="confirm_password" name="txtConfirmPassword" placeholder="Confirm password" required><span id='message'></span></div>
    <div><textarea class="inputbox" name="Company" placeholder="Company" required></textarea></div>
    <div><textarea class="inputbox" name="Designation" placeholder="Designation" required></textarea></div>
    <div>
      <input class="inputbox submiit" type="submit" id="regbtn" name="Submit" value="Submit" class="modal fade">
    </div>

  </div>
</form></code>```

Body:
This is my HTML Form and jQuery code, if password and confirm password do not match then a message is shown and along with that the submit button is getting disabled. But when the password matches, the error message disappears but button is not getting enabled. Kindly help.

$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else
    $('#message').html('Not Matching').css('color', 'red');
  $('#regbtn').prop('disabled', true);

});

<form name="emailus" class="" method="post" action="session.php">

      <input class="inputbox" type="text" name="Name" placeholder="Name" required>

      <input class="inputbox" type="email" name="Email" placeholder="Email" required>

      <input class="inputbox" type="Number" name="Mobile" placeholder="Mobile" required>

      <input class="inputbox" type="password" id="password" name="password" placeholder="password" required>

      <input class="inputbox" type="password" id="confirm_password" name="txtConfirmPassword" placeholder="Confirm password" required>

      <textarea class="inputbox" name="Company" placeholder="Company" required></textarea>

      <textarea class="inputbox" name="Designation" placeholder="Designation" required></textarea>

      <input class="inputbox submiit" type="submit" id="regbtn" name="Submit" value="Submit" class="modal fade">

</form>

Body:
You are missing brackets {} in your else statement if you add these it works.

$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else {
    $('#message').html('Not Matching').css('color', 'red');
    $('#regbtn').prop('disabled', true);
  }
});

demo

$('#password, #confirm_password').on('keyup', function() {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#regbtn').prop('disabled', false);
    $('#message').html('');
  } else {
    $('#message').html('Not Matching').css('color', 'red');
    $('#regbtn').prop('disabled', true);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="emailus" class="" method="post" action="session.php">
  <div class="signupform">

    <div><input class="inputbox" type="text" name="Name" placeholder="Name" required></div>
    <div><input class="inputbox" type="email" name="Email" placeholder="Email" required></div>
    <div><input class="inputbox" type="Number" name="Mobile" placeholder="Mobile" required></div>
    <div><input class="inputbox" type="password" id="password" name="password" placeholder="password" required></div>
    <div><input class="inputbox" type="password" id="confirm_password" name="txtConfirmPassword" placeholder="Confirm password" required><span id='message'></span></div>
    <div><textarea class="inputbox" name="Company" placeholder="Company" required></textarea></div>
    <div><textarea class="inputbox" name="Designation" placeholder="Designation" required></textarea></div>
    <div>
      <input class="inputbox submiit" type="submit" id="regbtn" name="Submit" value="Submit" class="modal fade">
    </div>

  </div>
</form>


问:
How to perform STIntersect between a polygon and point geometryfile?
What I have so far:</p>

```<code>select Metro.Object_ID
from Geocoding_tab.dbo.Part1_Part2_Combined_Final as paypal
    ,Object_id.dbo.All_Combined_9_Metros as Metro
where paypal.geom.STIntersect(Metro.GEOM) = 1;
</code>```

答:
You can amend the query to use JOIN syntax

```<code>SELECT Metro.Object_ID
FROM
    Geocoding_tab.dbo.Part1_Part2_Combined_Final as paypal
INNER JOIN
    Object_id.dbo.All_Combined_9_Metros as Metro ON paypal.geom.STIntersects(Metro.GEOM) = 1;
</code>```

EDIT - following error shown in comments below

You can use the STIsValid Method to detect if you have shape that's invalid.  The method will return 0 if invalid.

The MakeValid Method will fix invalid shape data

for example:

```<code>UPDATE table SET geom = geom.MakeValid() where geom.STIsValid() = 0
</code>```

Note

As the error suggests, the MakeValid could alter your shape in a way that you might consider incorrect, depending on the original problem with the shape. So you should confirm that you're happy with the  "corrected" shape before proceeding.

Body:
What I have so far:

select Metro.Object_ID
from Geocoding_tab.dbo.Part1_Part2_Combined_Final as paypal
    ,Object_id.dbo.All_Combined_9_Metros as Metro
where paypal.geom.STIntersect(Metro.GEOM) = 1;

Body:
You can amend the query to use JOIN syntax

SELECT Metro.Object_ID
FROM
    Geocoding_tab.dbo.Part1_Part2_Combined_Final as paypal
INNER JOIN
    Object_id.dbo.All_Combined_9_Metros as Metro ON paypal.geom.STIntersects(Metro.GEOM) = 1;

EDIT - following error shown in comments below

You can use the STIsValid Method to detect if you have shape that's invalid.  The method will return 0 if invalid.

The MakeValid Method will fix invalid shape data

for example:

UPDATE table SET geom = geom.MakeValid() where geom.STIsValid() = 0

Note

As the error suggests, the MakeValid could alter your shape in a way that you might consider incorrect, depending on the original problem with the shape. So you should confirm that you're happy with the  "corrected" shape before proceeding.


问:
Is checking for true explicity bad by design?
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

```<code>var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);
</code>```

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

答:
What can go wrong? Exactly, nothing. In the best case your function does nothing. That's still better then having some random argument be accepted as true.

If you use true all the other time, then you should also check explicitly for it.

While I'm certain in favor of if foo: in Python, there is a big difference here and that is the fact that in the end some random jQuery programmer may come a long and thinks "Oh! It also works with a string and new Boolean()" and uses that.

Concerning Sean's suggestion to use !! it really depends whether you only want a boolean to be accepted or anything that's true. For a clean API I would only accept booleans though.

Body:
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.


问:
How to force min-height on table
I have this code :

```<code><table cellspacing="0" cellpadding="0" border="0" style="width:415px">
    <tbody>
        <tr valign="top">
            <td style="font-family:Arial;min-height:60px;font-size:12px;line-height:14px;">
                This is my text that I need in 2 lines
            </td>
        </tr>

        <tr valign="top">
            <td style="font-size:12px;line-height:14px">
                Second Line
            </td>
        </tr>
    </tbody>
</table>
</code>```

As you can see, the first tr/td should be height 60px (min-height:60px) but in fact it isn't.

For many reasons, I can't use height directly (this code is formatted trought back office system, in a newsletter).

So, how can I take the whole height on the td trought min-height?

Also, tried putting min-height:60px; on tr, but nothing change...

答:
It may be reviving a 2012 post, for those who searched and found this post like me:

Note: Check these addresses for the email client support before using this method, at the time of writing this answer, the support was around 50% -ish.

E-mail client support range of :first-child

E-mail client support range of ::before

table tr:first-child td:before {
  min-height: 100px;
  display: block;
  content: ""
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
</table></code>```

Title: How to force min-height on table

Body:
I have this code :

                This is my text that I need in 2 lines

                Second Line

As you can see, the first tr/td should be height 60px (min-height:60px) but in fact it isn't.

For many reasons, I can't use height directly (this code is formatted trought back office system, in a newsletter).

So, how can I take the whole height on the td trought min-height?

Also, tried putting min-height:60px; on tr, but nothing change...

Body:
It may be reviving a 2012 post, for those who searched and found this post like me:

Note: Check these addresses for the email client support before using this method, at the time of writing this answer, the support was around 50% -ish.

E-mail client support range of :first-child

E-mail client support range of ::before

table tr:first-child td:before {
  min-height: 100px;
  display: block;
  content: ""
}

<table border="1">
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
</table>


问:
Get document from GET request
I need your help:
I have the following method

```<code>   @Path("/download")
    public class FileDownloadService {

        @GET
        public Response downloadFile(@QueryParam("filenet_id") String filenet_id, @QueryParam("version") String version) {
    ...
    Document document = (Document) cmisObject;
    return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
}
</code>```

and I want to get the document throught HTTP GET, I tried to write this code but I don't know how to get it, "output" don't conatains it:

```<code>URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("localhost:8080").setPath("/filenetintegration/rest/download")
    .setParameter("filenet_id", filenet_id)
    .setParameter("version", version+".0");
    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(uri.toString()).openConnection();
    urlConnection.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
    String output;
    while ((output = br.readLine()) != null) {
    System.out.println(output);
    }
</code>```

Edit:
maybe the problem is on this line, it don't put the document inside the response:

```<code>return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
</code>```

答:
You need something like this on the server side:</p>

```<code>Document document = (Document) cmisObject;

ContentStream contentStream = document.getContentStream();
final InputStream stream = contentStream.getStream();

StreamingOutput output = (OutputStream out) -> {
  try {
    int b;
    byte[] buffer = new byte[64*1024];

     while ((b = stream.read(buffer)) > -1) {
       out.write(buffer, 0, b);
     }
  } finally {
    try {
      stream.close();
    } catch (IOException ioe) {}
  }
};

return Response.ok(output, contentStream.getMimeType()).build();
</code>```

Title: Get document from GET request

Body:
I need your help:
I have the following method

   @Path("/download")
    public class FileDownloadService {

        @GET
        public Response downloadFile(@QueryParam("filenet_id") String filenet_id, @QueryParam("version") String version) {
    ...
    Document document = (Document) cmisObject;
    return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
}

and I want to get the document throught HTTP GET, I tried to write this code but I don't know how to get it, "output" don't conatains it:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("localhost:8080").setPath("/filenetintegration/rest/download")
    .setParameter("filenet_id", filenet_id)
    .setParameter("version", version+".0");
    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(uri.toString()).openConnection();
    urlConnection.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
    String output;
    while ((output = br.readLine()) != null) {
    System.out.println(output);
    }

Edit:
maybe the problem is on this line, it don't put the document inside the response:

return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();

Body:
You need something like this on the server side:

Document document = (Document) cmisObject;

ContentStream contentStream = document.getContentStream();
final InputStream stream = contentStream.getStream();

StreamingOutput output = (OutputStream out) -> {
  try {
    int b;
    byte[] buffer = new byte[64*1024];

     while ((b = stream.read(buffer)) > -1) {
       out.write(buffer, 0, b);
     }
  } finally {
    try {
      stream.close();
    } catch (IOException ioe) {}
  }
};

return Response.ok(output, contentStream.getMimeType()).build();