问:
Dynamically add buttons in swift
I am writing an iOS app. Server gives me buttons array to draw on view. So, the number of buttons can vary according to server response,
example:

```<code>let buttonArray=["Button 1","Button 2","Button 3"]
or
let buttonArray=["Button 1","Button 2","Button 3"," Button 4", "Button 5"]
</code>```

I have to stack these buttons vertically.
I created a stackview, add constraints to it, and then add buttons to this stackview as arrangedsubviews.
Buttons should have gap of 5 points between them:

Using stackview:

```<code>func addButtonsUsingStackView()
    {
        //create stackview:
        let stackView=UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 5
        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)

        //stackview constraints:
        let viewsDictionary = ["stackView":stackView]
        let stackView_H = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-20-[stackView]-20-|",
            options: NSLayoutFormatOptions(rawValue: 0),
            metrics: nil,
            views: viewsDictionary)
        let stackView_V = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-30-[stackView]-30-|",
            options: NSLayoutFormatOptions(rawValue:0),
            metrics: nil,
            views: viewsDictionary)
        view.addConstraints(stackView_H)
        view.addConstraints(stackView_V)

        //adding buttons to stackview:

        //let buttonArray=["Button 1","Button 2","Button 3"]
        let buttonArray=["Button 1","Button 2","Button 3"," Button 4"]

        for buttonName in buttonArray{

            let button=UIButton()
            button.setTitle(buttonName, for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor=UIColor.blue
            button.translatesAutoresizingMaskIntoConstraints=false

            stackView.addArrangedSubview(button)

        }

    }
</code>```

Without stackview:

```<code>var buttonArray=["Button 1","Button 2","Button 3"," Button 4"," Button 5"," Button 6"," Button 7"]

    func addButtonsLoop()
    {

        for _view in view.subviews{
            _view.removeFromSuperview()
        }

        var i=0
        var buttonY = 20
        let buttonGap=5

        for btn in buttonArray {

            let buttonHeight=Int(Int(view.frame.height) - 40 - (buttonArray.count * buttonGap))/buttonArray.count
            print(buttonHeight)
            let buttonWidth=Int(view.frame.width - 40)

            let button = UIButton()
            button.backgroundColor = UIColor.orange
            button.setTitle(btn, for: .normal)
            button.titleLabel?.textColor = UIColor.white
            button.frame = CGRect(x: 20, y: buttonY, width:buttonWidth , height:buttonHeight)
            button.contentMode = UIViewContentMode.scaleToFill
            buttonY += buttonHeight + buttonGap
            button.tag = i
            button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
            view.addSubview(button)

            i+=1

        }
    }

    func buttonTapped( _ button : UIButton)
    {
        buttonArray.remove(at: button.tag)
        addButtonsLoop()
    }
</code>```

My question is that instead of above code, how to apply NSLayoutConstraints or LayoutAnchors to solve this?

答: Instead of stack view you can use a tableview with the tableview cell containing a button and the number of rows can be the buttonarray count. In cellForRowAtIndexPath delegate method set the button title from button array.

Title: Dynamically add buttons in swift

Body:
I am writing an iOS app. Server gives me buttons array to draw on view. So, the number of buttons can vary according to server response,
example:

let buttonArray=["Button 1","Button 2","Button 3"]
or
let buttonArray=["Button 1","Button 2","Button 3"," Button 4", "Button 5"]

I have to stack these buttons vertically.
I created a stackview, add constraints to it, and then add buttons to this stackview as arrangedsubviews.
Buttons should have gap of 5 points between them:

Using stackview:

func addButtonsUsingStackView()
    {
        //create stackview:
        let stackView=UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 5
        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)

        //stackview constraints:
        let viewsDictionary = ["stackView":stackView]
        let stackView_H = NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-20-[stackView]-20-|",
            options: NSLayoutFormatOptions(rawValue: 0),
            metrics: nil,
            views: viewsDictionary)
        let stackView_V = NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-30-[stackView]-30-|",
            options: NSLayoutFormatOptions(rawValue:0),
            metrics: nil,
            views: viewsDictionary)
        view.addConstraints(stackView_H)
        view.addConstraints(stackView_V)

        //adding buttons to stackview:

        //let buttonArray=["Button 1","Button 2","Button 3"]
        let buttonArray=["Button 1","Button 2","Button 3"," Button 4"]

        for buttonName in buttonArray{

            let button=UIButton()
            button.setTitle(buttonName, for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor=UIColor.blue
            button.translatesAutoresizingMaskIntoConstraints=false

            stackView.addArrangedSubview(button)

        }

    }

Without stackview:

var buttonArray=["Button 1","Button 2","Button 3"," Button 4"," Button 5"," Button 6"," Button 7"]

    func addButtonsLoop()
    {

        for _view in view.subviews{
            _view.removeFromSuperview()
        }

        var i=0
        var buttonY = 20
        let buttonGap=5

        for btn in buttonArray {

            let buttonHeight=Int(Int(view.frame.height) - 40 - (buttonArray.count * buttonGap))/buttonArray.count
            print(buttonHeight)
            let buttonWidth=Int(view.frame.width - 40)

            let button = UIButton()
            button.backgroundColor = UIColor.orange
            button.setTitle(btn, for: .normal)
            button.titleLabel?.textColor = UIColor.white
            button.frame = CGRect(x: 20, y: buttonY, width:buttonWidth , height:buttonHeight)
            button.contentMode = UIViewContentMode.scaleToFill
            buttonY += buttonHeight + buttonGap
            button.tag = i
            button.addTarget(self, action: #selector(self.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
            view.addSubview(button)

            i+=1

        }
    }

    func buttonTapped( _ button : UIButton)
    {
        buttonArray.remove(at: button.tag)
        addButtonsLoop()
    }

My question is that instead of above code, how to apply NSLayoutConstraints or LayoutAnchors to solve this?


来源: stackexchange

问:
How do I use Inheritence in Models in Angular2 using TypeScript?
Hi I have a Model Class Question and a ModelClass TrueFalseQuestion, The Field are as following

question.model.ts

```<code>export class Question {
    answerId: number;
    questionTitle: string;
    questionDescription: string;
</code>```

}

truefalsequestion.model.ts

```<code>export class TrueFalseQuestion {
    answer: boolean;
</code>```

}

I want to inherit members from Question model to TrueFalseQuestion model.
How do I achieve so?

答:
You should use the extends keyword. Also be sure to import Question from question.model.ts

```<code>export class TrueFalseQuestion extends Question {
    answer: boolean;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I have a Model Class Question and a ModelClass TrueFalseQuestion, The Field are as following

question.model.ts

export class Question {
    answerId: number;
    questionTitle: string;
    questionDescription: string;

}

truefalsequestion.model.ts

export class TrueFalseQuestion {
    answer: boolean;

}

I want to inherit members from Question model to TrueFalseQuestion model.
How do I achieve so?

Body:
You should use the extends keyword. Also be sure to import Question from question.model.ts

export class TrueFalseQuestion extends Question {
    answer: boolean;
}


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
Prerequisite

Your Mac Machine should have at least Mac OSX 10.12.4 or later

Your iOS device should have at least iOS 11.0 or later

Both devices should be on same network.

Steps to Activate

Plug your iOS device with Mac machine from cable.

Open Xcode then from top menu Window -> Devices and Simulators

Chose Devices segment and chose your desired Device from left device list.

On right side you can see open Connect via network, enable this option as shown in attached image.

After few seconds you can see network sign in front of you device.

Unplug your device and use debugging as you're using normally.

Thanks


问:
Webpack has been initialised using a configuration object that does not match the API schema whent running a React demo project
I am trying to run a react project using nodejs.

According to the tutorial it is using web pack server. But when I am starting the project it is giving the below error

```<code>Webpack has been initialised using a configuration object that does not match the API schema
</code>```

I have installed the web server package project inside the same directory where I have created the node project and inside package.json I have server configuration like this.

```<code>"scripts": {
    "start": "webpack-dev-server --hot"
  },
</code>```

答:
Try this if it helps</p>

```<code>npm uninstall webpack --save-dev
npm install webpack@2.1.0-beta.22 --save-dev
</code>```

Body:
I am trying to run a react project using nodejs.

According to the tutorial it is using web pack server. But when I am starting the project it is giving the below error

Webpack has been initialised using a configuration object that does not match the API schema

I have installed the web server package project inside the same directory where I have created the node project and inside package.json I have server configuration like this.

"scripts": {
    "start": "webpack-dev-server --hot"
  },

Body:
Try this if it helps

npm uninstall webpack --save-dev
npm install webpack@2.1.0-beta.22 --save-dev


问:
Open CSV in Excel over Interop only reads first line
I have a CSV file and I want open it in an Excel and save it as an xlsx again. The reason I wanna do it this way, rather than write the data to an Excel file directly is that I hope it's faster that way since writing the data is very slow.

My csv looks like this:

```<code>sep=,
header1, header2, header3
data1, data2, data3
</code>```

And here is my code to write the data to a CSV, open it in Excel and save it again:

```<code>var csvPath = [MyCSVPath];
File.WriteAllBytes(csvPath, WriteCsv(result));

