问:
c# - Improve execution time when generating report
I have a program in visual studio 2010 where I have a function to generate report to crystal report. The query is supplied in one of my stored procedure to retrieve information from my database.

The issue I have when I click generate report, it takes a long time to return the result. I was wondering if anyone has suggestion on how to improve the execution time faster by optimizing the query in the stored procedure ?

Here is a snippet of the stored procedure:

```<code>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[M_RPT_DailyIssuedVoucher]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'ALTER PROCEDURE [dbo].[M_RPT_DailyIssuedVoucher]
    @EventCode [varchar](8),
    @LocID [varchar](10),
    @Status [char](2),
    @DtFrom [datetime],
    @DtTo [datetime],
    @IssuedBy [nvarchar](128)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

Select SerialNo,
         CardID,
         CardHolder AS [Name],
         CardType,
         EventCode,
         IssueDate,
         IssueBy,
         ValidFromDate,
         ValidToDate,
         IssueLocationID,
         IssueComputerName,
         ManualIssueReason,
         [Status],
         Remarks,
         CancelReason
/*      '' CollectedStatus ='' +
            '' CASE''+
                '' WHEN LTRIM(RTRIM(CollectBy))<>'''''''' THEN ''''Y''''''+
                '' ELSE ''''N''''''+
            '' END'' +
*/
    FROM IssuedVoucher with (nolock)
    WHERE
(@EventCode = '''' OR (EventCode = @EventCode))
And(@IssuedBy = '''' OR (IssueBy= @IssuedBy))
AND (@LocID = '''' OR (IssueLocationID = @LocID))
AND (@Status = '''' OR (Status = @Status))
AND(@DtFrom IS NULL OR IssueDate >= @DtFrom )
AND (@DtTo IS NULL OR IssueDate <= @DtTo)

 ORDER BY SerialNo, EventCode
</code>```

Here is the query for create table for issuedvoucher :

```<code>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[IssuedVoucher](
    [BatchNo] [decimal](18, 0) NOT NULL,
    [SerialNo] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ManualIssueReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [IssueLocationId] [varchar](8) COLLATE Latin1_General_CI_AS NULL,
    [IssueComputerName] [varchar](25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Remarks] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardId] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardHolder] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardType] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [EventCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PromotionBenefitCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ValidFromDate] [datetime] NOT NULL,
    [ValidToDate] [datetime] NOT NULL,
    [VisiblePoint] [decimal](18, 2) NOT NULL,
    [HiddenPoint] [decimal](18, 2) NOT NULL,
    [LoyaltyPoint] [decimal](18, 2) NOT NULL,
    [NNECash] [decimal](18, 0) NULL,
    [Status] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PrintStatus] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [IssueDate] [datetime] NOT NULL,
    [IssueBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CollectDate] [datetime] NOT NULL,
    [CollectBY] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CollectLocationId] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CancelReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [LastChangeBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [LastChangeDate] [datetime] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [AllotmentID] [decimal](18, 0) NOT NULL,
    [GuestType] [bit] NOT NULL,
    [CompanyID] [bigint] NULL,
    [DepartmentID] [smallint] NULL,
    [IDIssuedCountry] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
    [EVoucherBatchNo] [decimal](18, 0) NULL,
    [EVoucherGuestNo] [decimal](18, 0) NULL,
    [EVoucherSerialNo] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [Barcode] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [Monetary] [bit] NOT NULL,
    [Discount] [bit] NOT NULL,
    [ConsiderationValue] [decimal](18, 2) NULL,
    [FaceValue] [decimal](18, 0) NULL,
    [IntercoRate] [decimal](18, 0) NULL,
    [SAPCostCentre] [varchar](10) COLLATE Latin1_General_CI_AS NULL,
    [SAPIONumber] [varchar](25) COLLATE Latin1_General_CI_AS NULL,
    [IsGift] [bit] NOT NULL,
    [PrintCount] [int] NOT NULL,
    [TaxInvoiceID] [decimal](18, 0) NULL,
    [IdentificationNumber] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [IdentificationType] [varchar](5) COLLATE Latin1_General_CI_AS NULL,
    [CRMEntitlementMasterID] [nvarchar](20) COLLATE Latin1_General_CI_AS NULL,
    [DeductPointType] [smallint] NULL,
    [DeductCreditType] [smallint] NULL,
    [AwardPointType] [smallint] NULL,
    [AwardCreditType] [smallint] NULL,
    [AwardCreditValue] [decimal](18, 2) NULL,
    [deductPointvalue] [decimal](18, 2) NULL,
    [deductCreditvalue] [decimal](18, 2) NULL,
    [AwardPointvalue] [decimal](18, 2) NULL,
 CONSTRAINT [PK_IssuedVoucher2] PRIMARY KEY CLUSTERED
(
    [SerialNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Index [_dta_index_IssuedVoucher_18_1736445310__K1]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'_dta_index_IssuedVoucher_18_1736445310__K1')
CREATE NONCLUSTERED INDEX [_dta_index_IssuedVoucher_18_1736445310__K1] ON [dbo].[IssuedVoucher]
(
    [BatchNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55')
CREATE NONCLUSTERED INDEX [_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55] ON [dbo].[IssuedVoucher]
(
    [SerialNo] ASC,
    [EventCode] ASC
)
INCLUDE (   [CardId],
    [CancelReason],
    [IdentificationNumber]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [idx_CardID]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'idx_CardID')
CREATE NONCLUSTERED INDEX [idx_CardID] ON [dbo].[IssuedVoucher]
(
    [BatchNo] ASC,
    [CardId] ASC,
    [Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [IX_IssuedVoucher_1]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'IX_IssuedVoucher_1')
CREATE NONCLUSTERED INDEX [IX_IssuedVoucher_1] ON [dbo].[IssuedVoucher]
(
    [CardId] ASC,
    [CardType] ASC,
    [EventCode] ASC,
    [PromotionBenefitCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [RecordVoucher]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'RecordVoucher')
CREATE NONCLUSTERED INDEX [RecordVoucher] ON [dbo].[IssuedVoucher]
(
    [EVoucherSerialNo] ASC,
    [Barcode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
GO
</code>```

答:
First of all,  why you alter proc every time is not understandable to me ?

you may simply call proc from your code and put only Select onward in dynamic Sql.

you can modify your inner select query in this manner.If your table is well index then it may take advantage of index .

```<code>             declare @EventCode [varchar](8)
   declare @LocID [varchar](10)
   declare @Status [char](2)
   declare @DtFrom [datetime]
   declare @DtTo [datetime]
   declare @IssuedBy [nvarchar](128)
   declare @SqlCondtion nvarchar(max)=''

   DECLARE @ParmDefinition nvarchar(500);
    SET @ParmDefinition = N'@EventCode1 [varchar](8)
                            , @LocID1 [varchar](10)
                            , @Status1 [char](2)
                            , @DtFrom1 [datetime]
                            ,@DtTo1 [datetime]
                            ,@IssuedBy1 [nvarchar](128)';

declare @Sql nvarchar(max)=N'Select SerialNo,
         CardID,
         CardHolder AS [Name],
         CardType,
         EventCode,
         IssueDate,
         IssueBy,
         ValidFromDate,
         ValidToDate,
         IssueLocationID,
         IssueComputerName,
         ManualIssueReason,
         [Status],
         Remarks,
         CancelReason
    FROM IssuedVoucher with (nolock)
    WHERE 1=1 '

if(@EventCode is not null)
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and EventCode = @EventCode1 '

if(@IssuedBy is not null)
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and IssueBy = @IssuedBy1 '

if(@LocID is not null  )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and IssueLocationID = @LocID1 '

if(@Status is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [Status] = @Status1 '

if(@DtFrom is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [IssueDate] >= @DtFrom1 '

if(@DtTo is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [IssueDate] <= @DtTo1 '

set @Sql=@Sql+CHAR(10)+@SqlCondtion

print @Sql
EXECUTE sp_executesql @Sql, @ParmDefinition, @EventCode1 = @EventCode, @IssuedBy1=@IssuedBy ,@LocID1=@LocID
                                            ,@Status1=@Status,@DtFrom1=@DtFrom,@DtTo1=@DtTo;
</code>```

you can further modify this script suiting you requirement or fix bug.print should be commented after debug.

Body:
I have a program in visual studio 2010 where I have a function to generate report to crystal report. The query is supplied in one of my stored procedure to retrieve information from my database.

The issue I have when I click generate report, it takes a long time to return the result. I was wondering if anyone has suggestion on how to improve the execution time faster by optimizing the query in the stored procedure ?

Here is a snippet of the stored procedure:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[M_RPT_DailyIssuedVoucher]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'ALTER PROCEDURE [dbo].[M_RPT_DailyIssuedVoucher]
    @EventCode [varchar](8),
    @LocID [varchar](10),
    @Status [char](2),
    @DtFrom [datetime],
    @DtTo [datetime],
    @IssuedBy [nvarchar](128)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

Select SerialNo,
         CardID,
         CardHolder AS [Name],
         CardType,
         EventCode,
         IssueDate,
         IssueBy,
         ValidFromDate,
         ValidToDate,
         IssueLocationID,
         IssueComputerName,
         ManualIssueReason,
         [Status],
         Remarks,
         CancelReason
/*      '' CollectedStatus ='' +
            '' CASE''+
                '' WHEN LTRIM(RTRIM(CollectBy))<>'''''''' THEN ''''Y''''''+
                '' ELSE ''''N''''''+
            '' END'' +
*/
    FROM IssuedVoucher with (nolock)
    WHERE
