问:
Ajax call is returning null to controller using obect oriented JS
I am using below js for handling blocking details in my application.I used object oriented JS for implementing the same. but when i save trip details its passing null values to string

function triptable(tablename, isTripIn, addColumnButton, saveButton, result) {
    this.tableName = tablename;
    this.istripin = isTripIn;
    this.dataTable = null;
    this.rowNum = 1;
    this.colNum = 0;
    this.rowCell = 0;
    this.colCell = 0;
    this.iterator = 0;
    this.colsList = [];
    this.tableData = [{}];
    this.oTable = null;
    this.inEditMode = null;
    this.tripDetails = [{}];
    this.addColumnId = addColumnButton;
    this.saveId = saveButton;
    this.init(result);
    this.MasterScheduleId =[];
}

triptable.prototype = {
    init: function (result) {
        this.getSchedules(result);
    },
    getSchedules: function (result) {
        this.colsList = [];
        var returnedData = result;//JSON.parse(result);
        if (returnedData.length > 0) {
            var obj = returnedData[0];
            var s = 1;
            for (var key in obj) {
                var attrName = key;
                var myString = attrName.substr(attrName.indexOf("&") + 1)
                var TripNo = attrName.substr(attrName.indexOf("&") + 1)
                var MasterTripId = attrName.substr(0, attrName.indexOf("&"))
                var tripDetail = {
                    'TripNo': TripNo.toString(),
                    'MasterTripId': MasterTripId
                };
                this.tripDetails.push(tripDetail);
                var attrValue = obj[myString];
                var column = {
                    "mData": key,
                    "mDataProp": key,
                    "sTitle": "<input type='checkbox' id= 'chk" + s + "'></input> Trip" + myString,
                    "sType": "string"
                };
                this.colsList.push(column);
                s++;
            }
            results = returnedData;
            var stop = this.colsList[this.colsList.length - 1];
            $('#' + this.tableName + 'ColumnCount').text(this.colsList.length);
            this.colNum = this.colsList.length - 1;

            //var i = this.colsList.indexOf(stop);
            //if (i != -1) {
            //    this.colsList.splice(i, 1);
            //}
            // this.colsList.unshift(stop);
            i = this.colsList.length + 1;
            this.colsList[0].sTitle = this.colsList[0].sTitle.replace("<input type='checkbox' id= 'chk1'></input> Trip", '');
            this.tableData = returnedData;
            this.setTable();
            this.oTable = this.dataTable;
        }
    },
    setTable: function () {
        //Construct the measurement table
        this.dataTable = $('#' + this.tableName).dataTable({
            "bJQueryUI": true,
            "bDeferRender": true,
            "bInfo": false,
            "bSort": false,
            "bDestroy": true,
            "bFilter": false,
            "bPagination": false,
            "aaData": this.tableData,
            "aoColumns": this.colsList,
            //"scrollY": "220px",
            //"scrollX": false,
            "scrollCollapse": true,
            "paging": false,
            "fixedColumns": {
                "leftColumns": 1,
                "rightColumns": 0
            }
        });

        this.bindTableEvents(this);
    },

    saveRow: function (oTable, nRow) {
        var jqInputs = $('input', nRow);
        oTable.fnUpdate(jqInputs[0].value, this.rowCell, this.colCell, false);
    },

    unbindTableEvents: function (contextData) {
        $('#' + contextData.tableName + ' thead tr th').off('click', contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').off('click', contextData.onTableRowClicked);
        // $('#' + contextData.tableName + ' tbody tr').off('dblclick', contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').off('keydown', contextData.onTableKeyDown);
        $('#' + contextData.saveId).off('click', contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).off('click', contextData.onAddColumnClicked);
    },
    bindTableEvents: function (contextData) {
        contextData.unbindTableEvents(contextData);
        $('#' + contextData.tableName + ' thead tr th').on('click', { context: contextData }, contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').on('click', { context: contextData }, contextData.onTableRowClicked);
        // $('#' + contextData.tableName + ' tbody tr').on('dblclick', { context: contextData }, contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').on('keydown', { context: contextData }, contextData.onTableKeyDown);
        $('#' + contextData.saveId).on('click', { context: contextData }, contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).on('click', { context: contextData }, contextData.onAddColumnClicked);
    },

    onTableHeaderClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        var data = ev.currentTarget.innerText;
        data = data.replace("Trip", "");
        data = data.replace(/\n/g, '').trim();
        //var i = self.tripDetails.indexOf(data);
        //if (i != -1) {
        //    self.TripDetails.splice(i, 1);
        //}
        var removed = _.find(self.tripDetails, function (o) { return o.TripNo == data; });
          self.MasterScheduleId.push(removed.MasterTripId.toString());
        self.colNum = parseInt($(this).index());
        console.log("column_num =" + self.colNum);
        //_.forEach(self.tripDetails, function (product) {
        //debugger;
        //var s = _.findIndex(self.tripDetails, function (o) { return o.TripNo == data; });
        //var item = _.find(self.tripDetails, function (o) { return o.TripNo == data; });

        //});
    },
    onTableRowClicked: function (ev) {
        var self = ev.data.context;
        self.colCell = parseInt($(this).index());
        self.rowCell = parseInt($(this).parent().index());
        console.log("Row_num =" + self.rowCell + "  ,  column_num =" + self.colCell);

    },
    restoreRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);

        for (var i = 0, iLen = jqTds.length ; i < iLen ; i++) {
            oTable.fnUpdate(aData[i], nRow, i, false);
        }
    },

    editRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        jqTds[this.colCell].innerHTML = '<input type="text" id ="typ" value="' + aData[this.colsList[this.colCell].mData] + '"/>';
    },
    onTableDoubleClicked: function (e) {

        var self = e.data.context;
        e.preventDefault();
        var nRow = $(this)[0];
        var jqTds = $('>td', nRow);
        if ($.trim(jqTds[0].innerHTML.substr(0, 6)) != '<input') {
            if (self.inEditMode !== null && self.inEditMode != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                self.restoreRow(self.oTable, self.inEditMode);
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);

            }
            else {
                /* No edit in progress - let's start one */
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);
            }
        }
    },
    onTableKeyDown: function (ev) {
        var self = ev.data.context;
        if (ev.keyCode == 13) {
            ev.preventDefault();

            if (self.inEditMode == null)
                alert("Select Row");
            else
                self.saveRow(self.oTable, self.inEditMode);
            self.inEditMode = null;
        }
    },
    onAddColumnClicked: function (ev) {

        var self = ev.data.context;
        self.colsList.splice(self.colNum + 1, 0, { "mDataProp": "newField" + self.iterator, sTitle: "Col-" + self.iterator, sType: "string" });
        //update the result, actual data to be displayed
        for (var iRes = 0; iRes < self.tableData.length ; iRes++) {
            self.tableData[iRes]["newField" + self.iterator] = "data-" + self.iterator;
        }
        //destroy the table
        self.dataTable.fnDestroy();
        $('#' + self.tableName + ' thead tr th').eq(self.colNum).after('Trip-' + self.iterator + '	');
        //init again
        self.setTable();
        self.iterator++;
        self.bindTableEvents(self);
    },

    onTableSaveClicked: function (ev) {
        var self = ev.data.context;
        var timeTable = self.tripDetails;
        var masterTrip = self.MasterScheduleId;
        $.ajax({
            type: "POST",
            url: "/ScheduleManagement/Blocking/SaveBlocking",
            dataType: "json",
            data: masterTrip,
            success: function (values) {
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
}```
</div>
</div>
</p>

<p>Below given is the codes using to save tripdetails array</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> onTableSaveClicked: function (ev) {
            var self = ev.data.context;
            var timeTable = self.tripDetails;
            var masterTrip = self.MasterScheduleId;//It is array of tripNo
            $.ajax({
                type: "POST",
                url: "/ScheduleManagement/Blocking/SaveBlocking",
                dataType: "json",
                data: masterTrip,
                success: function (values) {
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }</code>```

And the controller action is

 public JsonResult SaveBlocking(string[] masterTrip)
        {
            int serviceId = Convert.ToInt32(Session["ServiceGroupId"]);
            int schedulePlanId = Convert.ToInt32(Session["SchedulePlanID"]);
            //int status = _blockingBL.SaveBlockingSheet(serviceId, schedulePlanId, timeTable);
            return Json(1, JsonRequestBehavior.AllowGet);
        }```
</div>
</div>
</p>

<p>Below given codes are using to create objects</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript">
    $(document).ready(function () {
        var req = $.ajax({
            type: "GET",
            url: "/ScheduleManagement/Blocking/GetBlockingCount/",
            dataType: "json",
            context: this,
        });

        req.done(function (result) {

            var buttons = '';
            var output = JSON.parse(result);
            for (var x = 0; x < output.length; x++) {
                var returnedData = output[x];
                buttons += '   <button type="button" id="' + returnedData.SchecdulePlanId + '" class="btn btn-primary"  onclick="getBlocking(' + returnedData.SchecdulePlanId + ')"> ' + returnedData.SchecdulePlanName + '</button> ';
            }
            $("#buttonsList").append(buttons);
        });

    });
    function getBlocking(id) {
        $.blockUI({ message: $('#throbber') });
        var req = $.ajax({
            type: "GET",
            url: "/ScheduleManagement/Blocking/GetBlockingSheet/?id=" + id,
            dataType: "json",
            context: this,
        });

        req.done(function (result) {
            var tripIn = '';
            tripIn = '<table class="table table-bordered trip" id="tripInTable"> </table>';
            $("#tripInTable").remove();
            $("#TripIn").append(tripIn);
            var tripOut = '';
            tripOut = '<table class="table table-bordered trip" id="tripOutTable"> </table>';
            $("#tripOutTable").remove();
            $("#TripOut").append(tripOut);

            var returnedData = JSON.parse(result);
            var tripIn = returnedData.TripInBlocking;
            var tripInTable = new triptable('tripInTable', '0', 'btnAddCol1', 'btnTrip1Save', tripIn);
            if (returnedData.TripOutBlocking != null) {
                var tripOut = returnedData.TripOutBlocking;
                var tripOutTable = new triptable('tripOutTable', '1', 'btnAddCol2', 'btnTrip2Save', tripOut);
            }

            $.unblockUI();
            $("#tripTableContainer").css("display", "block");

        });
    }
</script></code>```

Please help me to solve this issue..

Ajax call handling is always very difficult for me. it will be very helpful if any one can suggest a good tutorial for me.

答:
Below code solves my issue

  onTableSaveClicked: function (ev) {
        var self = ev.data.context;
        var timeTable = self.tripDetails;
        var masterTrip = self.MasterScheduleId;
        $.ajax({
            type: "POST",
            url: "/ScheduleManagement/Blocking/SaveBlocking",
            contentType: 'application/json;',
            dataType: "json",
            data: JSON.stringify(masterTrip),
            success: function (values) {
            },
            error: function (err) {
                console.log(err);
            }
        });
    }```

Body:
I am using below js for handling blocking details in my application.I used object oriented JS for implementing the same. but when i save trip details its passing null values to string

function triptable(tablename, isTripIn, addColumnButton, saveButton, result) {
    this.tableName = tablename;
    this.istripin = isTripIn;
    this.dataTable = null;
    this.rowNum = 1;
    this.colNum = 0;
    this.rowCell = 0;
    this.colCell = 0;
    this.iterator = 0;
    this.colsList = [];
    this.tableData = [{}];
    this.oTable = null;
    this.inEditMode = null;
    this.tripDetails = [{}];
    this.addColumnId = addColumnButton;
    this.saveId = saveButton;
    this.init(result);
    this.MasterScheduleId =[];
}

triptable.prototype = {
    init: function (result) {
        this.getSchedules(result);
    },
    getSchedules: function (result) {
        this.colsList = [];
        var returnedData = result;//JSON.parse(result);
        if (returnedData.length > 0) {
            var obj = returnedData[0];
            var s = 1;
            for (var key in obj) {
                var attrName = key;
                var myString = attrName.substr(attrName.indexOf("&") + 1)
                var TripNo = attrName.substr(attrName.indexOf("&") + 1)
                var MasterTripId = attrName.substr(0, attrName.indexOf("&"))
                var tripDetail = {
                    'TripNo': TripNo.toString(),
                    'MasterTripId': MasterTripId
                };
                this.tripDetails.push(tripDetail);
                var attrValue = obj[myString];
                var column = {
                    "mData": key,
                    "mDataProp": key,
                    "sTitle": "<input type='checkbox' id= 'chk" + s + "'></input> Trip" + myString,
                    "sType": "string"
                };
                this.colsList.push(column);
                s++;
            }
            results = returnedData;
            var stop = this.colsList[this.colsList.length - 1];
            $('#' + this.tableName + 'ColumnCount').text(this.colsList.length);
            this.colNum = this.colsList.length - 1;

            //var i = this.colsList.indexOf(stop);
            //if (i != -1) {
            //    this.colsList.splice(i, 1);
            //}
            // this.colsList.unshift(stop);
            i = this.colsList.length + 1;
            this.colsList[0].sTitle = this.colsList[0].sTitle.replace("<input type='checkbox' id= 'chk1'></input> Trip", '');
            this.tableData = returnedData;
            this.setTable();
            this.oTable = this.dataTable;
        }
    },
    setTable: function () {
        //Construct the measurement table
        this.dataTable = $('#' + this.tableName).dataTable({
            "bJQueryUI": true,
            "bDeferRender": true,
            "bInfo": false,
            "bSort": false,
            "bDestroy": true,
            "bFilter": false,
            "bPagination": false,
            "aaData": this.tableData,
            "aoColumns": this.colsList,
            //"scrollY": "220px",
            //"scrollX": false,
            "scrollCollapse": true,
            "paging": false,
            "fixedColumns": {
                "leftColumns": 1,
                "rightColumns": 0
            }
        });

        this.bindTableEvents(this);
    },

    saveRow: function (oTable, nRow) {
        var jqInputs = $('input', nRow);
        oTable.fnUpdate(jqInputs[0].value, this.rowCell, this.colCell, false);
    },

    unbindTableEvents: function (contextData) {
        $('#' + contextData.tableName + ' thead tr th').off('click', contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').off('click', contextData.onTableRowClicked);
        // $('#' + contextData.tableName + ' tbody tr').off('dblclick', contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').off('keydown', contextData.onTableKeyDown);
        $('#' + contextData.saveId).off('click', contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).off('click', contextData.onAddColumnClicked);
    },
    bindTableEvents: function (contextData) {
        contextData.unbindTableEvents(contextData);
        $('#' + contextData.tableName + ' thead tr th').on('click', { context: contextData }, contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').on('click', { context: contextData }, contextData.onTableRowClicked);
        // $('#' + contextData.tableName + ' tbody tr').on('dblclick', { context: contextData }, contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').on('keydown', { context: contextData }, contextData.onTableKeyDown);
        $('#' + contextData.saveId).on('click', { context: contextData }, contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).on('click', { context: contextData }, contextData.onAddColumnClicked);
    },

    onTableHeaderClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        var data = ev.currentTarget.innerText;
        data = data.replace("Trip", "");
        data = data.replace(/\n/g, '').trim();
        //var i = self.tripDetails.indexOf(data);
        //if (i != -1) {
        //    self.TripDetails.splice(i, 1);
        //}
        var removed = _.find(self.tripDetails, function (o) { return o.TripNo == data; });
          self.MasterScheduleId.push(removed.MasterTripId.toString());
        self.colNum = parseInt($(this).index());
        console.log("column_num =" + self.colNum);
        //_.forEach(self.tripDetails, function (product) {
        //debugger;
        //var s = _.findIndex(self.tripDetails, function (o) { return o.TripNo == data; });
        //var item = _.find(self.tripDetails, function (o) { return o.TripNo == data; });

        //});
    },
    onTableRowClicked: function (ev) {
        var self = ev.data.context;
        self.colCell = parseInt($(this).index());
        self.rowCell = parseInt($(this).parent().index());
        console.log("Row_num =" + self.rowCell + "  ,  column_num =" + self.colCell);

    },
    restoreRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);

        for (var i = 0, iLen = jqTds.length ; i < iLen ; i++) {
            oTable.fnUpdate(aData[i], nRow, i, false);
        }
    },

    editRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        jqTds[this.colCell].innerHTML = '<input type="text" id ="typ" value="' + aData[this.colsList[this.colCell].mData] + '"/>';
    },
    onTableDoubleClicked: function (e) {

        var self = e.data.context;
        e.preventDefault();
        var nRow = $(this)[0];
        var jqTds = $('>td', nRow);
        if ($.trim(jqTds[0].innerHTML.substr(0, 6)) != '<input') {
            if (self.inEditMode !== null && self.inEditMode != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                self.restoreRow(self.oTable, self.inEditMode);
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);

            }
            else {
                /* No edit in progress - let's start one */
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);
            }
        }
    },
    onTableKeyDown: function (ev) {
        var self = ev.data.context;
        if (ev.keyCode == 13) {
            ev.preventDefault();

            if (self.inEditMode == null)
                alert("Select Row");
            else
                self.saveRow(self.oTable, self.inEditMode);
            self.inEditMode = null;
        }
    },
    onAddColumnClicked: function (ev) {

        var self = ev.data.context;
        self.colsList.splice(self.colNum + 1, 0, { "mDataProp": "newField" + self.iterator, sTitle: "Col-" + self.iterator, sType: "string" });
        //update the result, actual data to be displayed
        for (var iRes = 0; iRes < self.tableData.length ; iRes++) {
            self.tableData[iRes]["newField" + self.iterator] = "data-" + self.iterator;
        }
        //destroy the table
        self.dataTable.fnDestroy();
        $('#' + self.tableName + ' thead tr th').eq(self.colNum).after('Trip-' + self.iterator + '	');
        //init again
        self.setTable();
        self.iterator++;
        self.bindTableEvents(self);
    },

    onTableSaveClicked: function (ev) {
        var self = ev.data.context;
        var timeTable = self.tripDetails;
        var masterTrip = self.MasterScheduleId;
        $.ajax({
            type: "POST",
            url: "/ScheduleManagement/Blocking/SaveBlocking",
            dataType: "json",
            data: masterTrip,
            success: function (values) {
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
}

Below given is the codes using to save tripdetails array

 onTableSaveClicked: function (ev) {
            var self = ev.data.context;
            var timeTable = self.tripDetails;
            var masterTrip = self.MasterScheduleId;//It is array of tripNo
            $.ajax({
                type: "POST",
                url: "/ScheduleManagement/Blocking/SaveBlocking",
                dataType: "json",
                data: masterTrip,
                success: function (values) {
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }

And the controller action is

 public JsonResult SaveBlocking(string[] masterTrip)
        {
            int serviceId = Convert.ToInt32(Session["ServiceGroupId"]);
            int schedulePlanId = Convert.ToInt32(Session["SchedulePlanID"]);
            //int status = _blockingBL.SaveBlockingSheet(serviceId, schedulePlanId, timeTable);
            return Json(1, JsonRequestBehavior.AllowGet);
        }

Below given codes are using to create objects

Please help me to solve this issue..

Ajax call handling is always very difficult for me. it will be very helpful if any one can suggest a good tutorial for me.


来源: stackexchange

问:
Roll not defined - Reference Error
I recently installed a node.js package called roll for my text based game that I am making. Here is my code:

```<code>var totalHealth = 100;

var swordAttack = roll.roll(d100);
console.log(swordAttack.result);
if (swordAttack.result >=50 ) {
  totalHealth = totalHealth * 0.15
}

console.log(); {
    return swordAttack
};
</code>```

The idea of this code is to roll a number 1-100 if it is more than or equal to 50 it will deal 15 damage if not it will miss. So the error I'm getting is coming through the console when I run the code: https://i.stack.imgur.com/S4CUB.png

I am using VS code if that helps.

答:
Here is the working examples

first import the  require the module

fixing the typos

Try this to see the output press run button

ContentLicense: CC BY-SA 3.0

Title: Roll not defined - Reference Error

Body:
I recently installed a node.js package called roll for my text based game that I am making. Here is my code:

var totalHealth = 100;

var swordAttack = roll.roll(d100);
console.log(swordAttack.result);
if (swordAttack.result >=50 ) {
  totalHealth = totalHealth * 0.15
}

console.log(); {
    return swordAttack
};

The idea of this code is to roll a number 1-100 if it is more than or equal to 50 it will deal 15 damage if not it will miss. So the error I'm getting is coming through the console when I run the code: https://i.stack.imgur.com/S4CUB.png

I am using VS code if that helps.


问:
How to replace "\\" to "\" C#
Here is an example: "\\\r\\\n\\\u003c"

Expected Result: "\r\n\u003c"

I have tried string.Replace(@"\\\", @"\");, but it doesn't work.

答: You can use Regex.Unescape method for this approach. It will replace all double \\ with \.

Title: How to replace "\\" to "\" C#


问:
What is the equivalent of foreach php in python
I have been using PHP for several years and now, I am trying to shift to a new one. I am interested of learning python.

In PHP, we use foreach something like this:

```<code><?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value;
}
</code>```

How do we integrate this code in python?

答:
See documentation here: https://wiki.python.org/moin/ForLoop</p>

```<code>collection = ['John', 'Adam', 'Ken']
for x in collection:
    print collection[x]
</code>```

Body:
I have been using PHP for several years and now, I am trying to shift to a new one. I am interested of learning python.

In PHP, we use foreach something like this:

<?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value;
}

How do we integrate this code in python?

Body:
See documentation here: https://wiki.python.org/moin/ForLoop

collection = ['John', 'Adam', 'Ken']
for x in collection:
    print collection[x]


问:
.Net Master Page Performance
I'm looking for some help on my discussion.  We're discussing two solutions to a customization problem.  One uses (nested) master-pages.  One master page per customized page.  Plus there is a standard master page for all pages.  The second uses a standard page, which redirects to the custom page if it exists.

My question is, which is more desirable?  Having to Load 2 master pages every time OR only having to load 1 master page and sometimes redirecting (Response.Redirect or Server.Transfer) to the customized page.

I can't really find any information on master page performance.  Should I just think of them as another (somewhat inverted) user-control or should they be used lightly?

Edit:
You can assume Response.Redirect for the transfer.
You can assume the Redirect occurs in the PreInit stage of the lifecycle.

答:
so, it's a webform application no matter what, right? Did you ponder Model View Controller perspective?

Regarding the nasted MasterPages, I did that on a client CRM application and I can assure you, you do not fell any problems loading unless the usual ones about the internet and server speed, for that, and if you think it's the best way to accomplish or objectives, go for it.

Each Master Page will fire their events and normally we think about ohh well, 2 master pages plus a content or several content pages could be a problem pointing the loading time, but this takes miliseconds performing all this, so... be safe.

the only thing that you need to take care is, don't fell up with all the javascript addons that you can find, choose a nice library and use only that, JQuery (now on version 1.3.0 would be the best choice).

at least that is my opinion :)

OwnerDisplayName: jhoven

ContentLicense: CC BY-SA 4.0

Title: .Net Master Page Performance

OwnerDisplayName: balexandre

ContentLicense: CC BY-SA 2.5


问:
How to write complex query for three tables?
Please help me.

I am having three tables as,

```<code>Users:id,name....

Message:id,title....

Messages_Users:id,message_id,sender_id,receiver_id......
</code>```

So i am using HABTM relation in message model for this as,

```<code>var $hasAndBelongsToMany = array(
    'Users' => array (
        'className' => 'User',
        'join_table' => 'messages_users',
        'foreignKey' => 'message_id',
        'associationForeignKey' => 'reciever_id',
        'conditions'=> array('MessagesUser.reciever_id => $this->Session->read("Id")')
    )
);
</code>```

So now i want to write a sql query to fetch the name of all the friends of the user who has sent messages to that particular logged in use.

i,e....when the user log in he will get list of messages he got along wid the name of the senders.

how to write query for this in messages_controller??

please let me if anybody is having any idea..

答:
I've no idea how the ORM works in cackephp, but the query you need is....

```<code>SELECT users.name, users.id, COUNT(*)
FROM users, message_users
WHERE users.id=message_users.sender_id
AND message_users.receiver_id=$current_user_id
GROUP BY users.name, users.id
ORDER BY COUNT(*) DESC
</code>```

i.e. using the messages table is unnecessary and will make your code run significantly slower.

Note that the database is NOT properly normalized - even if a user can send the same message to multiple recipients (not receivers), I can't imagine that multiple users can send the same message.

Body:
Please help me.

I am having three tables as,

Users:id,name....

Message:id,title....

Messages_Users:id,message_id,sender_id,receiver_id......

So i am using HABTM relation in message model for this as,

var $hasAndBelongsToMany = array(
    'Users' => array (
        'className' => 'User',
        'join_table' => 'messages_users',
        'foreignKey' => 'message_id',
        'associationForeignKey' => 'reciever_id',
        'conditions'=> array('MessagesUser.reciever_id => $this->Session->read("Id")')
    )
);

So now i want to write a sql query to fetch the name of all the friends of the user who has sent messages to that particular logged in use.

i,e....when the user log in he will get list of messages he got along wid the name of the senders.

how to write query for this in messages_controller??

please let me if anybody is having any idea..

Body:
I've no idea how the ORM works in cackephp, but the query you need is....

SELECT users.name, users.id, COUNT(*)
FROM users, message_users
WHERE users.id=message_users.sender_id
AND message_users.receiver_id=$current_user_id
GROUP BY users.name, users.id
ORDER BY COUNT(*) DESC

i.e. using the messages table is unnecessary and will make your code run significantly slower.

Note that the database is NOT properly normalized - even if a user can send the same message to multiple recipients (not receivers), I can't imagine that multiple users can send the same message.


问:
How can I get revert the changes of git pull?
I had taken VCS pull from Git but aborted the process. There after I messed up with my codes as the stash saved unncessary comments. To skip with the stash comments, I reverted the version. Now I lost some of the codes that I had changed.

Is there a way I can restore my local changes before taking that pull from VCS?

I'm new to Git and really don't have time to go through all the documents and stuff to read the whole process.

答: If you didn't commit your changes before pulling external changes then I don't think it's possible.</p>


问:
Nearest Neighbour interpolation for Direct3D sprites?
I'm working on a 2D game using Direct3D 10's ID3DX10Sprite interface. It works pretty well except for that the textures are filtered using a linear algorithm (I think?), which makes them look pretty ugly when you scale them.

Original texture (32 x 32):

What it looks like scaled up in-game:

What I want it to look like:

So my question is: Is there a way to use Nearest Neighbour filtering (aka Point filtering) for the sprites, and how do you do that?

This is my code:

Initialization:

```<code>float width = 818.0F;
float height = 646.0F;

IDXGISwapChain*             swapChain;
ID3D10Device*               device      = Direct3D_CreateDevice(hWnd, swapChain, (int)width, (int)height);
ID3D10RenderTargetView*     rtv         = Direct3D_CreateRenderTargetView(device, swapChain);
ID3DX10Sprite*              mainSprite  = Direct3D_CreateMainSpriteObject(device);
ID3D10ShaderResourceView*   texture     = Direct3D_CreateTexture(device, "C:\\Users\\Vincent\\Documents\\visual studio 2010\\Projects\\DirectX Test C++\\Debug\\base_grass.png", 32, 32);
D3DX10_SPRITE*              sprite      = Direct3D_CreateSprite(texture, 0.0F, 0.0F, 1.0F, 1.0F); //800.0F / 64.0F, 600.0F / 64.0F);

Direct3D_CreateViewport(device, 0, 0, (UINT)width, (UINT)height);
</code>```

Rendering:

```<code>FLOAT* backColor = new FLOAT[4];
backColor[0] = 0.0F;
backColor[1] = 0.5F;
backColor[2] = 0.0F;
backColor[3] = 1.0F;

device->ClearRenderTargetView(rtv, backColor);
device->Draw(3, 0);

Direct3D_DrawSpritesBuffered(mainSprite, sprite, 1);
swapChain->Present(0, 0);
</code>```

Direct3D functions:

```<code>/////////////////////////////////////////////////
//            Direct3D_CreateDevice            //
/////////////////////////////////////////////////
ID3D10Device * __stdcall Direct3D_CreateDevice(HWND hWnd, IDXGISwapChain* &swapChain, int width, int height)
{
    //Variables.
    ID3D10Device* D3DDevice;
    DXGI_SWAP_CHAIN_DESC swapChainDescription;

    ZeroMemory(&swapChainDescription, sizeof(DXGI_SWAP_CHAIN_DESC));

    //Buffer settings.
    swapChainDescription.BufferCount                            = 1;
    swapChainDescription.BufferDesc.Format                      = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDescription.BufferDesc.Width                       = width;
    swapChainDescription.BufferDesc.Height                      = height;
    swapChainDescription.BufferDesc.RefreshRate.Numerator       = 60;
    swapChainDescription.BufferDesc.RefreshRate.Denominator     = 1;
    swapChainDescription.BufferUsage                            = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    //Misc.
    swapChainDescription.Flags                                  = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    swapChainDescription.OutputWindow                           = hWnd;
    swapChainDescription.SampleDesc.Count                       = 1;
    swapChainDescription.SampleDesc.Quality                     = 0;
    swapChainDescription.SwapEffect                             = DXGI_SWAP_EFFECT_DISCARD;
    swapChainDescription.Windowed                               = TRUE;

    //Try to create the device and SwapChain.
    if (FAILED(D3D10CreateDeviceAndSwapChain(NULL,
                                             D3D10_DRIVER_TYPE_HARDWARE,
                                             NULL,
                                             D3D10_CREATE_DEVICE_DEBUG,
                                             D3D10_SDK_VERSION,
                                             &swapChainDescription,
                                             &swapChain,
                                             &D3DDevice))) return NULL;
    return D3DDevice;
}

/////////////////////////////////////////////////
//       Direct3D_CreateRenderTargetView       //
/////////////////////////////////////////////////
ID3D10RenderTargetView * __stdcall Direct3D_CreateRenderTargetView(ID3D10Device* device, IDXGISwapChain* swapChain)
{
    //Variables.
    HRESULT hRes = 0;
    ID3D10Texture2D* backBuffer;
    ID3D10RenderTargetView* renderTargetView;

    //Get the back buffer.
    hRes = swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&backBuffer);
    if(FAILED(hRes)) { return NULL; }

    //Try to create the RenderTargetView.
    hRes = device->CreateRenderTargetView(backBuffer, NULL, &renderTargetView);
    if(FAILED(hRes)) { return NULL; }

    //Release the back buffer
    backBuffer->Release();

    //Set the render target
    device->OMSetRenderTargets(1, &renderTargetView, NULL);

    return renderTargetView;
}

/////////////////////////////////////////////////
//           Direct3D_CreateViewport           //
/////////////////////////////////////////////////
void __stdcall Direct3D_CreateViewport(ID3D10Device* device, int x, int y, UINT width, UINT height)
{
    D3D10_VIEWPORT* viewport = new D3D10_VIEWPORT();

    viewport->TopLeftX = x;
    viewport->TopLeftY = y;
    viewport->Width = width;
    viewport->Height = height;
    viewport->MinDepth = 0.0F;
    viewport->MaxDepth = 1.0F;

    device->RSSetViewports(1, viewport);
}

/////////////////////////////////////////////////
//       Direct3D_CreateMainSpriteObject       //
/////////////////////////////////////////////////
ID3DX10Sprite * __stdcall Direct3D_CreateMainSpriteObject(ID3D10Device* device)
{
    //Create the sprite object.
    ID3DX10Sprite* s;
    HRESULT hRes = D3DX10CreateSprite(device, 4096, &s);

    if(FAILED(hRes)) { return NULL; }

    //Construct the Projection- and ViewTransform matrix.
    D3DXMATRIX matview;
    matview._12 = 0.0F;
    matview._13 = 0.0F;
    matview._14 = 0.0F;
    matview._21 = 0.0F;
    matview._23 = 0.0F;
    matview._24 = 0.0F;
    matview._31 = 0.0F;
    matview._32 = 0.0F;
    matview._34 = 0.0F;
    matview._41 = 0.0F;
    matview._42 = 0.0F;
    matview._43 = 0.0F;

    matview._11 = 1.0F;
    matview._22 = 1.0F;
    matview._33 = 1.0F;
    matview._44 = 1.0F;

    //Set the Projection- and ViewTransforms.
    s->SetProjectionTransform(&matview);
    s->SetViewTransform(&matview);

    return s;
}

/////////////////////////////////////////////////
//        Direct3D_DrawSpritesBuffered         //
/////////////////////////////////////////////////
void __stdcall Direct3D_DrawSpritesBuffered(ID3DX10Sprite* spriteObject, D3DX10_SPRITE* sprites, int count)
{
    spriteObject->Begin(0);
    spriteObject->DrawSpritesBuffered(sprites, count);
    spriteObject->Flush();
    spriteObject->End();
}

/////////////////////////////////////////////////
//           Direct3D_CreateTexture            //
/////////////////////////////////////////////////
ID3D10ShaderResourceView * __stdcall Direct3D_CreateTexture(ID3D10Device* device, LPCSTR file, int width, int height)
{
    //Variables.
    D3DX10_IMAGE_LOAD_INFO imgLoadInfo;
    ID3D10ShaderResourceView * shaderResourceView;

    ZeroMemory(&imgLoadInfo, sizeof(imgLoadInfo));

    //Image load settings.
    imgLoadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE;
    imgLoadInfo.CpuAccessFlags = 0;
    imgLoadInfo.Filter = D3DX10_FILTER_NONE;
    imgLoadInfo.FirstMipLevel = 0;
    imgLoadInfo.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    imgLoadInfo.MipFilter = D3DX10_FILTER_NONE;
    imgLoadInfo.MipLevels = 1;
    imgLoadInfo.MiscFlags = 0;
    imgLoadInfo.Usage = D3D10_USAGE_DEFAULT;

    //Get the source image's info.
    imgLoadInfo.pSrcInfo = new D3DX10_IMAGE_INFO();
    D3DX10GetImageInfoFromFileA(file, NULL, imgLoadInfo.pSrcInfo, NULL);

    //Set the texture dimensions.
    imgLoadInfo.Width = width;
    imgLoadInfo.Height = height;

    HRESULT hRes;

    //Attempt to create the ShaderResourceView.
    if(FAILED(D3DX10CreateShaderResourceViewFromFile(device, file, &imgLoadInfo, NULL, &shaderResourceView, &hRes)))
    {
        return NULL;
    }

    return shaderResourceView;
}

/////////////////////////////////////////////////
//            Direct3D_CreateSprite            //
/////////////////////////////////////////////////
D3DX10_SPRITE * __stdcall Direct3D_CreateSprite(ID3D10ShaderResourceView* texture, float textureX, float textureY, float textureWidth, float textureHeight)
{
    //Variables.
    D3DX10_SPRITE* sprite = new D3DX10_SPRITE();

    //Color settings.
    sprite->ColorModulate.r = 1.0f;
    sprite->ColorModulate.g = 1.0f;
    sprite->ColorModulate.b = 1.0f;
    sprite->ColorModulate.a = 1.0f;

    //Texture settings.
    sprite->pTexture = texture;
    sprite->TextureIndex = 0;

    sprite->TexCoord.x = textureX;
    sprite->TexCoord.y = textureY;
    sprite->TexSize.x = textureWidth;
    sprite->TexSize.y = textureHeight;

    //Dimension and location matrix.
    sprite->matWorld._12 = 0.0F;
    sprite->matWorld._13 = 0.0F;
    sprite->matWorld._14 = 0.0F;
    sprite->matWorld._21 = 0.0F;
    sprite->matWorld._23 = 0.0F;
    sprite->matWorld._24 = 0.0F;
    sprite->matWorld._31 = 0.0F;
    sprite->matWorld._32 = 0.0F;
    sprite->matWorld._34 = 0.0F;
    sprite->matWorld._41 = 0.0F;
    sprite->matWorld._42 = 0.0F;
    sprite->matWorld._43 = 0.0F;

    sprite->matWorld._11 = 1.0F;
    sprite->matWorld._22 = 1.0F;
    sprite->matWorld._33 = 1.0F;
    sprite->matWorld._44 = 1.0F;

    return sprite;
}
</code>```

答:
Legacy D3DX10_SPRITE only supports using a single sampler:

```<code>D3D10_SAMPLER_DESC splDesc;
ZeroMemory(&splDesc, sizeof(D3D10_SAMPLER_DESC));
splDesc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
splDesc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.ComparisonFunc = D3D10_COMPARISON_NEVER;
splDesc.MaxLOD = FLT_MAX;
VH( m_pDevice->CreateSamplerState(&splDesc, &m_pSampler) );
</code>```

It also does not provide any overloading/custom state mechanism.

SpriteBatch in the DirectX Tool Kit for DirectX 11 does provide the ability to set which sampler state to use and provides hooks for custom state call-backs:

```<code>void Begin(SpriteSortMode sortMode = SpriteSortMode_Deferred,
    ID3D11BlendState* blendState = nullptr,
    ID3D11SamplerState* samplerState = nullptr,
    ID3D11DepthStencilState* depthStencilState = nullptr,
    ID3D11RasterizerState* rasterizerState = nullptr,
    std::function<void __cdecl()> setCustomShaders = nullptr,
    XMMATRIX transformMatrix = MatrixIdentity);
</code>```

The most sensible solution is to port from Direct3D 10 to Direct3D 11 and stop using legacy Direct3D 10.

If there's some particularly compelling reason why you have to stay on Direct3D 10, then you can take a look at SpriteBatch.h / SpriteBatch.cpp which you could copy out and back-port to Direct3D 10.

See MSDN, Where is the DirectX SDK (2015 Edition?), and Living without D3DX

Body:
I'm working on a 2D game using Direct3D 10's ID3DX10Sprite interface. It works pretty well except for that the textures are filtered using a linear algorithm (I think?), which makes them look pretty ugly when you scale them.

Original texture (32 x 32):

What it looks like scaled up in-game:

What I want it to look like:

So my question is: Is there a way to use Nearest Neighbour filtering (aka Point filtering) for the sprites, and how do you do that?

This is my code:

Initialization:

float width = 818.0F;
float height = 646.0F;

IDXGISwapChain*             swapChain;
ID3D10Device*               device      = Direct3D_CreateDevice(hWnd, swapChain, (int)width, (int)height);
ID3D10RenderTargetView*     rtv         = Direct3D_CreateRenderTargetView(device, swapChain);
ID3DX10Sprite*              mainSprite  = Direct3D_CreateMainSpriteObject(device);
ID3D10ShaderResourceView*   texture     = Direct3D_CreateTexture(device, "C:\\Users\\Vincent\\Documents\\visual studio 2010\\Projects\\DirectX Test C++\\Debug\\base_grass.png", 32, 32);
D3DX10_SPRITE*              sprite      = Direct3D_CreateSprite(texture, 0.0F, 0.0F, 1.0F, 1.0F); //800.0F / 64.0F, 600.0F / 64.0F);

Direct3D_CreateViewport(device, 0, 0, (UINT)width, (UINT)height);

Rendering:

FLOAT* backColor = new FLOAT[4];
backColor[0] = 0.0F;
backColor[1] = 0.5F;
backColor[2] = 0.0F;
backColor[3] = 1.0F;

device->ClearRenderTargetView(rtv, backColor);
device->Draw(3, 0);

Direct3D_DrawSpritesBuffered(mainSprite, sprite, 1);
swapChain->Present(0, 0);

Direct3D functions:

/////////////////////////////////////////////////
//            Direct3D_CreateDevice            //
/////////////////////////////////////////////////
ID3D10Device * __stdcall Direct3D_CreateDevice(HWND hWnd, IDXGISwapChain* &swapChain, int width, int height)
{
    //Variables.
    ID3D10Device* D3DDevice;
    DXGI_SWAP_CHAIN_DESC swapChainDescription;

    ZeroMemory(&swapChainDescription, sizeof(DXGI_SWAP_CHAIN_DESC));

    //Buffer settings.
    swapChainDescription.BufferCount                            = 1;
    swapChainDescription.BufferDesc.Format                      = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDescription.BufferDesc.Width                       = width;
    swapChainDescription.BufferDesc.Height                      = height;
    swapChainDescription.BufferDesc.RefreshRate.Numerator       = 60;
    swapChainDescription.BufferDesc.RefreshRate.Denominator     = 1;
    swapChainDescription.BufferUsage                            = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    //Misc.
    swapChainDescription.Flags                                  = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    swapChainDescription.OutputWindow                           = hWnd;
    swapChainDescription.SampleDesc.Count                       = 1;
    swapChainDescription.SampleDesc.Quality                     = 0;
    swapChainDescription.SwapEffect                             = DXGI_SWAP_EFFECT_DISCARD;
    swapChainDescription.Windowed                               = TRUE;

    //Try to create the device and SwapChain.
    if (FAILED(D3D10CreateDeviceAndSwapChain(NULL,
                                             D3D10_DRIVER_TYPE_HARDWARE,
                                             NULL,
                                             D3D10_CREATE_DEVICE_DEBUG,
                                             D3D10_SDK_VERSION,
                                             &swapChainDescription,
                                             &swapChain,
                                             &D3DDevice))) return NULL;
    return D3DDevice;
}

/////////////////////////////////////////////////
//       Direct3D_CreateRenderTargetView       //
/////////////////////////////////////////////////
ID3D10RenderTargetView * __stdcall Direct3D_CreateRenderTargetView(ID3D10Device* device, IDXGISwapChain* swapChain)
{
    //Variables.
    HRESULT hRes = 0;
    ID3D10Texture2D* backBuffer;
    ID3D10RenderTargetView* renderTargetView;

    //Get the back buffer.
    hRes = swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&backBuffer);
    if(FAILED(hRes)) { return NULL; }

    //Try to create the RenderTargetView.
    hRes = device->CreateRenderTargetView(backBuffer, NULL, &renderTargetView);
    if(FAILED(hRes)) { return NULL; }

    //Release the back buffer
    backBuffer->Release();

    //Set the render target
    device->OMSetRenderTargets(1, &renderTargetView, NULL);

    return renderTargetView;
}

/////////////////////////////////////////////////
//           Direct3D_CreateViewport           //
/////////////////////////////////////////////////
void __stdcall Direct3D_CreateViewport(ID3D10Device* device, int x, int y, UINT width, UINT height)
{
    D3D10_VIEWPORT* viewport = new D3D10_VIEWPORT();

    viewport->TopLeftX = x;
    viewport->TopLeftY = y;
    viewport->Width = width;
    viewport->Height = height;
    viewport->MinDepth = 0.0F;
    viewport->MaxDepth = 1.0F;

    device->RSSetViewports(1, viewport);
}

/////////////////////////////////////////////////
//       Direct3D_CreateMainSpriteObject       //
/////////////////////////////////////////////////
ID3DX10Sprite * __stdcall Direct3D_CreateMainSpriteObject(ID3D10Device* device)
{
    //Create the sprite object.
    ID3DX10Sprite* s;
    HRESULT hRes = D3DX10CreateSprite(device, 4096, &s);

    if(FAILED(hRes)) { return NULL; }

    //Construct the Projection- and ViewTransform matrix.
    D3DXMATRIX matview;
    matview._12 = 0.0F;
    matview._13 = 0.0F;
    matview._14 = 0.0F;
    matview._21 = 0.0F;
    matview._23 = 0.0F;
    matview._24 = 0.0F;
    matview._31 = 0.0F;
    matview._32 = 0.0F;
    matview._34 = 0.0F;
    matview._41 = 0.0F;
    matview._42 = 0.0F;
    matview._43 = 0.0F;

    matview._11 = 1.0F;
    matview._22 = 1.0F;
    matview._33 = 1.0F;
    matview._44 = 1.0F;

    //Set the Projection- and ViewTransforms.
    s->SetProjectionTransform(&matview);
    s->SetViewTransform(&matview);

    return s;
}

/////////////////////////////////////////////////
//        Direct3D_DrawSpritesBuffered         //
/////////////////////////////////////////////////
void __stdcall Direct3D_DrawSpritesBuffered(ID3DX10Sprite* spriteObject, D3DX10_SPRITE* sprites, int count)
{
    spriteObject->Begin(0);
    spriteObject->DrawSpritesBuffered(sprites, count);
    spriteObject->Flush();
    spriteObject->End();
}

/////////////////////////////////////////////////
//           Direct3D_CreateTexture            //
/////////////////////////////////////////////////
ID3D10ShaderResourceView * __stdcall Direct3D_CreateTexture(ID3D10Device* device, LPCSTR file, int width, int height)
{
    //Variables.
    D3DX10_IMAGE_LOAD_INFO imgLoadInfo;
    ID3D10ShaderResourceView * shaderResourceView;

    ZeroMemory(&imgLoadInfo, sizeof(imgLoadInfo));

    //Image load settings.
    imgLoadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE;
    imgLoadInfo.CpuAccessFlags = 0;
    imgLoadInfo.Filter = D3DX10_FILTER_NONE;
    imgLoadInfo.FirstMipLevel = 0;
    imgLoadInfo.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    imgLoadInfo.MipFilter = D3DX10_FILTER_NONE;
    imgLoadInfo.MipLevels = 1;
    imgLoadInfo.MiscFlags = 0;
    imgLoadInfo.Usage = D3D10_USAGE_DEFAULT;

    //Get the source image's info.
    imgLoadInfo.pSrcInfo = new D3DX10_IMAGE_INFO();
    D3DX10GetImageInfoFromFileA(file, NULL, imgLoadInfo.pSrcInfo, NULL);

    //Set the texture dimensions.
    imgLoadInfo.Width = width;
    imgLoadInfo.Height = height;

    HRESULT hRes;

    //Attempt to create the ShaderResourceView.
    if(FAILED(D3DX10CreateShaderResourceViewFromFile(device, file, &imgLoadInfo, NULL, &shaderResourceView, &hRes)))
    {
        return NULL;
    }

    return shaderResourceView;
}

/////////////////////////////////////////////////
//            Direct3D_CreateSprite            //
/////////////////////////////////////////////////
D3DX10_SPRITE * __stdcall Direct3D_CreateSprite(ID3D10ShaderResourceView* texture, float textureX, float textureY, float textureWidth, float textureHeight)
{
    //Variables.
    D3DX10_SPRITE* sprite = new D3DX10_SPRITE();

    //Color settings.
    sprite->ColorModulate.r = 1.0f;
    sprite->ColorModulate.g = 1.0f;
    sprite->ColorModulate.b = 1.0f;
    sprite->ColorModulate.a = 1.0f;

    //Texture settings.
    sprite->pTexture = texture;
    sprite->TextureIndex = 0;

    sprite->TexCoord.x = textureX;
    sprite->TexCoord.y = textureY;
    sprite->TexSize.x = textureWidth;
    sprite->TexSize.y = textureHeight;

    //Dimension and location matrix.
    sprite->matWorld._12 = 0.0F;
    sprite->matWorld._13 = 0.0F;
    sprite->matWorld._14 = 0.0F;
    sprite->matWorld._21 = 0.0F;
    sprite->matWorld._23 = 0.0F;
    sprite->matWorld._24 = 0.0F;
    sprite->matWorld._31 = 0.0F;
    sprite->matWorld._32 = 0.0F;
    sprite->matWorld._34 = 0.0F;
    sprite->matWorld._41 = 0.0F;
    sprite->matWorld._42 = 0.0F;
    sprite->matWorld._43 = 0.0F;

    sprite->matWorld._11 = 1.0F;
    sprite->matWorld._22 = 1.0F;
    sprite->matWorld._33 = 1.0F;
    sprite->matWorld._44 = 1.0F;

    return sprite;
}

Body:
Legacy D3DX10_SPRITE only supports using a single sampler:

D3D10_SAMPLER_DESC splDesc;
ZeroMemory(&splDesc, sizeof(D3D10_SAMPLER_DESC));
splDesc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
splDesc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
splDesc.ComparisonFunc = D3D10_COMPARISON_NEVER;
splDesc.MaxLOD = FLT_MAX;
VH( m_pDevice->CreateSamplerState(&splDesc, &m_pSampler) );

It also does not provide any overloading/custom state mechanism.

SpriteBatch in the DirectX Tool Kit for DirectX 11 does provide the ability to set which sampler state to use and provides hooks for custom state call-backs:

void Begin(SpriteSortMode sortMode = SpriteSortMode_Deferred,
    ID3D11BlendState* blendState = nullptr,
    ID3D11SamplerState* samplerState = nullptr,
    ID3D11DepthStencilState* depthStencilState = nullptr,
    ID3D11RasterizerState* rasterizerState = nullptr,
    std::function<void __cdecl()> setCustomShaders = nullptr,
    XMMATRIX transformMatrix = MatrixIdentity);

The most sensible solution is to port from Direct3D 10 to Direct3D 11 and stop using legacy Direct3D 10.

If there's some particularly compelling reason why you have to stay on Direct3D 10, then you can take a look at SpriteBatch.h / SpriteBatch.cpp which you could copy out and back-port to Direct3D 10.

See MSDN, Where is the DirectX SDK (2015 Edition?), and Living without D3DX


问:
Index error in Python( index out of range)
```<code>given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)
</code>```

Got indexerror.Where is the fault?

答:
The problem is in your while loop. Apparently, your loop iterates through 0 to the length of your input string while the maximum index of 0 base list/array/string is

len(given_number)-1

Modify your code like this.

```<code>   given_number=str(input("Enter the number:"))
   total=str(0)
   num=0
   while num<len(given_number): # Note: I use < not <=
       total+=given_number[num]
       num+=1
   print(total)