excel.Workbooks.Open(csvPath, Delimiter: ",");

// Save the excel localy and load it's bytes again.
var path = [MyExcelPath]

workbook.SaveCopyAs(path);
excel.Workbooks.Close();
</code>```

When I open the csv in the excel manually it is opened correctly. But when I do it over the code above it contains only the first line. What am I doing wrong?

答:
Unfortunately, your code sample is not complete. But the following code works fine in Excel 2016 for your csv file example. By default SaveCopyAs doesn't change initial format, but SaveCopy allows to define format explicitly.

```<code>var excelApp = new Application();
excelApp.Workbooks.Open("d:\\1.csv", Delimiter: ",");

var workbook = excelApp.ActiveWorkbook;
// this saves in same CSV format
workbook.SaveCopyAs("d:\\2.xlsx");
// this saves to correct xlsx format
workbook.SaveAs("d:\\3.xlsx", XlFileFormat.xlOpenXMLWorkbook);

workbook.Close();
excelApp.Quit();
</code>```

Body:
I have a CSV file and I want open it in an Excel and save it as an xlsx again. The reason I wanna do it this way, rather than write the data to an Excel file directly is that I hope it's faster that way since writing the data is very slow.

My csv looks like this:

sep=,
header1, header2, header3
data1, data2, data3

And here is my code to write the data to a CSV, open it in Excel and save it again:

var csvPath = [MyCSVPath];
File.WriteAllBytes(csvPath, WriteCsv(result));

excel.Workbooks.Open(csvPath, Delimiter: ",");

// Save the excel localy and load it's bytes again.
var path = [MyExcelPath]

workbook.SaveCopyAs(path);
excel.Workbooks.Close();

When I open the csv in the excel manually it is opened correctly. But when I do it over the code above it contains only the first line. What am I doing wrong?

Body:
Unfortunately, your code sample is not complete. But the following code works fine in Excel 2016 for your csv file example. By default SaveCopyAs doesn't change initial format, but SaveCopy allows to define format explicitly.

var excelApp = new Application();
excelApp.Workbooks.Open("d:\\1.csv", Delimiter: ",");

var workbook = excelApp.ActiveWorkbook;
// this saves in same CSV format
workbook.SaveCopyAs("d:\\2.xlsx");
// this saves to correct xlsx format
workbook.SaveAs("d:\\3.xlsx", XlFileFormat.xlOpenXMLWorkbook);

workbook.Close();
excelApp.Quit();


问:
Temporary tables killing performance
I have written this query and because I used temporary tables (for the first time), it massively killed the performance of the query. </p>

<p>This is the query. Can you spot a massive mistake that I am making? </p>

```<code>SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

