问:
Making a dynamic pivot table but without using the fiddle
I have done this:

```<code>;WITH a AS
(
    SELECT
        a.account
        ,index_num_date = 'date ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,index_num_rate = 'rate ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,ratechangedate
        ,new_noterate
    FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
    INNER JOIN
    (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
    ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
)
,q1 AS
(
    SELECT DISTINCT
        account
        ,ratechangedate
        ,index_num_date
    FROM a
)
,q2 AS
(
    SELECT DISTINCT
        account
        ,new_noterate
        ,index_num_rate
    FROM a
)
,datepivot AS
(
    SELECT DISTINCT
        account
        ,[date 1]
        ,[date 2]
        ,[date 3]
        ,[date 4]
        ,[date 5]
        ,[date 6]
        ,[date 7]
        ,[date 8]
        ,[date 9]
        ,[date 10]
        ,[date 11]
        ,[date 12]
        ,[date 13]
    FROM q1
        PIVOT
        (
            MIN(ratechangedate)
            FOR index_num_date IN ( [date 1]
                ,[date 2]
                ,[date 3]
                ,[date 4]
                ,[date 5]
                ,[date 6]
                ,[date 7]
                ,[date 8]
                ,[date 9]
                ,[date 10]
                ,[date 11]
                ,[date 12]
                ,[date 13]
            )
        ) pvt1
)
,ratepivot AS
(
    SELECT DISTINCT
        account
        ,[rate 1]
        ,[rate 2]
        ,[rate 3]
        ,[rate 4]
        ,[rate 5]
        ,[rate 6]
        ,[rate 7]
        ,[rate 8]
        ,[rate 9]
        ,[rate 10]
        ,[rate 11]
        ,[rate 12]
        ,[rate 13]
    FROM q2
        PIVOT
        (
            MIN(new_noterate)
            FOR index_num_rate IN ( [rate 1]
                ,[rate 2]
                ,[rate 3]
                ,[rate 4]
                ,[rate 5]
                ,[rate 6]
                ,[rate 7]
                ,[rate 8]
                ,[rate 9]
                ,[rate 10]
                ,[rate 11]
                ,[rate 12]
                ,[rate 13]
            )
        ) pvt2
)
SELECT
    a.Account
    ,[date 1]
    ,[rate 1]
FROM datepivot a
LEFT JOIN ratepivot b ON a.Account = b.Account
</code>```

Which gives me this

But this is not dynamic and my Microsoft version 2016 does not allow me to use the Fiddle thing recommended in various posts. Thus I was recommended to use the Coalesce() function but I have no idea what to do to make the latter dynamic. Any help (not referring to some post) would really help.

Update:

Following the comment I tried this:

```<code>DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Account)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p '
</code>```

but get this error:

```<code>Msg 1056, Level 15, State 1, Line 37
The number of elements in the select list exceeds the maximum allowed number of 4096 elements.
Msg 102, Level 15, State 1, Line 43
Incorrect syntax near 'x'.
</code>```

Update:

I tried this to limit the amount

```<code>DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.RateChangeDate)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            WHERE c.ArchiveDate = '5/21/2019' AND c.AppliedDate > '1/2/2018'
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p
            pivot
            (
                min(new_noterate)
                for category in (' + @cols + ')
            )

            '

execute(@query)
</code>```

But I am getting this error:

```<code>Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.
</code>```

As requested here is the top 10 from the data table

答:
After playing around with a temp version of your table, I think I finally figured this one out. There are a few things to note first, though.

Because you're trying to pivot two columns, you have to pivot them separately and then join the subresults back together.

Since we're going to use @cols for both pivots, we have to create a version of the @cols variable that aliases the dynamically created pivot column names for the final select.

So let's get into the code.

First, we'll create the strings that will contain our dynamically created column names.

```<code>DECLARE @colsAll AS NVARCHAR(MAX);
DECLARE @cols AS NVARCHAR(MAX);

SET @cols =
STUFF((
        SELECT DISTINCT
            ',' + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate)))
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @colsAll =
STUFF((
        SELECT DISTINCT
            ',' + 'd.' + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate ))) + ' AS [Date'
            + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate )) + '], ' + 'r.'
            + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate ))) + ' AS [Rate'
            + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate )) + ']'
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
</code>```

When setting @colsAll, I'm using the table aliases that will be defined in the final select.

And now to generate the pivot:

```<code>DECLARE @query AS NVARCHAR(MAX);

SET @query = ';WITH dates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.ratechangedate
                    , DateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(ratechangedate)
                for DateIndex in (' + @cols + ')
            ) d)

            ,rates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.new_noterate
                    , RateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))
                from  #vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(new_noterate)
                for RateIndex in (' + @cols + ')
            ) r)

            SELECT d.Account, ' + @colsAll + '
            FROM dates d
            JOIN rates r ON d.Account = r.Account'

EXECUTE ( @query )
</code>```

If you were to PRINT the query, you'd see the query that will be run. I always like to PRINT the query, and then copy and paste the result into a new query window and run it. If any errors pop up, it's easier to debug the final query than to try to debug the dynamic sql. For reference, the query that gets spit out by the above code looks like this:

```<code>;WITH dates AS
(
    SELECT
        Account
        ,[1]
        ,[2]
        ,[3]
    FROM
    (
        SELECT
            a.Account
            ,a.ratechangedate
            ,DateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account
                                                                  ORDER BY a.ratechangedate
                                                           )
                         )
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
    ) x
    PIVOT
    (
        MIN(ratechangedate)
        FOR DateIndex IN ( [1]
            ,[2]
            ,[3]
        )
    ) d
)
,rates AS
(
    SELECT
        Account
        ,[1]
        ,[2]
        ,[3]
    FROM
    (
        SELECT
            a.Account
            ,a.new_noterate
            ,RateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account
                                                                  ORDER BY a.ratechangedate
                                                           )
                         )
        FROM #vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
    ) x
    PIVOT
    (
        MIN(new_noterate)
        FOR RateIndex IN ( [1]
            ,[2]
            ,[3]
        )
    ) r
)
SELECT
    d.Account
    ,d.[1] AS Date1
    ,r.[1] AS Rate1
    ,d.[2] AS Date2
    ,r.[2] AS Rate2
    ,d.[3] AS Date3
    ,r.[3] AS Rate3
FROM dates d
JOIN rates r ON d.Account = r.Account
</code>```

EDIT:

Here's an updated version of the query that pads the pivot column names with leading zeros to create a three-digit ordinal.

```<code>SET @cols =
STUFF((
        SELECT DISTINCT
            ',' + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3))
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @colsAll =
STUFF((
        SELECT DISTINCT
            ',' + 'd.' + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)) + ' AS [Date'
            + RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3) + '], ' + 'r.'
            + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)) + ' AS [Rate'
            + RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3) + ']'
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @query = ';WITH dates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.ratechangedate
                    , DateIndex = RIGHT((''00''+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(ratechangedate)
                for DateIndex in (' + @cols + ')
            ) d)

            ,rates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.new_noterate
                    , RateIndex = RIGHT((''00''+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(new_noterate)
                for RateIndex in (' + @cols + ')
            ) r)

            SELECT d.Account, ' + @colsAll + '
            FROM dates d
            JOIN rates r ON d.Account = r.Account'
</code>```

Body:
I have done this:

;WITH a AS
(
    SELECT
        a.account
        ,index_num_date = 'date ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,index_num_rate = 'rate ' + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY ratechangedate ))
        ,ratechangedate
        ,new_noterate
    FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
    INNER JOIN
    (
        SELECT *
        FROM mars..vw_loans
        WHERE loanstatus <> 'bk payment plan'
    ) b ON a.account = b.account
    WHERE archivedate = '5/20/2019'
)
,q1 AS
(
    SELECT DISTINCT
        account
        ,ratechangedate
        ,index_num_date
    FROM a
)
,q2 AS
(
    SELECT DISTINCT
        account
        ,new_noterate
        ,index_num_rate
    FROM a
)
,datepivot AS
(
    SELECT DISTINCT
        account
        ,[date 1]
        ,[date 2]
        ,[date 3]
        ,[date 4]
        ,[date 5]
        ,[date 6]
        ,[date 7]
        ,[date 8]
        ,[date 9]
        ,[date 10]
        ,[date 11]
        ,[date 12]
        ,[date 13]
    FROM q1
        PIVOT
        (
            MIN(ratechangedate)
            FOR index_num_date IN ( [date 1]
                ,[date 2]
                ,[date 3]
                ,[date 4]
                ,[date 5]
                ,[date 6]
                ,[date 7]
                ,[date 8]
                ,[date 9]
                ,[date 10]
                ,[date 11]
                ,[date 12]
                ,[date 13]
            )
        ) pvt1
)
,ratepivot AS
(
    SELECT DISTINCT
        account
        ,[rate 1]
        ,[rate 2]
        ,[rate 3]
        ,[rate 4]
        ,[rate 5]
        ,[rate 6]
        ,[rate 7]
        ,[rate 8]
        ,[rate 9]
        ,[rate 10]
        ,[rate 11]
        ,[rate 12]
        ,[rate 13]
    FROM q2
        PIVOT
        (
            MIN(new_noterate)
            FOR index_num_rate IN ( [rate 1]
                ,[rate 2]
                ,[rate 3]
                ,[rate 4]
                ,[rate 5]
                ,[rate 6]
                ,[rate 7]
                ,[rate 8]
                ,[rate 9]
                ,[rate 10]
                ,[rate 11]
                ,[rate 12]
                ,[rate 13]
            )
        ) pvt2
)
SELECT
    a.Account
    ,[date 1]
    ,[rate 1]