</code>```

I hope it will help you to overcome your problem.

Body:
given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)

Got indexerror.Where is the fault?

Body:
The problem is in your while loop. Apparently, your loop iterates through 0 to the length of your input string while the maximum index of 0 base list/array/string is

len(given_number)-1

Modify your code like this.

   given_number=str(input("Enter the number:"))
   total=str(0)
   num=0
   while num<len(given_number): # Note: I use < not <=
       total+=given_number[num]
       num+=1
   print(total)

I hope it will help you to overcome your problem.


答:
Python doesn't have a foreach statement per se. It has for loops built into the language.

```<code>for element in iterable:
    operate(element)
</code>```

If you really wanted to, you could define your own foreach function:

```<code>def foreach(function, iterable):
    for element in iterable:
        function(element)
</code>```

Reference: Is there a 'foreach' function in Python 3?

Title: What is the equivalent of foreach php in python

Body:
Python doesn't have a foreach statement per se. It has for loops built into the language.

for element in iterable:
    operate(element)

If you really wanted to, you could define your own foreach function:

def foreach(function, iterable):
    for element in iterable:
        function(element)

Reference: Is there a 'foreach' function in Python 3?


问:
Can consume Kafka messages in console but not with Python library?
I'm doing things locally on my laptop, and trying to read a topic 'test' from a remote server 'xxxxx'.
When using the console, I launch zookeeper, Kafka and then the consumer:

```<code>bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties
bin/kafka-console-consumer.sh --bootstrap-server xxxxx:9092 --topic test --from-beginning
</code>```

And the messages will display in the console.
But when using Python library as follow, I see nothing:

```<code>from kafka import KafkaConsumer