DECLARE @StartDate DATETIME
SET @StartDate = '20160720';
DECLARE @EndDate DATETIME
SET @EndDate = '20160729 23:59:59';

Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #1schargslack

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                       --INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'F'
                                                                                AND ts.SlackNoSlack = 'slack'
                                                                                or ts.slacknoslack like 'slack - tripped%'
                                                                                GROUP by mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweightns],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #1chargns

                                    FROM      dbo.whsConsignment wc                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                       --INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'F'
                                                                                and ts.SlackNoSlack like 'no slack%'
                                                                                GROUP BY mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2chargs

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                        inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                -- AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                AND ts.SlackNoSlack = 'slack'
                                                                                or ts.slacknoslack like 'slack - tripped%'
                                                                                GROUP BY mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweightns],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2chargns

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                        inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                -- AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                and ts.SlackNoSlack like 'no slack%'
                                                                                group by mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweightlate],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2charglate

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --  AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                and ts.SlackNoSlack like '%late%'
                                                                                group by mm.movementref
    SELECT --wh.WhsHeaderID,
              mu.Number AS Unit,
        m.MovementRef AS Reference,
        wh.ArrDepDate AS [Departure Date],
        wh.LastScannedTime AS [Last Scan],
        CONVERT(VARCHAR(5), wh.ArrDepDate, 108) AS [Scheduled Departure (h)],
        CONVERT(VARCHAR(5), wh.LastScannedTime, 108) AS [Last Scan (h)],
        CASE
            WHEN
            (
                m.DestinationPoint = 'SF'
                AND DATEDIFF(MINUTE, wh.ArrDepDate, wh.LastScannedTime) > 180
            )
            OR (m.DestinationPoint <> 'SF'  AND DATEDIFF(MINUTE, wh.ArrDepDate, wh.LastScannedTime) > 20) THEN
                'Late'
            ELSE
                'On Time'
        END AS Status,
        CAST(ch.ChargeableWt + ISNULL(LO.LeftOffWt, 0) AS DECIMAL(18, 2)) AS [Planned Chargeable Wt],
        Cast (isnull ([1stchargeableweights], 0) as decimal (18, 2)) as [1st Dep Left off Chargeable Wt With Slack],
        Cast (isnull ([1stchargeableweightns], 0) as decimal (18, 2)) as [1st Dep Left off Chargeable Wt No Slack],
        Cast (isnull ([2ndchargeableweights], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt With Slack],
        Cast (isnull ([2ndchargeableweightns], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt No Slack],
        Cast (isnull ([2ndchargeableweightlate], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt Late],
        CAST(ch.ChargeableWt AS DECIMAL(18, 2)) AS [Actual Chargeable Wt],

        CASE
            WHEN m.DestinationPoint IN ( 'AT', 'FR', 'PL', 'NL', 'BE', 'ES', 'IT', 'CH', 'CZ', 'TU', 'MT', 'DE' ) THEN
                22000
            ELSE
                20000
        END AS Target,
        CASE
            WHEN m.DestinationPoint IN ( 'AT', 'FR', 'PL', 'NL', 'BE', 'ES', 'IT', 'CH', 'CZ', 'TU', 'MT', 'DE' ) THEN
                CAST(ch.ChargeableWt - 22000 AS DECIMAL(18, 2))
            ELSE
                CAST(ch.ChargeableWt - 20000 AS DECIMAL(18, 2))
        END AS Variance
        --ISNULL(
        --          STUFF(
        --                                   (
        --                                          SELECT ', ' + COALESCE(R.Region, 'Region not found') + ': ' + SUBSTRING(cnor.PostCode,1,CHARINDEX(   ' ',cnor.PostCode + ' ') - 1) +
        --                                                                   ' (' + COALESCE(DC.Description, 'NA') + ')'
        --                                          FROM dbo.whsConsignment wc
        --                                                 INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference AND c.Cancelled = 0
        --                                                 INNER JOIN dbo.genAddress cnor ON cnor.AddressID = c.Consignor
        --                                                 LEFT OUTER JOIN dbo.disConsignment AS DC ON DC.ConsignmentRef = wc.ConsignmentReference AND DC.WhsHeaderID = wc.whsHeaderID
        --                                                 LEFT JOIN dbo.lstPostcode P ON P.Postcode = cnor.PostcodePrefix
        --                                                 LEFT JOIN dbo.lstPostcodeRegion R ON R.RegionID = P.RegionID
        --                                          WHERE wc.whsHeaderID = wh.WhsHeaderID AND wc.StatusCode = 'NL'
        --                                          FOR XML PATH('')
        --                                        ),
        --                   1,1,''
        --               )
        --     ,'') AS [Postcodes & Discrepancies]
    FROM dbo.movMovement m
    inner join #1schargslack on #1schargslack.movementref = m.MovementRef
    inner join #1chargns on #1chargns.movementref = m.MovementRef
    inner join #2chargs on #2chargs.movementref = m.MovementRef
    inner join #2chargns on #2chargns.MovementRef = m.MovementRef
    inner join #2charglate on #2charglate.movementref = m.MovementRef
        INNER JOIN dbo.movUnit mu ON mu.UnitID = m.TrailerID
        INNER JOIN dbo.whsHeader wh ON wh.RunMovID = m.MovementID AND wh.LocalDepotCode = 'NOT' AND wh.WhsJobType = 'CL' AND wh.WhsJobStatus = 'COMP'
        LEFT JOIN dbo.whsHeaderComments whc ON whc.ID = wh.WhsHeaderID
        INNER JOIN (
                                         SELECT MovementID,
                                                SUM(c.[Chargeable Weight]) AS ChargeableWt
                                         FROM dbo.movConLink mc
                                                 INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = mc.ConsignmentReference AND c.Cancelled = 0
                                         GROUP BY mc.MovementID
                                  ) ch ON ch.MovementID = m.MovementID
        LEFT JOIN (
                                  SELECT wc.whsHeaderID,
                                         SUM(c.[Chargeable Weight]) AS LeftOffWt
                                  FROM dbo.whsConsignment wc
                                         INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference AND c.Cancelled = 0
                                         INNER JOIN dbo.genAddress cnor ON cnor.AddressID = c.Consignor
                                  WHERE StatusCode IN ( 'NL' )
                                  GROUP BY wc.whsHeaderID
                              ) LO ON LO.whsHeaderID = wh.WhsHeaderID
    WHERE wh.ArrDepDate
    BETWEEN @StartDate AND @EndDate
    ORDER BY m.MovementRef;
</code>```

答: If you are populating a temp table and then only calling from it once, you can look at using CTE's. It will save a alot of time where SQL Server is populating the tables.</p>

Title: Temporary tables killing performance

Body:
I have written this query and because I used temporary tables (for the first time), it massively killed the performance of the query.

This is the query. Can you spot a massive mistake that I am making?

SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

DECLARE @StartDate DATETIME
SET @StartDate = '20160720';
DECLARE @EndDate DATETIME
SET @EndDate = '20160729 23:59:59';

Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #1schargslack

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                       --INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'F'
                                                                                AND ts.SlackNoSlack = 'slack'
                                                                                or ts.slacknoslack like 'slack - tripped%'
                                                                                GROUP by mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweightns],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #1chargns

                                    FROM      dbo.whsConsignment wc                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                       --INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'F'
                                                                                and ts.SlackNoSlack like 'no slack%'
                                                                                GROUP BY mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2chargs

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                        inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                -- AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                AND ts.SlackNoSlack = 'slack'
                                                                                or ts.slacknoslack like 'slack - tripped%'
                                                                                GROUP BY mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweightns],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2chargns

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                        inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                -- AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                and ts.SlackNoSlack like 'no slack%'
                                                                                group by mm.MovementRef
Select
SUM(c.[Chargeable Weight]) AS [2ndchargeableweightlate],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]
 Into #2charglate

                                    FROM      dbo.whsConsignment wc
                                                       INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                       INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                       inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                       inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                      -- INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
                                                                                --  AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                and ts.SlackNoSlack like '%late%'
                                                                                group by mm.movementref
    SELECT --wh.WhsHeaderID,
              mu.Number AS Unit,
        m.MovementRef AS Reference,
        wh.ArrDepDate AS [Departure Date],
        wh.LastScannedTime AS [Last Scan],
        CONVERT(VARCHAR(5), wh.ArrDepDate, 108) AS [Scheduled Departure (h)],
        CONVERT(VARCHAR(5), wh.LastScannedTime, 108) AS [Last Scan (h)],
        CASE
            WHEN
            (
                m.DestinationPoint = 'SF'
                AND DATEDIFF(MINUTE, wh.ArrDepDate, wh.LastScannedTime) > 180
            )
            OR (m.DestinationPoint <> 'SF'  AND DATEDIFF(MINUTE, wh.ArrDepDate, wh.LastScannedTime) > 20) THEN
                'Late'
            ELSE
                'On Time'
        END AS Status,
        CAST(ch.ChargeableWt + ISNULL(LO.LeftOffWt, 0) AS DECIMAL(18, 2)) AS [Planned Chargeable Wt],
        Cast (isnull ([1stchargeableweights], 0) as decimal (18, 2)) as [1st Dep Left off Chargeable Wt With Slack],
        Cast (isnull ([1stchargeableweightns], 0) as decimal (18, 2)) as [1st Dep Left off Chargeable Wt No Slack],
        Cast (isnull ([2ndchargeableweights], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt With Slack],
        Cast (isnull ([2ndchargeableweightns], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt No Slack],
        Cast (isnull ([2ndchargeableweightlate], 0) as decimal (18, 2)) as [2nd Dep Left off Chargeable Wt Late],
        CAST(ch.ChargeableWt AS DECIMAL(18, 2)) AS [Actual Chargeable Wt],

        CASE
            WHEN m.DestinationPoint IN ( 'AT', 'FR', 'PL', 'NL', 'BE', 'ES', 'IT', 'CH', 'CZ', 'TU', 'MT', 'DE' ) THEN
                22000
            ELSE
                20000
        END AS Target,
        CASE
            WHEN m.DestinationPoint IN ( 'AT', 'FR', 'PL', 'NL', 'BE', 'ES', 'IT', 'CH', 'CZ', 'TU', 'MT', 'DE' ) THEN
                CAST(ch.ChargeableWt - 22000 AS DECIMAL(18, 2))
            ELSE
                CAST(ch.ChargeableWt - 20000 AS DECIMAL(18, 2))
        END AS Variance
        --ISNULL(
        --          STUFF(
        --                                   (
        --                                          SELECT ', ' + COALESCE(R.Region, 'Region not found') + ': ' + SUBSTRING(cnor.PostCode,1,CHARINDEX(   ' ',cnor.PostCode + ' ') - 1) +
        --                                                                   ' (' + COALESCE(DC.Description, 'NA') + ')'
        --                                          FROM dbo.whsConsignment wc
        --                                                 INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference AND c.Cancelled = 0
        --                                                 INNER JOIN dbo.genAddress cnor ON cnor.AddressID = c.Consignor
        --                                                 LEFT OUTER JOIN dbo.disConsignment AS DC ON DC.ConsignmentRef = wc.ConsignmentReference AND DC.WhsHeaderID = wc.whsHeaderID
        --                                                 LEFT JOIN dbo.lstPostcode P ON P.Postcode = cnor.PostcodePrefix
        --                                                 LEFT JOIN dbo.lstPostcodeRegion R ON R.RegionID = P.RegionID
        --                                          WHERE wc.whsHeaderID = wh.WhsHeaderID AND wc.StatusCode = 'NL'
        --                                          FOR XML PATH('')
        --                                        ),
        --                   1,1,''
        --               )
        --     ,'') AS [Postcodes & Discrepancies]
    FROM dbo.movMovement m
    inner join #1schargslack on #1schargslack.movementref = m.MovementRef
    inner join #1chargns on #1chargns.movementref = m.MovementRef
    inner join #2chargs on #2chargs.movementref = m.MovementRef
    inner join #2chargns on #2chargns.MovementRef = m.MovementRef
    inner join #2charglate on #2charglate.movementref = m.MovementRef
        INNER JOIN dbo.movUnit mu ON mu.UnitID = m.TrailerID
        INNER JOIN dbo.whsHeader wh ON wh.RunMovID = m.MovementID AND wh.LocalDepotCode = 'NOT' AND wh.WhsJobType = 'CL' AND wh.WhsJobStatus = 'COMP'
        LEFT JOIN dbo.whsHeaderComments whc ON whc.ID = wh.WhsHeaderID
        INNER JOIN (
                                         SELECT MovementID,
                                                SUM(c.[Chargeable Weight]) AS ChargeableWt
                                         FROM dbo.movConLink mc
                                                 INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = mc.ConsignmentReference AND c.Cancelled = 0
                                         GROUP BY mc.MovementID
                                  ) ch ON ch.MovementID = m.MovementID
        LEFT JOIN (
                                  SELECT wc.whsHeaderID,
                                         SUM(c.[Chargeable Weight]) AS LeftOffWt
                                  FROM dbo.whsConsignment wc
                                         INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference AND c.Cancelled = 0
                                         INNER JOIN dbo.genAddress cnor ON cnor.AddressID = c.Consignor
                                  WHERE StatusCode IN ( 'NL' )
                                  GROUP BY wc.whsHeaderID
                              ) LO ON LO.whsHeaderID = wh.WhsHeaderID
    WHERE wh.ArrDepDate
    BETWEEN @StartDate AND @EndDate
    ORDER BY m.MovementRef;


问:
Unset Session for Particular Page not in whole Project?

Is it Possible to Unset $_SESSION['success'] for only one page?

not in whole website

答:
When comes to that page first save the session to cookie, something like this

```<code>setcookie('cookie_name', $_SESSION['session_value'],  time()+86400, "/",NULL,true);
unset($_SESSION['session_value']);
</code>```

when go to other page set session value using that cookie

Body:
When comes to that page first save the session to cookie, something like this

setcookie('cookie_name', $_SESSION['session_value'],  time()+86400, "/",NULL,true);
unset($_SESSION['session_value']);

when go to other page set session value using that cookie


问:
Check the answer and verify from database whether it is correct or not in PHP
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

Here is the code

```<code><?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>
</code>```

答: Make sure you have different names for each input field in the radio group so that it treats each question as a different record.</p>

Body:
Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.

Here is the code

<?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully

";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "
Question: " . $row["Question"] . "
";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '
';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '
';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '
';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '
';
$i++;
}
} else {
echo "0 results";
}
$conn->close();

?>


问:
How to change the scale of different plots in one go
I am new to python and matplotlib.
I have a code where I have multiple plots together in the same figure and want to change all of the axis scales to log scales. But when I write this code only the x and y axis of the last plot is changed. How should I make all the axis change their scale for all the plots together.

```<code>plt.plot(freq3, ps3 ,'y')

plt.plot(freq2, ps2 ,'r')

plt.plot(freq1, ps1 ,'b')

plt.plot(freq0, ps0,'g')

plt.yscale('log')

plt.xscale('log')
</code>```

I also need to add labels to each of the plots separately.

答:
This should solve your problem.</p>

```<code>freq = [freq3, freq2, freq1, freq0]
ps = [ps3, ps2, ps1, ps0]
labels = ['Label3', 'Label2', 'Label1', 'Label0']
colors = ['y', 'r', 'b', 'g']

for i in range(4):
    plt.plot(freq[i], ps[i], colors[i], label=labels[i])
    plt.yscale('log')
    plt.xscale('log')

# ...
plt.show()
</code>```

Body:
I am new to python and matplotlib.
I have a code where I have multiple plots together in the same figure and want to change all of the axis scales to log scales. But when I write this code only the x and y axis of the last plot is changed. How should I make all the axis change their scale for all the plots together.

plt.plot(freq3, ps3 ,'y')

plt.plot(freq2, ps2 ,'r')

plt.plot(freq1, ps1 ,'b')

plt.plot(freq0, ps0,'g')

plt.yscale('log')

plt.xscale('log')

I also need to add labels to each of the plots separately.

Body:
This should solve your problem.

freq = [freq3, freq2, freq1, freq0]
ps = [ps3, ps2, ps1, ps0]
labels = ['Label3', 'Label2', 'Label1', 'Label0']
colors = ['y', 'r', 'b', 'g']

for i in range(4):
    plt.plot(freq[i], ps[i], colors[i], label=labels[i])
    plt.yscale('log')
    plt.xscale('log')

# ...
plt.show()


问:
parsing Json data with jq
Need help in parsing Json data using jq , I used to parse the data using json path as [?(@.type=='router')].externalIP. I am not sure how to do the same using jq.

The result from the query should provide the .externalIp from the type=router.
198.22.66.99

Json data snippet as below

[
  {
    "externalHostName": "localhost",
    "externalIP": "198.22.66.99",
    "internalHostName": "localhost",
    "isUp": true,
    "pod": "gateway",
    "reachable": true,
    "region": "dc-1",
     "type": [
      "router"
    ],
    "uUID": "b5f986fe-982e-47ae-8260-8a3662f25fc2"
  },
  ]```

##

答:
```<code>cat your-data.json | jq '.[]|.externalIP|select(type=="string")'
"198.22.66.99"
"192.22.66.29"
"192.22.66.89"
"192.66.22.79"
</code>```

explanation:

```<code>.[]                   | .externalIP            | select(type=="string")
for every array entry | get field 'externalIP' | drop nulls
</code>```

EDIT/ADDENDUM: filter on type (expects router to be on index 0 of type array)

```<code>cat x | jq '.[]|select(.type[0] == "router")|.externalIP'
"198.22.66.99"
"192.22.66.89"
</code>```

Title: parsing Json data with jq

Body:
Need help in parsing Json data using jq , I used to parse the data using json path as [?(@.type=='router')].externalIP. I am not sure how to do the same using jq.

The result from the query should provide the .externalIp from the type=router.
198.22.66.99

Json data snippet as below

[
  {
    "externalHostName": "localhost",
    "externalIP": "198.22.66.99",
    "internalHostName": "localhost",
    "isUp": true,
    "pod": "gateway",
    "reachable": true,
    "region": "dc-1",
     "type": [
      "router"
    ],
    "uUID": "b5f986fe-982e-47ae-8260-8a3662f25fc2"
  },
  ]

##

Body:
cat your-data.json | jq '.[]|.externalIP|select(type=="string")'
"198.22.66.99"
"192.22.66.29"
"192.22.66.89"
"192.66.22.79"

explanation:

.[]                   | .externalIP            | select(type=="string")
for every array entry | get field 'externalIP' | drop nulls

EDIT/ADDENDUM: filter on type (expects router to be on index 0 of type array)

cat x | jq '.[]|select(.type[0] == "router")|.externalIP'
"198.22.66.99"
"192.22.66.89"


问:
Why after using strcat function original string changed?
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

```<code>#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}
</code>```

output:-

```<code>before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!
</code>```

答:
Function strcat has the signature char *strcat( char *dest, const char *src ) and appends the content of string src at the end of the string where dest points to, i.e. it alters the content of the memory to which dest points. This requires that the memory to which dest points is large enough to hold both strings src and dest.

Hence, your call strcat(b,a) actually yields undefined behaviour, as the memory block represented by b is capable of holding 14 bytes (i.e. the length of "hey kammo DJ "+ 1), but not for any additional string.

So you'd rather write something like:

```<code>strcpy (c,b);
strcat (c,a);
</code>```

or:

```<code>snprintf(c, 50, "%s%s", b, a);
</code>```

Body:
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}

output:-

before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!

Body:
Function strcat has the signature char *strcat( char *dest, const char *src ) and appends the content of string src at the end of the string where dest points to, i.e. it alters the content of the memory to which dest points. This requires that the memory to which dest points is large enough to hold both strings src and dest.

Hence, your call strcat(b,a) actually yields undefined behaviour, as the memory block represented by b is capable of holding 14 bytes (i.e. the length of "hey kammo DJ "+ 1), but not for any additional string.

So you'd rather write something like:

strcpy (c,b);
strcat (c,a);

or:

snprintf(c, 50, "%s%s", b, a);


问:
Which table store address of thumbnails of wordpress post?
which table store address of  thumbnails of word press post?
I want to know how can  access to  these addresses with mysql?</p>

答:
Any images added in wordpress post gets stored in wp_posts table. All the metadata related to post gets stored in wp_postmeta table.

For image it generally stores two meta_keys

_wp_attached_file : Path to the image

_wp_attachment_metadata : Serialize array having details about image like width, height, path, caption etc.

Note: Assuming wp_ is the table prefix you are using.


问:
Getting error while calling one sendOTP API using PHP
I am getting  error while calling one API using PHP.

Error:

```<code>Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"): failed to open stream: no suitable wrapper could be found in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(): Failed opening 'http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"' for inclusion (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/test/otp.php on line 8
</code>```

Here is my code:

```<code>$authkey="15529*************";
$mobile=9937229853;
$code=1111;
$message="Your verification code is:".$code;
$sender="Subhrajyoti";
$otp=1111;
include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');
</code>```

Here I am trying to send OTP but getting those message. Here I need to send OTP and get the response.

答:
Instead of this line:

```<code>include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');
</code>```

use cURL to hit the url appended with the message and mobile number and get the response from it. And don't forget to encode the entire url by using urlencode() function.

Ex:

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$APIresponse = curl_exec($ch);
curl_close($ch);
$res = json_decode($APIresponse, true);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting  error while calling one API using PHP.

Error:

Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"): failed to open stream: no suitable wrapper could be found in /opt/lampp/htdocs/test/otp.php on line 8

Warning: include(): Failed opening 'http://api.msg91.com/api/sendotp.php?authkey="15529*************"&mobile="9937229853"&message="Your verification code is:1111"&sender="Subhrajyoti"&otp="1111"' for inclusion (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/test/otp.php on line 8

Here is my code:

$authkey="15529*************";
$mobile=9937229853;
$code=1111;
$message="Your verification code is:".$code;
$sender="Subhrajyoti";
$otp=1111;
include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');

Here I am trying to send OTP but getting those message. Here I need to send OTP and get the response.

Body:
Instead of this line:

include ('http://api.msg91.com/api/sendotp.php?authkey="'.$authkey.'"&mobile="'.$mobile.'"&message="'.$message.'"&sender="'.$sender.'"&otp="'.$otp.'"');

use cURL to hit the url appended with the message and mobile number and get the response from it. And don't forget to encode the entire url by using urlencode() function.

Ex:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$APIresponse = curl_exec($ch);
curl_close($ch);
$res = json_decode($APIresponse, true);


问:
Insert custom post type with Custom field by using wp rest api
Hello i am unable to store the value of author field by using wp rest api. author is a custom field in custom  post type book.all other fields are stored correctly. it ignores all the custom field of custom post type book.</p>

```<code><?php

$curl = curl_init();
$data = array(
'title' => "book 1",
'status' => "publish",
'content' => "Inserting data through rest api ",
'format' => 'standard',
'author' => 'Jaipur',
);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost/wp-json/wp/v2/book/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_USERPWD => "admin" . ":" . "admin",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Type: application/x-www-form-urlencoded"
),

CURLOPT_POSTFIELDS => http_build_query($data),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
</code>```

答:
You need to mention The ID for the author of the object. Not the name or something.
https://developer.wordpress.org/rest-api/reference/posts/#create-a-post</p>

Body:
Hello i am unable to store the value of author field by using wp rest api. author is a custom field in custom  post type book.all other fields are stored correctly. it ignores all the custom field of custom post type book.

<?php

$curl = curl_init();
$data = array(
'title' => "book 1",
'status' => "publish",
'content' => "Inserting data through rest api ",
'format' => 'standard',
'author' => 'Jaipur',
);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost/wp-json/wp/v2/book/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_USERPWD => "admin" . ":" . "admin",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Type: application/x-www-form-urlencoded"
),

CURLOPT_POSTFIELDS => http_build_query($data),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}


问:
How to get an access to sprite in 2d array?
I want to replace array string 'a' with sprite, thus I display images :

```<code>arr = ['a','a','a','a']
for i in arr:
    if i == 'p':
        arr[i] = Alien("Alien.png", (20,40))
print(arr[1])
# give  <Alien sprite(in 0 groups)>
</code>```

Next I tried to figure out how to get access to each image to give a motion for every image after replace in array, but code doesn't work as I expected. I don't know how to operate each image apart?

```<code>for j in arr:
    if j == '<Alien sprite(in 0 groups)>':
        j.move(9,11)
</code>```

答:
In the second loop, I don't think j == .. would work in you favour. When you print the object in the python prompt it would print <PawnBlue sprite(in 0 groups)>, however checking the string equality as you have wouldn't be right way to check if that particular array index contains an image or not.

I see in your previous loop you are inserting instances of the Alien class into the array. Assuming those are the images that you are talking about, in the second loop change the if statement to if type(j) == Alien :  This should work.

Body:
I want to replace array string 'a' with sprite, thus I display images :

arr = ['a','a','a','a']
for i in arr:
    if i == 'p':
        arr[i] = Alien("Alien.png", (20,40))
print(arr[1])
# give  <Alien sprite(in 0 groups)>

Next I tried to figure out how to get access to each image to give a motion for every image after replace in array, but code doesn't work as I expected. I don't know how to operate each image apart?

for j in arr:
    if j == '<Alien sprite(in 0 groups)>':
        j.move(9,11)


问:
Convert KeyDerivation.Pbkdf2 in .Net 4.5.1 to .Net 4.0
I have two project which using .net 4.0 and .net 4.6.1, the KeyDerivation only available after .net 4.5.1. How can I get the same hash result in .Net 4.0 using other hash library such as Rfc2898DeriveBytes/ Crypto</p>

```<code>byte[] salt = new byte[128 / 8];
var hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
    password: "GN(o@D30",
    salt: salt,
    prf: KeyDerivationPrf.HMACSHA512,
    iterationCount: 100000,
    numBytesRequested: 256 / 8)
);
</code>```

答:
Problem with Rfc2898DeriveBytes is that it only supports HMACSHA1 (for unknown reasons). In your case you want to use HMACSHA512. You can use implementation described here, note that it's not some custom implementation - author just took source code of Rfc2898DeriveBytes standard built-in class and adjusted it to use hmac implementation you provide via constructor argument (and thrown away irrelevant parts). I'll provide full source code here for clarity:

```<code>[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pbkdf", Justification = "Spelling is correct.")]
public class Pbkdf2
{

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <param name="iterations">The number of iterations for the operation.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, Byte[] password, Byte[] salt, Int32 iterations)
    {
        if (algorithm == null) { throw new ArgumentNullException("algorithm", "Algorithm cannot be null."); }
        if (salt == null) { throw new ArgumentNullException("salt", "Salt cannot be null."); }
        if (password == null) { throw new ArgumentNullException("password", "Password cannot be null."); }
        this.Algorithm = algorithm;
        this.Algorithm.Key = password;
        this.Salt = salt;
        this.IterationCount = iterations;
        this.BlockSize = this.Algorithm.HashSize / 8;
        this.BufferBytes = new byte[this.BlockSize];
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, Byte[] password, Byte[] salt)
        : this(algorithm, password, salt, 1000)
    {
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <param name="iterations">The number of iterations for the operation.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, String password, String salt, Int32 iterations) :
        this(algorithm, UTF8Encoding.UTF8.GetBytes(password), UTF8Encoding.UTF8.GetBytes(salt), iterations)
    {
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, String password, String salt) :
        this(algorithm, password, salt, 1000)
    {
    }

    private readonly int BlockSize;
    private uint BlockIndex = 1;

    private byte[] BufferBytes;
    private int BufferStartIndex = 0;
    private int BufferEndIndex = 0;

    /// <summary>
    /// Gets algorithm used for generating key.
    /// </summary>
    public HMAC Algorithm { get; private set; }

    /// <summary>
    /// Gets salt bytes.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Byte array is proper return value in this case.")]
    public Byte[] Salt { get; private set; }

    /// <summary>
    /// Gets iteration count.
    /// </summary>
    public Int32 IterationCount { get; private set; }

    /// <summary>
    /// Returns a pseudo-random key from a password, salt and iteration count.
    /// </summary>
    /// <param name="count">Number of bytes to return.</param>
    /// <returns>Byte array.</returns>
    public Byte[] GetBytes(int count)
    {
        byte[] result = new byte[count];
        int resultOffset = 0;
        int bufferCount = this.BufferEndIndex - this.BufferStartIndex;

        if (bufferCount > 0)
        { //if there is some data in buffer
            if (count < bufferCount)
            { //if there is enough data in buffer
                Buffer.BlockCopy(this.BufferBytes, this.BufferStartIndex, result, 0, count);
                this.BufferStartIndex += count;
                return result;
            }
            Buffer.BlockCopy(this.BufferBytes, this.BufferStartIndex, result, 0, bufferCount);
            this.BufferStartIndex = this.BufferEndIndex = 0;
            resultOffset += bufferCount;
        }

        while (resultOffset < count)
        {
            int needCount = count - resultOffset;
            this.BufferBytes = this.Func();
            if (needCount > this.BlockSize)
            { //we one (or more) additional passes
                Buffer.BlockCopy(this.BufferBytes, 0, result, resultOffset, this.BlockSize);
                resultOffset += this.BlockSize;
            }
            else
            {
                Buffer.BlockCopy(this.BufferBytes, 0, result, resultOffset, needCount);
                this.BufferStartIndex = needCount;
                this.BufferEndIndex = this.BlockSize;
                return result;
            }
        }
        return result;
    }

    private byte[] Func()
    {
        var hash1Input = new byte[this.Salt.Length + 4];
        Buffer.BlockCopy(this.Salt, 0, hash1Input, 0, this.Salt.Length);
        Buffer.BlockCopy(GetBytesFromInt(this.BlockIndex), 0, hash1Input, this.Salt.Length, 4);
        var hash1 = this.Algorithm.ComputeHash(hash1Input);

        byte[] finalHash = hash1;
        for (int i = 2; i <= this.IterationCount; i++)
        {
            hash1 = this.Algorithm.ComputeHash(hash1, 0, hash1.Length);
            for (int j = 0; j < this.BlockSize; j++)
            {
                finalHash[j] = (byte)(finalHash[j] ^ hash1[j]);
            }
        }
        if (this.BlockIndex == uint.MaxValue) { throw new InvalidOperationException("Derived key too long."); }
        this.BlockIndex += 1;

        return finalHash;
    }

    private static byte[] GetBytesFromInt(uint i)
    {
        var bytes = BitConverter.GetBytes(i);
        if (BitConverter.IsLittleEndian)
        {
            return new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] };
        }
        else
        {
            return bytes;
        }
    }

}
</code>```

Now with that class complete analog of code in your question would be:

```<code>byte[] salt = new byte[128 / 8];
string hashedPassword;
using (var hmac = new HMACSHA512()) {
     hashedPassword = Convert.ToBase64String(new Pbkdf2(
         hmac, "GN(o@D30", Encoding.UTF8.GetString(salt), 100000).GetBytes(256 / 8));
}
</code>```

Body:
I have two project which using .net 4.0 and .net 4.6.1, the KeyDerivation only available after .net 4.5.1. How can I get the same hash result in .Net 4.0 using other hash library such as Rfc2898DeriveBytes/ Crypto

byte[] salt = new byte[128 / 8];
var hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
    password: "GN(o@D30",
    salt: salt,
    prf: KeyDerivationPrf.HMACSHA512,
    iterationCount: 100000,
    numBytesRequested: 256 / 8)
);