FROM datepivot a
LEFT JOIN ratepivot b ON a.Account = b.Account

Which gives me this

But this is not dynamic and my Microsoft version 2016 does not allow me to use the Fiddle thing recommended in various posts. Thus I was recommended to use the Coalesce() function but I have no idea what to do to make the latter dynamic. Any help (not referring to some post) would really help.

Update:

Following the comment I tried this:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Account)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p '

but get this error:

Msg 1056, Level 15, State 1, Line 37
The number of elements in the select list exceeds the maximum allowed number of 4096 elements.
Msg 102, Level 15, State 1, Line 43
Incorrect syntax near 'x'.

Update:

I tried this to limit the amount

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.RateChangeDate)
            FROM MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive] c
            WHERE c.ArchiveDate = '5/21/2019' AND c.AppliedDate > '1/2/2018'
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Account, ' + @cols + ' from
            (
                select Account
                    , ratechangedate
                    , new_noterate
                from  MARS_DW.[dbo].[vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive]
           ) x
            pivot
            (
                 min(ratechangedate)
                for category in (' + @cols + ')
            ) p
            pivot
            (
                min(new_noterate)
                for category in (' + @cols + ')
            )

            '

execute(@query)

But I am getting this error:

Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.

As requested here is the top 10 from the data table

Body:
After playing around with a temp version of your table, I think I finally figured this one out. There are a few things to note first, though.

Because you're trying to pivot two columns, you have to pivot them separately and then join the subresults back together.

Since we're going to use @cols for both pivots, we have to create a version of the @cols variable that aliases the dynamically created pivot column names for the final select.

So let's get into the code.

First, we'll create the strings that will contain our dynamically created column names.

DECLARE @colsAll AS NVARCHAR(MAX);
DECLARE @cols AS NVARCHAR(MAX);

SET @cols =
STUFF((
        SELECT DISTINCT
            ',' + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate)))
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @colsAll =
STUFF((
        SELECT DISTINCT
            ',' + 'd.' + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate ))) + ' AS [Date'
            + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate )) + '], ' + 'r.'
            + QUOTENAME(CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate ))) + ' AS [Rate'
            + CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY account ORDER BY ratechangedate )) + ']'
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

When setting @colsAll, I'm using the table aliases that will be defined in the final select.

And now to generate the pivot:

DECLARE @query AS NVARCHAR(MAX);

SET @query = ';WITH dates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.ratechangedate
                    , DateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(ratechangedate)
                for DateIndex in (' + @cols + ')
            ) d)

            ,rates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.new_noterate
                    , RateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))
                from  #vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(new_noterate)
                for RateIndex in (' + @cols + ')
            ) r)

            SELECT d.Account, ' + @colsAll + '
            FROM dates d
            JOIN rates r ON d.Account = r.Account'

EXECUTE ( @query )

If you were to PRINT the query, you'd see the query that will be run. I always like to PRINT the query, and then copy and paste the result into a new query window and run it. If any errors pop up, it's easier to debug the final query than to try to debug the dynamic sql. For reference, the query that gets spit out by the above code looks like this:

;WITH dates AS
(
    SELECT
        Account
        ,[1]
        ,[2]
        ,[3]
    FROM
    (
        SELECT
            a.Account
            ,a.ratechangedate
            ,DateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account
                                                                  ORDER BY a.ratechangedate
                                                           )
                         )
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
    ) x
    PIVOT
    (
        MIN(ratechangedate)
        FOR DateIndex IN ( [1]
            ,[2]
            ,[3]
        )
    ) d
)
,rates AS
(
    SELECT
        Account
        ,[1]
        ,[2]
        ,[3]
    FROM
    (
        SELECT
            a.Account
            ,a.new_noterate
            ,RateIndex = CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account
                                                                  ORDER BY a.ratechangedate
                                                           )
                         )
        FROM #vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
    ) x
    PIVOT
    (
        MIN(new_noterate)
        FOR RateIndex IN ( [1]
            ,[2]
            ,[3]
        )
    ) r
)
SELECT
    d.Account
    ,d.[1] AS Date1
    ,r.[1] AS Rate1
    ,d.[2] AS Date2
    ,r.[2] AS Rate2
    ,d.[3] AS Date3
    ,r.[3] AS Rate3
FROM dates d
JOIN rates r ON d.Account = r.Account

EDIT:

Here's an updated version of the query that pads the pivot column names with leading zeros to create a three-digit ordinal.

SET @cols =
STUFF((
        SELECT DISTINCT
            ',' + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3))
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @colsAll =
STUFF((
        SELECT DISTINCT
            ',' + 'd.' + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)) + ' AS [Date'
            + RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3) + '], ' + 'r.'
            + QUOTENAME(RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)) + ' AS [Rate'
            + RIGHT(('00'+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3) + ']'
        FROM MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
        INNER JOIN
        (
            SELECT account
            FROM mars..vw_loans
            WHERE loanstatus <> 'bk payment plan'
        ) b ON a.account = b.account
        WHERE
            a.ArchiveDate = '5/21/2019'
            AND a.AppliedDate > '1/2/2018'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)

SET @query = ';WITH dates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.ratechangedate
                    , DateIndex = RIGHT((''00''+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(ratechangedate)
                for DateIndex in (' + @cols + ')
            ) d)

            ,rates as (SELECT Account, ' + @cols
             + ' from
            (
                select a.Account
                    , a.new_noterate
                    , RateIndex = RIGHT((''00''+CONVERT(VARCHAR(30), DENSE_RANK() OVER ( PARTITION BY a.account ORDER BY a.ratechangedate ))),3)
                from  MARS_DW.dbo.vw_GTMScheduledRateAndPaymentChangesWithAccountNumber_Archive a
                INNER JOIN (SELECT account
                                FROM mars..vw_loans
                                WHERE loanstatus <> ''bk payment plan''
                            ) b ON a.account = b.account
                WHERE a.ArchiveDate = ''5/21/2019'' AND a.AppliedDate > ''1/2/2018''
           ) x

            pivot
            (
                min(new_noterate)
                for RateIndex in (' + @cols + ')
            ) r)

            SELECT d.Account, ' + @colsAll + '
            FROM dates d
            JOIN rates r ON d.Account = r.Account'


来源: stackexchange

问:
Colon : in Dart constructor syntax

class X extends Y {
  X(int a, int b) : super(a,b);
}
```

Can someone give me an explanation about the syntax meaning of the colon :?

答:
It's ok to access non static member in initializer list.

class Point {
  num x, y;

  Point(this.x, this.y);
  Point.origin(): this.x = 10, this.y = 10;
}

main() {
  Point p = Point.origin();
  print(p.x); // 10
}
```

ContentLicense: CC BY-SA 4.0

Title: Colon : in Dart constructor syntax

Body:
class X extends Y {
  X(int a, int b) : super(a,b);
}

Can someone give me an explanation about the syntax meaning of the colon :?


问:
Is it possible to Decompile and read an SSIS package code?
I am working on a project which was owned by a different person. He created a job to update bunch of fields in handful of tables in SQL server. That job was based on an SSIS package. Now I have the DTSX file and the disabled job. When I tried to enable the job after changing the old credentials in the DTSX file, I am getting weird errors. I want to see the code behind the SSIS package and want to see how the update process is coded.
Is there a way to do this?</p>

答:
Depending on which version of SSIS you're working with, you'd want to look at the XML of the package (F7 if you have the package open) and find a block like the following

```<code><DTS:Executable
  DTS:refId="Package\Execute SQL Task"
  DTS:CreationName="Microsoft.ExecuteSQLTask"
  DTS:Description="Execute SQL Task"
  DTS:DTSID="{93D895E6-A316-4718-9C97-4A5652ABD28C}"
  DTS:ExecutableType="Microsoft.ExecuteSQLTask"
  DTS:LocaleID="-1"
  DTS:ObjectName="Execute SQL Task"
  DTS:TaskContact="Execute SQL Task; Microsoft Corporation; SQL Server 2017; © 2017 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1"
  DTS:ThreadHint="0">
  <DTS:Variables />
  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStatementSource="UPDATE T SET Count = Count+1 FROM dbo.Table AS T;" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>
</DTS:Executable>
</code>```