server = {'server': 'xxxxx:9092', 'topic': 'test'}

# To consume latest messages and auto-commit offsets
consumer = KafkaConsumer(server['topic'],
                         group_id='my-group',
                         bootstrap_servers=server['server'])

for message in consumer:
    # message value and key are raw bytes -- decode if necessary!
    # e.g., for unicode: `message.value.decode('utf-8')`
    print("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                         message.offset, message.key,
                                         message.value))
</code>```

I can also successfully send messages locally from Kafka in console to Python Kafka consumer, the problem only happens when trying to consume remote messages.
Also the connection seems well established to the remote server (it can see me), but nothing is received unfortunately.

答:
The solution I found is using another library, Confluent Kafka Python, and this library worked out of the box just by configuring the server IP and the name of the topic to listen to

Edit: here is the solution I implemented:

I thought Avro library was just to read Avro files, but it actually solved the problem of decoding Kafka messages, as follow: I first import the libraries and give the schema file as a parameter and then create a function to decode the message into a dictionary, that I can use in the consumer loop.

```<code>from confluent_kafka import Consumer, KafkaError
from avro.io import DatumReader, BinaryDecoder
import avro.schema

schema = avro.schema.Parse(open("data_sources/EventRecord.avsc").read())
reader = DatumReader(schema)