(@EventCode = '''' OR (EventCode = @EventCode))
And(@IssuedBy = '''' OR (IssueBy= @IssuedBy))
AND (@LocID = '''' OR (IssueLocationID = @LocID))
AND (@Status = '''' OR (Status = @Status))
AND(@DtFrom IS NULL OR IssueDate >= @DtFrom )
AND (@DtTo IS NULL OR IssueDate <= @DtTo)

 ORDER BY SerialNo, EventCode

Here is the query for create table for issuedvoucher :

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[IssuedVoucher](
    [BatchNo] [decimal](18, 0) NOT NULL,
    [SerialNo] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ManualIssueReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [IssueLocationId] [varchar](8) COLLATE Latin1_General_CI_AS NULL,
    [IssueComputerName] [varchar](25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Remarks] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardId] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardHolder] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CardType] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [EventCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PromotionBenefitCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ValidFromDate] [datetime] NOT NULL,
    [ValidToDate] [datetime] NOT NULL,
    [VisiblePoint] [decimal](18, 2) NOT NULL,
    [HiddenPoint] [decimal](18, 2) NOT NULL,
    [LoyaltyPoint] [decimal](18, 2) NOT NULL,
    [NNECash] [decimal](18, 0) NULL,
    [Status] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PrintStatus] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [IssueDate] [datetime] NOT NULL,
    [IssueBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CollectDate] [datetime] NOT NULL,
    [CollectBY] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CollectLocationId] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [CancelReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [LastChangeBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [LastChangeDate] [datetime] NOT NULL,
    [RecordVersion] [timestamp] NOT NULL,
    [AllotmentID] [decimal](18, 0) NOT NULL,
    [GuestType] [bit] NOT NULL,
    [CompanyID] [bigint] NULL,
    [DepartmentID] [smallint] NULL,
    [IDIssuedCountry] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
    [EVoucherBatchNo] [decimal](18, 0) NULL,
    [EVoucherGuestNo] [decimal](18, 0) NULL,
    [EVoucherSerialNo] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [Barcode] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [Monetary] [bit] NOT NULL,
    [Discount] [bit] NOT NULL,
    [ConsiderationValue] [decimal](18, 2) NULL,
    [FaceValue] [decimal](18, 0) NULL,
    [IntercoRate] [decimal](18, 0) NULL,
    [SAPCostCentre] [varchar](10) COLLATE Latin1_General_CI_AS NULL,
    [SAPIONumber] [varchar](25) COLLATE Latin1_General_CI_AS NULL,
    [IsGift] [bit] NOT NULL,
    [PrintCount] [int] NOT NULL,
    [TaxInvoiceID] [decimal](18, 0) NULL,
    [IdentificationNumber] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [IdentificationType] [varchar](5) COLLATE Latin1_General_CI_AS NULL,
    [CRMEntitlementMasterID] [nvarchar](20) COLLATE Latin1_General_CI_AS NULL,
    [DeductPointType] [smallint] NULL,
    [DeductCreditType] [smallint] NULL,
    [AwardPointType] [smallint] NULL,
    [AwardCreditType] [smallint] NULL,
    [AwardCreditValue] [decimal](18, 2) NULL,
    [deductPointvalue] [decimal](18, 2) NULL,
    [deductCreditvalue] [decimal](18, 2) NULL,
    [AwardPointvalue] [decimal](18, 2) NULL,
 CONSTRAINT [PK_IssuedVoucher2] PRIMARY KEY CLUSTERED
(
    [SerialNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Index [_dta_index_IssuedVoucher_18_1736445310__K1]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'_dta_index_IssuedVoucher_18_1736445310__K1')
CREATE NONCLUSTERED INDEX [_dta_index_IssuedVoucher_18_1736445310__K1] ON [dbo].[IssuedVoucher]
(
    [BatchNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55')
CREATE NONCLUSTERED INDEX [_dta_index_IssuedVoucher_18_1736445310__K2_K10_7_25_55] ON [dbo].[IssuedVoucher]
(
    [SerialNo] ASC,
    [EventCode] ASC
)
INCLUDE (   [CardId],
    [CancelReason],
    [IdentificationNumber]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [idx_CardID]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'idx_CardID')
CREATE NONCLUSTERED INDEX [idx_CardID] ON [dbo].[IssuedVoucher]
(
    [BatchNo] ASC,
    [CardId] ASC,
    [Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [IX_IssuedVoucher_1]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'IX_IssuedVoucher_1')
CREATE NONCLUSTERED INDEX [IX_IssuedVoucher_1] ON [dbo].[IssuedVoucher]
(
    [CardId] ASC,
    [CardType] ASC,
    [EventCode] ASC,
    [PromotionBenefitCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 80) ON [PRIMARY]
GO

SET ANSI_PADDING ON
GO

/****** Object:  Index [RecordVoucher]    Script Date: 04/12/2017 3:39:19 PM ******/
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[IssuedVoucher]') AND name = N'RecordVoucher')
CREATE NONCLUSTERED INDEX [RecordVoucher] ON [dbo].[IssuedVoucher]
(
    [EVoucherSerialNo] ASC,
    [Barcode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
GO

Body:
First of all,  why you alter proc every time is not understandable to me ?

you may simply call proc from your code and put only Select onward in dynamic Sql.

you can modify your inner select query in this manner.If your table is well index then it may take advantage of index .

             declare @EventCode [varchar](8)
   declare @LocID [varchar](10)
   declare @Status [char](2)
   declare @DtFrom [datetime]
   declare @DtTo [datetime]
   declare @IssuedBy [nvarchar](128)
   declare @SqlCondtion nvarchar(max)=''

   DECLARE @ParmDefinition nvarchar(500);
    SET @ParmDefinition = N'@EventCode1 [varchar](8)
                            , @LocID1 [varchar](10)
                            , @Status1 [char](2)
                            , @DtFrom1 [datetime]
                            ,@DtTo1 [datetime]
                            ,@IssuedBy1 [nvarchar](128)';

declare @Sql nvarchar(max)=N'Select SerialNo,
         CardID,
         CardHolder AS [Name],
         CardType,
         EventCode,
         IssueDate,
         IssueBy,
         ValidFromDate,
         ValidToDate,
         IssueLocationID,
         IssueComputerName,
         ManualIssueReason,
         [Status],
         Remarks,
         CancelReason
    FROM IssuedVoucher with (nolock)
    WHERE 1=1 '

if(@EventCode is not null)
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and EventCode = @EventCode1 '

if(@IssuedBy is not null)
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and IssueBy = @IssuedBy1 '

if(@LocID is not null  )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and IssueLocationID = @LocID1 '

if(@Status is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [Status] = @Status1 '

if(@DtFrom is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [IssueDate] >= @DtFrom1 '

if(@DtTo is not null )
set @SqlCondtion=@SqlCondtion+CHAR(10)+ 'and [IssueDate] <= @DtTo1 '

set @Sql=@Sql+CHAR(10)+@SqlCondtion

print @Sql
EXECUTE sp_executesql @Sql, @ParmDefinition, @EventCode1 = @EventCode, @IssuedBy1=@IssuedBy ,@LocID1=@LocID
                                            ,@Status1=@Status,@DtFrom1=@DtFrom,@DtTo1=@DtTo;

you can further modify this script suiting you requirement or fix bug.print should be commented after debug.


来源: stackexchange

问:
How to update SQL Table from two gridviews
Merging three gridview into one.
This is the First Gridview

```<code>ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
   1         Soap         1
   2         Bag          2
   3         Cycle        3
   4         Scissors     4
   5         Pen          5
</code>```

This is the Second Gridview

```<code> ItemCode   NewCode
 1          55874
 2          889746210
 5          466897
</code>```

This is the Third Gridview

```<code>ItemCode   SellingPrice   PurchasePrice   MRP
 1            25               20          25
 2            150              130         150
 3            7500             6500        7500
 4            20               17          17
 5            10               8           10
</code>```

I want the first gridview to be updated with the above values and save it into the database

```<code>ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
1         Soap       55874         25            20          25
2         Bag        889746210     150           130         150
3         Cycle      3             7500          6500        7500
4         Scissors   4             20            17          17
5         Pen        466897        10            8           10
</code>```

答:
try something like this:</p>

```<code>    SELECT
a.ItemCode,a.Itemname,a.NewCode,a.SellingPrice,a.PurchasePrice,a.MRP,
b.ItemCode,IFNULL(b.NewCode, a.NewCode) as NewCode,
c.ItemCode,c.SellingPrice,c.PurchasePrice,c.MRP
FROM First a
LEFT JOIN Second b
    on a.ItemCode=b.ItemCode
LEFT JOIN Third c
    on a.ItemCode=c.ItemCode
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Merging three gridview into one.
This is the First Gridview

ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
   1         Soap         1
   2         Bag          2
   3         Cycle        3
   4         Scissors     4
   5         Pen          5

This is the Second Gridview

 ItemCode   NewCode
 1          55874
 2          889746210
 5          466897

This is the Third Gridview

ItemCode   SellingPrice   PurchasePrice   MRP
 1            25               20          25
 2            150              130         150
 3            7500             6500        7500
 4            20               17          17
 5            10               8           10

I want the first gridview to be updated with the above values and save it into the database

ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
1         Soap       55874         25            20          25
2         Bag        889746210     150           130         150
3         Cycle      3             7500          6500        7500
4         Scissors   4             20            17          17
5         Pen        466897        10            8           10

Body:
try something like this:

    SELECT
a.ItemCode,a.Itemname,a.NewCode,a.SellingPrice,a.PurchasePrice,a.MRP,
b.ItemCode,IFNULL(b.NewCode, a.NewCode) as NewCode,
c.ItemCode,c.SellingPrice,c.PurchasePrice,c.MRP
FROM First a
LEFT JOIN Second b
    on a.ItemCode=b.ItemCode
LEFT JOIN Third c
    on a.ItemCode=c.ItemCode


问:
How do i get right the directory of my application?
I've made a small console application (first publish in c#). but i cant use my resource files. I used textfiles can give it. It worked when i used the debug directory

My goal is to create a directory like this:
Applicationmap
+ application.exe
+ setup
resource map
+ configurations.txt
Logger
+ .

Now if i try to reach the configuration file it sends me to:
C:\Users\<username> \AppData\Local\Apps\2.0\D01L7N51.9EW\R7HB7NAB.B7Y
\sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

While i'm expecting C:/Users/<username>/ Documents/<application>/ + resources/config.txt.

I've tried

```<code>string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);
</code>```

&&

```<code>Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
</code>```

&&

```<code>Console.WriteLine(Directory.GetCurrentDirectory());
</code>```

but i always end up at the appdata map.

答:
How about:</p>

```<code>System.IO.Path.GetDirectoryName(Application.ExecutablePath);
</code>```

Body:
I've made a small console application (first publish in c#). but i cant use my resource files. I used textfiles can give it. It worked when i used the debug directory

My goal is to create a directory like this:
Applicationmap
+ application.exe
+ setup
resource map
+ configurations.txt
Logger
+ .

Now if i try to reach the configuration file it sends me to:
C:\Users\<username> \AppData\Local\Apps\2.0\D01L7N51.9EW\R7HB7NAB.B7Y
\sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

While i'm expecting C:/Users/<username>/ Documents/<application>/ + resources/config.txt.

I've tried

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);

&&

Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

&&

Console.WriteLine(Directory.GetCurrentDirectory());

but i always end up at the appdata map.

Body:
How about:

System.IO.Path.GetDirectoryName(Application.ExecutablePath);


问:
Most useful Rails plugins, Ruby libraries and Ruby gems?
I have seen many sites which provide the whole list of Rails plugins, Ruby libraries and Ruby gems, but we hardly use few of them and some may not suit our requirement and we spend a whole lot of time searching for useful Plugins which suits our requirement.

I have created this poll, people can post useful libraries, gems and plugins which they have come across.  It would be great help for newbies like me and to the entire Ruby on Rails community.

Note: to keep this poll as useful as possible, please remember:

Post only one library, gem, or plugin per answer

Mention the name of the library, gem, or plugin which you find it useful.

URL of the location of the resource

We don't want duplicate answers, so before posting check if the library has been mentioned already.

Edit:  Any new plugins/Gems for Rails 3 ?

Thanks!

答:
Cucumber - BDD and testing

It lets software development teams describe how software should behave in plain text. The text is written in a business-readable domain-specific language and serves as documentation, automated tests and development-aid - all rolled into one format.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
How can I show filenames in quickfix window as relative path to current (:pwd) directory?
When I run :make with maven the filenames are reported by maven as absolute paths, and the quickfix window will present the absolute path which is much wider that the size of the window.

```<code>:set makeprg=mvn\ install
:set errorformat=[%tRROR]\ %f:[%l\\,%c]%m,%-G%.%#
:make
</code>```

How can I get the quickfix window to show filenames relative to my current directory :pwd?

答:
As a workaround it is possible to run :lcd . before :copen. It seems that paths are actually relative to the current directory of the current window and by running :lcd . you make the current directory and the current direction of the current window the same. So when the quickfix window opens it will inherit the "right" current directory.

You don't need to rerun :make for the change to make effect. You can just :cclose the quickfix and lcd . and reopen the quickfix :copen

```<code>:set makeprg=mvn\ install
:set errorformat=[%tRROR]\ %f:[%l\\,%c]%m,%-G%.%#
:make
:lcd .
:copen
</code>```

Body:
When I run :make with maven the filenames are reported by maven as absolute paths, and the quickfix window will present the absolute path which is much wider that the size of the window.

:set makeprg=mvn\ install
:set errorformat=[%tRROR]\ %f:[%l\\,%c]%m,%-G%.%#
:make

How can I get the quickfix window to show filenames relative to my current directory :pwd?

Body:
As a workaround it is possible to run :lcd . before :copen. It seems that paths are actually relative to the current directory of the current window and by running :lcd . you make the current directory and the current direction of the current window the same. So when the quickfix window opens it will inherit the "right" current directory.

You don't need to rerun :make for the change to make effect. You can just :cclose the quickfix and lcd . and reopen the quickfix :copen

:set makeprg=mvn\ install
:set errorformat=[%tRROR]\ %f:[%l\\,%c]%m,%-G%.%#
:make
:lcd .
:copen


问:
unicode code points to utf-8 python

I downloaded tweets in Urdu language. When I read the csv file using pandas in python, the tweet is shown as follows:

Sample tweet text

Unicode code point
I want to convert this into utf-8.

答:
When you are writing the tweet data to a file use .decode('utf-8')
And when you try to read data from that file use .encode('utf-8')

Here I am posting an example:

```<code># -*- coding: utf-8 -*-
string1 = "آکاش کمار"
string2 = string1.decode('utf-8')
string3 = string2.encode('utf-8')
print(string3)
</code>```

Title: unicode code points to utf-8 python

Body:
When you are writing the tweet data to a file use .decode('utf-8')
And when you try to read data from that file use .encode('utf-8')

Here I am posting an example:

# -*- coding: utf-8 -*-
string1 = "آکاش کمار"
string2 = string1.decode('utf-8')
string3 = string2.encode('utf-8')
print(string3)


问:
How to convert a varchar data type field to a timestamp with time zone type field in redshift?
I have a table where the timestamp is stored as a varchar. I need to convert it to timestamp with timezone but every time I get "Invalid Operation" error.

The format of the field is:

```<code>2017-10-30 10:12:34:154 +1100
</code>```

I tried the following:

```<code>'2017-10-30 10:12:34:154 +1100'::timestamptz
'2017-10-30 10:12:34:154 +1100'::timestamp
to_timestamp('2017-10-30 10:12:34:154 +1100')
to_date('2017-10-30 10:12:34:154 +1100')
to_timestamp(to_char('2017-10-30 10:12:34:154 +1100'))
</code>```

All gave an error like this:

```<code>[Amazon](500310) Invalid operation: function to_timestamp(character varying) does not exist;
</code>```

Can somebody please help?

答:
For the benefit of all, here's how I solved my question. Basically, the problem was that the acceptable syntax for timestamp with timezone in redshift was '2017-10-30 10:12:34.154 +1100' where the milliseconds was after the '.' and not after ':'. Although, I am not sure of this. But this seemed to be the only problem from the redshift documentation and playing around a bit.

The substr_replace didn't work in my case since the length of the date and time keeps varying like these two -

```<code>'2017-10-30 10:12:34:154 +1100' , '2017-10-3 5:12:34:154 +1100'
</code>```

So, I split all three fields and added them back in proper syntax after removing milliseconds since I didn't need that.

```<code>(split_part(m.properties_date_time_tz,' ',1)||' '||substring(split_part(m.properties_date_time_tz,' ',2),0,length(split_part(m.properties_date_time_tz,' ',2))-3)||' '||split_part(m.properties_date_time_tz,' ',3))::timestamptz
</code>```

where properties_date_time_tz had a value like '2017-10-30 10:12:34:154 +1100'

Body:
I have a table where the timestamp is stored as a varchar. I need to convert it to timestamp with timezone but every time I get "Invalid Operation" error.

The format of the field is:

2017-10-30 10:12:34:154 +1100

I tried the following:

'2017-10-30 10:12:34:154 +1100'::timestamptz
'2017-10-30 10:12:34:154 +1100'::timestamp
to_timestamp('2017-10-30 10:12:34:154 +1100')
to_date('2017-10-30 10:12:34:154 +1100')
to_timestamp(to_char('2017-10-30 10:12:34:154 +1100'))

All gave an error like this:

[Amazon](500310) Invalid operation: function to_timestamp(character varying) does not exist;

Can somebody please help?

Body:
For the benefit of all, here's how I solved my question. Basically, the problem was that the acceptable syntax for timestamp with timezone in redshift was '2017-10-30 10:12:34.154 +1100' where the milliseconds was after the '.' and not after ':'. Although, I am not sure of this. But this seemed to be the only problem from the redshift documentation and playing around a bit.

The substr_replace didn't work in my case since the length of the date and time keeps varying like these two -

'2017-10-30 10:12:34:154 +1100' , '2017-10-3 5:12:34:154 +1100'

So, I split all three fields and added them back in proper syntax after removing milliseconds since I didn't need that.

(split_part(m.properties_date_time_tz,' ',1)||' '||substring(split_part(m.properties_date_time_tz,' ',2),0,length(split_part(m.properties_date_time_tz,' ',2))-3)||' '||split_part(m.properties_date_time_tz,' ',3))::timestamptz

where properties_date_time_tz had a value like '2017-10-30 10:12:34:154 +1100'


问:
How to create a QJsonDocument?
I would like to create a QJsonDocument but I can't find a way to push my data in the document. At the end of JsonBuilder::CreateContact my document seem to be empty. Some help would be great please X).

I've tried to use some pointer and add them to my doc because I was thinking of the destruction of my different object (contactObj, detailObj, addressObj, date) but with this method I can't build the type QJsonValue (can't access private member of QjsonValue::QJsonValue) so am I wrong ?

JsonBuilder.h

```<code>#ifndef JSONBUILDER_H
#define JSONBUILDER_H
#include <QObject>
#include <QJsonDocument>
#include <QMap>
#include <QString>
#include <QList>

class JsonBuilder: public QObject
{
    Q_OBJECT
private:
    QJsonDocument* document;
public:
    JsonBuilder();
    ~JsonBuilder();
    void CreateContact(QMap<QString,QList<QString>> map);
    void CreateMessage(QMap<QString,QString> map);

    QJsonDocument* getDocument(){ return document; }
};

#endif // JSONBUILDER_H
</code>```

JsonBuilder.cpp

```<code>#include "Jsonbuilder.h"
#include <QPair>
#include <QJsonObject>
#include <QJsonValue>
#include <Global.h>
#include <QDebug>
#include <QMapIterator>
#include <QJsonArray>

JsonBuilder::JsonBuilder(){
    document = new QJsonDocument(QJsonArray());
}

void JsonBuilder::CreateContact(QMap<QString, QList<QString>> map){
    QJsonObject contactObj;
    QJsonObject detailObj;
    QJsonObject addressObj;
    QJsonObject date;

    contactObj.insert(Global::KEY_TYPE_OBJ,QJsonValue("contact"));

    QMapIterator<QString, QList<QString>> it(map);

    while (it.hasNext()) {

        it.next();
        qDebug()<< "Key value = "+it.key();
        if(it.key() == Global::KEY_FIRST_NAME){
            contactObj.insert(Global::KEY_FIRST_NAME,QJsonValue(it.value()[0]));
            qDebug()<< "create firstName in Json " + it.value()[0];
        }

        if(it.key() == Global::KEY_LAST_NAME){
            contactObj.insert(Global::KEY_LAST_NAME,QJsonValue(it.value()[0]));
            qDebug()<< "create LastName in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_PSEUDO){
            QJsonArray Pseudos;
            foreach (QString contact, it.value()) {
                Pseudos.append(QJsonValue(contact));
                qDebug()<< "create Pseudo in Json "+ contact;
            }
            contactObj.insert(Global::KEY_PSEUDO,QJsonValue(Pseudos));
        }

        //Detail Object
        if(it.key() == Global::KEY_DETAIL_ROLE){
            detailObj.insert(Global::KEY_DETAIL_ROLE,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailRole in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_ORGANIZATION){
            detailObj.insert(Global::KEY_DETAIL_ORGANIZATION,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailOrganization in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_DEPARTMENT){
            detailObj.insert(Global::KEY_DETAIL_DEPARTMENT,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailDepartment in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_FUNCTION){
            detailObj.insert(Global::KEY_DETAIL_FUNCTION,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailFunction in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_PHONE){
            QJsonArray phones;
            foreach (QString phone, it.value()) {
                phones.append(QJsonValue(phone));
                qDebug()<< "create Phones in Json "+phone;
            }
            contactObj.insert(Global::KEY_PHONE,QJsonValue(phones));
        }

        if(it.key() == Global::KEY_EMAIL){
            QJsonArray emails;
            foreach (QString email, it.value()) {
                emails.append(QJsonValue(email));
                qDebug()<< "create Emails in Json "+email;
            }
            contactObj.insert(Global::KEY_EMAIL,QJsonValue(emails));

        }

        //Dates Object
        if(it.key() == Global::KEY_BIRTHDAY){
            date.insert(Global::KEY_BIRTHDAY,QJsonValue(it.value()[0]));
            qDebug()<< "create Birthday in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_WEDDING){
            foreach (QString dateWedding, it.value()) {
                date.insert(Global::KEY_WEDDING, QJsonValue(dateWedding));
                qDebug()<< "create wedding in Json "+dateWedding;
            }
        }

        //Address Object
        if(it.key() == Global::KEY_STREET){
            addressObj.insert(Global::KEY_STREET,QJsonValue(it.value()[0]));
            qDebug()<< "create street in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_POSTAL_CODE){
            addressObj.insert(Global::KEY_POSTAL_CODE,QJsonValue(it.value()[0]));
            qDebug()<< "create PostalCode in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_CITY){
            addressObj.insert(Global::KEY_CITY, QJsonValue(it.value()[0]));
            qDebug()<< "create city in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_COUNTRY){
            addressObj.insert(Global::KEY_COUNTRY, QJsonValue(it.value()[0]));
            qDebug()<< "create Country in Json "+it.value()[0];
        }
    }

    contactObj.insert(Global::KEY_DETAIL,QJsonValue(detailObj));
    contactObj.insert(Global::KEY_ADDRESS_OBJ,QJsonValue(addressObj));
    contactObj.insert(Global::KEY_DATE,QJsonValue(date));

    if(document->isArray()){
        document->array().append(contactObj);
    }
    else {
        qDebug()<<"JsonDocument not ready for insert";
    }

    qDebug()<< "Doc in function create : ";
    qDebug()<< *document;
}

void JsonBuilder::CreateMessage(QMap<QString, QString> map){

}

JsonBuilder::~JsonBuilder(){
    delete document;
}
</code>```

答:
Notice (in documentation) the signature of the array() method:

```<code>QJsonArray QJsonDocument::array() const
</code>```

When you use it this way:

```<code>document->array().append(contactObj);
</code>```

you're appending an object to a temporary copy of the doc array.

You'd be better create an array, append your objects, then set the array to the document, this way:

```<code>QJsonArray array;
array.append(contactObj);
//append every else object you need
document->setArray(array);
</code>```

instead of

```<code>if(document->isArray()){
    document->array().append(contactObj);
}
else {
    qDebug()<<"JsonDocument not ready for insert";
}
</code>```

Title: How to create a QJsonDocument?

Body:
I would like to create a QJsonDocument but I can't find a way to push my data in the document. At the end of JsonBuilder::CreateContact my document seem to be empty. Some help would be great please X).

I've tried to use some pointer and add them to my doc because I was thinking of the destruction of my different object (contactObj, detailObj, addressObj, date) but with this method I can't build the type QJsonValue (can't access private member of QjsonValue::QJsonValue) so am I wrong ?

JsonBuilder.h

#ifndef JSONBUILDER_H
#define JSONBUILDER_H
#include <QObject>
#include <QJsonDocument>
#include <QMap>
#include <QString>
#include <QList>

class JsonBuilder: public QObject
{
    Q_OBJECT
private:
    QJsonDocument* document;
public:
    JsonBuilder();
    ~JsonBuilder();
    void CreateContact(QMap<QString,QList<QString>> map);
    void CreateMessage(QMap<QString,QString> map);

    QJsonDocument* getDocument(){ return document; }
};

#endif // JSONBUILDER_H

JsonBuilder.cpp

#include "Jsonbuilder.h"
#include <QPair>
#include <QJsonObject>
#include <QJsonValue>
#include <Global.h>
#include <QDebug>
#include <QMapIterator>
#include <QJsonArray>

JsonBuilder::JsonBuilder(){
    document = new QJsonDocument(QJsonArray());
}

void JsonBuilder::CreateContact(QMap<QString, QList<QString>> map){
    QJsonObject contactObj;
    QJsonObject detailObj;
    QJsonObject addressObj;
    QJsonObject date;

    contactObj.insert(Global::KEY_TYPE_OBJ,QJsonValue("contact"));

    QMapIterator<QString, QList<QString>> it(map);

    while (it.hasNext()) {

        it.next();
        qDebug()<< "Key value = "+it.key();
        if(it.key() == Global::KEY_FIRST_NAME){
            contactObj.insert(Global::KEY_FIRST_NAME,QJsonValue(it.value()[0]));
            qDebug()<< "create firstName in Json " + it.value()[0];
        }

        if(it.key() == Global::KEY_LAST_NAME){
            contactObj.insert(Global::KEY_LAST_NAME,QJsonValue(it.value()[0]));
            qDebug()<< "create LastName in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_PSEUDO){
            QJsonArray Pseudos;
            foreach (QString contact, it.value()) {
                Pseudos.append(QJsonValue(contact));
                qDebug()<< "create Pseudo in Json "+ contact;
            }
            contactObj.insert(Global::KEY_PSEUDO,QJsonValue(Pseudos));
        }

        //Detail Object
        if(it.key() == Global::KEY_DETAIL_ROLE){
            detailObj.insert(Global::KEY_DETAIL_ROLE,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailRole in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_ORGANIZATION){
            detailObj.insert(Global::KEY_DETAIL_ORGANIZATION,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailOrganization in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_DEPARTMENT){
            detailObj.insert(Global::KEY_DETAIL_DEPARTMENT,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailDepartment in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_DETAIL_FUNCTION){
            detailObj.insert(Global::KEY_DETAIL_FUNCTION,QJsonValue(it.value()[0]));
            qDebug()<< "create DetailFunction in Json "+ it.value()[0];
        }

        if(it.key() == Global::KEY_PHONE){
            QJsonArray phones;
            foreach (QString phone, it.value()) {
                phones.append(QJsonValue(phone));
                qDebug()<< "create Phones in Json "+phone;
            }
            contactObj.insert(Global::KEY_PHONE,QJsonValue(phones));
        }

        if(it.key() == Global::KEY_EMAIL){
            QJsonArray emails;
            foreach (QString email, it.value()) {
                emails.append(QJsonValue(email));
                qDebug()<< "create Emails in Json "+email;
            }
            contactObj.insert(Global::KEY_EMAIL,QJsonValue(emails));

        }

        //Dates Object
        if(it.key() == Global::KEY_BIRTHDAY){
            date.insert(Global::KEY_BIRTHDAY,QJsonValue(it.value()[0]));
            qDebug()<< "create Birthday in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_WEDDING){
            foreach (QString dateWedding, it.value()) {
                date.insert(Global::KEY_WEDDING, QJsonValue(dateWedding));
                qDebug()<< "create wedding in Json "+dateWedding;
            }
        }

        //Address Object
        if(it.key() == Global::KEY_STREET){
            addressObj.insert(Global::KEY_STREET,QJsonValue(it.value()[0]));
            qDebug()<< "create street in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_POSTAL_CODE){
            addressObj.insert(Global::KEY_POSTAL_CODE,QJsonValue(it.value()[0]));
            qDebug()<< "create PostalCode in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_CITY){
            addressObj.insert(Global::KEY_CITY, QJsonValue(it.value()[0]));
            qDebug()<< "create city in Json "+it.value()[0];
        }

        if(it.key() == Global::KEY_COUNTRY){
            addressObj.insert(Global::KEY_COUNTRY, QJsonValue(it.value()[0]));
            qDebug()<< "create Country in Json "+it.value()[0];
        }
    }

    contactObj.insert(Global::KEY_DETAIL,QJsonValue(detailObj));
    contactObj.insert(Global::KEY_ADDRESS_OBJ,QJsonValue(addressObj));
    contactObj.insert(Global::KEY_DATE,QJsonValue(date));

    if(document->isArray()){
        document->array().append(contactObj);
    }
    else {
        qDebug()<<"JsonDocument not ready for insert";
    }

    qDebug()<< "Doc in function create : ";
    qDebug()<< *document;
}

void JsonBuilder::CreateMessage(QMap<QString, QString> map){

}

JsonBuilder::~JsonBuilder(){
    delete document;
}

Body:
Notice (in documentation) the signature of the array() method:

QJsonArray QJsonDocument::array() const

When you use it this way:

document->array().append(contactObj);

you're appending an object to a temporary copy of the doc array.

You'd be better create an array, append your objects, then set the array to the document, this way:

QJsonArray array;
array.append(contactObj);
//append every else object you need
document->setArray(array);

instead of

if(document->isArray()){
    document->array().append(contactObj);
}
else {
    qDebug()<<"JsonDocument not ready for insert";
}


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
You'll need to check for the existence of two rows, rather than being able to do a simple IN (which will only check the values within each joined record).  Maybe something like:

```<code>SELECT *
from users
WHERE EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag1')
  AND EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag2');
</code>```

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
You'll need to check for the existence of two rows, rather than being able to do a simple IN (which will only check the values within each joined record).  Maybe something like:

SELECT *
from users
WHERE EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag1')
  AND EXISTS (SELECT NULL FROM tags WHERE tags.user_id = users.id AND tags.name = 'tag2');


问:
select option displayed without dropdown
The Below code we are using. Please check and update:

`

                   dashboard

```<code>           </div>
        <div class="form-group">

            <label for="to_user">Turbine</label>
            <select name="to_user" class="form-control">
                <option value="pick">--Select All--</option>
                 <option>   <?php
                    $query = "SELECT DISTINCT Turbine FROM [JMDWF].[dbo].[TENAVG]";

                    $sql = sqlsrv_query($link,$query);
                    $row = sqlsrv_num_rows($sql);
                    $menu = "";

                        echo "<select name='to_user'>";
                        while ($row = sqlsrv_fetch_array($sql)){
                           /* echo "<option value='". $row['Turbine'] ."'>" .$row['Turbine'] ."</option>" ;*/
                           $menu.="<option>".$row['Turbine']."</option>";
                        }
                     echo "$menu";
                    ?>
                    </option>

            </select>

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

Still we getting output out of the drop down list. I need to show the values in drop down.

答:
Your are printing the output from PHP into your <option></option> node of the html - it won't be visible.

Try this instead:

```<code>      <div class="form-group">
        <label for="to_user">Turbine</label>
            <?php
                $query = "SELECT DISTINCT Turbine FROM [JMDWF].[dbo].[TENAVG]";
                $sql = sqlsrv_query($link,$query);
                $row = sqlsrv_num_rows($sql);
                $menu = "";
                echo "<select name='to_user'>";
                echo "<option value='pick'>--Select All--</option>";
                while ($row = sqlsrv_fetch_array($sql)){
                       /* echo "<option value='". $row['Turbine'] ."'>" .$row['Turbine'] ."</option>" ;*/
                       $menu.="<option>".$row['Turbine']."</option>";
                }
                echo "</select>";
                echo "$menu";
            ?>
    </div>`
</code>```

Body:
The Below code we are using. Please check and update:

`

                   dashboard

            Turbine
            <select name="to_user" class="form-control">
                <option value="pick">--Select All--</option>
                 <option>   <?php
                    $query = "SELECT DISTINCT Turbine FROM [JMDWF].[dbo].[TENAVG]";

                    $sql = sqlsrv_query($link,$query);
                    $row = sqlsrv_num_rows($sql);
                    $menu = "";

                        echo "<select name='to_user'>";
                        while ($row = sqlsrv_fetch_array($sql)){
                           /* echo "<option value='". $row['Turbine'] ."'>" .$row['Turbine'] ."</option>" ;*/
                           $menu.="<option>".$row['Turbine']."</option>";
                        }
                     echo "$menu";
                    ?>
                    </option>

            </select>

`

Still we getting output out of the drop down list. I need to show the values in drop down.

Body:
Your are printing the output from PHP into your <option></option> node of the html - it won't be visible.

Try this instead:

      <div class="form-group">
        <label for="to_user">Turbine</label>
            <?php
                $query = "SELECT DISTINCT Turbine FROM [JMDWF].[dbo].[TENAVG]";
                $sql = sqlsrv_query($link,$query);
                $row = sqlsrv_num_rows($sql);
                $menu = "";
                echo "<select name='to_user'>";
                echo "<option value='pick'>--Select All--</option>";
                while ($row = sqlsrv_fetch_array($sql)){
                       /* echo "<option value='". $row['Turbine'] ."'>" .$row['Turbine'] ."</option>" ;*/
                       $menu.="<option>".$row['Turbine']."</option>";
                }
                echo "</select>";
                echo "$menu";
            ?>
    </div>`


问:
Get started on NFC P2P communication between Android and Linux (libnfc)
Eventually, I need to implement a cryptographic protocol between an Android device and a Linux host that has a NFC adapter using libfc.

I have never used NFC before with Android. At the moment my idea is to use NFC in Peer-to-Peer mode in the passive variant, e.g. the smartcard reader at the linux host plays the role of the initiator and provides the HF field while the smartphone is the target.

As far as I understand the callback createNdefMessage can be used to react to an NFC request and send back a reply message. However, I do not understand how I obtain the request message in my Android program.

At the moment -- as a toy example -- I try to achieve the following: The linux host sends a random number via NFC, the android device draws a random number and replies with the sum.

I have

```<code>package edu.kit.iti.crypto.nfctest1;

import android.app.Activity;
import android.content.Intent;
import android.nfc.*;
import android.os.Bundle;
import android.provider.Settings;
import java.nio.ByteBuffer;

public class MainActivity extends Activity implements NfcAdapter.CreateNdefMessageCallback {

    protected NfcAdapter nfcAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        nfcAdapter = NfcAdapter.getDefaultAdapter( getApplicationContext() );
        nfcAdapter.setNdefPushMessageCallback( this, this );
    }

    protected void onResume() {
        super.onResume();
        if( !nfcAdapter.isEnabled() ) {
            startActivity( new Intent( Settings.ACTION_NFC_SETTINGS) );
        } else if( !nfcAdapter.isNdefPushEnabled() ) {
            startActivity( new Intent( Settings.ACTION_NFCSHARING_SETTINGS) );
        }
    }

    public NdefMessage createNdefMessage( NfcEvent event ) {
        int randomNumber = 42;
        // How to obtain the request message here?
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt( randomNumber );
        NdefRecord replyRecord = NdefRecord.createExternal( "edu.kit.iti.crypto.nfctest1", "app-randomness", buffer.array() );
        return new NdefMessage( replyRecord );
    }
}
</code>```

My very basic question is the comment in the method at the bottom: How do I get the request message?

答:
There simply is no request message. Android Beam (which is the only way to use NFC peer-to-peer mode on Android) is based on SNEP (over LLCP). The method createNdefMessage() is called to build the NDEF message served by the SNEP client on your device. Upon bringing two devices together (and after tapping the Beam UI), Android tries to locate the SNEP server on the other device and pushes the NDEF message to its inbox.

So the only "request" that plays a role in Android Beam is the PUT request that's used by your device to send the message. The process is started by NFC discovery and there is no specific request received from the other side.

Body:
Eventually, I need to implement a cryptographic protocol between an Android device and a Linux host that has a NFC adapter using libfc.

I have never used NFC before with Android. At the moment my idea is to use NFC in Peer-to-Peer mode in the passive variant, e.g. the smartcard reader at the linux host plays the role of the initiator and provides the HF field while the smartphone is the target.

As far as I understand the callback createNdefMessage can be used to react to an NFC request and send back a reply message. However, I do not understand how I obtain the request message in my Android program.

At the moment -- as a toy example -- I try to achieve the following: The linux host sends a random number via NFC, the android device draws a random number and replies with the sum.

I have

package edu.kit.iti.crypto.nfctest1;

import android.app.Activity;
import android.content.Intent;
import android.nfc.*;
import android.os.Bundle;
import android.provider.Settings;
import java.nio.ByteBuffer;

public class MainActivity extends Activity implements NfcAdapter.CreateNdefMessageCallback {

    protected NfcAdapter nfcAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        nfcAdapter = NfcAdapter.getDefaultAdapter( getApplicationContext() );
        nfcAdapter.setNdefPushMessageCallback( this, this );
    }

    protected void onResume() {
        super.onResume();
        if( !nfcAdapter.isEnabled() ) {
            startActivity( new Intent( Settings.ACTION_NFC_SETTINGS) );
        } else if( !nfcAdapter.isNdefPushEnabled() ) {
            startActivity( new Intent( Settings.ACTION_NFCSHARING_SETTINGS) );
        }
    }

    public NdefMessage createNdefMessage( NfcEvent event ) {
        int randomNumber = 42;
        // How to obtain the request message here?
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt( randomNumber );
        NdefRecord replyRecord = NdefRecord.createExternal( "edu.kit.iti.crypto.nfctest1", "app-randomness", buffer.array() );
        return new NdefMessage( replyRecord );
    }
}

My very basic question is the comment in the method at the bottom: How do I get the request message?


问:
Exception creating a trading bot
I'm trying to create WordPress plugin which trades cryptocoins for my website in PHP, and I'm trying to use Bittrex API for this purpose.

My problem is that when I try to call the methods from the Class with the API, an exception is thrown.
Could someone help me to find the problem in my code?

Here is the code inside the main class, where I'm creating an Object from Client class.

```<code>require 'bittrex-master/src/edsonmedina/bittrex/Client.php';
use edsonmedina\bittrex\Client;

$keya = "xxx";
$secreta = "xxx";

$b = new Client ($keya, $secreta);

try{
    $list = $b->getMarkets ();
    echo "$list";

}catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

echo "\n\n";
</code>```

Here is the portion of code from the Client class

```<code>namespace edsonmedina\bittrex;

class Client
{
private $baseUrl;
private $apiVersion = 'v1.1';
private $apiKey;
private $apiSecret;

public function __construct ($apiKey, $apiSecret)
{
    $this->apiKey    = $apiKey;
    $this->apiSecret = $apiSecret;
    $this->baseUrl   = 'https://bittrex.com/api/'.$this->apiVersion.'/';
}

/**
 * Invoke API
 * @param string $method API method to call
 * @param array $params parameters
 * @param bool $apiKey  use apikey or not
 * @return object
 */
private function call ($method, $params = array(), $apiKey = false)
{
    $uri  = $this->baseUrl.$method;

    if ($apiKey == true) {
        $params['apikey'] = $this->apiKey;
        $params['nonce']  = time();
    }

    if (!empty($params)) {
        $uri .= '?'.http_build_query($params);
    }

    $sign = hash_hmac ('sha512', $uri, $this->apiSecret);

    $ch = curl_init ($uri);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('apisign: '.$sign));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    $answer = json_decode($result);

    if ($answer->success == false) {
        throw new \Exception ($answer->message);
    }

    return $answer->result;
}

/**
 * Get the open and available trading markets at Bittrex along with other meta data.
 * @return array
 */
public function getMarkets ()
{
    return $this->call ('public/getmarkets');
}
</code>```

答:
As per your comment and exception APIKEY_NOT_PROVIDED, by default your APIKEY is false in your call method.

```<code>return $this->call ('public/getmarkets', null, true);
</code>```

Title: Exception creating a trading bot

Body:
I'm trying to create WordPress plugin which trades cryptocoins for my website in PHP, and I'm trying to use Bittrex API for this purpose.

My problem is that when I try to call the methods from the Class with the API, an exception is thrown.
Could someone help me to find the problem in my code?

Here is the code inside the main class, where I'm creating an Object from Client class.

require 'bittrex-master/src/edsonmedina/bittrex/Client.php';
use edsonmedina\bittrex\Client;

$keya = "xxx";
$secreta = "xxx";

$b = new Client ($keya, $secreta);

try{
    $list = $b->getMarkets ();
    echo "$list";

}catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

echo "\n\n";

Here is the portion of code from the Client class

namespace edsonmedina\bittrex;

class Client
{
private $baseUrl;
private $apiVersion = 'v1.1';
private $apiKey;
private $apiSecret;

public function __construct ($apiKey, $apiSecret)
{
    $this->apiKey    = $apiKey;
    $this->apiSecret = $apiSecret;
    $this->baseUrl   = 'https://bittrex.com/api/'.$this->apiVersion.'/';
}

/**
 * Invoke API
 * @param string $method API method to call
 * @param array $params parameters
 * @param bool $apiKey  use apikey or not
 * @return object
 */
private function call ($method, $params = array(), $apiKey = false)
{
    $uri  = $this->baseUrl.$method;

    if ($apiKey == true) {
        $params['apikey'] = $this->apiKey;
        $params['nonce']  = time();
    }

    if (!empty($params)) {
        $uri .= '?'.http_build_query($params);
    }

    $sign = hash_hmac ('sha512', $uri, $this->apiSecret);

    $ch = curl_init ($uri);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('apisign: '.$sign));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    $answer = json_decode($result);

    if ($answer->success == false) {
        throw new \Exception ($answer->message);
    }

    return $answer->result;
}

/**
 * Get the open and available trading markets at Bittrex along with other meta data.
 * @return array
 */
public function getMarkets ()
{
    return $this->call ('public/getmarkets');
}

Body:
As per your comment and exception APIKEY_NOT_PROVIDED, by default your APIKEY is false in your call method.

return $this->call ('public/getmarkets', null, true);


问:
Javascript syntax of "a= object,object"
Yesterday I found this function:

```<code>function clone(obj) {
    return typeof obj === 'undefined' ?
        this : (clone.prototype = Object(obj), new clone);
}
</code>```

I though that i saw alot in Javascript, but this syntax is unknown for me:

```<code> clone.prototype = Object(obj), new clone
</code>```

Can someone explain me how to read this?? Can you give me link to proper definition ? I couldn't find it in Mozilla's MDC, and dont know how to find this on web, but this is first time ever I saw that syntax. Thanks for effort here.

Final solution:

I did some testing according to answers here and there is what I found:

```<code>var b;
b=alert('test'),6;
alert(b);  // alert undefined
b=5,alert('test2');
alert(b);  // alert 5
</code>```

Thanks to christoph research we found more:

```<code>var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2
</code>```

Ahh and I tested it also on IE6 and it works, so this have to be realy old syntax and there is no information about it? :( Strange...

Both of you guys gave good solution, thanks for solution here!

答:
Your 'final solution' gives unexpected results because of operator precedence. The following example might help to clarify the issue:

```<code>var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2
</code>```

Also notice that

```<code>var a = 1, 2;
</code>```

produces a syntax error!

Title: Javascript syntax of "a= object,object"

Body:
Yesterday I found this function:

function clone(obj) {
    return typeof obj === 'undefined' ?
        this : (clone.prototype = Object(obj), new clone);
}

I though that i saw alot in Javascript, but this syntax is unknown for me:

 clone.prototype = Object(obj), new clone

Can someone explain me how to read this?? Can you give me link to proper definition ? I couldn't find it in Mozilla's MDC, and dont know how to find this on web, but this is first time ever I saw that syntax. Thanks for effort here.

Final solution:

I did some testing according to answers here and there is what I found:

var b;
b=alert('test'),6;
alert(b);  // alert undefined
b=5,alert('test2');
alert(b);  // alert 5

Thanks to christoph research we found more:

var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2

Ahh and I tested it also on IE6 and it works, so this have to be realy old syntax and there is no information about it? :( Strange...

Both of you guys gave good solution, thanks for solution here!

Body:
Your 'final solution' gives unexpected results because of operator precedence. The following example might help to clarify the issue:

var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2

Also notice that

var a = 1, 2;

produces a syntax error!

OwnerDisplayName: Christoph


问:
How to register a SIP account in xlite Softphone?
I am trying to build a SIP PBX in c#. I am following this tutorial. But I am stuck after doing the first part of the tutorial. Where I run the application for the first time and I get the following console window.

Now I am supposed to use the xlite Softphone to register a SIP account? But for the life of me, I can't figure out what I am supposed to enter in the "Account Settings" window from xlite Softphone Software.

I mean what is Domain, Password, User ID, Authorization Name and all the other fields? I am new to this whole subject and any help is appreciated. Thanks!

答: I managed to connect to the application. I just used the following settings if anyone might be interested. Here A in User ID is just a random letter I selected. It has no connection to the code or any of the settings. Domain is the same as the IP shown on my console window. Display Name again a random name. Authorization Name is the same as User ID. Leave the rest as it is.


问:
If required field is empty, don't open popup
I have a contact form that when you press the send button, opens a popup asking for confirmation of reading the privacy policy.

For now, the form doesn't send anything if there are empty required field, but it opens the popup.

I need to prevent the popup to open if there are still required field to complete.

Here's the code:

$('#myCheck').click(function() {
     $(this).toggleClass("checked");
});

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

$('.checkz').click(function () {
    $('#invias').toggleDisabled();
    $('#invias').toggleClass("activ3");
    });

    $(".pex").click(function (e) {
    e.stopPropagation();
});

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checkz {width:20px;
height:20px;
background: transparent;
background-size: contain;
border:1px solid #CCC;
border-radius:5px;
display:inline-block;
    margin-bottom: 5px;
    margin-right: 10px;}

#invias {opacity:0.5}

.activ3 {opacity:1 !important}

#popup {
    background-color: rgba( 231, 135, 74, 0.85 );
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1999999999;
    overflow: initial;
    transition: all .15s ease-in-out;
}

.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}

.cst {display: inline-block;
    text-align: left;}

.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}

button:disabled {opacity:0.5 !important}</code>```

<form method="post" name="contactform" class="peThemeContactForm">

            <input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />

            <input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />

            <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

            <textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>

    Send message

Dichiaro di aver letto, compreso ed accettato

l'informativa sul trattamento dei miei dati personali

Close <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>

```

You could use the following fiddle to test: http://jsfiddle.net/2BgdD/12/

Thanks a lot.

答:
```<code>function popupshow() {
    if(checkInputs()) document.getElementById("popup").style = "";
}
</code>```

Body:
I have a contact form that when you press the send button, opens a popup asking for confirmation of reading the privacy policy.

For now, the form doesn't send anything if there are empty required field, but it opens the popup.

I need to prevent the popup to open if there are still required field to complete.

Here's the code:

$('#myCheck').click(function() {
     $(this).toggleClass("checked");
});

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

$('.checkz').click(function () {
    $('#invias').toggleDisabled();
    $('#invias').toggleClass("activ3");
    });

    $(".pex").click(function (e) {
    e.stopPropagation();
});

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()

.checkz {width:20px;
height:20px;
background: transparent;
background-size: contain;
border:1px solid #CCC;
border-radius:5px;
display:inline-block;
    margin-bottom: 5px;
    margin-right: 10px;}

#invias {opacity:0.5}

.activ3 {opacity:1 !important}

#popup {
    background-color: rgba( 231, 135, 74, 0.85 );
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1999999999;
    overflow: initial;
    transition: all .15s ease-in-out;
}

.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}

.cst {display: inline-block;
    text-align: left;}

.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}

button:disabled {opacity:0.5 !important}

<form method="post" name="contactform" class="peThemeContactForm">

            <input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />

            <input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />

            <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

            <textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>

    Send message

Dichiaro di aver letto, compreso ed accettato

l'informativa sul trattamento dei miei dati personali

Close <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>

You could use the following fiddle to test: http://jsfiddle.net/2BgdD/12/

Thanks a lot.


问:
In Java, can the this/super keywords represent anything other than classes/enums?
I've noticed that:

```<code>class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}
</code>```

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

答: In Java this is always the current class even if it is an anonymous class. No, this or super cannot represent an interface.

Body:
I've noticed that:

class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?


问:
React: "this" is undefined inside a component function
```<code>class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }

  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

    return (
      <div className="player-controls">
        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />
      </div>
    );
  }

  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }
</code>```

I want to update loopActive state on toggle, but this object is undefined in the handler. According to the tutorial doc, I this should refer to the component. Am I missing something?

答:
Write your function this way:

```<code>onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}
</code>```

Fat Arrow Functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).

Body:
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }

  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

    return (

        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />

    );
  }

  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }

I want to update loopActive state on toggle, but this object is undefined in the handler. According to the tutorial doc, I this should refer to the component. Am I missing something?

Body:
Write your function this way:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}

Fat Arrow Functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).


问:
Correct way to handle undefined declaration files (index.d.ts)
I got following error

```<code>error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`
</code>```

As a quick fix I created typings/index.d.ts (there is no @types/react-native-camera) file at root of my project and populated it with

```<code>declare module 'react-native-camera';
</code>```

then, in my tsconfig file I added it to my type roots like this

```<code>"typeRoots": ["node_modules/@types", "./typings"],
</code>```

however I am still getting same error when I build, leading me to think that my implementation is incorrect, what did I miss?

Edit, my full tsconfig looks like this

```<code>{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}
</code>```

答:
From flowtype document, of library definitions section, it said:

A libdef is a special file that informs Flow about the type signature
  of some specific third-party module or package of modules that your
  application uses. If you’re familiar with languages that have header
  files (like C++), you can think of libdefs as a similar concept.

General Best Practices

Try to provide a libdef for each third-party library your project uses.

Look into .flowconfig in the root path, you will see it already defined there.

```<code>[libs]
node_modules/react-native/Libraries/react-native/react-native-interface.js
node_modules/react-native/flow
./libdefs.js
</code>```

And then look for libdefs.js in the root path, it should be there. Or just create it on your own.

For every module, declare it like below. Take rxjs for example:

```<code>declare module 'rxjs' { declare var exports: any; }
</code>```

It's the official suggestion way, no index.d.ts modify needed.

Body:
I got following error

error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`

As a quick fix I created typings/index.d.ts (there is no @types/react-native-camera) file at root of my project and populated it with

declare module 'react-native-camera';

then, in my tsconfig file I added it to my type roots like this

"typeRoots": ["node_modules/@types", "./typings"],

however I am still getting same error when I build, leading me to think that my implementation is incorrect, what did I miss?

Edit, my full tsconfig looks like this

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}

Body:
From flowtype document, of library definitions section, it said:

A libdef is a special file that informs Flow about the type signature
  of some specific third-party module or package of modules that your
  application uses. If you’re familiar with languages that have header
  files (like C++), you can think of libdefs as a similar concept.

General Best Practices

Try to provide a libdef for each third-party library your project uses.

Look into .flowconfig in the root path, you will see it already defined there.

[libs]
node_modules/react-native/Libraries/react-native/react-native-interface.js
node_modules/react-native/flow
./libdefs.js

And then look for libdefs.js in the root path, it should be there. Or just create it on your own.

For every module, declare it like below. Take rxjs for example:

declare module 'rxjs' { declare var exports: any; }

It's the official suggestion way, no index.d.ts modify needed.


问:
WebStorm annotate cutting off usernames on dashes and spaces
When using the Annotate functionality in WebStorm, if a user that commited code has a username that contains a space or dash, WebStorm only shows the part of their name after the space or dash.

I'm not sure if this is intentional functionality, or if there is an option to change it (I couldn't find one).  But I would expect it to behave like git blame by default.

Currently:

"user-name" -> "name" shows

"firstName lastName" -> "lastName" shows

Expected:

"user-name" -> "user-name"

"firstName lastName" -> "firstName lastName"

Question: is there an option to switch the functionality? or is it a bug or expected behavior?

答: Yup, right click the annotation bar > view > name > full name:


问:
Sahi unable to run the for loop
I have been using a test tool call Sahi.

So basically I transferred one of my file, Example.sah , from one computer to another computer. When I run it on my another computer, it can't read the for loop for the code below. I have changed it to while loop and it doesn't work either. However, the codes below worked on my previous computer.

-----------------------------------CODES----------------------------------------

```<code>var $userinfo = _readExcelFile("C:/Work/Example.xls");
var $userinfo1 = _readExcelFile("C:/Work/CheckExample.xls");

var $i=0
for ($i++; $i<$userinfo;){

    var $Id = $userinfo[$i][0];
    var $Int = $userinfo[$i][1];
    var $Int2 = $userinfo[$i][2];
    var $BigInt1 = $userinfo[$i][3];
    var $BigInt2 = $userinfo[$i][4];
    var $Double1 = $userinfo[$i][5];
    var $Double2 = $userinfo[$i][6];

    _click(_link("Edit"));
    _click(_link("New"));
    _setValue(_textbox("Title"), $Id);
    _setValue(_numberbox("TestInt001"), $Int);
    _setValue(_numberbox("TestInt002"), $Int2);
    _setValue(_numberbox("TestBigint001"), $BigInt1);
    _setValue(_numberbox("TestBigint002"), $BigInt2);
    _setValue(_numberbox("TestDouble001"), $Double1);
    _setValue(_numberbox("TestDouble002"), $Double2);
    _click(_cell(0));
    _doubleClick(_cell(0));
    _click(_submit("Ok"));

    var $Idx = $userinfo1[$i][0];
    var $Intx = $userinfo1[$i][1];
    var $Int2x = $userinfo1[$i][2];
    var $BigInt1x = $userinfo1[$i][3];
    var $BigInt2x = $userinfo1[$i][4];
    var $Double1x = $userinfo1[$i][5];
    var $Double2x = $userinfo1[$i][6];

    _assertContainsText($Idx, _link($Id));
    _assertContainsText($Intx, _cell($Int));
    _assertContainsText($Int2x, _cell($Int2));
    _assertContainsText($BigInt1x, _cell($BigInt1));
    _assertContainsText($BigInt2x, _cell($BigInt2));
    _assertEqual($Double1x, _getText(_cell($Double1)));
    _assertEqual($Double2x, _getText(_cell($Double2)));

}
</code>```

--------------------------OUTPUT----------------------------------------------

------------------- Stopped Playback: SUCCESS-------------------

答:
I feel your error is in the below section : </p>

```<code>var $i=0
for ($i++; $i<$userinfo;){
</code>```

<p>You can try replacing it with this </p>

```<code>for ($var $i=0;$i<$userinfo;$i++){
</code>```

Title: Sahi unable to run the for loop

Body:
I have been using a test tool call Sahi.

So basically I transferred one of my file, Example.sah , from one computer to another computer. When I run it on my another computer, it can't read the for loop for the code below. I have changed it to while loop and it doesn't work either. However, the codes below worked on my previous computer.

-----------------------------------CODES----------------------------------------

var $userinfo = _readExcelFile("C:/Work/Example.xls");
var $userinfo1 = _readExcelFile("C:/Work/CheckExample.xls");

var $i=0
for ($i++; $i<$userinfo;){

    var $Id = $userinfo[$i][0];
    var $Int = $userinfo[$i][1];
    var $Int2 = $userinfo[$i][2];
    var $BigInt1 = $userinfo[$i][3];
    var $BigInt2 = $userinfo[$i][4];
    var $Double1 = $userinfo[$i][5];
    var $Double2 = $userinfo[$i][6];

    _click(_link("Edit"));
    _click(_link("New"));
    _setValue(_textbox("Title"), $Id);
    _setValue(_numberbox("TestInt001"), $Int);
    _setValue(_numberbox("TestInt002"), $Int2);
    _setValue(_numberbox("TestBigint001"), $BigInt1);
    _setValue(_numberbox("TestBigint002"), $BigInt2);
    _setValue(_numberbox("TestDouble001"), $Double1);
    _setValue(_numberbox("TestDouble002"), $Double2);
    _click(_cell(0));
    _doubleClick(_cell(0));
    _click(_submit("Ok"));

    var $Idx = $userinfo1[$i][0];
    var $Intx = $userinfo1[$i][1];
    var $Int2x = $userinfo1[$i][2];
    var $BigInt1x = $userinfo1[$i][3];
    var $BigInt2x = $userinfo1[$i][4];
    var $Double1x = $userinfo1[$i][5];
    var $Double2x = $userinfo1[$i][6];

    _assertContainsText($Idx, _link($Id));
    _assertContainsText($Intx, _cell($Int));
    _assertContainsText($Int2x, _cell($Int2));
    _assertContainsText($BigInt1x, _cell($BigInt1));
    _assertContainsText($BigInt2x, _cell($BigInt2));
    _assertEqual($Double1x, _getText(_cell($Double1)));
    _assertEqual($Double2x, _getText(_cell($Double2)));

}

--------------------------OUTPUT----------------------------------------------

------------------- Stopped Playback: SUCCESS-------------------

Body:
I feel your error is in the below section :

var $i=0
for ($i++; $i<$userinfo;){

You can try replacing it with this

for ($var $i=0;$i<$userinfo;$i++){


问:
toggle pseudo class :active with css/jquery
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

```<code>(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);
</code>```

And the HTML around the Elements we are looking for

```<code><div class="helpmark">
    <img class="emoticon" src="http://*********/plugins/cute/static/resource/SD-CGM-TT/help_16.gif"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>
</code>```

by clicking on .helpmark .description is displayed

And the CSS i have

```<code>.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}
</code>```

I hope anybody can help me.

Best regards,
Stephan

答:
It is a little bit frustrating to see that there are many good answers but when i add a comment because there is a little problem nobody is reading it.

I'm an absolute newbie with scripting and I'm sorry to need a little more help then you normal expected.

Body:
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('
'
+ ''
+ ' @message'
+   '
');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);

And the HTML around the Elements we are looking for

Hier können Sie einen kurzen Betreff einfügen

by clicking on .helpmark .description is displayed

And the CSS i have

.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}

I hope anybody can help me.

Best regards,
Stephan


问:
How to force Kubernetes to update deployment with a pod in every node
I would like to know if there is a way to force Kubernetes, during a deploy, to use every node in the cluster.
The question is due some attempts that I have done where I noticed a situation like this:

a cluster of 3 nodes

I update a deployment with a command like: kubectl set image deployment/deployment_name my_repo:v2.1.2

Kubernetes updates the cluster

At the end I execute kubectl get pod and I notice that 2 pods have been deployed in the same node.
So after the update, the cluster has this configuration:

one node with 2 pods

one node with 1 pod

one node without any pod (totally without any workload)

答:
The scheduler will try to figure out the most reasonable way of scheduling at given point in time, which can change later on and results in situations like you described. Two simple ways to manage this in one way or another are :

use DaemonSet instead of Deployment : will make sure you have one and only one pod per node (matching nodeSelector / tolerations etc.)

use PodAntiAffinity : you can make sure that two pods of the same deployment in the same version are never deployed on the same node. This is what I personally prefer for many apps (unless I want more then one to be scheduled per node). Note that it will be in a bit of trouble if you decide to scale your deployment to more replicas then you have nodes.
Example for versioned PodAntiAffinity I use :

```<code>metadata:
  labels:
    app: {{ template "fullname" . }}
    version: {{ .Values.image.tag }}
spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: app
            operator: In
            values: ["{{ template "fullname" . }}"]
          - key: version
            operator: In
            values: ["{{ .Values.image.tag }}"]
        topologyKey: kubernetes.io/hostname
</code>```

consider fiddling with Descheduler which is like an evil twin of Kubes Scheduler component which will cause deleting of pods for them tu reschedule differently

Body:
The scheduler will try to figure out the most reasonable way of scheduling at given point in time, which can change later on and results in situations like you described. Two simple ways to manage this in one way or another are :

use DaemonSet instead of Deployment : will make sure you have one and only one pod per node (matching nodeSelector / tolerations etc.)

use PodAntiAffinity : you can make sure that two pods of the same deployment in the same version are never deployed on the same node. This is what I personally prefer for many apps (unless I want more then one to be scheduled per node). Note that it will be in a bit of trouble if you decide to scale your deployment to more replicas then you have nodes.
Example for versioned PodAntiAffinity I use :

metadata:
  labels:
    app: {{ template "fullname" . }}
    version: {{ .Values.image.tag }}
spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: app
            operator: In
            values: ["{{ template "fullname" . }}"]
          - key: version
            operator: In
            values: ["{{ .Values.image.tag }}"]
        topologyKey: kubernetes.io/hostname

consider fiddling with Descheduler which is like an evil twin of Kubes Scheduler component which will cause deleting of pods for them tu reschedule differently


问:
Put data side by side after the end of the csv file
I have a macro who allows me to import data of several csv file into a workbook containing several sheets :

```<code>Option Explicit
Sub ImportCSVs()
'Import all CSV files from a folder into separate sheets

Dim fPath   As String
Dim fCSV    As String
Dim wbCSV   As Workbook
Dim wbMST   As Workbook

Set wbMST = ActiveWorkbook

'Update the path to your CSV files below. Add your-username and your-folder
'Don't remove the the final \ from the file path

fPath = "C:\Users\your-username\Documents\your-folder\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
fCSV = Dir(fPath & "*.csv")

    Do While Len(fCSV) > 0
        Set wbCSV = Workbooks.Open(fPath & fCSV)
        ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count)

        fCSV = Dir
    Loop

Set wbCSV = Nothing

Application.ScreenUpdating = True
End Sub
</code>```

I would like to get each csv file into the same Excel file, thus, when a csv is finish, go to the column just after (A, B, C....)

Hope that's possible with the existing code...

答:
this code probably will satisfy your condition and also code added to renaming the sheets.</p>

```<code>Sub ImportCSVs()
'Import all CSV files from a folder into separate sheets

Dim fPath   As String
Dim fCSV    As String
Dim wbCSV   As Workbook
Dim wbMST   As Workbook

Set wbMST = ThisWorkbook

'Update the path to your CSV files below. Add your-username and your-folder
'Don't remove the the final \ from the file path

fPath = "C:\Users\your-username\Documents\your-folder\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
fCSV = Dir(fPath & "*.CSV")

    Do While Len(fCSV) > 0
        Set wbCSV = Workbooks.Open(fPath & fCSV)
      wbCSV.ActiveSheet.Copy wbMST.ActiveSheet
      With wbMST
      Sheets(ActiveSheet.Name).Name = Left(fCSV, 6)
      'Sheets.Add
      End With
        fCSV = Dir
    Loop

Set wbCSV = Nothing

Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have a macro who allows me to import data of several csv file into a workbook containing several sheets :

Option Explicit
Sub ImportCSVs()
'Import all CSV files from a folder into separate sheets

Dim fPath   As String
Dim fCSV    As String
Dim wbCSV   As Workbook
Dim wbMST   As Workbook

Set wbMST = ActiveWorkbook

'Update the path to your CSV files below. Add your-username and your-folder
'Don't remove the the final \ from the file path

fPath = "C:\Users\your-username\Documents\your-folder\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
fCSV = Dir(fPath & "*.csv")

    Do While Len(fCSV) > 0
        Set wbCSV = Workbooks.Open(fPath & fCSV)
        ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count)

        fCSV = Dir
    Loop

Set wbCSV = Nothing

Application.ScreenUpdating = True
End Sub

I would like to get each csv file into the same Excel file, thus, when a csv is finish, go to the column just after (A, B, C....)

Hope that's possible with the existing code...

Body:
this code probably will satisfy your condition and also code added to renaming the sheets.

Sub ImportCSVs()
'Import all CSV files from a folder into separate sheets

Dim fPath   As String
Dim fCSV    As String
Dim wbCSV   As Workbook
Dim wbMST   As Workbook

Set wbMST = ThisWorkbook

'Update the path to your CSV files below. Add your-username and your-folder
'Don't remove the the final \ from the file path

fPath = "C:\Users\your-username\Documents\your-folder\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
fCSV = Dir(fPath & "*.CSV")

    Do While Len(fCSV) > 0
        Set wbCSV = Workbooks.Open(fPath & fCSV)
      wbCSV.ActiveSheet.Copy wbMST.ActiveSheet
      With wbMST
      Sheets(ActiveSheet.Name).Name = Left(fCSV, 6)
      'Sheets.Add
      End With
        fCSV = Dir
    Loop

Set wbCSV = Nothing

Application.ScreenUpdating = True
End Sub


问:
Launch MongoDB with Maven
I am using the MongoDB Java driver to perform some persistence in my application. The build for my application is managed via Maven and I'm looking for the best way to integrate a series of MongoDB-related unit tests into my Maven build process. I cannot assume that the user building the application has installed the MongoDB dameon as a service and therefore need to launch the daemon prior to the execution of the related unit tests.

My first thought was to store the binaries in the resources folder of the test directory (e.g., src/test/resources) and launch the daemon using Runtime.exec(). Is there an approach that's cleaner? I feel like Runtime.exec() is a quick and dirty way to get something working but not the most ideal...I need this to work on both linux and windows.

答:
My team had this exact same problem but we could not find any clean way to solve it. We even went down a bad path of using the ant-run plugin to execute some Ant tasks (OS independent) which would start up the MongoDB daemon if necessary. We ended up scrapping the whole thing in favor for an AbstractMongoDbTest class which in it's @Before method, asserts MongoDB is running, and if not, fails the test with a very specific message prompting the user to start Mongo. It is not perfect but, unfortunately, if you are introducing an external dependency to your unit tests, they are not unit tests anymore, they are integration tests and it is not unreasonable to require people to have the dependency available.

Other options:

If all the developers are all on the same network, you could set up a dedicated MongoDB instance on a server and have the tests all point at it's hostname instead of localhost (the default).

You could also abstract all of the interactions with MongoDB behind repository-patterned interfaces with MongoDB implementations. This is probably a good idea anyway. This would allow your tests to either mock out the repo interfaces or create stubs of the services. This would keep your unit tests from becoming integration tests. It also has the advantage of if you ever decide to move away from MongoDB to maybe CouchDB or even a relational database like Oracle, your tests don't need to change, you simply need to create new implementations of your repo interfaces.

Title: Launch MongoDB with Maven