问:
How to redirect stdout to both file and console with scripting?
I want to run a python script and capture the output on a text file as well as want to show on console.

I want to specify it as a property of the python script itself.  NOT to use the command echo "hello world" | tee test.txt on command prompt every time.

Within script I tried:

```<code>sys.stdout = open('log.txt','w')
</code>```

But this does not show the stdout output on screen.

I have heard about logging module but I could not get luck using that module to do the job.

答:
I tried this:</p>

```<code>"""
Transcript - direct print output to a file, in addition to terminal.

Usage:
    import transcript
    transcript.start('logfile.log')
    print("inside file")
    transcript.stop()
    print("outside file")
"""

import sys

class Transcript(object):

    def __init__(self, filename):
        self.terminal = sys.stdout, sys.stderr
        self.logfile = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.logfile.write(message)

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass

def start(filename):
    """Start transcript, appending print output to given filename"""
    sys.stdout = Transcript(filename)

def stop():
    """Stop transcript and return print functionality to normal"""
    sys.stdout.logfile.close()
    sys.stdout = sys.stdout.terminal
    sys.stderr = sys.stderr.terminal
</code>```

Body:
I want to run a python script and capture the output on a text file as well as want to show on console.

I want to specify it as a property of the python script itself.  NOT to use the command echo "hello world" | tee test.txt on command prompt every time.

Within script I tried:

sys.stdout = open('log.txt','w')

But this does not show the stdout output on screen.

I have heard about logging module but I could not get luck using that module to do the job.

Body:
I tried this:

"""
Transcript - direct print output to a file, in addition to terminal.

Usage:
    import transcript
    transcript.start('logfile.log')
    print("inside file")
    transcript.stop()
    print("outside file")
"""

import sys

class Transcript(object):

    def __init__(self, filename):
        self.terminal = sys.stdout, sys.stderr
        self.logfile = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.logfile.write(message)

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass

def start(filename):
    """Start transcript, appending print output to given filename"""
    sys.stdout = Transcript(filename)

def stop():
    """Stop transcript and return print functionality to normal"""
    sys.stdout.logfile.close()
    sys.stdout = sys.stdout.terminal
    sys.stderr = sys.stderr.terminal


来源: stackexchange

问:
Laravel From Request Validaton doesn't show errors
My Laravel Framework is 5.4.19

I have followed the tutorial:
http://www.easylaravelbook.com/blog/2015/08/17/creating-and-validating-a-laravel-5-form-the-definitive-guide/

and created form request file tours2_create_tableRequest.php:

```<code><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class tours2_create_tableRequest extends FormRequest
{

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'doc_fullnumber' => 'unique:tourists'

    ];
}
</code>```

}

(it tests if "doc_fullnumber" from request has no duplicates in 'tourists" model)

I have added this code to the form blade.php file:

```<code> @if($errors->count() > 0 )
    <div>
   @foreach ($errors->all() as $error)
      {{ $error }}
   @endforeach
    </div>
 @endif
</code>```

it seems to me that validation works fine (it redirects the user back to create form page when "doc_fullnumber" is not unique), but it doesn't pass $errors variable.

I've browsed Stackoverflow and found several topics with the same problem. They suggest to wrap all my routes (in web.php) in:

```<code>Route::group(['middleware' => ['web']], function () {
});
</code>```

I've done it, but it doesn't help...

here is the form page, actually (temporary): http://f832ee57.ngrok.io/tours_2/create
(the "doc_fullnumber" field is the last one. You can add "2001" there to check validation).

my project on git: https://github.com/Sergey1983/first

Appreciate any help!

答:
To make the unique rule work, you need to have `'doc_fullnumber' field in DB or you need to specify a custom name field:

```<code>'doc_fullnumber' => 'unique:tourists,custom_fullnumber_field'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My Laravel Framework is 5.4.19

I have followed the tutorial:
http://www.easylaravelbook.com/blog/2015/08/17/creating-and-validating-a-laravel-5-form-the-definitive-guide/

and created form request file tours2_create_tableRequest.php:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class tours2_create_tableRequest extends FormRequest
{

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'doc_fullnumber' => 'unique:tourists'

    ];
}

}