def decode(msg_value):
    message_bytes = io.BytesIO(msg_value)
    decoder = BinaryDecoder(message_bytes)
    event_dict = reader.read(decoder)
    return event_dict

c = Consumer()
c.subscribe(topic)
running = True
while running:
    msg = c.poll()
    if not msg.error():
        msg_value = msg.value()
        event_dict = decode(msg_value)
        print(event_dict)
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False
</code>```

Body:
I'm doing things locally on my laptop, and trying to read a topic 'test' from a remote server 'xxxxx'.
When using the console, I launch zookeeper, Kafka and then the consumer:

bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties
bin/kafka-console-consumer.sh --bootstrap-server xxxxx:9092 --topic test --from-beginning

And the messages will display in the console.
But when using Python library as follow, I see nothing:

from kafka import KafkaConsumer

server = {'server': 'xxxxx:9092', 'topic': 'test'}

# To consume latest messages and auto-commit offsets
consumer = KafkaConsumer(server['topic'],
                         group_id='my-group',
                         bootstrap_servers=server['server'])

for message in consumer:
    # message value and key are raw bytes -- decode if necessary!
    # e.g., for unicode: `message.value.decode('utf-8')`
    print("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                         message.offset, message.key,
                                         message.value))

I can also successfully send messages locally from Kafka in console to Python Kafka consumer, the problem only happens when trying to consume remote messages.
Also the connection seems well established to the remote server (it can see me), but nothing is received unfortunately.

Body:
The solution I found is using another library, Confluent Kafka Python, and this library worked out of the box just by configuring the server IP and the name of the topic to listen to

Edit: here is the solution I implemented:

I thought Avro library was just to read Avro files, but it actually solved the problem of decoding Kafka messages, as follow: I first import the libraries and give the schema file as a parameter and then create a function to decode the message into a dictionary, that I can use in the consumer loop.

from confluent_kafka import Consumer, KafkaError
from avro.io import DatumReader, BinaryDecoder
import avro.schema

schema = avro.schema.Parse(open("data_sources/EventRecord.avsc").read())
reader = DatumReader(schema)

def decode(msg_value):
    message_bytes = io.BytesIO(msg_value)
    decoder = BinaryDecoder(message_bytes)
    event_dict = reader.read(decoder)
    return event_dict

c = Consumer()
c.subscribe(topic)
running = True
while running:
    msg = c.poll()
    if not msg.error():
        msg_value = msg.value()
        event_dict = decode(msg_value)
        print(event_dict)
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False


问:
Triggering a class with its own id with find
I am using a waypoint to trigger specific elements. The div elements below all have the same class, so I am trying to trigger the id and then find the element's class and then `addClass('fadeDisplay').