This task uses a "hard coded" statement which is associated with the SQLTask:SqlStatementSource entity.

However, if the Execute SQL Task is driven by a Variable, then you'd see a block of XML as follows. There's no actual query there so you'd have to find the <Variables> collection that define User::MyQueryVariable and then you'd only have the design time value and not the run-time value

```<code>  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStmtSourceType="Variable"
      SQLTask:SqlStatementSource="User::MyQueryVariable" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>
</code>```

Finally, for completeness, if the developer had specified File Source, you'd see something like this

```<code>  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStmtSourceType="FileConnection"
      SQLTask:SqlStatementSource="FileConnectionSource" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>
</code>```

You would then need to find the definition for FileConnectionSource within the XML as well.

Body:
Depending on which version of SSIS you're working with, you'd want to look at the XML of the package (F7 if you have the package open) and find a block like the following

<DTS:Executable
  DTS:refId="Package\Execute SQL Task"
  DTS:CreationName="Microsoft.ExecuteSQLTask"
  DTS:Description="Execute SQL Task"
  DTS:DTSID="{93D895E6-A316-4718-9C97-4A5652ABD28C}"
  DTS:ExecutableType="Microsoft.ExecuteSQLTask"
  DTS:LocaleID="-1"
  DTS:ObjectName="Execute SQL Task"
  DTS:TaskContact="Execute SQL Task; Microsoft Corporation; SQL Server 2017; © 2017 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1"
  DTS:ThreadHint="0">
  <DTS:Variables />
  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStatementSource="UPDATE T SET Count = Count+1 FROM dbo.Table AS T;" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>
</DTS:Executable>

This task uses a "hard coded" statement which is associated with the SQLTask:SqlStatementSource entity.

However, if the Execute SQL Task is driven by a Variable, then you'd see a block of XML as follows. There's no actual query there so you'd have to find the <Variables> collection that define User::MyQueryVariable and then you'd only have the design time value and not the run-time value

  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStmtSourceType="Variable"
      SQLTask:SqlStatementSource="User::MyQueryVariable" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>

Finally, for completeness, if the developer had specified File Source, you'd see something like this

  <DTS:ObjectData>
    <SQLTask:SqlTaskData
      SQLTask:Connection="{CEE71D69-1F9F-46FA-A22F-C9EB60670EA0}"
      SQLTask:SqlStmtSourceType="FileConnection"
      SQLTask:SqlStatementSource="FileConnectionSource" xmlns:SQLTask="www.microsoft.com/sqlserver/dts/tasks/sqltask" />
  </DTS:ObjectData>

You would then need to find the definition for FileConnectionSource within the XML as well.


问:
Printing in java doesn't complete in windows 7
When i print something by java application in windows 7 the output is blank page and the last graphic only is printed but when i print it in windows 10 it printed successfully .. so i don't no why this happen in windows 7 specially it was printing before on windows 7 and suddenly it happen what i told before (blank page)

this is my code and the output in the picture below

```<code>    public void printed_bill_printing() {
    totals_panelB.setVisible(true);
    footer_panelB.setVisible(true);

    int count_rows = tableEB.getRowCount();
    int count = 0;
    int table_height = 0;
    while (count <= count_rows - 1) {
        int row_height = tableEB.getRowHeight(count);
        table_height = row_height + table_height;
        count++;
    }

    float widtha = scrollPaneEB.getWidth();
    float heighta = table_height + 30;

    scrollPaneEB.setSize(Math.round(widtha), Math.round(heighta));

    PrinterJob printJob = PrinterJob.getPrinterJob();
    final int finalTable_height = table_height;
    printJob.setPrintable(new Printable() {
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

            if (pageIndex > 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D paint_PF = (Graphics2D) graphics;
            paint_PF.scale(.68, .6);
            B.print(paint_PF);

            Graphics2D paint_table = (Graphics2D) graphics;
            paint_table.translate(1, 430);
            paint_table.scale(.68, 1);
            scrollPaneB.setVisible(false);
            scrollPaneEB.print(paint_table);

            Graphics2D paint_egmaly = (Graphics2D) graphics;
            paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
            paint_egmaly.scale(1.45, 1);
            totals_panelB.setVisible(false);
            totals_panelB.print(paint_egmaly);

            Graphics2D paint_tawke3 = (Graphics2D) graphics;
            paint_tawke3.translate(0, 200);
            footer_panelB.setVisible(false);
            footer_panelB.print(paint_tawke3);

            return Printable.PAGE_EXISTS;
        }
    });

    PrintRequestAttributeSet printRequestAttrSet = new HashPrintRequestAttributeSet();
    printRequestAttrSet.add(new MediaPrintableArea(0, 0, 350, 500, MediaPrintableArea.MM));
    printRequestAttrSet.add(Chromaticity.MONOCHROME);

    try {
        PrintService ps = findPrintService(String.valueOf(printer1PST_combo.getSelectedItem()));
        printJob.setPrintService(ps);
        printJob.print(printRequestAttrSet);
    } catch (PrinterException ex) {

    }
    adapt_table_size(scrollPaneEB, 440, 351);

}
</code>```

答:
Casting a Graphics object does not create a new Graphics object.  You repeatedly cast the Graphics object and place it in new variables, but it’s still the same Graphics object, so your changes are cumulative.

Stepping through the code:

```<code>Graphics2D paint_PF = (Graphics2D) graphics;
</code>```

This causes paint_PF to contain the same print Graphics object that was passed to the method.  It is referring to the graphics object as a Graphics2D, but it’s still the same object.

```<code>paint_PF.scale(.68, .6);
B.print(paint_PF);
</code>```

Now the original print Graphics object is at 0.68 by 0.6 scale.

```<code>Graphics2D paint_table = (Graphics2D) graphics;
</code>```

Again, this is the same Graphics object, which the code just set to have a 0.68 by 0.6 scale.

```<code>paint_table.translate(1, 430);
paint_table.scale(.68, 1);
</code>```

The print Graphics object is still scaled by 0.68 by 0.6;  now you are scaling it further by 0.68, resulting in a Graphics object which is actually scaled by 0.04624 by 0.6 (because 0.68 × 0.68 = 0.04624).

```<code>scrollPaneB.setVisible(false);
scrollPaneEB.print(paint_table);

Graphics2D paint_egmaly = (Graphics2D) graphics;
</code>```

paint_egmaly still contains the original print Graphics object.

```<code>paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
paint_egmaly.scale(1.45, 1);
</code>```

Now your print Graphics has been scaled, scaled again, translated, and scaled yet again.

```<code>totals_panelB.setVisible(false);
totals_panelB.print(paint_egmaly);

Graphics2D paint_tawke3 = (Graphics2D) graphics;
</code>```

paint_tawke3 contains the original graphics object, with all of the previous scaling and translation.

```<code>paint_tawke3.translate(0, 200);
</code>```

Now the Graphics object has been scaled, scaled, translated, scaled, and translated again.

```<code>footer_panelB.setVisible(false);
footer_panelB.print(paint_tawke3);
</code>```

One way to make your changes to the Graphics temporary is by creating a new Graphics object, using Graphics.create, then apply your changes to that.  If you do this, you are responsible for deallocating the Graphics object by calling its dispose method.

```<code>Graphics2D paint_PF = (Graphics2D) graphics.create();
paint_PF.scale(.68, .6);
B.print(paint_PF);
paint_PF.dispose();     // DO NOT FORGET THIS

Graphics2D paint_table = (Graphics2D) graphics.create();
paint_table.translate(1, 430);
paint_table.scale(.68, 1);
scrollPaneB.setVisible(false);
scrollPaneEB.print(paint_table);
paint_table.dispose();  // DO NOT FORGET THIS

Graphics2D paint_egmaly = (Graphics2D) graphics.create();
paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
paint_egmaly.scale(1.45, 1);
totals_panelB.setVisible(false);
totals_panelB.print(paint_egmaly);
paint_egmaly.dispose(); // DO NOT FORGET THIS

Graphics2D paint_tawke3 = (Graphics2D) graphics.create();
paint_tawke3.translate(0, 200);
footer_panelB.setVisible(false);
footer_panelB.print(paint_tawke3);
paint_tawke3.dispose(); // DO NOT FORGET THIS
</code>```

Another option, which uses fewer resources, is to restore the transform of the Graphics object after each change:

```<code>paint_PF.scale(.68, .6);
B.print(paint_PF);
</code>```0