Body:
Problem with Rfc2898DeriveBytes is that it only supports HMACSHA1 (for unknown reasons). In your case you want to use HMACSHA512. You can use implementation described here, note that it's not some custom implementation - author just took source code of Rfc2898DeriveBytes standard built-in class and adjusted it to use hmac implementation you provide via constructor argument (and thrown away irrelevant parts). I'll provide full source code here for clarity:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pbkdf", Justification = "Spelling is correct.")]
public class Pbkdf2
{

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <param name="iterations">The number of iterations for the operation.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, Byte[] password, Byte[] salt, Int32 iterations)
    {
        if (algorithm == null) { throw new ArgumentNullException("algorithm", "Algorithm cannot be null."); }
        if (salt == null) { throw new ArgumentNullException("salt", "Salt cannot be null."); }
        if (password == null) { throw new ArgumentNullException("password", "Password cannot be null."); }
        this.Algorithm = algorithm;
        this.Algorithm.Key = password;
        this.Salt = salt;
        this.IterationCount = iterations;
        this.BlockSize = this.Algorithm.HashSize / 8;
        this.BufferBytes = new byte[this.BlockSize];
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, Byte[] password, Byte[] salt)
        : this(algorithm, password, salt, 1000)
    {
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <param name="iterations">The number of iterations for the operation.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, String password, String salt, Int32 iterations) :
        this(algorithm, UTF8Encoding.UTF8.GetBytes(password), UTF8Encoding.UTF8.GetBytes(salt), iterations)
    {
    }

    /// <summary>
    /// Creates new instance.
    /// </summary>
    /// <param name="algorithm">HMAC algorithm to use.</param>
    /// <param name="password">The password used to derive the key.</param>
    /// <param name="salt">The key salt used to derive the key.</param>
    /// <exception cref="System.ArgumentNullException">Algorithm cannot be null - Password cannot be null. -or- Salt cannot be null.</exception>
    public Pbkdf2(HMAC algorithm, String password, String salt) :
        this(algorithm, password, salt, 1000)
    {
    }

    private readonly int BlockSize;
    private uint BlockIndex = 1;

    private byte[] BufferBytes;
    private int BufferStartIndex = 0;
    private int BufferEndIndex = 0;

    /// <summary>
    /// Gets algorithm used for generating key.
    /// </summary>
    public HMAC Algorithm { get; private set; }

    /// <summary>
    /// Gets salt bytes.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Byte array is proper return value in this case.")]
    public Byte[] Salt { get; private set; }

    /// <summary>
    /// Gets iteration count.
    /// </summary>
    public Int32 IterationCount { get; private set; }

    /// <summary>
    /// Returns a pseudo-random key from a password, salt and iteration count.
    /// </summary>
    /// <param name="count">Number of bytes to return.</param>
    /// <returns>Byte array.</returns>
    public Byte[] GetBytes(int count)
    {
        byte[] result = new byte[count];
        int resultOffset = 0;
        int bufferCount = this.BufferEndIndex - this.BufferStartIndex;

        if (bufferCount > 0)
        { //if there is some data in buffer
            if (count < bufferCount)
            { //if there is enough data in buffer
                Buffer.BlockCopy(this.BufferBytes, this.BufferStartIndex, result, 0, count);
                this.BufferStartIndex += count;
                return result;
            }
            Buffer.BlockCopy(this.BufferBytes, this.BufferStartIndex, result, 0, bufferCount);
            this.BufferStartIndex = this.BufferEndIndex = 0;
            resultOffset += bufferCount;
        }

        while (resultOffset < count)
        {
            int needCount = count - resultOffset;
            this.BufferBytes = this.Func();
            if (needCount > this.BlockSize)
            { //we one (or more) additional passes
                Buffer.BlockCopy(this.BufferBytes, 0, result, resultOffset, this.BlockSize);
                resultOffset += this.BlockSize;
            }
            else
            {
                Buffer.BlockCopy(this.BufferBytes, 0, result, resultOffset, needCount);
                this.BufferStartIndex = needCount;
                this.BufferEndIndex = this.BlockSize;
                return result;
            }
        }
        return result;
    }

    private byte[] Func()
    {
        var hash1Input = new byte[this.Salt.Length + 4];
        Buffer.BlockCopy(this.Salt, 0, hash1Input, 0, this.Salt.Length);
        Buffer.BlockCopy(GetBytesFromInt(this.BlockIndex), 0, hash1Input, this.Salt.Length, 4);
        var hash1 = this.Algorithm.ComputeHash(hash1Input);

        byte[] finalHash = hash1;
        for (int i = 2; i <= this.IterationCount; i++)
        {
            hash1 = this.Algorithm.ComputeHash(hash1, 0, hash1.Length);
            for (int j = 0; j < this.BlockSize; j++)
            {
                finalHash[j] = (byte)(finalHash[j] ^ hash1[j]);
            }
        }
        if (this.BlockIndex == uint.MaxValue) { throw new InvalidOperationException("Derived key too long."); }
        this.BlockIndex += 1;

        return finalHash;
    }

    private static byte[] GetBytesFromInt(uint i)
    {
        var bytes = BitConverter.GetBytes(i);
        if (BitConverter.IsLittleEndian)
        {
            return new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] };
        }
        else
        {
            return bytes;
        }
    }

}