Initially I tried creating a function for it to reduce the code, but once I could not get '$(this)to work with it, I attempted to do it by writing each specific element, like this$('#section3-box-img1')`.

My class is not adding and the waypoint element is firing in the correct place.

Does anyone see what I am doing wrong?

```<code><div class="section3-box-img" id="section3-box-img1"></div>
<div class="section3-box-img" id="section3-box-img2"></div>
<div class="section3-box-img" id="section3-box-img3"></div>

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').find(section3img).addClass('fadeDisplay');
}, {
    offset: '75%'
});
function section3Fade() {
    $(this).find('.section3-box-img').addClass('fadeDisplay');
}
</code>```

答:
Try to make use of 'this' keyword. Something like this:</p>

```<code><div class="section3-box-img" id="section3-box-img1"></div>
<div class="section3-box-img" id="section3-box-img2"></div>
<div class="section3-box-img" id="section3-box-img3"></div>

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
    $(this).addClass('fadeDisplay');
}, {
    offset: '75%'
});
</code>```

Body:
I am using a waypoint to trigger specific elements. The div elements below all have the same class, so I am trying to trigger the id and then find the element's class and then `addClass('fadeDisplay').

Initially I tried creating a function for it to reduce the code, but once I could not get '$(this)to work with it, I attempted to do it by writing each specific element, like this$('#section3-box-img1')`.