Body:
When i print something by java application in windows 7 the output is blank page and the last graphic only is printed but when i print it in windows 10 it printed successfully .. so i don't no why this happen in windows 7 specially it was printing before on windows 7 and suddenly it happen what i told before (blank page)

this is my code and the output in the picture below

    public void printed_bill_printing() {
    totals_panelB.setVisible(true);
    footer_panelB.setVisible(true);

    int count_rows = tableEB.getRowCount();
    int count = 0;
    int table_height = 0;
    while (count <= count_rows - 1) {
        int row_height = tableEB.getRowHeight(count);
        table_height = row_height + table_height;
        count++;
    }

    float widtha = scrollPaneEB.getWidth();
    float heighta = table_height + 30;

    scrollPaneEB.setSize(Math.round(widtha), Math.round(heighta));

    PrinterJob printJob = PrinterJob.getPrinterJob();
    final int finalTable_height = table_height;
    printJob.setPrintable(new Printable() {
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

            if (pageIndex > 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D paint_PF = (Graphics2D) graphics;
            paint_PF.scale(.68, .6);
            B.print(paint_PF);

            Graphics2D paint_table = (Graphics2D) graphics;
            paint_table.translate(1, 430);
            paint_table.scale(.68, 1);
            scrollPaneB.setVisible(false);
            scrollPaneEB.print(paint_table);

            Graphics2D paint_egmaly = (Graphics2D) graphics;
            paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
            paint_egmaly.scale(1.45, 1);
            totals_panelB.setVisible(false);
            totals_panelB.print(paint_egmaly);

            Graphics2D paint_tawke3 = (Graphics2D) graphics;
            paint_tawke3.translate(0, 200);
            footer_panelB.setVisible(false);
            footer_panelB.print(paint_tawke3);

            return Printable.PAGE_EXISTS;
        }
    });

    PrintRequestAttributeSet printRequestAttrSet = new HashPrintRequestAttributeSet();
    printRequestAttrSet.add(new MediaPrintableArea(0, 0, 350, 500, MediaPrintableArea.MM));
    printRequestAttrSet.add(Chromaticity.MONOCHROME);

    try {
        PrintService ps = findPrintService(String.valueOf(printer1PST_combo.getSelectedItem()));
        printJob.setPrintService(ps);
        printJob.print(printRequestAttrSet);
    } catch (PrinterException ex) {

    }
    adapt_table_size(scrollPaneEB, 440, 351);

}

Body:
Casting a Graphics object does not create a new Graphics object.  You repeatedly cast the Graphics object and place it in new variables, but it’s still the same Graphics object, so your changes are cumulative.

Stepping through the code:

Graphics2D paint_PF = (Graphics2D) graphics;

This causes paint_PF to contain the same print Graphics object that was passed to the method.  It is referring to the graphics object as a Graphics2D, but it’s still the same object.

paint_PF.scale(.68, .6);
B.print(paint_PF);

Now the original print Graphics object is at 0.68 by 0.6 scale.

Graphics2D paint_table = (Graphics2D) graphics;

Again, this is the same Graphics object, which the code just set to have a 0.68 by 0.6 scale.

paint_table.translate(1, 430);
paint_table.scale(.68, 1);

The print Graphics object is still scaled by 0.68 by 0.6;  now you are scaling it further by 0.68, resulting in a Graphics object which is actually scaled by 0.04624 by 0.6 (because 0.68 × 0.68 = 0.04624).

scrollPaneB.setVisible(false);
scrollPaneEB.print(paint_table);

Graphics2D paint_egmaly = (Graphics2D) graphics;

paint_egmaly still contains the original print Graphics object.

paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
paint_egmaly.scale(1.45, 1);

Now your print Graphics has been scaled, scaled again, translated, and scaled yet again.

totals_panelB.setVisible(false);
totals_panelB.print(paint_egmaly);

Graphics2D paint_tawke3 = (Graphics2D) graphics;

paint_tawke3 contains the original graphics object, with all of the previous scaling and translation.

paint_tawke3.translate(0, 200);

Now the Graphics object has been scaled, scaled, translated, scaled, and translated again.

footer_panelB.setVisible(false);
footer_panelB.print(paint_tawke3);

One way to make your changes to the Graphics temporary is by creating a new Graphics object, using Graphics.create, then apply your changes to that.  If you do this, you are responsible for deallocating the Graphics object by calling its dispose method.

Graphics2D paint_PF = (Graphics2D) graphics.create();
paint_PF.scale(.68, .6);
B.print(paint_PF);
paint_PF.dispose();     // DO NOT FORGET THIS

Graphics2D paint_table = (Graphics2D) graphics.create();
paint_table.translate(1, 430);
paint_table.scale(.68, 1);
scrollPaneB.setVisible(false);
scrollPaneEB.print(paint_table);
paint_table.dispose();  // DO NOT FORGET THIS

Graphics2D paint_egmaly = (Graphics2D) graphics.create();
paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
paint_egmaly.scale(1.45, 1);
totals_panelB.setVisible(false);
totals_panelB.print(paint_egmaly);
paint_egmaly.dispose(); // DO NOT FORGET THIS

Graphics2D paint_tawke3 = (Graphics2D) graphics.create();
paint_tawke3.translate(0, 200);
footer_panelB.setVisible(false);
footer_panelB.print(paint_tawke3);
paint_tawke3.dispose(); // DO NOT FORGET THIS

Another option, which uses fewer resources, is to restore the transform of the Graphics object after each change:

AffineTransform originalTransform = ((Graphics2D) graphics).getTransform();

Graphics2D paint_PF = (Graphics2D) graphics;
paint_PF.scale(.68, .6);
B.print(paint_PF);
paint_PF.setTransform(originalTransform);

Graphics2D paint_table = (Graphics2D) graphics;
paint_table.translate(1, 430);
paint_table.scale(.68, 1);
scrollPaneB.setVisible(false);
scrollPaneEB.print(paint_table);
paint_table.setTransform(originalTransform);

Graphics2D paint_egmaly = (Graphics2D) graphics;
paint_egmaly.translate(1, finalTable_height + tableEB.getTableHeader().getHeight() + 2);
paint_egmaly.scale(1.45, 1);
totals_panelB.setVisible(false);
totals_panelB.print(paint_egmaly);
paint_egmaly.setTransform(originalTransform);

Graphics2D paint_tawke3 = (Graphics2D) graphics;
paint_tawke3.translate(0, 200);
footer_panelB.setVisible(false);
footer_panelB.print(paint_tawke3);
paint_tawke3.setTransform(originalTransform);


问:
How to increment a MySQL timestamp in PHP?
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

```<code>$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;
</code>```

Thanks

答: Use the SUBTIME() function in your query if you cannot change the server time to reflect a appropriate timestamp</p>

ContentLicense: CC BY-SA 3.0

Body:
So I have a MYSQL timestampl that is generating values that are 4hours ahead of what they should be. How would i subtract 4hrs from the MySQL time stamp and display that?

Here's my current code

$mdate = date('F j, Y, g:i a',strtotime( $bm->date_added));
//$bm->dated_added returns the times stamp//
echo $mdate;

Thanks


问:
How to calculate table values dynamically and find Min and Max target from parameter in SQL Server
I want to calculate table values dynamically and find Min and Max target from parameter

I have the following target table with data:

```<code>Name        Quarter Method  MethodID    GivenTarget Percentage
Json Ray    1       AB      1           153000      0.2
Json Ray    1       BC      2           208000      0.5
Json Ray    1       CD      3           252000      0.8
Json Ray    1       DE      4           450000      0.2
Json Ray    2       AB      1           223000      1.4
Json Ray    2       BC      2           308000      1.8
Json Ray    2       CD      3           352000      1.2
Json Ray    2       DE      4           550000      1.5
Json Ray    3       AB      1           323000      2.8
Json Ray    3       BC      2           408000      2.3
Json Ray    3       CD      3           552000      2.4
Json Ray    3       DE      4           650000      2.9
Json Ray    4       AB      1           423000      2.2
Json Ray    4       BC      2           508000      3.3
Json Ray    4       CD      3           652000      3.5
Json Ray    4       DE      4           750000      3.9
</code>```

I am passing a parameter AchievedTarget for a particular quarter (1, 2, 3, 4).

IF quarter = 1 and AchievedTarget = 250000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 1 and AchievedTarget = 400000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 2 and AchievedTarget = 400000, I want to sum GivenTarget column  from Target tables where Quarter = 1, Method = ’AB’, Method_ID = 1
With  Quarter= 2  Method = ’AB’ Method_ID = 1 and so on for add each respective method and Method_ID with quarters, and need to pick Percentage values from current Quarter i.e Quarter 2 in this case with respective Method and Method_ID

Expected New Target tables for Quarter 2 should be as follows:

Now depend upon above table I want to calculate Min_Target  and Max_Target as calculated earlier

Expected output with Quarter= 2   and AchievedTarget= 500000 should be:

Following is the code which i was trying, its gives me output for Quarter = 1 only

```<code>--DECLARE Input Parameters
DECLARE @AchievedTarget Money =200000
DECLARE @Name varchar(30)='Json Ray' , @Quarter int =1, @Mothod varchar(10)='AB'

--DECLARE Ouput variable
DECLARE @Min_Target Money, @Max_Target Money, @Min_Percenatge float ,@Max_Percenatge float

--Finding Min_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] desc)
IF @Min_Target IS Null
SET @Min_Target=(@AchievedTarget)

--Finding Max_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] ASC)
IF @Max_Target IS Null
SET @Max_Target=(@AchievedTarget)

--Finding @Min_Percenatge
SET @Min_Percenatge=(SELECT TOP 1 [Percenatge] AS Min_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target))

--Finding @Max_Percenatge
SET @Max_Percenatge=(SELECT TOP 1 [Percenatge] AS Max_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target)
ORDER BY [Percenatge] DESC)

--Display Ouput
SELECT @Name, @Quarter,@Mothod ,@Min_Target, @Max_Target, @Min_Percenatge,@Max_Percenatge
</code>```

I am not able to calculate table values dynamically and find Min and Max target from parameter quarter.

答:
I have put together a set of sample data and query that will do this. I have removed references to Mothod, as you only have 1 row per Mothod per quarter. You can add the column back in to my solution if you have more rows that your sample.

First set up the table and test data

```<code>declare @comm table(Name varchar(20), Qtr int, Mothod varchar(2), Method_ID int, GivenTarget int, Pct decimal(5,2))
insert @comm values
('Json Ray',1,'AB',1,153000,0.2 )
,('Json Ray',1,'BC',2,208000,0.5 )
,('Json Ray',1,'CD',3,252000,0.8 )
,('Json Ray',1,'DE',4,450000,0.2 )
,('Json Ray',2,'AB',1,223000,1.4 )
,('Json Ray',2,'BC',2,308000,1.8 )
,('Json Ray',2,'CD',3,352000,1.2 )
,('Json Ray',2,'DE',4,550000,1.5 )
,('Json Ray',3,'AB',1,323000,2.8 )
,('Json Ray',3,'BC',2,408000,2.3 )
,('Json Ray',3,'CD',3,552000,2.4 )
,('Json Ray',3,'DE',4,650000,2.9 )
,('Json Ray',4,'AB',1,423000,2.2 )
,('Json Ray',4,'BC',2,508000,3.3 )
,('Json Ray',4,'CD',3,652000,3.5 )
,('Json Ray',4,'DE',4,750000,3.9 )
</code>```

Add a top row in case as a catch for anyone who has achieved higher than your top target

```<code>insert @comm
select Name, qtr, null, null, 999999, max(pct) from @comm group by Name, qtr
</code>```

Set up your conditions. I have taken out Mothod as you only have one row per Mothos per Qtr

```<code>DECLARE @AchievedTarget Money
DECLARE @Name varchar(30), @Quarter int
select @AchievedTarget=500000,  @Name='Json Ray' , @Quarter=2
</code>```

Use a CTE to get cumulative totals per qtr, and a second CTE to flatten each row so it also had the values of the previous row. I've used row_number to make sure I correctly order your rows, even though in your sample date mothod_id appears to also have the same data.

The final query then simply finds the correct row out of the CTE.

```<code>;with c as (
select Name, upto as qtr, Mothod, Method_ID,
    sum(GivenTarget) as GivenTarget,
    max(case when c.qtr=q.upto then c.pct else 0 end) as Pct,
    row_number() over (partition by Name, upto order by sum(GivenTarget)) as rn
from @comm c
join (select distinct qtr as upto from @comm) q on c.qtr<=upto
group by Name, upto, Mothod, Method_ID
)
, c2 as (
select c.Name, c.Qtr, c.GivenTarget as MaxTarget, c.Pct as MaxPct,
    isnull(c2.GivenTarget,0) as MinTarget, isnull(c2.Pct,0) as MinPct
from c
left join c c2 on c2.name=c.name and c2.qtr=c.qtr and c2.rn=c.rn-1
where c.name=@name and c.qtr=@Quarter
)
select Name, Qtr, MinTarget, MaxTarget, MinPct, MaxPct
from c2
where @AchievedTarget>MinTarget and @AchievedTarget<=MaxTarget
</code>```

Result, using @qtr=2 and @achieved=500000:

```<code>Name       Qtr  MinTarget   MaxTarget   MinPct  MaxPct
Json Ray    2   376000      516000      1.40    1.80
</code>```

Body:
I want to calculate table values dynamically and find Min and Max target from parameter

I have the following target table with data:

Name        Quarter Method  MethodID    GivenTarget Percentage
Json Ray    1       AB      1           153000      0.2
Json Ray    1       BC      2           208000      0.5
Json Ray    1       CD      3           252000      0.8
Json Ray    1       DE      4           450000      0.2
Json Ray    2       AB      1           223000      1.4
Json Ray    2       BC      2           308000      1.8
Json Ray    2       CD      3           352000      1.2
Json Ray    2       DE      4           550000      1.5
Json Ray    3       AB      1           323000      2.8
Json Ray    3       BC      2           408000      2.3
Json Ray    3       CD      3           552000      2.4
Json Ray    3       DE      4           650000      2.9
Json Ray    4       AB      1           423000      2.2
Json Ray    4       BC      2           508000      3.3
Json Ray    4       CD      3           652000      3.5
Json Ray    4       DE      4           750000      3.9

I am passing a parameter AchievedTarget for a particular quarter (1, 2, 3, 4).

IF quarter = 1 and AchievedTarget = 250000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 1 and AchievedTarget = 400000 I want the record where AchievedTarget lies in between

Output should be like:

IF quarter = 2 and AchievedTarget = 400000, I want to sum GivenTarget column  from Target tables where Quarter = 1, Method = ’AB’, Method_ID = 1
With  Quarter= 2  Method = ’AB’ Method_ID = 1 and so on for add each respective method and Method_ID with quarters, and need to pick Percentage values from current Quarter i.e Quarter 2 in this case with respective Method and Method_ID

Expected New Target tables for Quarter 2 should be as follows:

Now depend upon above table I want to calculate Min_Target  and Max_Target as calculated earlier

Expected output with Quarter= 2   and AchievedTarget= 500000 should be:

Following is the code which i was trying, its gives me output for Quarter = 1 only

--DECLARE Input Parameters
DECLARE @AchievedTarget Money =200000
DECLARE @Name varchar(30)='Json Ray' , @Quarter int =1, @Mothod varchar(10)='AB'

--DECLARE Ouput variable
DECLARE @Min_Target Money, @Max_Target Money, @Min_Percenatge float ,@Max_Percenatge float

--Finding Min_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] desc)
IF @Min_Target IS Null
SET @Min_Target=(@AchievedTarget)

--Finding Max_Target
SET @Min_Target=(SELECT TOP 1 [GivenTarget] as Min_Target
FROM [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
and [GivenTarget] < @AchievedTarget
order by [GivenTarget] ASC)
IF @Max_Target IS Null
SET @Max_Target=(@AchievedTarget)

--Finding @Min_Percenatge
SET @Min_Percenatge=(SELECT TOP 1 [Percenatge] AS Min_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target))

--Finding @Max_Percenatge
SET @Max_Percenatge=(SELECT TOP 1 [Percenatge] AS Max_Percenatge
from [Target ]
WHERE  [Name] = @Name
AND Quarter = @Quarter
AND Mothod =@Mothod
AND [GivenTarget] in (@Min_Target,@Max_Target)
ORDER BY [Percenatge] DESC)

--Display Ouput
SELECT @Name, @Quarter,@Mothod ,@Min_Target, @Max_Target, @Min_Percenatge,@Max_Percenatge

I am not able to calculate table values dynamically and find Min and Max target from parameter quarter.

Body:
I have put together a set of sample data and query that will do this. I have removed references to Mothod, as you only have 1 row per Mothod per quarter. You can add the column back in to my solution if you have more rows that your sample.

First set up the table and test data