(it tests if "doc_fullnumber" from request has no duplicates in 'tourists" model)

I have added this code to the form blade.php file:

 @if($errors->count() > 0 )

   @foreach ($errors->all() as $error)
      {{ $error }}
   @endforeach

 @endif

it seems to me that validation works fine (it redirects the user back to create form page when "doc_fullnumber" is not unique), but it doesn't pass $errors variable.

I've browsed Stackoverflow and found several topics with the same problem. They suggest to wrap all my routes (in web.php) in:

Route::group(['middleware' => ['web']], function () {
});

I've done it, but it doesn't help...

here is the form page, actually (temporary): http://f832ee57.ngrok.io/tours_2/create
(the "doc_fullnumber" field is the last one. You can add "2001" there to check validation).

my project on git: https://github.com/Sergey1983/first

Appreciate any help!

Body:
To make the unique rule work, you need to have `'doc_fullnumber' field in DB or you need to specify a custom name field:

'doc_fullnumber' => 'unique:tourists,custom_fullnumber_field'


问:
Dispose of WPF Window
I have a WPF Window that I show with Window.Show().
When I click X the form closes.
But it is still in memory and the GC never comes and cleans it up.
Also I do not have any refrences/handles to it.

does any one know what could be causing it to stay in memory?

Thanks!

Update:
I am using the following code to create the window:

```<code>   Public Sub OpenPageWindow(ByVal nick As String)
        Dim found As Boolean

        For Each pw As PageWindow In Application.Current.Windows.OfType(Of PageWindow)()
            If Not pw.Tag Is Nothing Then
                If pw.Tag.ToString() = nick Then
                    If pw.IsVisible = False Then
                        pw.Show()
                    End If
                    Exit Sub
                End If
            End If
        Next

        If found = False Then
            Dim p As New PageWindow With {.Name = "pw" & nick, .Tag = nick, _
                                          .Title = "Chatting with " & nick, .ShowActivated = False}
            p.Show()
        End If
    End Sub
</code>```

and the following code-behind for the window itself:

```<code>Public Class PageWindow
    Implements System.IDisposable

    Public UserPressedExit As Boolean
    Dim MainWin As MainWindow

    Private _IsBuddy As Boolean
    Private _IsBlocked As Boolean
    Private _IsOnline As Boolean

    Public Property FirstOpen As Boolean

    Public Property IsOnline As Boolean
        Get
            Return _IsOnline
        End Get
        Set(ByVal value As Boolean)
            If _IsOnline <> value Then
                _IsOnline = value
            End If
        End Set
    End Property

    Public Property IsBuddy As Boolean
        Get
            Return _IsBuddy
        End Get
        Set(ByVal value As Boolean)
            If _IsBuddy <> value Then
                _IsBuddy = value
                'If value Then
                '    btnAddBuddy.IsEnabled = False
                '    iDeleteBuddy.IsEnabled = True
                'Else
                '    btnAddBuddy.IsEnabled = True
                '    iDeleteBuddy.IsEnabled = False
                'End If
            End If
        End Set
    End Property

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MainWin = CType(Application.Current.Windows(0), MainWindow)
        Catch ex As Exception
            txtChat.AppendText("ERROR: " & ex.Message.ToString() & Environment.NewLine)
        End Try
    End Sub

    Private Sub Window_Closed(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Dispose()
    End Sub

    Private Sub txtTitle_PreviewMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Me.DragMove()
    End Sub

    Private Sub pbMin_PreviewMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        WindowState = Windows.WindowState.Minimized
    End Sub

    Private Sub pbClose_PreviewMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        UserPressedExit = True
        txtChat.Clear()
        Me.Close()
    End Sub

    Private Sub txtSend_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.Enter Then
            btnSend_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If String.IsNullOrWhiteSpace(txtSend.Text) Then
            MessageBox.Show("Empty Message.")
            txtSend.Text = ""
        Else
            Send(txtSend.Text)

            txtSend.Text = ""
        End If
    End Sub

    Public Sub Page(ByVal message As String)
        If String.IsNullOrEmpty(message) = False Then
            If MainWin.Settings.ShowPageTimestamp Then
                txtChat.AppendText(Me.Tag.ToString() & " (" & Format(Date.Now, "HH:mm:ss") & "): " & message & Environment.NewLine)
            Else
                txtChat.AppendText(Me.Tag.ToString() & ": " & message & Environment.NewLine)
            End If

            If Me.IsFocused = False Then

            End If
        End If
    End Sub

    Private Sub Send(ByVal text As String)
        'work on 389 event
        MainWin.Send("PAGE " + Me.Tag.ToString + " " + text)

        If MainWin.Settings.ShowPageTimestamp Then
            txtChat.AppendText(MainWin.Settings.Nick & ": " & text & Environment.NewLine)
        Else
            txtChat.AppendText(MainWin.Settings.Nick & " (" & Format(Date.Now, "HH:mm:ss") & "): " & text & Environment.NewLine)
        End If
    End Sub

#Region "IDisposable Support"
    Private disposed As Boolean ' To detect redundant calls

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposed Then
            If disposing Then
                'dispose managed state (managed objects).
                RemoveHandler Me.Loaded, AddressOf Window_Loaded
                RemoveHandler txtTitle.PreviewMouseDown, AddressOf txtTitle_PreviewMouseDown
                RemoveHandler pbMin.PreviewMouseUp, AddressOf pbMin_PreviewMouseUp
                RemoveHandler pbClose.PreviewMouseUp, AddressOf pbClose_PreviewMouseUp
                RemoveHandler txtSend.KeyUp, AddressOf txtSend_KeyUp
                RemoveHandler btnSend.Click, AddressOf btnSend_Click
                RemoveHandler Me.Closed, AddressOf Window_Closed

                BindingOperations.ClearBinding(txtTitle, TextBlock.TextProperty)

                Me.Icon = Nothing
                ibBackground = Nothing
                'iDeleteBuddy = Nothing
                'btnAddBuddy = Nothing
                'iBlockUser = Nothing
                pbMin = Nothing
                pbClose = Nothing
                MainWin = Nothing

                Me.Resources.Clear()

                GC.Collect()
            End If
        End If
        Me.disposed = True
    End Sub

    Protected Overrides Sub Finalize()
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(False)
        MyBase.Finalize()
    End Sub
#End Region
End Class
</code>```

Then the following code for the XAML:

```<code><Window x:Class="PageWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PageWindow" Height="300" Width="400"
        Icon="Images\R2.ico" WindowStyle="None" ResizeMode="NoResize"
        WindowStartupLocation="Manual" Loaded="Window_Loaded"
        BorderThickness="2" BorderBrush="#FFAE28"
        Closed="Window_Closed">
    <Window.Resources>
        <Style x:Key="sRenegadeButton" TargetType="Button">
            <Setter Property="FontFamily" Value="Franklin Gothic Medium" />
            <Setter Property="FontSize" Value="12px" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Foreground" Value="#FFAE28" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="Border" BorderBrush="#FFAE28" BorderThickness="1" CornerRadius="3"
                                Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                            <Border Name="innerborder" BorderBrush="#FFAE28" BorderThickness="1" CornerRadius="3"
                                    Background="{TemplateBinding Background}" SnapsToDevicePixels="True" Margin="1">
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Name="content" />
                            </Border>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="Border" Property="BorderBrush" Value="#FFD528" />
                                <Setter TargetName="innerborder" Property="BorderBrush" Value="#FFD528" />
                                <Setter Property="Background" Value="#28FFAE28" />
                                <Setter Property="Foreground" Value="#FFD528" />
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter Property="Background" Value="#28FFAE28" />
                                <Setter TargetName="content" Property="RenderTransform" >
                                    <Setter.Value>
                                        <TranslateTransform Y="1.0" />
                                    </Setter.Value>
                                </Setter>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter TargetName="Border" Property="BorderBrush" Value="#80E6A023" />
                                <Setter TargetName="innerborder" Property="BorderBrush" Value="#80E6A023" />
                                <Setter Property="Foreground" Value="#8CFFD528" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="sRenegadeTextBox" TargetType="TextBox">
            <Setter Property="FontFamily" Value="Franklin Gothic Medium" />
            <Setter Property="FontSize" Value="12px" />
            <Setter Property="Foreground" Value="#FFD528" />
            <Setter Property="Background" Value="#28FFAE28" />
            <Setter Property="BorderBrush" Value="#FFAE28" />
            <Setter Property="CaretBrush" Value="#FFAE28" />
            <Setter Property="SelectionBrush" Value="#FFD528" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <Border Name="Bd" BorderThickness="{TemplateBinding BorderThickness}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ScrollViewer Name="PART_ContentHost" Background="{TemplateBinding Background}"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Foreground" Value="#8CFFD528" />
                                <Setter Property="Background" Value="#1EFFAE28" />
                                <Setter Property="BorderBrush" Value="#80E6A023" />
                                <Setter TargetName="PART_ContentHost" Property="Background" Value="#1EFFAE28"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="21" />
            <RowDefinition Height="32" />
            <RowDefinition Height="*" />
            <RowDefinition Height="27" />
        </Grid.RowDefinitions>

        <Grid.Background>
            <ImageBrush x:Name="ibBackground"  ImageSource="Images\page_back.gif" />
        </Grid.Background>

        <Border Grid.Row="0" BorderBrush="#FFAE28" BorderThickness="0,0,0,2"
                SnapsToDevicePixels="True" />

        <Grid Name="gTitleBar" Grid.Row="0" Background="#32FFAE28">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="32" />
            </Grid.ColumnDefinitions>

            <TextBlock Name="txtTitle" Grid.Column="0" Text="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}"
                       HorizontalAlignment="Stretch" VerticalAlignment="Center"
                       TextAlignment="Left" Margin="4,0,1,0"
                       PreviewMouseDown="txtTitle_PreviewMouseDown"
                       Foreground="#FED528" FontFamily="Franklin Gothic Medium" />

            <Image Name="pbMin" Grid.Column="1" Width="28" Height="15"
                    HorizontalAlignment="Center" VerticalAlignment="Center"
                    PreviewMouseUp="pbMin_PreviewMouseUp" Stretch="None">
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Setter Property="Source" Value="Images\min.png" />

                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Source" Value="Images\min_o.png" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
            <Image Name="pbClose" Grid.Column="2" Width="28" Height="15"
                    HorizontalAlignment="Left" VerticalAlignment="Center"
                    PreviewMouseUp="pbClose_PreviewMouseUp" Stretch="None">
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Setter Property="Source" Value="Images\close2.png" />

                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Source" Value="Images\close2_o.png" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
        </Grid>

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

            <!--<Button Name="btnAddBuddy" Grid.Column="1" Margin="0,2,0,0">
                <Button.Style>
                    <Style TargetType="{x:Type Button}">
                        <Setter Property="Background" Value="Transparent" />
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type Button}">
                                    <Grid>
                                        <Border Name="Border" BorderBrush="Transparent" BorderThickness="1" CornerRadius="3"
                                            Background="{TemplateBinding Background}" SnapsToDevicePixels="True">

                                        </Border>
                                        <Image Name="iAddBuddy" Margin="1" Source="Images\Add Buddy 32x36.png" />
                                        <Image Name="iAddBuddyDissabled" Margin="1" Source="Images\Add Buddy 32x36.png" Visibility="Hidden" />
                                    </Grid>

                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsMouseOver" Value="True">
                                            <Setter TargetName="Border" Property="BorderBrush" Value="#FFD528" />
                                        </Trigger>
                                        <Trigger Property="IsPressed" Value="True">
                                            <Setter Property="Background" Value="#FFD528" />
                                        </Trigger>
                                        <Trigger Property="IsEnabled" Value="False">
                                            <Setter TargetName="Border" Property="BorderBrush" Value="Transparent" />
                                            <Setter TargetName="iAddBuddy" Property="Visibility" Value="Hidden" />
                                            <Setter TargetName="iAddBuddyDissabled" Property="Visibility" Value="Visible" />
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Button.Style>
            </Button>

            <Border Name="bDeleteBuddyBorder" Grid.Column="2" BorderThickness="1"
                    SnapsToDevicePixels="True" Margin="0,2,0,0">
                <Image Name="iDeleteBuddy" Margin="1" IsEnabled="True"
                   Source="Images\Delete 32x32.png">
                    <Image.Style>
                        <Style TargetType="{x:Type Image}">
                            <Style.Triggers>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Source" Value="Images\Delete Disabled 32x32.png" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Image.Style>
                </Image>
                <Border.Style>
                    <Style TargetType="Border">
                        <Setter Property="BorderBrush" Value="Transparent" />
                        <Setter Property="Background" Value="Transparent" />
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="BorderBrush" Value="#FFD528" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Border.Style>
            </Border>

            <Border Name="bBlockUserBorder" Grid.Column="3" BorderThickness="1"
                    SnapsToDevicePixels="True" Margin="0,2,0,0">
                <Image Name="iBlockUser" Margin="1" IsEnabled="True"
                       Source="Images\Block Buddy 32x36.png">
                    <Image.Style>
                        <Style TargetType="{x:Type Image}">
                            <Style.Triggers>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Source" Value="Images\Block Buddy Dissabled 32x36.png" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Image.Style>
                </Image>
                <Border.Style>
                    <Style TargetType="Border">
                        <Setter Property="BorderBrush" Value="Transparent" />
                        <Setter Property="Background" Value="Transparent" />
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="BorderBrush" Value="#FFD528" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Border.Style>
            </Border>-->
        </Grid>

        <TextBox Name="txtChat" Grid.Row="2" Margin="4,2,4,2"
                 Style="{StaticResource sRenegadeTextBox}" UndoLimit="0" />

        <Grid Grid.Row="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="45" />
            </Grid.ColumnDefinitions>

            <TextBox Name="txtSend" Grid.Column="0" MaxLength="495"
                     Height="22" Margin="4,1,2,4" VerticalContentAlignment="Center"
                     Style="{StaticResource sRenegadeTextBox}" UndoLimit="0"
                     KeyUp="txtSend_KeyUp" />
            <Button Name="btnSend" Content="Send" Grid.Column="1"
                    Style="{StaticResource sRenegadeButton}"
                    Height="22" Width="40" Margin="0,1,4,4" Click="btnSend_Click" />
        </Grid>
    </Grid>
</Window>
</code>```

Basically even if I create an empty WPF Window with a background image for the main grid and 2 eventhandlers Opening and Closed it still stays in memory, but when all the 'empty wpf' windows are closed the memory only decreases a little. just a little. Why arent simple windows disposed of entirely? I have even tried implementing the disposed functionality coded above.

答:
What is as important as the memory is if you are leaking handles - in processes (in taskmanager) add a column for GDI objects and Handles.

When you open and close your window it will increase and decrease - if not you have a leak - with the leak comes some memory.
I would'n worry too much about some kb's not dissapearing right away they will eventually be cleaned up or reused, but handles have to dissapear so they can be a good indication.

Usually leaks arise when using static eventhandlers or other static stuctures that holds a reference to a control or window - i.e. static dictionaries or hashtables. If the reference is needed, remember to clean it up on close or use WeakReference.

Dispose methods are only needed when you have resources as member variables on your window/class and it have to be implemented right (yours does look right - but unnesesary :) - you also have to make sure that Dispose() is actually called...

ContentLicense: CC BY-SA 2.5

Title: Dispose of WPF Window

Body:
I have a WPF Window that I show with Window.Show().
When I click X the form closes.
But it is still in memory and the GC never comes and cleans it up.
Also I do not have any refrences/handles to it.

does any one know what could be causing it to stay in memory?

Thanks!

Update:
I am using the following code to create the window:

   Public Sub OpenPageWindow(ByVal nick As String)
        Dim found As Boolean

        For Each pw As PageWindow In Application.Current.Windows.OfType(Of PageWindow)()
            If Not pw.Tag Is Nothing Then
                If pw.Tag.ToString() = nick Then
                    If pw.IsVisible = False Then
                        pw.Show()
                    End If
                    Exit Sub
                End If
            End If
        Next

        If found = False Then
            Dim p As New PageWindow With {.Name = "pw" & nick, .Tag = nick, _
                                          .Title = "Chatting with " & nick, .ShowActivated = False}
            p.Show()
        End If
    End Sub

and the following code-behind for the window itself:

Public Class PageWindow
    Implements System.IDisposable

    Public UserPressedExit As Boolean
    Dim MainWin As MainWindow

    Private _IsBuddy As Boolean
    Private _IsBlocked As Boolean
    Private _IsOnline As Boolean

    Public Property FirstOpen As Boolean

    Public Property IsOnline As Boolean
        Get
            Return _IsOnline
        End Get
        Set(ByVal value As Boolean)
            If _IsOnline <> value Then
                _IsOnline = value
            End If
        End Set
    End Property

    Public Property IsBuddy As Boolean
        Get
            Return _IsBuddy
        End Get
        Set(ByVal value As Boolean)
            If _IsBuddy <> value Then
                _IsBuddy = value
                'If value Then
                '    btnAddBuddy.IsEnabled = False
                '    iDeleteBuddy.IsEnabled = True
                'Else
                '    btnAddBuddy.IsEnabled = True
                '    iDeleteBuddy.IsEnabled = False
                'End If
            End If
        End Set
    End Property

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MainWin = CType(Application.Current.Windows(0), MainWindow)
        Catch ex As Exception
            txtChat.AppendText("ERROR: " & ex.Message.ToString() & Environment.NewLine)
        End Try
    End Sub

    Private Sub Window_Closed(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Dispose()
    End Sub

    Private Sub txtTitle_PreviewMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Me.DragMove()
    End Sub

    Private Sub pbMin_PreviewMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        WindowState = Windows.WindowState.Minimized
    End Sub

    Private Sub pbClose_PreviewMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        UserPressedExit = True
        txtChat.Clear()
        Me.Close()
    End Sub

    Private Sub txtSend_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.Enter Then
            btnSend_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If String.IsNullOrWhiteSpace(txtSend.Text) Then
            MessageBox.Show("Empty Message.")
            txtSend.Text = ""
        Else
            Send(txtSend.Text)

            txtSend.Text = ""
        End If
    End Sub

    Public Sub Page(ByVal message As String)
        If String.IsNullOrEmpty(message) = False Then
            If MainWin.Settings.ShowPageTimestamp Then
                txtChat.AppendText(Me.Tag.ToString() & " (" & Format(Date.Now, "HH:mm:ss") & "): " & message & Environment.NewLine)
            Else
                txtChat.AppendText(Me.Tag.ToString() & ": " & message & Environment.NewLine)
            End If

            If Me.IsFocused = False Then

            End If
        End If
    End Sub

    Private Sub Send(ByVal text As String)
        'work on 389 event
        MainWin.Send("PAGE " + Me.Tag.ToString + " " + text)

        If MainWin.Settings.ShowPageTimestamp Then
            txtChat.AppendText(MainWin.Settings.Nick & ": " & text & Environment.NewLine)
        Else
            txtChat.AppendText(MainWin.Settings.Nick & " (" & Format(Date.Now, "HH:mm:ss") & "): " & text & Environment.NewLine)
        End If
    End Sub

#Region "IDisposable Support"
    Private disposed As Boolean ' To detect redundant calls

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposed Then
            If disposing Then
                'dispose managed state (managed objects).
                RemoveHandler Me.Loaded, AddressOf Window_Loaded
                RemoveHandler txtTitle.PreviewMouseDown, AddressOf txtTitle_PreviewMouseDown
                RemoveHandler pbMin.PreviewMouseUp, AddressOf pbMin_PreviewMouseUp
                RemoveHandler pbClose.PreviewMouseUp, AddressOf pbClose_PreviewMouseUp
                RemoveHandler txtSend.KeyUp, AddressOf txtSend_KeyUp
                RemoveHandler btnSend.Click, AddressOf btnSend_Click
                RemoveHandler Me.Closed, AddressOf Window_Closed

                BindingOperations.ClearBinding(txtTitle, TextBlock.TextProperty)

                Me.Icon = Nothing
                ibBackground = Nothing
                'iDeleteBuddy = Nothing
                'btnAddBuddy = Nothing
                'iBlockUser = Nothing
                pbMin = Nothing
                pbClose = Nothing
                MainWin = Nothing

                Me.Resources.Clear()

                GC.Collect()
            End If
        End If
        Me.disposed = True
    End Sub

    Protected Overrides Sub Finalize()
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(False)
        MyBase.Finalize()
    End Sub
#End Region
End Class

Then the following code for the XAML:

<Window x:Class="PageWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PageWindow" Height="300" Width="400"
        Icon="Images\R2.ico" WindowStyle="None" ResizeMode="NoResize"
        WindowStartupLocation="Manual" Loaded="Window_Loaded"
        BorderThickness="2" BorderBrush="#FFAE28"
        Closed="Window_Closed">
    <Window.Resources>

    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="21" />
            <RowDefinition Height="32" />
            <RowDefinition Height="*" />
            <RowDefinition Height="27" />
        </Grid.RowDefinitions>

        <Grid.Background>
            <ImageBrush x:Name="ibBackground"  ImageSource="Images\page_back.gif" />
        </Grid.Background>

        <Border Grid.Row="0" BorderBrush="#FFAE28" BorderThickness="0,0,0,2"
                SnapsToDevicePixels="True" />

        <Grid Name="gTitleBar" Grid.Row="0" Background="#32FFAE28">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="32" />
            </Grid.ColumnDefinitions>

            <TextBlock Name="txtTitle" Grid.Column="0" Text="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}"
                       HorizontalAlignment="Stretch" VerticalAlignment="Center"
                       TextAlignment="Left" Margin="4,0,1,0"
                       PreviewMouseDown="txtTitle_PreviewMouseDown"
                       Foreground="#FED528" FontFamily="Franklin Gothic Medium" />

            <Image Name="pbMin" Grid.Column="1" Width="28" Height="15"
                    HorizontalAlignment="Center" VerticalAlignment="Center"
                    PreviewMouseUp="pbMin_PreviewMouseUp" Stretch="None">
                <Image.Style>

                    </Style>
                </Image.Style>
            </Image>
            <Image Name="pbClose" Grid.Column="2" Width="28" Height="15"
                    HorizontalAlignment="Left" VerticalAlignment="Center"
                    PreviewMouseUp="pbClose_PreviewMouseUp" Stretch="None">
                <Image.Style>

                    </Style>
                </Image.Style>
            </Image>
        </Grid>

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

        </Grid>

        <TextBox Name="txtChat" Grid.Row="2" Margin="4,2,4,2"
                 Style="{StaticResource sRenegadeTextBox}" UndoLimit="0" />

        <Grid Grid.Row="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="45" />
            </Grid.ColumnDefinitions>

            <TextBox Name="txtSend" Grid.Column="0" MaxLength="495"
                     Height="22" Margin="4,1,2,4" VerticalContentAlignment="Center"
                     Style="{StaticResource sRenegadeTextBox}" UndoLimit="0"
                     KeyUp="txtSend_KeyUp" />
            <Button Name="btnSend" Content="Send" Grid.Column="1"
                    Style="{StaticResource sRenegadeButton}"
                    Height="22" Width="40" Margin="0,1,4,4" Click="btnSend_Click" />
        </Grid>
    </Grid>
</Window>

Basically even if I create an empty WPF Window with a background image for the main grid and 2 eventhandlers Opening and Closed it still stays in memory, but when all the 'empty wpf' windows are closed the memory only decreases a little. just a little. Why arent simple windows disposed of entirely? I have even tried implementing the disposed functionality coded above.


问:
Python - Exclude variable if list element doesn't exist
Python novice here - was unable to find anything similar online.

I am trying to analyze a large data set containing many rows with varying column lengths. An example of my data may be: "LY R15 515 750 601 999" where the number of elements is different for each row. I want the column variables to refer to each subsequent element, but only if that element exists. I am going to use all column variables for if statements with numeric expressions later on.

```<code>data = 'LY R15 515 750 601 999'
remove_blanks = ['']
entries = data.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
column_4 = int(entries[6])
column_5 = int(entries[7])
column_6 = int(entries[8])
column_7 = int(entries[9])
column_8 = int(entries[10])
column_9 = int(entries[11])
column_10 = int(entries[12])
column_11 = int(entries[13])
column_12 = int(entries[14])
column_13 = int(entries[15])
column_14 = int(entries[16])
column_15 = int(entries[17])
column_16 = int(entries[18])
column_17 = int(entries[19])
column_18 = int(entries[20])
print(entries)
</code>```

The error I am receiving:

column_3 = int(entries[5])

IndexError: list index out of range

I understand it is happening because that element does not exist in the list. Essentially, if an element does not exist, I do not want that variable to be considered. Please help!

P.S. I am sure there is a much simpler way to write this, so if there is, please let me know!

答:
A dictionary could probably do the work

```<code>variables = {}
for ix, value in enumerate(entries[3:]):
    variables["column_{0}".format(ix)] = int(value)
</code>```

You get

```<code>{'column_1': 601, 'column_0': 750, 'column_2': 999}
</code>```

However, it would be much easier for you to use some package like pandas for data analysis

Body:
Python novice here - was unable to find anything similar online.

I am trying to analyze a large data set containing many rows with varying column lengths. An example of my data may be: "LY R15 515 750 601 999" where the number of elements is different for each row. I want the column variables to refer to each subsequent element, but only if that element exists. I am going to use all column variables for if statements with numeric expressions later on.

data = 'LY R15 515 750 601 999'
remove_blanks = ['']
entries = data.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
column_4 = int(entries[6])
column_5 = int(entries[7])
column_6 = int(entries[8])
column_7 = int(entries[9])
column_8 = int(entries[10])
column_9 = int(entries[11])
column_10 = int(entries[12])
column_11 = int(entries[13])
column_12 = int(entries[14])
column_13 = int(entries[15])
column_14 = int(entries[16])
column_15 = int(entries[17])
column_16 = int(entries[18])
column_17 = int(entries[19])
column_18 = int(entries[20])
print(entries)

The error I am receiving:

column_3 = int(entries[5])

IndexError: list index out of range

I understand it is happening because that element does not exist in the list. Essentially, if an element does not exist, I do not want that variable to be considered. Please help!

P.S. I am sure there is a much simpler way to write this, so if there is, please let me know!

Body:
A dictionary could probably do the work

variables = {}
for ix, value in enumerate(entries[3:]):
    variables["column_{0}".format(ix)] = int(value)

You get

{'column_1': 601, 'column_0': 750, 'column_2': 999}

However, it would be much easier for you to use some package like pandas for data analysis


问:
SQL minimum date value after today's date Now()
I am writing a query and am having trouble filtering data as I would like.  In the table, there is a date field and an ItemCode field. I would like to return one record per ItemCode with the earliest date that is after today.

If today is 6/6/2017 and my data looks like:

```<code>ItemCode     Date
1            6/1/2017
1            6/7/2017
1            6/10/2017
2            6/2/2017
2            6/8/2017
2            6/15/2017
</code>```

I would want the result to be

```<code>ItemCode     Date
1            6/7/2017
2            6/8/2017
</code>```

My query so far is:

```<code>SELECT PO_PurchaseOrderDetail.ItemCode, Min(PO_PurchaseOrderDetail.RequiredDate) AS NextPO
FROM PO_PurchaseOrderDetail
GROUP BY PO_PurchaseOrderDetail.ItemCode
HAVING (((Min(PO_PurchaseOrderDetail.RequiredDate))>=Now()));
</code>```

The problem is that the Min function fires first and grabs the earliest dates per ItemCode, which are before today.  Then the >=Now() is evaluated and because the min dates are before today, the query returns nothing.

I've tried putting the >=Now() inside the min function in the HAVING part of the query but it does not change the result.

My structure is wrong and I would appreciate any advice. Thanks!

答:
Put the date condition in the where clause (not the having clause):

```<code>select ItemCode, min(Date) as NextPO
from PO_PurchaseOrderDetail
where Date > '6/6/2017'
group by ItemCode
</code>```

Body:
I am writing a query and am having trouble filtering data as I would like.  In the table, there is a date field and an ItemCode field. I would like to return one record per ItemCode with the earliest date that is after today.

If today is 6/6/2017 and my data looks like:

ItemCode     Date
1            6/1/2017
1            6/7/2017
1            6/10/2017
2            6/2/2017
2            6/8/2017
2            6/15/2017

I would want the result to be

ItemCode     Date
1            6/7/2017
2            6/8/2017

My query so far is:

SELECT PO_PurchaseOrderDetail.ItemCode, Min(PO_PurchaseOrderDetail.RequiredDate) AS NextPO
FROM PO_PurchaseOrderDetail
GROUP BY PO_PurchaseOrderDetail.ItemCode
HAVING (((Min(PO_PurchaseOrderDetail.RequiredDate))>=Now()));

The problem is that the Min function fires first and grabs the earliest dates per ItemCode, which are before today.  Then the >=Now() is evaluated and because the min dates are before today, the query returns nothing.

I've tried putting the >=Now() inside the min function in the HAVING part of the query but it does not change the result.

My structure is wrong and I would appreciate any advice. Thanks!

Body:
Put the date condition in the where clause (not the having clause):

select ItemCode, min(Date) as NextPO
from PO_PurchaseOrderDetail
where Date > '6/6/2017'
group by ItemCode


问:
code has error: unable to get the vlookup property of the worksheetfunction class
I had an issue with this code before and when I tried fixing it another issue occurred. On this line of code,

```<code>If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
</code>```

I get the error unable to get the vlookup property of the worksheetfunction class"

The whole code is below. Thanks for any help!

```<code>Sub code()
Columns("E:G").Insert shift:=xlToRight, copyorigin:=xlFormatFromLeftOrAbove
Range("E6").value = "Drink Price"
Range("F6").value = "Drink Revenue"
Range("G6").value = "Gross Sales less Drink Revenue"
Dim i As Variant
Dim item As Variant
Dim lookup_range As Range
Dim rev_wksht As Worksheet
Dim rev_wbk As Workbook
Dim vlkup_wbk As Workbook
Set rev_wksht = ActiveWorkbook.Sheets(1)
Set vlkup_wbk = Workbooks.Open("C:\Users\user\Documents\vlookup table drink prices.xlsx")
Set lookup_range = vlkup_wbk.Worksheets("Sheet1").Range("A:B")
i = 7
Do While rev_wksht.Cells(i, 1).value <> ""
   Set item = rev_wbk.Sheets(1).Cells(i, 1).value
    If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
        rev_wksht.Cells(i, 6).Formula = rev_wksht.Cells(i, 11).value * rev_wksht.Cells(i, 5).value
        rev_wksht.Cells(i, 7).Formula = rev_wksht.Cells(i, 4).value - rev_wksht.Cells(i, 6).value
    ElseIf (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Empty
    End If
i = i + 1
Loop
rev_wksht.Range("F:G").NumberFormat = "#,##0.00"
rev_wksht.Cells.EntireColumn.AutoFit
End Sub
</code>```

答:
You need to use Application.Vlookup

I'm not 100% sure why application.worksheetfunction.vlookup stopped working, but it used to be distinct from application.vlookup because it returned different error objects if an error occurred.

At some point since office 2007, it appears to have been removed but the intellisense has stayed there.

Body:
I had an issue with this code before and when I tried fixing it another issue occurred. On this line of code,

If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then

I get the error unable to get the vlookup property of the worksheetfunction class"

The whole code is below. Thanks for any help!

Sub code()
Columns("E:G").Insert shift:=xlToRight, copyorigin:=xlFormatFromLeftOrAbove
Range("E6").value = "Drink Price"
Range("F6").value = "Drink Revenue"
Range("G6").value = "Gross Sales less Drink Revenue"
Dim i As Variant
Dim item As Variant
Dim lookup_range As Range
Dim rev_wksht As Worksheet
Dim rev_wbk As Workbook
Dim vlkup_wbk As Workbook
Set rev_wksht = ActiveWorkbook.Sheets(1)
Set vlkup_wbk = Workbooks.Open("C:\Users\user\Documents\vlookup table drink prices.xlsx")
Set lookup_range = vlkup_wbk.Worksheets("Sheet1").Range("A:B")
i = 7
Do While rev_wksht.Cells(i, 1).value <> ""
   Set item = rev_wbk.Sheets(1).Cells(i, 1).value
    If Not (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
        rev_wksht.Cells(i, 6).Formula = rev_wksht.Cells(i, 11).value * rev_wksht.Cells(i, 5).value
        rev_wksht.Cells(i, 7).Formula = rev_wksht.Cells(i, 4).value - rev_wksht.Cells(i, 6).value
    ElseIf (IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False))) Then
        rev_wksht.Cells(i, 5).value = Empty
    End If
i = i + 1
Loop
rev_wksht.Range("F:G").NumberFormat = "#,##0.00"
rev_wksht.Cells.EntireColumn.AutoFit
End Sub


问:
For loop is not working as planned
So I have been trying to get something to work for a few days here and there only putting in an hour or so of work each day.

My current code is:

```<code>function NewNameChange() {
  var Dashboard = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Dashboard')
  var NameChanges = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Name Changes')
  //var Number1 = 0
  var Number2 = 6
  var CellCheck = NameChanges.getRange('B' + Number2)
  var Cell1 = NameChanges.getRange('B' + Number2)
  var Cell2 = NameChanges.getRange('D' + Number2)
  var Cell3 = NameChanges.getRange('F' + Number2)
  var Cell4 = NameChanges.getRange('H' + Number2)

  for (var Number1 = 0; Number1 == 0; Number2++) {
    if (CellCheck.isBlank()) {

      Dashboard.getRange('B14').copyTo(Cell1)
      Dashboard.getRange('D14').copyTo(Cell2)
      Dashboard.getRange('F14').copyTo(Cell3)
      Dashboard.getRange('H14').copyTo(Cell4)

      Dashboard.getRange('B14').clear()
      Dashboard.getRange('D14').clear()
      Dashboard.getRange('F14').clear()
      Dashboard.getRange('H14').clear()

      Number1 = 1;
    }
  }
}
</code>```

The goal of this code is to look at the cell B6 on the sheet named Name Changes, if this cell is empty then it goes to the sheet named Dashboard and copies the four feilds B14, D14, F14, H14, and copies this to the cells B6, D6, F6, H6, onto the Name Changes sheet. Then finally it clears the cells B14, D14, F14, and H14. Which is does wonderfully, the issue is that when the cell is not empty, because the script has been ran before and there's now data in B6, D6, F6, and H6, the script will run until timeout. When in theory it should get to the end of the for loop and had one to Number2 which then causes for the CellCheck to look at B7, although nothing ever happens.

First time on this forum and figured I would make an account to look for some help considering how helpful other answers have been. If I've used it wrong I am sorry, also if you need some further explanation please let me know!

答: CellCheck thru Cell4 are not modified inside the loop; while Number2 was used to initialize them, changing Number2 doesn't change those other values automatically: they have to be explicitly re-assigned to.

Title: For loop is not working as planned

Body:
So I have been trying to get something to work for a few days here and there only putting in an hour or so of work each day.

My current code is:

function NewNameChange() {
  var Dashboard = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Dashboard')
  var NameChanges = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Name Changes')
  //var Number1 = 0
  var Number2 = 6
  var CellCheck = NameChanges.getRange('B' + Number2)
  var Cell1 = NameChanges.getRange('B' + Number2)
  var Cell2 = NameChanges.getRange('D' + Number2)
  var Cell3 = NameChanges.getRange('F' + Number2)
  var Cell4 = NameChanges.getRange('H' + Number2)

  for (var Number1 = 0; Number1 == 0; Number2++) {
    if (CellCheck.isBlank()) {

      Dashboard.getRange('B14').copyTo(Cell1)
      Dashboard.getRange('D14').copyTo(Cell2)
      Dashboard.getRange('F14').copyTo(Cell3)
      Dashboard.getRange('H14').copyTo(Cell4)

      Dashboard.getRange('B14').clear()
      Dashboard.getRange('D14').clear()
      Dashboard.getRange('F14').clear()
      Dashboard.getRange('H14').clear()

      Number1 = 1;
    }
  }
}

The goal of this code is to look at the cell B6 on the sheet named Name Changes, if this cell is empty then it goes to the sheet named Dashboard and copies the four feilds B14, D14, F14, H14, and copies this to the cells B6, D6, F6, H6, onto the Name Changes sheet. Then finally it clears the cells B14, D14, F14, and H14. Which is does wonderfully, the issue is that when the cell is not empty, because the script has been ran before and there's now data in B6, D6, F6, and H6, the script will run until timeout. When in theory it should get to the end of the for loop and had one to Number2 which then causes for the CellCheck to look at B7, although nothing ever happens.

First time on this forum and figured I would make an account to look for some help considering how helpful other answers have been. If I've used it wrong I am sorry, also if you need some further explanation please let me know!


问:
Which code is read first when I start my program?
Which part of my C# code is first read when I start my program?

I would like to instantly close the application if a debugger is attached, so where do I put my if (Debugger.IsAttached) code? I've tried putting it inside Program.cs (Main) and I've also tried putting it right after "InitializerComponent();" in "public Form1()" Screenshot: http://prntscr.com/fgl6ql

Screenshot of Program.cs: http://prntscr.com/fgl6zu

答: Whatever is in Main() is executed first, that's usually always the entry point for .NET Console/Windows Applications.


问:
Verilog input error
I have a couple of errors in my verilog code that pop up when I compile. I believe they are all related. But I can't figure out what the error is. Any help will be greatly appreciated.

The errors are: Two for the input

vlog_a: Error 31004 Syntax error near `input' found

blog_a: Error 31004 Syntax error near 'output' found

```<code>module threeBitComparator;
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to

  wire X1,X2,X3; //xnor gate
  wire Y1,Y2,Y3,Y4,Y5,Y6; // and & or gates

  xnor
      G1a(X1,A2,B2),
      G1b(X2,A1,B1),
      G1c(X3,A0,B0);

  and
     G2a(Y1,A2,~B2),
     G2b(Y2,A1,~B1),
     G2c(Y3,A0,~B0),
     G2d(Y4,X1,Y2),
     G2e(Y5,X1,X2,Y3),
     G2f(E,X1,X2,X3);

  or
    G3a(Y6,Y1,Y4,Y5),
    G3b(GE,Y6,E);
endmodule
</code>```

答:
You declared your inputs and outputs but you haven't declared a port list. Your module header needs to look like below code to be IEEE 1364-1995 complaint

```<code>module threeBitComparator(A2,A1,A0,B2,B1,B0,E,GE); // <-- port list
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to
</code>```

Or you can use the ANSI style header introduce in IEEE Std 1364-2001. This style works on any modern Verilog simulator.

```<code>module threeBitComparator(
  input A2,A1,A0,
  input B2,B1,B0,
  output E,GE ); //E-Equal,  GE-Greater than or Equal to
</code>```

Title: Verilog input error

Body:
I have a couple of errors in my verilog code that pop up when I compile. I believe they are all related. But I can't figure out what the error is. Any help will be greatly appreciated.

The errors are: Two for the input

vlog_a: Error 31004 Syntax error near `input' found

blog_a: Error 31004 Syntax error near 'output' found

module threeBitComparator;
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to

  wire X1,X2,X3; //xnor gate
  wire Y1,Y2,Y3,Y4,Y5,Y6; // and & or gates

  xnor
      G1a(X1,A2,B2),
      G1b(X2,A1,B1),
      G1c(X3,A0,B0);

  and
     G2a(Y1,A2,~B2),
     G2b(Y2,A1,~B1),
     G2c(Y3,A0,~B0),
     G2d(Y4,X1,Y2),
     G2e(Y5,X1,X2,Y3),
     G2f(E,X1,X2,X3);

  or
    G3a(Y6,Y1,Y4,Y5),
    G3b(GE,Y6,E);
endmodule

Body:
You declared your inputs and outputs but you haven't declared a port list. Your module header needs to look like below code to be IEEE 1364-1995 complaint

module threeBitComparator(A2,A1,A0,B2,B1,B0,E,GE); // <-- port list
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to

Or you can use the ANSI style header introduce in IEEE Std 1364-2001. This style works on any modern Verilog simulator.

module threeBitComparator(
  input A2,A1,A0,
  input B2,B1,B0,
  output E,GE ); //E-Equal,  GE-Greater than or Equal to


问:
Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

```<code><!doctype html>
<html>
  <head>
   <title>title</title>
   <script>
     window.location='./main.html';
   </script>
  <body>
  </body>
</html>
</code>```

Or modify in the config.xml this line :

```<code><preference name="SplashScreenDelay" value="3000" />
</code>```

to this line :

```<code><preference name="SplashScreenDelay" value="70000" />
</code>```

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline

答:
Try updating your Cordova android platform:</p>

```<code>ionic platform remove android
ionic platform add android
</code>```

Body:
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

<!doctype html>

   <title>title</title>

Or modify in the config.xml this line :

<preference name="SplashScreenDelay" value="3000" />

to this line :

<preference name="SplashScreenDelay" value="70000" />

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline

Body:
Try updating your Cordova android platform:

ionic platform remove android
ionic platform add android


问:
Execute multiple url
I have a little problem. I need to execute an script that execute 5000 URL in php.

```<code>$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}
</code>```

Any idea??

Thx.

答:
First thing: header() is a primitive to send http headers to browser. It must be called before any stdout output (like 'print' or 'echo').

Second thing: "Location: " header will tell your browser to redirect to that URL. You can not specify more that one URL.

If you need your script to do http queries, use curl or fopen, and do not call your script from your browser.

Title: Execute multiple url

Body:
I have a little problem. I need to execute an script that execute 5000 URL in php.

$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}

Any idea??

Thx.


问:
Mockito: Intercept any methods that return a type
I've an interface like this:

```<code>public interface ICustomer extends IEnd<Customer> {
    String getId();
    ICustomer id(String id);
    ICustomer email(String email);
    ICustomer description(String description);
}
</code>```

I need to mock any methods which returns an ICustomer regardless of parameters.

When these methods are called, the self called ICustomer have to be returned.

Any ideas?

答:
To do this you need a custom Answer class:

```<code>public class CustomerAnswer implements Answer {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Class retType = invocation.getMethod().getReturnType();
        if (ICustomer.class.isInstance(retType)) {
            return invocation.getMock();
        }
        // provide default logic here -- override with "when()" calls.
        return null;
    }
}
</code>```

Then create your mock, specifying the default behavior:

```<code>Foo mockCustomer = mock(ICustomer.class, new CustomerAnswer());
</code>```

Add, when() statements for other methods that need to be stubbed.

But as I commented in the OP, be sure you actually want to mock this class  before you go thru all the trouble.  Only mock when it will make the test code simpler.  If you have some simple implementation of the interface that is just a POJO with fluent API (no side-effects, no complicated dependencies or injections), there is probably no need to mock it.  Instead use a real instance, because the real instance already returns the original object.

If you need to verify() on the ICustomer object, then use a @Spy of a real instance of a ICustomer.

Body:
I've an interface like this:

public interface ICustomer extends IEnd<Customer> {
    String getId();
    ICustomer id(String id);
    ICustomer email(String email);
    ICustomer description(String description);
}

I need to mock any methods which returns an ICustomer regardless of parameters.

When these methods are called, the self called ICustomer have to be returned.

Any ideas?

Body:
To do this you need a custom Answer class:

public class CustomerAnswer implements Answer {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Class retType = invocation.getMethod().getReturnType();
        if (ICustomer.class.isInstance(retType)) {
            return invocation.getMock();
        }
        // provide default logic here -- override with "when()" calls.
        return null;
    }
}

Then create your mock, specifying the default behavior:

Foo mockCustomer = mock(ICustomer.class, new CustomerAnswer());

Add, when() statements for other methods that need to be stubbed.

But as I commented in the OP, be sure you actually want to mock this class  before you go thru all the trouble.  Only mock when it will make the test code simpler.  If you have some simple implementation of the interface that is just a POJO with fluent API (no side-effects, no complicated dependencies or injections), there is probably no need to mock it.  Instead use a real instance, because the real instance already returns the original object.

If you need to verify() on the ICustomer object, then use a @Spy of a real instance of a ICustomer.


问:
Improve performance in Lat/Long geo location
I have two tables, Bins and Locations, the first with 3 million records, the second with 30 million. I am trying to match Bin for Location with the following code

```<code>Create Table #tbl_locations (LocationID int not null, Lat float not null, Lon float not null)
Create Table #tbl_bins (BinID int not null, MinLat float not null, MaxLat float not null, MinLon float not null, MaxLon float not null)

CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [#tbl_locations] ([Lat] ASC, [Lon] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [#tbl_bins] ([MinLat] ASC, [MaxLat] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [#tbl_bins] ([MinLon] ASC, [MaxLon] ASC)
ON [PRIMARY]

Select L.LocationID, C.BinID
From   #tbl_bins C
Inner Join #tbl_locations L
ON (L.Lat Between C.MinLat And C.MaxLat)
AND (L.Lon Between C.MinLon And C.MaxLon)
</code>```

Unfortunately the performance is extremely bad, I have already tried to index the different fields but that did not help enough. Everything still takes more than 10 minutes to run.

Any idea of how can I make this perform better? Maybe a better matching algorithm? SQL Server 2012 SP3.
BinID and LocationID already have a PRIMARY KEY CLUSTERED created on them.
When I check the Execution Plan I see that the JOIN is performed by a NESTED LOOP.

The output of STATISTICS IO is

```<code>Table '#tbl_locations_________________________________________________________________________________________________________000000000283'.
Scan count 2631070, logical reads 25575057, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#tbl_bins________________________________________________________________________________________________________000000000284'.
Scan count 17, logical reads 14741, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
</code>```

Thanks a lot!

Edit - if instead of Temp Tables I use real ones, this would be the schema exported

```<code>/****** Object:  Table [dbo].[tbl_Bins]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Bins](
    [BinID] [int] NOT NULL,
    [MinLat] [float] NOT NULL,
    [MaxLat] [float] NOT NULL,
    [MinLon] [float] NOT NULL,
    [MaxLon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_Bins] PRIMARY KEY CLUSTERED
(
    [BinID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tbl_Locations]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Locations](
    [ExposureID] [int] NOT NULL,
    [Accgrpid] [int] NOT NULL,
    [LocID] [int] NOT NULL,
    [Lat] [float] NOT NULL,
    [Lon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_locations] PRIMARY KEY CLUSTERED
(
    [ExposureID] ASC,
    [Accgrpid] ASC,
    [LocID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Index [IX_tbl_bins1]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [dbo].[tbl_Bins]
(
    [MinLat] ASC,
    [MaxLat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_bins2_ABC]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [dbo].[tbl_Bins]
(
    [MinLon] ASC,
    [MaxLon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_locations]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [dbo].[tbl_Locations]
(
    [Lat] ASC,
    [Lon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
</code>```

答:
I have found a way to improve this.

```<code>SELECT     L.LocationID, C.BinID
FROM       #tbl_bins C
INNER JOIN #tbl_locations L
ON         (L.Lat Between C.MinLat And C.MaxLat)
AND        (L.Lon Between C.MinLon And C.MaxLon)
WHERE FLOOR(C.MinLat * 1000 ) <= FLOOR(L.Lat*1000)
AND   FLOOR(C.MinLon * 1000 ) <= FLOOR(L.Lon*1000)
AND CEILING(C.MaxLat * 1000 ) >= CEILING(L.Lat*1000)
AND CEILING(C.MaxLon * 1000 ) >= CEILING(L.Lon*1000)
</code>```

This helps the query by reducing the amounts of Bins to join to 1.

Body:
I have two tables, Bins and Locations, the first with 3 million records, the second with 30 million. I am trying to match Bin for Location with the following code

Create Table #tbl_locations (LocationID int not null, Lat float not null, Lon float not null)
Create Table #tbl_bins (BinID int not null, MinLat float not null, MaxLat float not null, MinLon float not null, MaxLon float not null)

CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [#tbl_locations] ([Lat] ASC, [Lon] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [#tbl_bins] ([MinLat] ASC, [MaxLat] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [#tbl_bins] ([MinLon] ASC, [MaxLon] ASC)
ON [PRIMARY]

Select L.LocationID, C.BinID
From   #tbl_bins C
Inner Join #tbl_locations L
ON (L.Lat Between C.MinLat And C.MaxLat)
AND (L.Lon Between C.MinLon And C.MaxLon)

Unfortunately the performance is extremely bad, I have already tried to index the different fields but that did not help enough. Everything still takes more than 10 minutes to run.

Any idea of how can I make this perform better? Maybe a better matching algorithm? SQL Server 2012 SP3.
BinID and LocationID already have a PRIMARY KEY CLUSTERED created on them.
When I check the Execution Plan I see that the JOIN is performed by a NESTED LOOP.

The output of STATISTICS IO is

Table '#tbl_locations_________________________________________________________________________________________________________000000000283'.
Scan count 2631070, logical reads 25575057, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#tbl_bins________________________________________________________________________________________________________000000000284'.
Scan count 17, logical reads 14741, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Thanks a lot!

Edit - if instead of Temp Tables I use real ones, this would be the schema exported

/****** Object:  Table [dbo].[tbl_Bins]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Bins](
    [BinID] [int] NOT NULL,
    [MinLat] [float] NOT NULL,
    [MaxLat] [float] NOT NULL,
    [MinLon] [float] NOT NULL,
    [MaxLon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_Bins] PRIMARY KEY CLUSTERED
(
    [BinID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tbl_Locations]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Locations](
    [ExposureID] [int] NOT NULL,
    [Accgrpid] [int] NOT NULL,
    [LocID] [int] NOT NULL,
    [Lat] [float] NOT NULL,
    [Lon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_locations] PRIMARY KEY CLUSTERED
(
    [ExposureID] ASC,
    [Accgrpid] ASC,
    [LocID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Index [IX_tbl_bins1]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [dbo].[tbl_Bins]
(
    [MinLat] ASC,
    [MaxLat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_bins2_ABC]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [dbo].[tbl_Bins]
(
    [MinLon] ASC,
    [MaxLon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_locations]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [dbo].[tbl_Locations]
(
    [Lat] ASC,
    [Lon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Body:
I have found a way to improve this.

SELECT     L.LocationID, C.BinID
FROM       #tbl_bins C
INNER JOIN #tbl_locations L
ON         (L.Lat Between C.MinLat And C.MaxLat)
AND        (L.Lon Between C.MinLon And C.MaxLon)
WHERE FLOOR(C.MinLat * 1000 ) <= FLOOR(L.Lat*1000)
AND   FLOOR(C.MinLon * 1000 ) <= FLOOR(L.Lon*1000)
AND CEILING(C.MaxLat * 1000 ) >= CEILING(L.Lat*1000)
AND CEILING(C.MaxLon * 1000 ) >= CEILING(L.Lon*1000)

This helps the query by reducing the amounts of Bins to join to 1.


问:
Qt fails to open shell32.lib even when included
I have a QT 5.4 project compiling with MSVC2013 64 bit that throws the linker error
LNK1104: cannot open file 'shell32.lib'. Every Qt Widgets app on Windows requires this library.

This error is thrown regardless of whether a path to that lib is specified, and
if I include some other library, I get no error for that library, which leads me to believe that the Qt Creator is automatically looking for shell32 in a location specified somewhere other than the .pro file.

The .pro file looks like this.

```<code>QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app

SOURCES += main.cpp\
    mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

win32:CONFIG(release, debug|release): LIBS += $$quote(C:/Program Files             (x86)/Microsoft SDKs/Windows/v7.1A/Lib/shell32.lib)
else:win32:CONFIG(debug, debug|release): LIBS += $$quote(C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib/shell32.lib)

INCLUDEPATH += $$quote(C:/Program Files (x86)/Microsoft   SDKs/Windows/v7.1A/Include)
DEPENDPATH += $$quote(C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Include)
</code>```

Not sure if this is relevant, but shell32.lib is one of the libraries listed under the QMAKE_LIBS_CORE variable in qmake.conf.

SOLUTION

In the Projects tab on the left pane, add the desired library paths to the LIB variable, and add the path to SC.exe (also in the Windows SDK) to the PATH variable. The latter is necessary or else you get "LNK 1158: can't execute rc.exe."
Apparently the LIBS += statement in my .pro doesn't work, although INCLUDEPATH +=  does (I get "can't find windows.h" when it's removed).

I don't know why the LIBS+= doesn't work or why I also need the path to RC.exe (I never had to add it using Visual Studio), but at least there is a solution.

答: Visual Studio default install didn't include desktop apps:

Body:
I have a QT 5.4 project compiling with MSVC2013 64 bit that throws the linker error
LNK1104: cannot open file 'shell32.lib'. Every Qt Widgets app on Windows requires this library.

This error is thrown regardless of whether a path to that lib is specified, and
if I include some other library, I get no error for that library, which leads me to believe that the Qt Creator is automatically looking for shell32 in a location specified somewhere other than the .pro file.

The .pro file looks like this.

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app

SOURCES += main.cpp\
    mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

win32:CONFIG(release, debug|release): LIBS += $$quote(C:/Program Files             (x86)/Microsoft SDKs/Windows/v7.1A/Lib/shell32.lib)
else:win32:CONFIG(debug, debug|release): LIBS += $$quote(C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib/shell32.lib)

INCLUDEPATH += $$quote(C:/Program Files (x86)/Microsoft   SDKs/Windows/v7.1A/Include)
DEPENDPATH += $$quote(C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Include)

Not sure if this is relevant, but shell32.lib is one of the libraries listed under the QMAKE_LIBS_CORE variable in qmake.conf.

SOLUTION

In the Projects tab on the left pane, add the desired library paths to the LIB variable, and add the path to SC.exe (also in the Windows SDK) to the PATH variable. The latter is necessary or else you get "LNK 1158: can't execute rc.exe."
Apparently the LIBS += statement in my .pro doesn't work, although INCLUDEPATH +=  does (I get "can't find windows.h" when it's removed).

I don't know why the LIBS+= doesn't work or why I also need the path to RC.exe (I never had to add it using Visual Studio), but at least there is a solution.


问:
Java Android code in WinDev
I'm new in WinDev and I'm trying to create an Android application on a honeywell device with a barcode scanner.
I tried 2 different ways in Android Studio and they work.
One is the following:

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.honeywell.scanintent.ScanIntent;

public class MainActivity extends Activity {
    TextView barcodeData = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        barcodeData = (TextView) findViewById(R.id.textView);
    }

    public void onSendButtonClick(View v) {
        Intent intentScan = new Intent(ScanIntent.SCAN_ACTION);
        intentScan.addCategory(Intent.CATEGORY_DEFAULT);

        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        int loadmode = 0;

        intentScan.putExtra("scan_mode",ScanIntent.SCAN_MODE_RESULT_AS_URI);
        this.startActivityForResult(intentScan, 5);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == ScanIntent.SCAN_RESULT_SUCCESSED) {
            String data = intent.getStringExtra(ScanIntent.EXTRA_RESULT_BARCODE_DATA);
            int format = intent.getIntExtra(ScanIntent.EXTRA_RESULT_BARCODE_FORMAT, 0);
            barcodeData.setText(data);
        }
        else{
            barcodeData.setText("FALLITO");
        }
    }
}
</code>```

And the other way is this:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import com.honeywell.decodemanager.DecodeManager;
import com.honeywell.decodemanager.SymbologyConfigs;
import com.honeywell.decodemanager.barcode.DecodeResult;
import com.honeywell.decodemanager.symbologyconfig.SymbologyConfigCode39;

public final class MainActivity extends Activity {

    private final int ID_SCANSETTING = 0x12;
    private final int ID_CLEAR_SCREEN = 0x13;
    private final int SCANKEY        = 0x94;
    private DecodeManager mDecodeManager = null;
    private TextView mDecodeResultEdit = null;
    private final int SCANTIMEOUT = 2000;
    long mScanAccount = 0;
    private boolean mbKeyDown = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.button);
        mDecodeResultEdit = (TextView) findViewById(R.id.textView);
        button.setOnTouchListener(new Button.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                final int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        try {
                            if (mbKeyDown) {
                                DoScan();
                                mbKeyDown = false;
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        try {
                            mbKeyDown = true;
                            cancleScan();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                return true;
            }
        });
    }
        private void DoScan() throws Exception {
            try {
                mDecodeManager.doDecode(SCANTIMEOUT);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    @Override
    protected void onResume() {
        super.onResume();

        if (mDecodeManager == null) {
            mDecodeManager = new DecodeManager(this ,ScanResultHandler);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mDecodeManager != null) {
            try {
                mDecodeManager.release();
                mDecodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private Handler ScanResultHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DecodeManager.MESSAGE_DECODER_COMPLETE:
                    String strDecodeResult = "";
                    DecodeResult decodeResult = (DecodeResult) msg.obj;
                    strDecodeResult = "Decode Result::"+ decodeResult.barcodeData;

                    mDecodeResultEdit.setText(strDecodeResult);
                    break;

                case DecodeManager.MESSAGE_DECODER_FAIL:
                    mDecodeResultEdit.setText("FAILED");
                    break;

                case DecodeManager.MESSAGE_DECODER_READY:
                {
                    try {
                        SymbologyConfigCode39 code39 = new SymbologyConfigCode39();
                        code39.enableCheckEnable(false);
                        code39.enableSymbology(false);
                        code39.setMaxLength(48);
                        code39.setMinLength(2);

                        SymbologyConfigs symconfig = new SymbologyConfigs();

                        symconfig.addSymbologyConfig(code39);
                        mDecodeManager.setSymbologyConfigs(symconfig);

                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                    break;

                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private void cancleScan() throws Exception {
        mDecodeManager.cancelDecode();
    }
}
</code>```

On WinDev I created a GLOBAL JAVA PROCEDURE and I generated the application, importing the honeywell library, but I don't understand how to implement the android native functions. How can I do this?

Thank you so much!

答:
First add a Global Procedure set to your project and then in this set create an empty Global procedure.

Once the procedure is created on its header bar click on the letters WL and it will convert to JAVA code mode. Now paste you JAVA code!

HTH

Yogi Yang

Title: Java Android code in WinDev

Body:
I'm new in WinDev and I'm trying to create an Android application on a honeywell device with a barcode scanner.
I tried 2 different ways in Android Studio and they work.
One is the following:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.honeywell.scanintent.ScanIntent;

public class MainActivity extends Activity {
    TextView barcodeData = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        barcodeData = (TextView) findViewById(R.id.textView);
    }

    public void onSendButtonClick(View v) {
        Intent intentScan = new Intent(ScanIntent.SCAN_ACTION);
        intentScan.addCategory(Intent.CATEGORY_DEFAULT);

        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        int loadmode = 0;

        intentScan.putExtra("scan_mode",ScanIntent.SCAN_MODE_RESULT_AS_URI);
        this.startActivityForResult(intentScan, 5);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == ScanIntent.SCAN_RESULT_SUCCESSED) {
            String data = intent.getStringExtra(ScanIntent.EXTRA_RESULT_BARCODE_DATA);
            int format = intent.getIntExtra(ScanIntent.EXTRA_RESULT_BARCODE_FORMAT, 0);
            barcodeData.setText(data);
        }
        else{
            barcodeData.setText("FALLITO");
        }
    }
}

And the other way is this:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import com.honeywell.decodemanager.DecodeManager;
import com.honeywell.decodemanager.SymbologyConfigs;
import com.honeywell.decodemanager.barcode.DecodeResult;
import com.honeywell.decodemanager.symbologyconfig.SymbologyConfigCode39;

public final class MainActivity extends Activity {

    private final int ID_SCANSETTING = 0x12;
    private final int ID_CLEAR_SCREEN = 0x13;
    private final int SCANKEY        = 0x94;
    private DecodeManager mDecodeManager = null;
    private TextView mDecodeResultEdit = null;
    private final int SCANTIMEOUT = 2000;
    long mScanAccount = 0;
    private boolean mbKeyDown = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.button);
        mDecodeResultEdit = (TextView) findViewById(R.id.textView);
        button.setOnTouchListener(new Button.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                final int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        try {
                            if (mbKeyDown) {
                                DoScan();
                                mbKeyDown = false;
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        try {
                            mbKeyDown = true;
                            cancleScan();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                return true;
            }
        });
    }
        private void DoScan() throws Exception {
            try {
                mDecodeManager.doDecode(SCANTIMEOUT);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    @Override
    protected void onResume() {
        super.onResume();

        if (mDecodeManager == null) {
            mDecodeManager = new DecodeManager(this ,ScanResultHandler);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mDecodeManager != null) {
            try {
                mDecodeManager.release();
                mDecodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private Handler ScanResultHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DecodeManager.MESSAGE_DECODER_COMPLETE:
                    String strDecodeResult = "";
                    DecodeResult decodeResult = (DecodeResult) msg.obj;
                    strDecodeResult = "Decode Result::"+ decodeResult.barcodeData;

                    mDecodeResultEdit.setText(strDecodeResult);
                    break;

                case DecodeManager.MESSAGE_DECODER_FAIL:
                    mDecodeResultEdit.setText("FAILED");
                    break;

                case DecodeManager.MESSAGE_DECODER_READY:
                {
                    try {
                        SymbologyConfigCode39 code39 = new SymbologyConfigCode39();
                        code39.enableCheckEnable(false);
                        code39.enableSymbology(false);
                        code39.setMaxLength(48);
                        code39.setMinLength(2);

                        SymbologyConfigs symconfig = new SymbologyConfigs();

                        symconfig.addSymbologyConfig(code39);
                        mDecodeManager.setSymbologyConfigs(symconfig);

                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                    break;

                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private void cancleScan() throws Exception {
        mDecodeManager.cancelDecode();
    }
}

On WinDev I created a GLOBAL JAVA PROCEDURE and I generated the application, importing the honeywell library, but I don't understand how to implement the android native functions. How can I do this?

Thank you so much!


问:
Asp.net convert textbox input to upper case on key down with jQuery
I want to convert the text in a textbox to uppercase as the user writes it.

Html/aspx:

```<code><asp:TextBox runat="server" ID="mytextbox" onkeydown="toUpperCase()"></asp:TextBox>
</code>```

jQuery

```<code>function toUpperCase() {
    $(this.val) = this.val.toUpperCase();
}
</code>```

答:
Your code should look like $(this).val($(this).val().toUpperCase());

Also you could just use pure css.

```<code> #mytextbox{
    text-transform:uppercase;
 }
</code>```

$('#mytextbox').keyup(function() {
    $(this).val($(this).val().toUpperCase());
})```
<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>
<textarea id="mytextbox"></textarea></code>```

Body:
I want to convert the text in a textbox to uppercase as the user writes it.

Html/aspx:

<asp:TextBox runat="server" ID="mytextbox" onkeydown="toUpperCase()"></asp:TextBox>

jQuery

function toUpperCase() {
    $(this.val) = this.val.toUpperCase();
}

Body:
Your code should look like $(this).val($(this).val().toUpperCase());

Also you could just use pure css.

 #mytextbox{
    text-transform:uppercase;
 }

$('#mytextbox').keyup(function() {
    $(this).val($(this).val().toUpperCase());
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytextbox"></textarea>