Now with that class complete analog of code in your question would be:

byte[] salt = new byte[128 / 8];
string hashedPassword;
using (var hmac = new HMACSHA512()) {
     hashedPassword = Convert.ToBase64String(new Pbkdf2(
         hmac, "GN(o@D30", Encoding.UTF8.GetString(salt), 100000).GetBytes(256 / 8));
}


问:
Why can't Codan find size_t
I've just started using Eclipse Indigo (coming from Galileo) and I'm getting little red bugs in the gutter for every use of size_t.

The code compiles without issue but I suspect I have to explicitly add a path to the include directories. I already have the usual suspects in there. I am cross compiling for a ColdFire processor using the Gnu tool chain so in addition to the standard include from mfg of the chip I have the includes under m68k-elf

```<code>\include
\include\c++\4.2.1
\include\c++\4.2.1\include
\include\c++\4.2.1\m68k-elf
</code>```

Update

I noticed that the only place stddef.h exists for this toolchain is in a lib directory

```<code>gcc-m68k\lib\gcc\m68k-elf\4.2.1\include
</code>```

I added that path, the parent path and \include-fixed from the parent but the problem still exists.

Note on testing

When testing what works and what doesn't I noticed a couple of things

Code analysis does not get re-triggered when modifying Code Analysis preference settings, I still need to make an editor change (simply adding a space works)