declare @comm table(Name varchar(20), Qtr int, Mothod varchar(2), Method_ID int, GivenTarget int, Pct decimal(5,2))
insert @comm values
('Json Ray',1,'AB',1,153000,0.2 )
,('Json Ray',1,'BC',2,208000,0.5 )
,('Json Ray',1,'CD',3,252000,0.8 )
,('Json Ray',1,'DE',4,450000,0.2 )
,('Json Ray',2,'AB',1,223000,1.4 )
,('Json Ray',2,'BC',2,308000,1.8 )
,('Json Ray',2,'CD',3,352000,1.2 )
,('Json Ray',2,'DE',4,550000,1.5 )
,('Json Ray',3,'AB',1,323000,2.8 )
,('Json Ray',3,'BC',2,408000,2.3 )
,('Json Ray',3,'CD',3,552000,2.4 )
,('Json Ray',3,'DE',4,650000,2.9 )
,('Json Ray',4,'AB',1,423000,2.2 )
,('Json Ray',4,'BC',2,508000,3.3 )
,('Json Ray',4,'CD',3,652000,3.5 )
,('Json Ray',4,'DE',4,750000,3.9 )

Add a top row in case as a catch for anyone who has achieved higher than your top target

insert @comm
select Name, qtr, null, null, 999999, max(pct) from @comm group by Name, qtr

Set up your conditions. I have taken out Mothod as you only have one row per Mothos per Qtr

DECLARE @AchievedTarget Money
DECLARE @Name varchar(30), @Quarter int
select @AchievedTarget=500000,  @Name='Json Ray' , @Quarter=2

Use a CTE to get cumulative totals per qtr, and a second CTE to flatten each row so it also had the values of the previous row. I've used row_number to make sure I correctly order your rows, even though in your sample date mothod_id appears to also have the same data.

The final query then simply finds the correct row out of the CTE.

;with c as (
select Name, upto as qtr, Mothod, Method_ID,
    sum(GivenTarget) as GivenTarget,
    max(case when c.qtr=q.upto then c.pct else 0 end) as Pct,
    row_number() over (partition by Name, upto order by sum(GivenTarget)) as rn
from @comm c
join (select distinct qtr as upto from @comm) q on c.qtr<=upto
group by Name, upto, Mothod, Method_ID
)
, c2 as (
select c.Name, c.Qtr, c.GivenTarget as MaxTarget, c.Pct as MaxPct,
    isnull(c2.GivenTarget,0) as MinTarget, isnull(c2.Pct,0) as MinPct
from c
left join c c2 on c2.name=c.name and c2.qtr=c.qtr and c2.rn=c.rn-1
where c.name=@name and c.qtr=@Quarter
)
select Name, Qtr, MinTarget, MaxTarget, MinPct, MaxPct
from c2
where @AchievedTarget>MinTarget and @AchievedTarget<=MaxTarget

Result, using @qtr=2 and @achieved=500000:

Name       Qtr  MinTarget   MaxTarget   MinPct  MaxPct
Json Ray    2   376000      516000      1.40    1.80


问:
How to join two XML files based on an element in SSIS?
I have two XML files, one with 2 elements and the other file with 4 elements. One of them is common between the two files. I would like to pull the contents of both XML files, do a join with the common element (like an inner join between two SQL server tables) and then dump the output of the columns in both files into one output file. Below is the content of file1.xml.

```<code><?xml version="1.0" standalone="yes"?>
<DataPairs>
<DataPair>
<LicenseNumber>12345</LicenseNumber>
<DataValue>12331234</DataValue>
</DataPair>
<DataPair>
<LicenseNumber>43432</LicenseNumber>
<DataValue>435432134</DataValue>
</DataPair>
</DataPairs>
</code>```

Below is the content of file2.xml

```<code><LastRecords>
<DataRecord><AgentNum>013512</AgentNum><EmpId>124532523</EmpId><LicenseKey>12345</LicenseKey></DataRecord>
<DataRecord><AgentNum>013512</AgentNum><EmpId>124532523</EmpId><LicenseKey>12345</LicenseKey></DataRecord>
</LastRecords>
</code>```

I would like to do a join between the above files (like INNER JOIN). Whereever the LicenseNumber from file1 is matching with LicenseKey in file2.xml, I would like to output the following values into a SQL server table.

```<code>LicenseKey
AgentId
EmplId
DataValue
</code>```

I have tried using join, join merge, lookup, etc in Visual Studio 2017 by creating an SSIS package, but I don't see any component that can help me merge two xml files to get the results I want.

I am looking for a SSIS component to merge two XML files based on a common element, but I can't seem to find one. I did google search and also looked at couple of youtube videos, but to no avail.

Can someone help?

答:
Unfortunately, there is no official XML destination component found in Integration Services. There are some third party component or you can use a workaround to write to a XML file.

In order to merge two Xml files you have to follow these steps:

Add 2 XML Source component (one for each file)

Add a sort component after each XML source and select the LicenseNumber and LicenseKey as Sorting columns

Add a Merge Join component to merge both flows

To store data in XML file you can follow one of the following links:

Yet another SSIS XML Destination

An “secret” SSIS XML Destination Provider you might not found yet (You need to import data to a staging table first)

How to export data from database tables to an XML file using SSIS (staging table needed)

Or you can use a third party component:

Task Factory Feature: SSIS XML Components

XML SSIS Destination

Body:
I have two XML files, one with 2 elements and the other file with 4 elements. One of them is common between the two files. I would like to pull the contents of both XML files, do a join with the common element (like an inner join between two SQL server tables) and then dump the output of the columns in both files into one output file. Below is the content of file1.xml.

<?xml version="1.0" standalone="yes"?>
<DataPairs>
<DataPair>
<LicenseNumber>12345</LicenseNumber>
<DataValue>12331234</DataValue>
</DataPair>
<DataPair>
<LicenseNumber>43432</LicenseNumber>
<DataValue>435432134</DataValue>
</DataPair>
</DataPairs>

Below is the content of file2.xml

<LastRecords>
<DataRecord><AgentNum>013512</AgentNum><EmpId>124532523</EmpId><LicenseKey>12345</LicenseKey></DataRecord>
<DataRecord><AgentNum>013512</AgentNum><EmpId>124532523</EmpId><LicenseKey>12345</LicenseKey></DataRecord>
</LastRecords>

I would like to do a join between the above files (like INNER JOIN). Whereever the LicenseNumber from file1 is matching with LicenseKey in file2.xml, I would like to output the following values into a SQL server table.

LicenseKey
AgentId
EmplId
DataValue

I have tried using join, join merge, lookup, etc in Visual Studio 2017 by creating an SSIS package, but I don't see any component that can help me merge two xml files to get the results I want.

I am looking for a SSIS component to merge two XML files based on a common element, but I can't seem to find one. I did google search and also looked at couple of youtube videos, but to no avail.

Can someone help?


问:
Writing to MongoDB without waiting for response
I'm trying to figure out how to write to a MongoDB using Mongoose and Node.js without waiting for the response. The typical way to write to MongoDB is either to use the callback syntax or use the await/async pattern. Both of these patterns don't execute the query unless you specify a call back or await the response.

Is there a way to write to MongoDB in a 'best-effort' fashion? I.e. just make the call, don't wait for the response, and if it succeeds great, and if not, no problem.

EDIT:

Code:

Async/await pattern:

```<code>const doc = await Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}});
console.log(doc);
</code>```

Callback pattern

```<code>Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}, func(err, doc) {
    console.log(doc)
});
</code>```

Both of these wait for the response.

答:
You can do the write using w:0 write concern setting. This will instruct MongoDB to do the write, but not waiting for feedback. For example:

```<code>  conn.db('test').collection('test').insertOne({'a': 1}, {'w': 0}, function(err, res) {
    assert.equal(null, err);
    console.log(res);
  })
</code>```

The default write concern is w:1 (wait for confirmation from the node you're connecting to). If you check the res output of the code above using w:1, it will show:

```<code>  ...
  insertedCount: 1,
  ...
</code>```

In contrast, using w:0 will show:

```<code>  ...
  insertedCount: undefined,
  ...
</code>```

Note: although writes will return quickly with best-effort using this setting, this is essentially UDP for your writes. Use at your own risk.

Body:
I'm trying to figure out how to write to a MongoDB using Mongoose and Node.js without waiting for the response. The typical way to write to MongoDB is either to use the callback syntax or use the await/async pattern. Both of these patterns don't execute the query unless you specify a call back or await the response.

Is there a way to write to MongoDB in a 'best-effort' fashion? I.e. just make the call, don't wait for the response, and if it succeeds great, and if not, no problem.

EDIT:

Code:

Async/await pattern:

const doc = await Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}});
console.log(doc);

Callback pattern

Product.findByIdAndUpdate('prod1', {$inc: {viewed: 1}, func(err, doc) {
    console.log(doc)
});

Both of these wait for the response.

Body:
You can do the write using w:0 write concern setting. This will instruct MongoDB to do the write, but not waiting for feedback. For example:

  conn.db('test').collection('test').insertOne({'a': 1}, {'w': 0}, function(err, res) {
    assert.equal(null, err);
    console.log(res);
  })

The default write concern is w:1 (wait for confirmation from the node you're connecting to). If you check the res output of the code above using w:1, it will show:

  ...
  insertedCount: 1,
  ...

In contrast, using w:0 will show:

  ...
  insertedCount: undefined,
  ...

Note: although writes will return quickly with best-effort using this setting, this is essentially UDP for your writes. Use at your own risk.


问:
Evaluate sum of values without clicking a button
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.

However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).

I think change method can be used in the same manner.

@Edit:

Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with  -566,2202888.

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $('#total').val(total);
}