My class is not adding and the waypoint element is firing in the correct place.

Does anyone see what I am doing wrong?

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').find(section3img).addClass('fadeDisplay');
}, {
    offset: '75%'
});
function section3Fade() {
    $(this).find('.section3-box-img').addClass('fadeDisplay');
}

Body:
Try to make use of 'this' keyword. Something like this:

<div class="section3-box-img" id="section3-box-img1"></div>
<div class="section3-box-img" id="section3-box-img2"></div>
<div class="section3-box-img" id="section3-box-img3"></div>

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
    $(this).addClass('fadeDisplay');
}, {
    offset: '75%'
});


问:
timeout for 10 seconds while loop in python
What is the best way to timeout while loop in python

say:

```<code>while not buff.endswith('/abc #'):
</code>```

After 10 secs, if it does not match, break the  loop.

Thanks

答:
If your only concern is to end the loop after 10 seconds, try the below code.

```<code>from datetime import datetime
t1 = datetime.now()
while (datetime.now()-t1).seconds <= 10:
  #do something
  print(datetime.now())
</code>```

Else check for the time difference inside the loop and break it. Like,

```<code>t1 = datetime.now()
while not buff.endswith('/abc #'):
  if (datetime.now()-t1).seconds > 10:
    break
</code>```

Body:
What is the best way to timeout while loop in python

say:

while not buff.endswith('/abc #'):

After 10 secs, if it does not match, break the  loop.