Turning off the Code analysis setting for Symbol is not resolved will not make the error go away.

Turning off all Syntax and Semantic Errors, triggering the analysis, going back in and turning them all back on and then turning off Symbol is not resolved keeps the error from reappearing.

答:
I actually had the same problem. The issue seemed to be the same like the one described in the post of fquinner, the stddef.h located in /usr/include/linux/stddef.h was empty as well. Strangely enough, the correct stddef.h was found by eclipse and even could be openened without any issues.

If you just need to fix the indexing by eclipse like me (for example when building with another build tool anyway), this indexing issue can be worked around by defining __SIZE_TYPE__ to the expected type, e.g. long unsigned int under C/C++ General -> Paths and Symbols.

Title: Why can't Codan find size_t

Body:
I've just started using Eclipse Indigo (coming from Galileo) and I'm getting little red bugs in the gutter for every use of size_t.

The code compiles without issue but I suspect I have to explicitly add a path to the include directories. I already have the usual suspects in there. I am cross compiling for a ColdFire processor using the Gnu tool chain so in addition to the standard include from mfg of the chip I have the includes under m68k-elf

\include
\include\c++\4.2.1
\include\c++\4.2.1\include
\include\c++\4.2.1\m68k-elf

Update

I noticed that the only place stddef.h exists for this toolchain is in a lib directory

gcc-m68k\lib\gcc\m68k-elf\4.2.1\include

I added that path, the parent path and \include-fixed from the parent but the problem still exists.

Note on testing

When testing what works and what doesn't I noticed a couple of things

Code analysis does not get re-triggered when modifying Code Analysis preference settings, I still need to make an editor change (simply adding a space works)

Turning off the Code analysis setting for Symbol is not resolved will not make the error go away.

Turning off all Syntax and Semantic Errors, triggering the analysis, going back in and turning them all back on and then turning off Symbol is not resolved keeps the error from reappearing.


问:
Non-linear classification with tensorflow
I am new to machine learning and Tensorflow and want to do a simple 2-dimensional classification with data, that cannot be linear separated.