$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">

  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>

  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>

  m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />

  <br/>
  <br/> Features:

  <br/>
  <br/>
  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
  <br/>
  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
  <br/>
  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
  <br/>
  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
  <br/>
  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
  <br/>
  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
  <br/>
  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
  <br/>
  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
  <br/>
  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
  <br/>
  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
  <br/>
  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
  <br/>
  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
  <br/>
  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
  <br/>
  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
  <br/>
  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
  <br/>
</div>
<input type="text" id="total" value="0" /></code>```

答:
You can loop over all the <select> boxes and text inputs with:

```<code>function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
    let multiplier = 1;
    if (this.id == "m2") {
      multiplier = 3134.204499;
    }
    else if (this.id == "binayasi") {
      multiplier = -566.2202888;
    }
    if (this.value) {
      total += parseFloat(this.value) * multiplier;
    }
  });
  $('#total').val(total);
}
</code>```

And if you change the checkboxes to use value instead of price, you can do them all in one loop:

```<code>function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
    let multiplier = 1;
    if (this.id == "m2") {
      multiplier = 3134.204499;
    else if (this.id == "binyasi") {
      multiplier = -566.2202888;
    }
    if (this.value) {
      total += parseFloat(this.value) * multiplier;
    }
  });
  $('#total').val(total);
}
</code>```

And call the function when any of the inputs are changed:

```<code>$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();
</code>```

Body:
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.

However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).

I think change method can be used in the same manner.

@Edit:

Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with  -566,2202888.

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $('#total').val(total);
}

$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();

  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>

  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>

  m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />

 Features:

  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> Bati

  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> Dogu

  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> Guney

  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> Kuzey

  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> Amerikan Mutfak

  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> Dusakabin

  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> Akilli Ev

  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> Ebeveyn Banyosu

  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> Kiler

  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> Kuvet

  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> Parke Zemin

  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> Seramik Zemin

  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> Sauna

  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> Spor Salonu

  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> Tenis Kortu

<input type="text" id="total" value="0" />

Body:
You can loop over all the <select> boxes and text inputs with:

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
    let multiplier = 1;
    if (this.id == "m2") {
      multiplier = 3134.204499;
    }
    else if (this.id == "binayasi") {
      multiplier = -566.2202888;
    }
    if (this.value) {
      total += parseFloat(this.value) * multiplier;
    }
  });
  $('#total').val(total);
}

And if you change the checkboxes to use value instead of price, you can do them all in one loop:

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
    let multiplier = 1;
    if (this.id == "m2") {
      multiplier = 3134.204499;
    else if (this.id == "binyasi") {
      multiplier = -566.2202888;
    }
    if (this.value) {
      total += parseFloat(this.value) * multiplier;
    }
  });
  $('#total').val(total);
}

And call the function when any of the inputs are changed:

$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();


问:
How to click on navigation bar using selenium web driver with python?
using the office 365 navbar, I try to click on the user icon to enter another mailbox, but selenium does not recognize it by id, class_name or xpath?

elem6 = driver.find_element_by_xpath('//*[@id="O365_MeFlexPane_ButtonID"]')
elem6.send_keys(Keys.RETURN)
```

<p>html tag</p>

<pre class="lang-html prettyprint-override"><code><button type="button" class="o365cs-nav-item o365cs-nav-button o365button ms-bgc-nlr ms-fcl-b o365cs-spo-topbarMenuOpen" role="menuitem" title="Carlos Loayza Cuestas" id="O365_MeFlexPane_ButtonID" aria-disabled="false" aria-label="Use la flecha hacia abajo para utilizar el panel Mi cuenta para ver y editar su cuenta y cerrar la sesión"><div class="o365cs-mfp-header"> <div class="o365cs-mfp-header-displayname o365cs-rsp-tn-hide o365cs-mfp-header-displayname-wrap o365cs-display-none"> <span class="" role="presentation">Carlos Loayza Cuestas</span> </div> <div class="o365cs-nav-button o365cs-mfp-header-img"> <div class="o365cs-mfp-doughboy-container"> <span class="ms-bgc-nt ms-fcl-w o365cs-mfp-doughboy o365cs-mfp-circular-small owaimg ms-Icon ms-Icon--Contact ms-icon-font-size-52" aria-hidden="true"> </span> </div> <div class="o365cs-mfp-textboy o365cs-mfp-circular-small" style=""><div class="" style=""><div style="background-color: rgb(118, 118, 118); outline-color: rgb(118, 118, 118);">CC</div></div></div> <div style="display: none;"></div> <div class="o365cs-mfp-header-img-container o365cs-mfp-circular-small" style="display: none;"><img aria-hidden="true" src="service.svc/s/GetPersonaPhoto?email=carlos.loayza@telefonica.com&UA=0&size=HR64x64&sc=1559170428032"></div> <div autoid="__Microsoft_O365_ShellG2_MeFlexHeaderButton_Owa_templates_cs_0" class="o365cs-mfp-presenceButton ms-Icon--skypeCheck o365cs-mfp-skypeAvailable"></div> </div> </div><div class="o365cs-flexPane-unseenitems"> <span class="o365cs-flexPane-unseenCount ms-fcl-w ms-bgc-tdr" style="display: none;"></span> <span class="o365cs-flexPane-unseenCount owaimg ms-Icon--starburst ms-icon-font-size-12 ms-fcl-w ms-bgc-tdr" style="display: none;"> </span> </div></button>
</code>```

python gives me the following result

Traceback (most recent call last):
  File "C:\Users\wcondorp\Videos\Selenium\prueba.py", line 80, in <module>
    elem6 = driver.find_element_by_xpath('//*[@id="O365_MeFlexPane_ButtonID"]') #mail, onedrive, calendaria
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="O365_MeFlexPane_ButtonID"]"}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)
```

答:
Try adding Expected Conditions to wait for the element present using below code.

```<code>ele =WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.XPATH,"//button[@id='O365_MeFlexPane_ButtonID']")))
ele.click()
</code>```

If you are referring to the below button

Try with below xpath.

```<code>//div[@id='meInitialsButton']
</code>```

Or you can also use the below xpath.

```<code>//div[@id='O365_MainLink_MePhoto']
</code>```

Body:
using the office 365 navbar, I try to click on the user icon to enter another mailbox, but selenium does not recognize it by id, class_name or xpath?

elem6 = driver.find_element_by_xpath('//*[@id="O365_MeFlexPane_ButtonID"]')
elem6.send_keys(Keys.RETURN)

html tag

<button type="button" class="o365cs-nav-item o365cs-nav-button o365button ms-bgc-nlr ms-fcl-b o365cs-spo-topbarMenuOpen" role="menuitem" title="Carlos Loayza Cuestas" id="O365_MeFlexPane_ButtonID" aria-disabled="false" aria-label="Use la flecha hacia abajo para utilizar el panel Mi cuenta para ver y editar su cuenta y cerrar la sesión">

 Carlos Loayza Cuestas

CC

</button>

python gives me the following result

Traceback (most recent call last):
  File "C:\Users\wcondorp\Videos\Selenium\prueba.py", line 80, in <module>
    elem6 = driver.find_element_by_xpath('//*[@id="O365_MeFlexPane_ButtonID"]') #mail, onedrive, calendaria
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\wcondorp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="O365_MeFlexPane_ButtonID"]"}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)

Body:
Try adding Expected Conditions to wait for the element present using below code.

ele =WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.XPATH,"//button[@id='O365_MeFlexPane_ButtonID']")))
ele.click()

If you are referring to the below button

Try with below xpath.

//div[@id='meInitialsButton']

Or you can also use the below xpath.

//div[@id='O365_MainLink_MePhoto']


问:
Is std::push_back relatively expensive to use?
I want to improve the performance of the following code. What aspect might affect the performance of the code when it's executed?

Also, considering that there is no limit to how many objects you can add to the container, what improvements could be made to “Object” or “addToContainer” to improve the performance of the program?

I was wondering if std::push_back in C++ affects performance of the code in any way? Especially if there is no limit to adding to list.

```<code>struct Object{
    string name;
    string description;
};

vector<Object> container;
void addToContainer(Object object) {
    container.push_back(object);
}

int main() {
    addToContainer({ "Fira", "+5 ATTACK" });
    addToContainer({ "Potion", "+10 HP" });
}
</code>```

答:
without any other requirements, unfortunately this is the most efficient:

```<code> void addToContainer(Object) { }
</code>```