Thanks

Body:
If your only concern is to end the loop after 10 seconds, try the below code.

from datetime import datetime
t1 = datetime.now()
while (datetime.now()-t1).seconds <= 10:
  #do something
  print(datetime.now())

Else check for the time difference inside the loop and break it. Like,

t1 = datetime.now()
while not buff.endswith('/abc #'):
  if (datetime.now()-t1).seconds > 10:
    break


问:
Rails 3.2 : Duplicate entry for key index in mysql?
I am using rails 3.2. Here! I am facing a problem, stats below.

I am having two model classes RequestedTrip and TagTrip. Here! are two other models RequestedTripAgent and Tag on which I operate in before_save callback of RequestedTrip and after_update callback of TagTrip.

There is a case in which I am facing Duplicate entry problem. The case is ...

I am updating RequestedTrip object. There is a before_save callback in which I am using find_or_create_by to find or create RequestedTripAgent object. I also assigning Tags to RequestedTrip object through which another callbacks fire in TagTrip after_update. In TagTrip after_update callback, I also using find_or_create_by of same object of RequestedTripAgent.

Here I am using find_or_create_by but getting Duplicate key index error for RequestedTripAgent. What is wrong with me?

Thanks

答: find_or_create_by in before_save is probably creating the resource and again after the callback it is trying to save the same resource..either move everything to after_save or replace it with .first_or_initialize.


问:
Redux-Form - Array of errors
I'm stuck with handling array of objects that contain errors inside my react-native/redux application.

I have a handleResponse function that looks something like this:

function handleResponse (response) {
  let status = JSON.stringify(response.data.Status)
  let res = JSON.stringify(response)
  if (Number(status) === 200) {
    return res
  } else {
    throw new SubmissionError('Something happened')
  }
}
```

<p>But instead of plain text passed as argument to SubmissionError function - I want somehow to take out errors from array of objects.</p>

<p>Array of objects containing error messages looks like this: </p>

<pre class="lang-json prettyprint-override"><code>{
  ErrorMessages: [
    { ErrorMessage: 'foo' },
    { ErrorMessage: 'bar' }
  ]
}
</code>```

How can I, for example, throw foo and bar errors?

答:
You can't really throw two things at once, unless you wrap them in a Promise or do other tricks, I would just concatenate the errors together and do a single throw:

function handleResponse (res) {
  if (Number(res.data.Status) === 200) {
    return JSON.stringify(res)
  }

  const errors = res.ErrorMessages.map(e => e.ErrorMessage).join(', ')
  throw new SubmissionError(`Some errors occurred: ${errors}.`)
}
```

Title: Redux-Form - Array of errors

Body:
I'm stuck with handling array of objects that contain errors inside my react-native/redux application.

I have a handleResponse function that looks something like this:

function handleResponse (response) {
  let status = JSON.stringify(response.data.Status)
  let res = JSON.stringify(response)
  if (Number(status) === 200) {
    return res
  } else {
    throw new SubmissionError('Something happened')
  }
}

But instead of plain text passed as argument to SubmissionError function - I want somehow to take out errors from array of objects.

Array of objects containing error messages looks like this:

{
  ErrorMessages: [
    { ErrorMessage: 'foo' },
    { ErrorMessage: 'bar' }
  ]
}

How can I, for example, throw foo and bar errors?


问:
complex orderby that links to another table
I have the following query to start with:

```<code>var query = from p in db.Products
                        from pc in p.NpProductCategories
                        where pc.CategoryId == categoryId
                        select p;
</code>```

I'm applying some more filtering on it and in the end I want to sort the results:

```<code>if (orderBy == ProductSortingEnum.Name)
                    query = query.OrderBy(x => x.Name);
                else
                    query = query.OrderBy(............);
</code>```

My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
 and sort by the Price of the NpProductVariant

答:
Assuming you have the relationship set up in the dbml...

For one to one (and many to one):

```<code>query = query.OrderBy(p => p.NpProductVariant.Price);
</code>```

For one to many:

```<code>query = query.OrderBy(p => p.NpProductVariants.Select(v => v.Price).Max());
</code>```

Also:

```<code>var query =
  from p in db.Products
  where p.NpProductCategories.Any(pc => pc.CategoryId == categoryId)
  select p;
</code>```

Body:
I have the following query to start with:

var query = from p in db.Products
                        from pc in p.NpProductCategories
                        where pc.CategoryId == categoryId
                        select p;

I'm applying some more filtering on it and in the end I want to sort the results:

if (orderBy == ProductSortingEnum.Name)
                    query = query.OrderBy(x => x.Name);
                else
                    query = query.OrderBy(............);

My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
 and sort by the Price of the NpProductVariant

Body:
Assuming you have the relationship set up in the dbml...

For one to one (and many to one):

query = query.OrderBy(p => p.NpProductVariant.Price);

For one to many:

query = query.OrderBy(p => p.NpProductVariants.Select(v => v.Price).Max());

Also:

var query =
  from p in db.Products
  where p.NpProductCategories.Any(pc => pc.CategoryId == categoryId)
  select p;


问:
How do i add text before footer in wordpress?
text just before the footer. I'm not a coder so please help me out and suggest me how to do it?</p>

答:
You can use wp_footer hook.

```<code>function your_function() {
    echo '<p>This is inserted at the bottom</p>';
}
add_action( 'wp_footer', 'your_function', 100 );
</code>```

For Different page diffrent content you can use is_page function.

When any single Page is being displayed.

```<code>is_page();
</code>```

When Page 42 (ID) is being displayed.

```<code>is_page( 42 );
</code>```

When the Page with a post_title of "Contact" is being displayed.

```<code>is_page( 'Contact' );
</code>```

When the Page with a post_name (slug) of "about-me" is being displayed.

```<code>is_page( 'about-me' );
</code>```

EXAMPLE:

```<code>function your_function() {
    if(is_page( 42 )){ // Enter your page ID
        echo '<p>This is inserted at the bottom</p>';
    }
}
add_action( 'wp_footer', 'your_function', 100 );
</code>```

Add above code in your active theme functions.php.

Body:
You can use wp_footer hook.

function your_function() {
    echo '<p>This is inserted at the bottom</p>';
}
add_action( 'wp_footer', 'your_function', 100 );

For Different page diffrent content you can use is_page function.

When any single Page is being displayed.

is_page();

When Page 42 (ID) is being displayed.

is_page( 42 );

When the Page with a post_title of "Contact" is being displayed.

is_page( 'Contact' );

When the Page with a post_name (slug) of "about-me" is being displayed.

is_page( 'about-me' );

EXAMPLE:

function your_function() {
    if(is_page( 42 )){ // Enter your page ID
        echo '<p>This is inserted at the bottom</p>';
    }
}
add_action( 'wp_footer', 'your_function', 100 );

Add above code in your active theme functions.php.


答:
Just Removed the find function. (i don't know why u want to find the class if you are using an id). Try Something like Below.</p>

```<code>$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').addClass('fadeDisplay');
}, {
    offset: '75%'
});

function section3Fade() {
    $(this).addClass('fadeDisplay');
}
</code>```

Title: Triggering a class with its own id with find

Body:
Just Removed the find function. (i don't know why u want to find the class if you are using an id). Try Something like Below.

$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').addClass('fadeDisplay');
}, {
    offset: '75%'
});

function section3Fade() {
    $(this).addClass('fadeDisplay');
}


问:
how to fixed undefined offset if array data is not equal to limit declared in forloop
so i have a single row data from my db.. from one id i have

```<code>id |  prescription
1  |  sildenafil  ()      25 mg ---- #60---1X per day    morning/
   |  lanoxin  ()      25 mg ---- #60---1X per day    morning/
   |  caltrate plus (caco3)       ---- #60---1X per day    evening/
</code>```

i use this loop to display the data above. so first after getting the data i use explode to separate those data with '/' at the end.. and then limit the data that is being displayed.

```<code><tbody>
    <?php
    for ($n=0; $n < 10; $n++) { ?>
        <tr>
            <td><?php

      $prescription_array=explode('/',$new_array2[$n]);
            echo $n+1;
            ?>
            </td>
            <td><?php

            for ($i=0; $i < 10; $i++) {
                echo "<font size='5'>".$prescription_array[$i]."</font>";
                $i++;
            }
                ?>
            </td>
        </tr>
    <?php }?>
</tbody>
</code>```

what im trying to achieve here is after getting the data from my data and separate it.. i want to limit the data that is being displayed to 10.
sample if have those 3 data only 3 will be displayed.. but my problem is since i limit the loop into 10 what happen is if my data consist only less than 10 i get an error.. Notice: Undefined offset since the data is less than 10.

is there any better approach to fix this?..

答:
Use foreach instead of for

Replace your this code

```<code>for ($i=0; $i < 10; $i++) {
                echo "<font size='5'>".$prescription_array[$i]."</font>";
                $i++;
            }
</code>```

with this

```<code>foreach(array_slice($prescription_array, 0, 10) as $key=> $value) {
    echo "<font size='5'>".$value."</font>";
    $i++;
 }