On the left side, you can see the training data for the model.
The right side shows, what the trained model predicts.

As of now I am overfitting my model, so every possible input is fed to the model.
My expected result would be a very high accurancy as the model already 'knows' each answer.
Unfortunately the Deep Neural Network I am using is only able to separate by a linear divider, which doesn't fit my data.

This is how I train my Model:

```<code>def testDNN(data):
  """
  * data is a list of tuples (x, y, b),
  * where (x, y) is the input vector and b is the expected output
  """
  # Build neural network
  net = tflearn.input_data(shape=[None, 2])

  net = tflearn.fully_connected(net, 100)
  net = tflearn.fully_connected(net, 100)
  net = tflearn.fully_connected(net, 100)

  net = tflearn.fully_connected(net, 2, activation='softmax')
  net = tflearn.regression(net)

  # Define model
  model = tflearn.DNN(net)

  # check if we already have a trained model
  # Start training (apply gradient descent algorithm)
  model.fit(
    [(x,y) for (x,y,b) in data],
    [([1, 0] if b else [0, 1]) for (x,y,b) in data],
    n_epoch=2, show_metric=True)

  return lambda x,y: model.predict([[x, y]])[0][0]
</code>```

Most of it is taken from the examples of tflearn, so I do not exactly understand, what every line does.

答: You need an activation function in your network for non-linearity. An activation function is the way for a neural network to fit non-linear function. Tflearn by default uses a linear activation, you could change this to 'sigmoid' and see if the results improve.</p>

Body:
I am new to machine learning and Tensorflow and want to do a simple 2-dimensional classification with data, that cannot be linear separated.

On the left side, you can see the training data for the model.
The right side shows, what the trained model predicts.

As of now I am overfitting my model, so every possible input is fed to the model.
My expected result would be a very high accurancy as the model already 'knows' each answer.
Unfortunately the Deep Neural Network I am using is only able to separate by a linear divider, which doesn't fit my data.

This is how I train my Model:

def testDNN(data):
  """
  * data is a list of tuples (x, y, b),
  * where (x, y) is the input vector and b is the expected output
  """
  # Build neural network
  net = tflearn.input_data(shape=[None, 2])

  net = tflearn.fully_connected(net, 100)
  net = tflearn.fully_connected(net, 100)
  net = tflearn.fully_connected(net, 100)

  net = tflearn.fully_connected(net, 2, activation='softmax')
  net = tflearn.regression(net)

  # Define model
  model = tflearn.DNN(net)

  # check if we already have a trained model
  # Start training (apply gradient descent algorithm)
  model.fit(
    [(x,y) for (x,y,b) in data],
    [([1, 0] if b else [0, 1]) for (x,y,b) in data],
    n_epoch=2, show_metric=True)

  return lambda x,y: model.predict([[x, y]])[0][0]

Most of it is taken from the examples of tflearn, so I do not exactly understand, what every line does.


问:
JQuery modal dialog form that send data over https
I have already working modal login dialog. The problem is that if the origin page is loaded via http I still want to pass credentials to server via https. And of course I want to do with as little rewriting of working code as it can be.

I cannot use JSONP for my case because login data is passed to server via POST AJAX request.

Any ideas?

答: Just out of curiosity, why don't you force the user to a secure page to begin with? Why had a similar issue a while back, so now, we force the user to https (via redirect) as soon as they hit our page.</p>

ContentLicense: CC BY-SA 2.5


问:
Vectorizing multi categorical data with pandas
Hej, I'm trying to vectorize items that can belong to multiple categories and put them into a pandas dataframe. I already came up with a solution but it's very slow. So here's what I'm doing:

That's how my data looks like:

```<code>data = {
    'A':['c1','c2','c3'],
    'B':['c4','c5','c2'],
    'C':['c2','c1','c4']
}
</code>```

I have three items (A-C) that belong to five different categories (c1-c5).

So I create a an empty dataframe, iterate over the items turn them into boolean Series objects with the right index and append them:

```<code>df = pd.SparseDataFrame()
for k, v in data.items():
    s = pd.Series(np.ones_like(v, dtype=bool), index=v, name=k)
    df = df.append(s)
</code>```

My result looks like this:

Resulting Dataframe

I'm happy with this result but my real data has ~200k categories which makes this approach horribly slow. Do you have any suggestions how to speed up?

Remark: Extracting all categories and passing them as columns into the empty Dataframe doesn't help:

```<code>df = pd.SparseDataFrame(columns=all_categories)
</code>```

答:
Consider the following memory saving approach:</p>

```<code>In [143]: df = pd.DataFrame([' '.join(data[k]) for k in data.keys()],
                            index=data.keys(),
                            columns=['text'])

In [144]: df
Out[144]:
       text
C  c2 c1 c4
A  c1 c2 c3
B  c4 c5 c2

In [145]: from sklearn.feature_extraction.text import CountVectorizer

In [146]: cv = CountVectorizer()

In [147]: df = pd.SparseDataFrame(cv.fit_transform(df['text']),
                                  columns=cv.get_feature_names(),
                                  index=df.index)

In [148]: df
Out[148]:
    c1  c2   c3   c4   c5
C  1.0   1  NaN  1.0  NaN
A  1.0   1  1.0  NaN  NaN
B  NaN   1  NaN  1.0  1.0

In [149]: df.memory_usage()
Out[149]:
Index    80
c1       16
c2       24
c3        8
c4       16
c5        8
dtype: int64
</code>```

Body:
Hej, I'm trying to vectorize items that can belong to multiple categories and put them into a pandas dataframe. I already came up with a solution but it's very slow. So here's what I'm doing:

That's how my data looks like:

data = {
    'A':['c1','c2','c3'],
    'B':['c4','c5','c2'],
    'C':['c2','c1','c4']
}

I have three items (A-C) that belong to five different categories (c1-c5).

So I create a an empty dataframe, iterate over the items turn them into boolean Series objects with the right index and append them:

df = pd.SparseDataFrame()
for k, v in data.items():
    s = pd.Series(np.ones_like(v, dtype=bool), index=v, name=k)
    df = df.append(s)

My result looks like this:

Resulting Dataframe

I'm happy with this result but my real data has ~200k categories which makes this approach horribly slow. Do you have any suggestions how to speed up?

Remark: Extracting all categories and passing them as columns into the empty Dataframe doesn't help:

df = pd.SparseDataFrame(columns=all_categories)

Body:
Consider the following memory saving approach:

In [143]: df = pd.DataFrame([' '.join(data[k]) for k in data.keys()],
                            index=data.keys(),
                            columns=['text'])

In [144]: df
Out[144]:
       text
C  c2 c1 c4
A  c1 c2 c3
B  c4 c5 c2

In [145]: from sklearn.feature_extraction.text import CountVectorizer

In [146]: cv = CountVectorizer()

In [147]: df = pd.SparseDataFrame(cv.fit_transform(df['text']),
                                  columns=cv.get_feature_names(),
                                  index=df.index)

In [148]: df
Out[148]:
    c1  c2   c3   c4   c5
C  1.0   1  NaN  1.0  NaN
A  1.0   1  1.0  NaN  NaN
B  NaN   1  NaN  1.0  1.0

In [149]: df.memory_usage()
Out[149]:
Index    80
c1       16
c2       24
c3        8
c4       16
c5        8
dtype: int64


问:
BackgroundWorker to read database and update GUI
I am trying to keep my indeterminate ProgressBar animation running smoothly as I query database and updating DataGrid in DoWork in BackgroundWorker. I understand that I cannot update UIThread in DoWork, so I use Dispatcher.BeginInvoke to access DataGrid, yet I still receive the owned-by-another-thread exception.

Question 1

Why is this happening? DoWork should be on
  BackgroundWorker's thread owned by UIThread, and Dispatcher should
  allow my DoWork to access my GUI.

Looking further into BackgroundWorker suggest UI operation should be handled in ProgressChanged(). But if I move all database/GUI operation to ProgressChanged() and put a Thread.Sleep(5000) on DoWork() to emulate something to work on to lend enough time for ProgressChanged() to run, the GUI is not being updated, although the ProgressBar continue its indeterminate smooth animation.

Question 2

I called a Thread.Sleep(5000) on BackgroundWorker thread.
  ProgressChanged() should spend 5 seconds querying database and
  updating GUI. Why not?

XAML:

```<code><DataGrid x:Name="myDataGrid" ScrollViewer.CanContentScroll="True"
          EnableRowVirtualization="True" EnableColumnVirtualization="True"
          VirtualizingPanel.IsContainerVirtualizable="True"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.IsVirtualizingWhenGrouping="True"
          Height="500" MaxHeight="500" />

<ProgressBar x:Name="myProgressBar" Height="20" Width="400"
             IsIndeterminate="True" Visibility="Visible" />

<Button x:Name="mySearch" Click="btnSearch_Click">Search</Button>
</code>```