to answer the rest of your question.  In general push_back will just add to the end of the allocated vector O(1), but will need to grow the vector on occasion, which can be amortized out but is O(N)

also, it would likely be more efficient not to use string, but to keep char *   although memory management might be tricky unless it is always a literal being added

Body:
I want to improve the performance of the following code. What aspect might affect the performance of the code when it's executed?

Also, considering that there is no limit to how many objects you can add to the container, what improvements could be made to “Object” or “addToContainer” to improve the performance of the program?

I was wondering if std::push_back in C++ affects performance of the code in any way? Especially if there is no limit to adding to list.

struct Object{
    string name;
    string description;
};

vector<Object> container;
void addToContainer(Object object) {
    container.push_back(object);
}

int main() {
    addToContainer({ "Fira", "+5 ATTACK" });
    addToContainer({ "Potion", "+10 HP" });
}

Body:
without any other requirements, unfortunately this is the most efficient:

 void addToContainer(Object) { }

to answer the rest of your question.  In general push_back will just add to the end of the allocated vector O(1), but will need to grow the vector on occasion, which can be amortized out but is O(N)

also, it would likely be more efficient not to use string, but to keep char *   although memory management might be tricky unless it is always a literal being added


问:
Terminal control library that blocks on both input and some custom data channel?
ncurses' blocking mode appears to only allow for blocking on stdin - that is, I have no option of doing some select()-esque thing where getch() blocks until either a key is pressed or e.g. data arrives in a pipe. Am I missing something, or is there some other terminal control library that allows me to do this?

Edit: I'm targeting Linux platforms, although the more general the solution, the better.

答:
There's an experimental configure-option, which is rarely used:

--enable-wgetch-events

  Compile with experimental wgetch-events code. See ncurses/README.IZ


问:
Function that stars all but first 3 chars of a word and removes blank space in separate .txt file
takes a copy of a .txt file (the file_name) and then copies but replaces all but the first 3 characters of every word with the character '*' in the destination .txt file. How do I replace all whitespace so each word is followed by a singular space also?

```<code>def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        output = ""
        for word in word_list:
            output += word[:3] + ("*" * (len(word)-3))

    with open(destination, "w") as writefile:
        writefile.write(''.join(output))
</code>```

this is what I have so far.

edit: I just realized I haven't done it correctly looking at the output .txt file.

答:
When replacing characters with stars, add a space to the end of each word.</p>

```<code>....
    ....
        output = ""
        for word in word_list:
            output += word[:3] + "*" * (len(word)-3) + " "
</code>```

Body:
takes a copy of a .txt file (the file_name) and then copies but replaces all but the first 3 characters of every word with the character '*' in the destination .txt file. How do I replace all whitespace so each word is followed by a singular space also?

def speed_reader(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        output = ""
        for word in word_list:
            output += word[:3] + ("*" * (len(word)-3))

    with open(destination, "w") as writefile:
        writefile.write(''.join(output))

this is what I have so far.

edit: I just realized I haven't done it correctly looking at the output .txt file.

Body:
When replacing characters with stars, add a space to the end of each word.

....
    ....
        output = ""
        for word in word_list:
            output += word[:3] + "*" * (len(word)-3) + " "


问:
How to set a variable value based on if-statement in batch file
I am trying to assign a value to a variable based on an if-else statement in a batch file. I am searching a text file for a string and if the string is found I need to assign a certain value to the variable.

I have used the if-else statement to assign the value but after exiting the if-else statement when I try to echo the variable i get value as 0

```<code>@echo off

set "logfile=results.txt"
find /n /i "Orientation      : 0" "%logfile%" >nul
if %errorlevel% equ 0 (
    set org = "landscape"

) else (
    set org = "portrait"

)

echo %org%
</code>```

The output for this should be 'landscape', I have verified that the string does exist in the file. For some reason, I am getting 0 as the output.

答:
As an addition to the already provided answer, where it has been highlighted that you have used spaces either side of your = character. It means that you are setting, for example:
org = "portrait".
Unless you remove those spaces, you'd need to Echo:
%org %
to see the value you'd set, (and that also includes the doublequotes).

I would additionally suggest that you use this syntax:

@Echo Off
Set "logfile=results.txt"
Set "org="
Find /I "Orientation      : 0" <"%logfile%" >Nul && (
    Set "org=landscape"
) || (
    Set "org=portrait"
)
Echo %org%
```

<p>Alternatively, using <code>FindStr</code> gives you a little manoeuvre with the existence or number of spaces, e.g. the following would still match:<br><strong><code>Orientation:0</code></strong><br>or<br><strong><code>Orientation : 0</code></strong></p>

<pre class="lang-bat prettyprint-override"><code>@Echo Off
Set "logfile=results.txt"
Set "org="
FindStr /IRC:"Orientation[\ :]*0" "%logfile%" >Nul && (
    Set "org=landscape"
) || (
    Set "org=portrait"
)
Echo %org%
</code>```

Put into simple terms, the conditional operators && and || effectively mean, if the previous command was successful and if the previous command failed, respectively.

Body:
I am trying to assign a value to a variable based on an if-else statement in a batch file. I am searching a text file for a string and if the string is found I need to assign a certain value to the variable.

I have used the if-else statement to assign the value but after exiting the if-else statement when I try to echo the variable i get value as 0

@echo off

set "logfile=results.txt"
find /n /i "Orientation      : 0" "%logfile%" >nul
if %errorlevel% equ 0 (
    set org = "landscape"

) else (
    set org = "portrait"

)

echo %org%

The output for this should be 'landscape', I have verified that the string does exist in the file. For some reason, I am getting 0 as the output.

Body:
As an addition to the already provided answer, where it has been highlighted that you have used spaces either side of your = character. It means that you are setting, for example:
org = "portrait".
Unless you remove those spaces, you'd need to Echo:
%org %
to see the value you'd set, (and that also includes the doublequotes).

I would additionally suggest that you use this syntax:

@Echo Off
Set "logfile=results.txt"
Set "org="
Find /I "Orientation      : 0" <"%logfile%" >Nul && (
    Set "org=landscape"
) || (
    Set "org=portrait"
)
Echo %org%

Alternatively, using FindStr gives you a little manoeuvre with the existence or number of spaces, e.g. the following would still match:
Orientation:0
or
Orientation : 0

@Echo Off
Set "logfile=results.txt"
Set "org="
FindStr /IRC:"Orientation[\ :]*0" "%logfile%" >Nul && (
    Set "org=landscape"
) || (
    Set "org=portrait"
)
Echo %org%

Put into simple terms, the conditional operators && and || effectively mean, if the previous command was successful and if the previous command failed, respectively.


问:
Generate regularly spaced points in polygon
Is there a way to generate regularly spaced (e.g., 500 meters apart) points within a polygon using R? I have been trying to use the sp package but can't seem to define a set of points that are spaced a certain distance apart from one another. My aim is to generate the points, then extract their lat/long coordinates into a new dataframe. Any help would be much appreciated! Thanks</p>

答:
Here is a way to do assuming you have a lonlat polygon by first transforming it to a planar crs (not as nifty as Roman's solution with destPoint).

Packages and example data

```<code>library(raster)
library(rgdal)
p <- shapefile(system.file("external/lux.shp", package="raster"))[1,]
</code>```

Transform to planar crs (pick one that matches your data!)

```<code>putm <- spTransform(p, "+proj=utm +zone=32 +datum=WGS84")
</code>```

Create a raster with 500 m resolution, rasterize the polygon and transform to points

```<code>r <- raster(putm, res=500)
r <- rasterize(putm, r)
pts <- rasterToPoints(r, spatial=TRUE)
</code>```

Transform the points to lon/lat and plot the results

```<code>pts_lonlat <- spTransform(pts, "+proj=longlat +datum=WGS84")
result <- coordinates(pts_lonlat)

plot(p)
points(result, pch="+", cex=.5)
</code>```

(looks like an elephant)

Body:
Here is a way to do assuming you have a lonlat polygon by first transforming it to a planar crs (not as nifty as Roman's solution with destPoint).

Packages and example data

library(raster)
library(rgdal)
p <- shapefile(system.file("external/lux.shp", package="raster"))[1,]

Transform to planar crs (pick one that matches your data!)

putm <- spTransform(p, "+proj=utm +zone=32 +datum=WGS84")

Create a raster with 500 m resolution, rasterize the polygon and transform to points

r <- raster(putm, res=500)
r <- rasterize(putm, r)
pts <- rasterToPoints(r, spatial=TRUE)

Transform the points to lon/lat and plot the results

pts_lonlat <- spTransform(pts, "+proj=longlat +datum=WGS84")
result <- coordinates(pts_lonlat)

plot(p)
points(result, pch="+", cex=.5)

(looks like an elephant)