</code>```

Body:
so i have a single row data from my db.. from one id i have

id |  prescription
1  |  sildenafil  ()      25 mg ---- #60---1X per day    morning/
   |  lanoxin  ()      25 mg ---- #60---1X per day    morning/
   |  caltrate plus (caco3)       ---- #60---1X per day    evening/

i use this loop to display the data above. so first after getting the data i use explode to separate those data with '/' at the end.. and then limit the data that is being displayed.

    <?php
    for ($n=0; $n < 10; $n++) { ?>

            <?php

      $prescription_array=explode('/',$new_array2[$n]);
            echo $n+1;
            ?>

            <?php

            for ($i=0; $i < 10; $i++) {
                echo "".$prescription_array[$i]."";
                $i++;
            }
                ?>

    <?php }?>

what im trying to achieve here is after getting the data from my data and separate it.. i want to limit the data that is being displayed to 10.
sample if have those 3 data only 3 will be displayed.. but my problem is since i limit the loop into 10 what happen is if my data consist only less than 10 i get an error.. Notice: Undefined offset since the data is less than 10.

is there any better approach to fix this?..

Body:
Use foreach instead of for

Replace your this code

for ($i=0; $i < 10; $i++) {
                echo "<font size='5'>".$prescription_array[$i]."</font>";
                $i++;
            }

with this

foreach(array_slice($prescription_array, 0, 10) as $key=> $value) {
    echo "<font size='5'>".$value."</font>";
    $i++;
 }


问:
How to make an logic to separate the data from SQL with Cakephp2?
Currently, I have a site that shows a list of Developers name that I pulled out from the MySQL from the database in Cakephp2. What I want to achieve is to separate "Developers" into two types like "developer" and "programmer". I tried to give an extra field for the id to separate the developers with the programmers in the table that contains the developer's name. But I'm stuck with how I can do this. My explanation might be confusing so I will put the sample of what I want to do below. Some tips and examples with be a great help. I would love to hear from you.</p>

```<code>    Currently, Employee table consitsts of list of names
     of all developers and is retrieved and displayed in cakephp2.
             (Developer)
                    ------------------------------
                        Tim
                        Jim
                        Joe
                        Blake
                        Mike
                        Ron
                ------------------------------

            Now, I want to separate the Developers into two parts "Developer" and "Programmer" maybe by adding a programmer_id field .

                (Developers)
                ------------------------------
                        Tim
                        Jim   ← programmer_id
                        Joe
                        Blake
                        Mike ← programmer_id
                        Ron
                 ------------------------------

Want to show the separated data in cakephp2 like the following.

                (Developer)
                        Tim
                        Joe
                        Blake
                        Ron

                ------------------------------
                (Programmer)
                        Jim
                        Mike
</code>```

答:
I am not getting exactly what you are asking but as per your table structure you can do something like this.       </p>

```<code>     developer   Tim
     programer   Jim   ← programmer_id
     developer   Joe
     developer   Blake
     programer   Mike ← programmer_id
     developer   Ron

  $developer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'developer')
    ));

  $programmer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'programmer')
    ));
</code>```

Body:
Currently, I have a site that shows a list of Developers name that I pulled out from the MySQL from the database in Cakephp2. What I want to achieve is to separate "Developers" into two types like "developer" and "programmer". I tried to give an extra field for the id to separate the developers with the programmers in the table that contains the developer's name. But I'm stuck with how I can do this. My explanation might be confusing so I will put the sample of what I want to do below. Some tips and examples with be a great help. I would love to hear from you.

    Currently, Employee table consitsts of list of names
     of all developers and is retrieved and displayed in cakephp2.
             (Developer)
                    ------------------------------
                        Tim
                        Jim
                        Joe
                        Blake
                        Mike
                        Ron
                ------------------------------

            Now, I want to separate the Developers into two parts "Developer" and "Programmer" maybe by adding a programmer_id field .

                (Developers)
                ------------------------------
                        Tim
                        Jim   ← programmer_id
                        Joe
                        Blake
                        Mike ← programmer_id
                        Ron
                 ------------------------------

Want to show the separated data in cakephp2 like the following.

                (Developer)
                        Tim
                        Joe
                        Blake
                        Ron

                ------------------------------
                (Programmer)
                        Jim
                        Mike

Body:
I am not getting exactly what you are asking but as per your table structure you can do something like this.

     developer   Tim
     programer   Jim   ← programmer_id
     developer   Joe
     developer   Blake
     programer   Mike ← programmer_id
     developer   Ron

  $developer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'developer')
    ));

  $programmer = $this->Employee->find('all', array(
        'conditions' => array('Employee.category' => 'programmer')
    ));


问:
wrap content elements in specific pages differently
All of my content elements are wrapped using stdWrap.wrap.
I am looking for a solution to wrap content elements in the page which i have my ke_search added differently .

答:
Why do you need another HTML-markup?

Normaly you have another
 around your search results which should enable you to add another styling by CSS.

your page may look like:

```<code><body>
  <div class="header">
     :
  </div>
  <div class="content">
     <div id="C123">
        <h3>my very special CE</h3>
        <p class="bodytext">with some text to demonstrate.</p>
     </div>
     <div id="345">
        <h3>your search results:</h3>
        <div class="search-results">
           <a href="index.php?id=67&s=special">
              <div id="C123">
                 <h3>my very special CE</h3>
                 <p class="bodytext">with some text to demonstrate.</p>
              </div>
           </a>
           <a href="index.php?id=83&s=special">
              <div id="C52">
                 <h2>just a demo</h3>
                 <p class="bodytext">this text is nothing special.</p>
              </div>
           </a>
        </div>
    </div>
  </div>
</body>
</code>```

with appropiate CSS the first CE looks completely different to the same CE in the search results.

```<code>h3 { color:black; font-size:16px; }
p.bodytext { color:#444; font-size:12px; }

.search-results h3 { color:blue; font-size:10px; font-weight:bold; }
.search-results p.bodytext { color:#44b; font-size:10px; font-style:italics; }
</code>```

Body:
Why do you need another HTML-markup?

Normaly you have another <div> around your search results which should enable you to add another styling by CSS.

your page may look like:

<body>
  <div class="header">
     :
  </div>
  <div class="content">
     <div id="C123">
        <h3>my very special CE</h3>
        <p class="bodytext">with some text to demonstrate.</p>
     </div>
     <div id="345">
        <h3>your search results:</h3>
        <div class="search-results">
           <a href="index.php?id=67&s=special">
              <div id="C123">
                 <h3>my very special CE</h3>
                 <p class="bodytext">with some text to demonstrate.</p>
              </div>
           </a>
           <a href="index.php?id=83&s=special">
              <div id="C52">
                 <h2>just a demo</h3>
                 <p class="bodytext">this text is nothing special.</p>
              </div>
           </a>
        </div>
    </div>
  </div>
</body>

with appropiate CSS the first CE looks completely different to the same CE in the search results.

h3 { color:black; font-size:16px; }
p.bodytext { color:#444; font-size:12px; }

.search-results h3 { color:blue; font-size:10px; font-weight:bold; }
.search-results p.bodytext { color:#44b; font-size:10px; font-style:italics; }


问:
Trying to pass SqlCommand in SqlDataAdapter as parameters
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

```<code>if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }
</code>```

Successful connection class code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}
</code>```

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}
</code>```

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

答:
Actually you should pass the connection object on SQLCommand.Hope it helped you   </p>

```<code> DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
</code>```

Body:
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }

Successful connection class code

public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

Body:
Actually you should pass the connection object on SQLCommand.Hope it helped you

 DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);


问:
Position of All Matching Elements in List
I'm trying to write a function in Common Lisp similar to the built in position function, that returns a list of the positions of all elements in the haystack that match the needle, as opposed to just the first. I've come up with a few possible solutions (for example recursively searching for the next element using a cdr-from function on the position and adding the result to the previous position) but none of the approaches I've come up with so far seem particularly elegant.

Can anyone suggest what would be the best way of approaching this, as I'm currently struggling.

答:
The obvious way to solve the problem is just to look at each element of the list in turn, and each time one compares as equal to the needle collect its position into an output list. Getting the position is very easy in this case, because we are starting from the beginning of haystack; we can use a variable to count the current position starting from 0.

So if we describe the full algorithm in a sentence, we'd say something like "to find all the positions of a needle in a haystack, for each element in the haystack, and the position starting from 0, when the element is equal to the needle, collect the position."

The LOOP facility is basically the right thing to break out when you want to do iterative processing. Even though its syntax is complicated to describe formally, after some experience you can pretty much just put the English-language description of the algorithm in the body of LOOP and it will work.

```
(defun all-positions (needle haystack)
  (loop
    for element in haystack
    and position from 0
     when (eql element needle)
      collect position))
```

Body:
The obvious way to solve the problem is just to look at each element of the list in turn, and each time one compares as equal to the needle collect its position into an output list. Getting the position is very easy in this case, because we are starting from the beginning of haystack; we can use a variable to count the current position starting from 0.

So if we describe the full algorithm in a sentence, we'd say something like "to find all the positions of a needle in a haystack, for each element in the haystack, and the position starting from 0, when the element is equal to the needle, collect the position."

The LOOP facility is basically the right thing to break out when you want to do iterative processing. Even though its syntax is complicated to describe formally, after some experience you can pretty much just put the English-language description of the algorithm in the body of LOOP and it will work.

(defun all-positions (needle haystack)
  (loop
    for element in haystack
    and position from 0
     when (eql element needle)
      collect position))


问:
tensorflow: what's the difference between tf.nn.dropout and tf.layers.dropout
I'm quite confused about whether to use tf.nn.dropout or tf.layers.dropout.

many MNIST CNN examples seems to use tf.nn.droput, with keep_prop as one of params.

but how is it different with tf.layers.dropout? is the "rate" params in tf.layers.dropout similar to tf.nn.dropout?

Or generally speaking, is the difference between tf.nn.dropout and tf.layers.dropout applies to all other similar situations, like similar functions in tf.nn and tf.layers.

答:
A quick glance through
tensorflow/python/layers/core.py and tensorflow/python/ops/nn_ops.py
reveals that tf.layers.dropout is a wrapper for tf.nn.dropout.

The only differences in the two functions are:

The tf.nn.dropout has parameter keep_prob: "Probability that each element is kept"
 tf.layers.dropout has parameter rate: "The dropout rate"
 Thus, keep_prob = 1 - rate as defined here

The tf.layers.dropout has training parameter: "Whether to return the output in training mode (apply dropout) or in inference mode (return the input untouched)."