C#

```<code>private BackgroundWorker bgw = new BackgroundWorker();

private void btnSearch_Click(object sendoer, RoutedEventArgs e)
{
    bgw.WorkerReportsProgress = true;
    bgw.ProgressChanged += ProgressChanged;
    bgw.DoWork += DoWork;
    bgw.RunWorkerCompleted += BGW_RunWorkerCompleted;

    bgw.RunWorkerAsync();
}

private void DoWork(object sender, DoWorkEventArgs e)
{
    // Thread.Sleep(5000);
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + MyTableName, conn))
        {
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        myDataGrid.Items.Add(new
                        {
                            Id = rdr.GetInt32(0),
                            Name = rdr.GetString(1).ToString(),
                        });
                    }));
                }
            }
        }
    }
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   // Paste code from DoWork and uncomment Thread.Sleep(5000)
}

private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
</code>```

答:
Create a collection of items in your DoWork event handler and then set the ItemsSource property of the DataGrid to this one in the RunWorkerCompleted event handler once you are done fetching the data on a background thread:

```<code>private void btnSearch_Click(object sendoer, RoutedEventArgs e)
{
    bgw.WorkerReportsProgress = true;
    bgw.ProgressChanged += ProgressChanged;
    bgw.DoWork += DoWork;
    bgw.RunWorkerCompleted += BGW_RunWorkerCompleted;

    myProgressBar.Visibility = Visibility.Visible;
    bgw.RunWorkerAsync();
}

private void DoWork(object sender, DoWorkEventArgs e)
{
    List<object> results = new List<object>();
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + MyTableName, conn))
        {
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    results.Add(new
                    {
                        Id = rdr.GetInt32(0),
                        Name = rdr.GetString(1).ToString(),
                    });
                }
            }
        }
    }

    e.Result = results;
}

private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    myDataGrid.ItemsSource = e.Result as List<object>;
    myProgressBar.Visibility = Visibility.Collapsed;
}
</code>```

You need to call the ReportProgress method of the BackgroundWorker for any progress to be reported but it is pretty meaningless to report progress from a database retrieval operation since you have no clue about the actual progress anyway. You'd better just use an indeterminate ProgressBar and show it when you start the operation and hiding it when the operation has completed as demonstrated in the sample code above.

And Thread.Sleep will block the current thread. If you block the UI thread, your UI, including your ProgressBar, cannot be updated so you don't want to do this.

Body:
I am trying to keep my indeterminate ProgressBar animation running smoothly as I query database and updating DataGrid in DoWork in BackgroundWorker. I understand that I cannot update UIThread in DoWork, so I use Dispatcher.BeginInvoke to access DataGrid, yet I still receive the owned-by-another-thread exception.

Question 1

Why is this happening? DoWork should be on
  BackgroundWorker's thread owned by UIThread, and Dispatcher should
  allow my DoWork to access my GUI.

Looking further into BackgroundWorker suggest UI operation should be handled in ProgressChanged(). But if I move all database/GUI operation to ProgressChanged() and put a Thread.Sleep(5000) on DoWork() to emulate something to work on to lend enough time for ProgressChanged() to run, the GUI is not being updated, although the ProgressBar continue its indeterminate smooth animation.

Question 2

I called a Thread.Sleep(5000) on BackgroundWorker thread.
  ProgressChanged() should spend 5 seconds querying database and
  updating GUI. Why not?

XAML:

<DataGrid x:Name="myDataGrid" ScrollViewer.CanContentScroll="True"
          EnableRowVirtualization="True" EnableColumnVirtualization="True"
          VirtualizingPanel.IsContainerVirtualizable="True"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.IsVirtualizingWhenGrouping="True"
          Height="500" MaxHeight="500" />

<ProgressBar x:Name="myProgressBar" Height="20" Width="400"
             IsIndeterminate="True" Visibility="Visible" />

<Button x:Name="mySearch" Click="btnSearch_Click">Search</Button>

C#

private BackgroundWorker bgw = new BackgroundWorker();

private void btnSearch_Click(object sendoer, RoutedEventArgs e)
{
    bgw.WorkerReportsProgress = true;
    bgw.ProgressChanged += ProgressChanged;
    bgw.DoWork += DoWork;
    bgw.RunWorkerCompleted += BGW_RunWorkerCompleted;

    bgw.RunWorkerAsync();
}

private void DoWork(object sender, DoWorkEventArgs e)
{
    // Thread.Sleep(5000);
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + MyTableName, conn))
        {
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        myDataGrid.Items.Add(new
                        {
                            Id = rdr.GetInt32(0),
                            Name = rdr.GetString(1).ToString(),
                        });
                    }));
                }
            }
        }
    }
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   // Paste code from DoWork and uncomment Thread.Sleep(5000)
}

private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}

Body:
Create a collection of items in your DoWork event handler and then set the ItemsSource property of the DataGrid to this one in the RunWorkerCompleted event handler once you are done fetching the data on a background thread:

private void btnSearch_Click(object sendoer, RoutedEventArgs e)
{
    bgw.WorkerReportsProgress = true;
    bgw.ProgressChanged += ProgressChanged;
    bgw.DoWork += DoWork;
    bgw.RunWorkerCompleted += BGW_RunWorkerCompleted;

    myProgressBar.Visibility = Visibility.Visible;
    bgw.RunWorkerAsync();
}

private void DoWork(object sender, DoWorkEventArgs e)
{
    List<object> results = new List<object>();
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM " + MyTableName, conn))
        {
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    results.Add(new
                    {
                        Id = rdr.GetInt32(0),
                        Name = rdr.GetString(1).ToString(),
                    });
                }
            }
        }
    }

    e.Result = results;
}

private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    myDataGrid.ItemsSource = e.Result as List<object>;
    myProgressBar.Visibility = Visibility.Collapsed;
}

You need to call the ReportProgress method of the BackgroundWorker for any progress to be reported but it is pretty meaningless to report progress from a database retrieval operation since you have no clue about the actual progress anyway. You'd better just use an indeterminate ProgressBar and show it when you start the operation and hiding it when the operation has completed as demonstrated in the sample code above.

And Thread.Sleep will block the current thread. If you block the UI thread, your UI, including your ProgressBar, cannot be updated so you don't want to do this.


问:
Python Pandas DataFrame with only a single number stored?
AzureML's Python Script module requires to return a Pandas DataFrame. I want to return only a value and I do this:

```<code>result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result
</code>```

by which I am able to return just a single value in Azure ML's Python Script module.

What is a proper way to create a pandas DataFrame with a single value?

答:
As EdChum commented

```<code>dataframe1=pd.DataFrame([result], dtype=float)
</code>```

and it works, tested, instead of

```<code>result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result
</code>```

where we don't need to use numpy to initiate the return value with zeroes.

P.s. EdChum can make this his answer if he wants.

Body:
AzureML's Python Script module requires to return a Pandas DataFrame. I want to return only a value and I do this:

result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result

by which I am able to return just a single value in Azure ML's Python Script module.

What is a proper way to create a pandas DataFrame with a single value?

Body:
As EdChum commented

dataframe1=pd.DataFrame([result], dtype=float)

and it works, tested, instead of

result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result

where we don't need to use numpy to initiate the return value with zeroes.

P.s. EdChum can make this his answer if he wants.


问:
Exiting a shell script from inside a while loop
I'm writing a simple shell script that should exit with 0 if an input string is found in a file, and exit with 1 if it isn't

```<code>INPSTR=$1

cat ~/file.txt | while read line
do
    if [[ $line == *$INPSTR* ]]; then
        exit 0
    fi
done

#string not found
exit 1
</code>```

What's actually happening is that when the string is found, the loop exits, and the shell then goes to "exit 1". What's the correct way to exit from the shell script entirely while in a loop?

答:
you can catch return code of subshell using $? like this</p>

```<code>INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
    exit 0
fi
done
if [[ $? -eq 0 ]]; then
    exit 0
else
#string not found
    exit 1
fi
</code>```

Body:
I'm writing a simple shell script that should exit with 0 if an input string is found in a file, and exit with 1 if it isn't

INPSTR=$1

cat ~/file.txt | while read line
do
    if [[ $line == *$INPSTR* ]]; then
        exit 0
    fi
done

#string not found
exit 1

What's actually happening is that when the string is found, the loop exits, and the shell then goes to "exit 1". What's the correct way to exit from the shell script entirely while in a loop?

Body:
you can catch return code of subshell using $? like this

INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
    exit 0
fi
done
if [[ $? -eq 0 ]]; then
    exit 0
else
#string not found
    exit 1
fi