问:
Looping through dynamic ranges on another sheet for rows with specific text in VBA
I have a macro that does a lot of things to build a report. Its a template named "Report" that has a user add another sheet, via GetOpenFile, with data to parse. The intent is to have the user open the book, push the button, select a file and generate a full report.

The data sheet, imported and renamed "Source" contains a row of headers and a variably long list of work orders. Each row contains a reference to a product code and and multiple references to order status. I have part of the macro pulling the product codes from Source column O and sorting alphabetically without duplicates.

```<code>    Sub ReportBuilder()

    'Variables for opening and copying the Sourcesheet, building and formatting the report.
    Dim sImportFile As String, sFile As String, cellName As String
    Dim sThisBk As Workbook, wbBk As Workbook
    Dim wSheet As Worksheet, sSheet As Worksheet, keepThis As Worksheet
    Dim nameRange As Range, orderRange As Range
    Dim rowCounterW As Integer, rowCounterS As Integer, pediCounter As Integer, adhoCounter As Integer, workCounter As Integer, holdCounter As Integer

    'Turns off display of screen updates and alerts.
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    'Removes all but the summary sheet "Report".
    For Each keepThis In Application.ActiveWorkbook.Worksheets
        If keepThis.Name <> "Report" Then
            keepThis.Delete
        End If
    Next

    'Displays an open file dialog box for selecting the target Source file.
    Set sThisBk = ActiveWorkbook
    sImportFile = Application.GetOpenFilename( _
    FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Select a file saved from Source")

    'Handles no sheet selection.
    If sImportFile = "False" Then
        MsgBox "No File Selected!"
        Exit Sub

    'Opens the targeted file and copies the sheet.
    Else
        sFile = Dir(sImportFile)
        Application.Workbooks.Open fileName:=sImportFile
        Set wbBk = Workbooks(sFile)
        With wbBk
            Set wSheet = .Sheets("Sheet1")
            wSheet.Copy after:=sThisBk.Sheets("PBUS Report")
            ActiveSheet.Name = "Source"
            Sheets("PBUS Report").Activate
            wbBk.Close SaveChanges:=False
        End With
    End If

    'Clears everything below the headers.
    Worksheets("Report").Rows(7 & ":" & Worksheets("Report").Rows.Count).Delete

    'Inserts the list of unique PRODICT CODEs from the Source sheet.
    Set wSheet = Worksheets("Report")
    Set sSheet = Worksheets("Source")
    sSheet.Activate
    sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp)).Copy
    wSheet.Activate
    wSheet.Range("B7").PasteSpecial

    'Sorts and adjusts after paste, also captures the range of PRODUCT CODEs.
    Selection.Interior.Color = xlNone
    Selection.Font.Bold = False
    wSheet.Columns("B:B").EntireColumn.AutoFit
    Application.Selection.RemoveDuplicates Columns:=1, Header:=xlNo
    Set nameRange = wSheet.Range("B7", Cells(Rows.Count, "B").End(xlUp))
    nameRange.Sort key1:=ActiveCell, order1:=xlAscending
</code>```

This part works great, I get a unique and alphabetized list of product codes from Source column O starting at row 2 in Report column B starting at row 7.

I'm stuck with the loop that counts rows on the Source sheet. For every unique product code in Report (column B starting at 7), I need to count the number of rows in Source (column O starting at 2) where the code matches AND another column contains a status description. Descriptions being either "Plant" or "Storage" in Source column Z, or "Working" or "Holding" in Source column C. There are more descriptions in either but I only track those 4 per product code.

```<code>    'Loop through the range of PRODUCT CODEs to build report.
    Set orderRange = sSheet.Range("O2", sSheet.Cells(Rows.Count, "O").End(xlUp))
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange.Rows
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For Each d In orderRange.Rows
             rowCounterS = orderRange.Row + 1
             If sSheet.Cells(rowCounterS, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(rowCounterS, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(rowCounterS, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If

        Next d
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounter + 1
    Next c
</code>```

This iteration does not count or populate correctly, but it does compile. It only populates the row of B7 with 0s and gives up. I am trying to accomplish:

```<code>    For Each "product code" in "range of product codes" on Report
        For Each row on Source starting at 2
            If "that row" contains a matching "product code" from Report
                And If "that row" also contains "desired status1"
                    Add 1 to counter for "desired status1"
                And If "that row" also contains "desired status2"
                    Add 1 to a counter for "desired status2"
                etc...
    Populate Report column C with status 1 from the counter
    Populate Report column D with status 2 from the counter
    etc...
    Next "product code"
</code>```

How did I mess this up? Trying all day with variations on that syntax once got all the fields to populate with status numbers, but they were all 0s like the first row. Currently only getting top row populating 0s. I don't understand why the dynamic range worked once to get the unique product code list once but not in the next step to loop.

EDIT: Caught a typo with rowCounterW at the bottom that stopped it from looping more than once. Also replaces some variables to count rows on the Source sheet better. Working as follows:

```<code>    'Loop through the range of PRODUCT CODEs to build report.
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For i = 2 To sSheet.Cells(Rows.Count, 2).End(xlUp).Row
            If sSheet.Cells(i, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(i, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(i, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(i, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(i, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If
        Next i
        'Populates the report after parsing every row.
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounterW + 1
    Next c
</code>```

答:
Caught a typo with rowCounterW at the bottom that stopped it from looping more than once. Also replaces some variables to count rows on the Source sheet better. Working as follows:</p>

```<code>    'Loop through the range of PRODUCT CODEs to build report.
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For i = 2 To sSheet.Cells(Rows.Count, 2).End(xlUp).Row
            If sSheet.Cells(i, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(i, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(i, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(i, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(i, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If
        Next i
        'Populates the report after parsing every row.
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounterW + 1
    Next c
</code>```

Body:
I have a macro that does a lot of things to build a report. Its a template named "Report" that has a user add another sheet, via GetOpenFile, with data to parse. The intent is to have the user open the book, push the button, select a file and generate a full report.

The data sheet, imported and renamed "Source" contains a row of headers and a variably long list of work orders. Each row contains a reference to a product code and and multiple references to order status. I have part of the macro pulling the product codes from Source column O and sorting alphabetically without duplicates.

    Sub ReportBuilder()

    'Variables for opening and copying the Sourcesheet, building and formatting the report.
    Dim sImportFile As String, sFile As String, cellName As String
    Dim sThisBk As Workbook, wbBk As Workbook
    Dim wSheet As Worksheet, sSheet As Worksheet, keepThis As Worksheet
    Dim nameRange As Range, orderRange As Range
    Dim rowCounterW As Integer, rowCounterS As Integer, pediCounter As Integer, adhoCounter As Integer, workCounter As Integer, holdCounter As Integer

    'Turns off display of screen updates and alerts.
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    'Removes all but the summary sheet "Report".
    For Each keepThis In Application.ActiveWorkbook.Worksheets
        If keepThis.Name <> "Report" Then
            keepThis.Delete
        End If
    Next

    'Displays an open file dialog box for selecting the target Source file.
    Set sThisBk = ActiveWorkbook
    sImportFile = Application.GetOpenFilename( _
    FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Select a file saved from Source")

    'Handles no sheet selection.
    If sImportFile = "False" Then
        MsgBox "No File Selected!"
        Exit Sub

    'Opens the targeted file and copies the sheet.
    Else
        sFile = Dir(sImportFile)
        Application.Workbooks.Open fileName:=sImportFile
        Set wbBk = Workbooks(sFile)
        With wbBk
            Set wSheet = .Sheets("Sheet1")
            wSheet.Copy after:=sThisBk.Sheets("PBUS Report")
            ActiveSheet.Name = "Source"
            Sheets("PBUS Report").Activate
            wbBk.Close SaveChanges:=False
        End With
    End If

    'Clears everything below the headers.
    Worksheets("Report").Rows(7 & ":" & Worksheets("Report").Rows.Count).Delete

    'Inserts the list of unique PRODICT CODEs from the Source sheet.
    Set wSheet = Worksheets("Report")
    Set sSheet = Worksheets("Source")
    sSheet.Activate
    sSheet.Range("O2", Cells(Rows.Count, "O").End(xlUp)).Copy
    wSheet.Activate
    wSheet.Range("B7").PasteSpecial

    'Sorts and adjusts after paste, also captures the range of PRODUCT CODEs.
    Selection.Interior.Color = xlNone
    Selection.Font.Bold = False
    wSheet.Columns("B:B").EntireColumn.AutoFit
    Application.Selection.RemoveDuplicates Columns:=1, Header:=xlNo
    Set nameRange = wSheet.Range("B7", Cells(Rows.Count, "B").End(xlUp))
    nameRange.Sort key1:=ActiveCell, order1:=xlAscending

This part works great, I get a unique and alphabetized list of product codes from Source column O starting at row 2 in Report column B starting at row 7.

I'm stuck with the loop that counts rows on the Source sheet. For every unique product code in Report (column B starting at 7), I need to count the number of rows in Source (column O starting at 2) where the code matches AND another column contains a status description. Descriptions being either "Plant" or "Storage" in Source column Z, or "Working" or "Holding" in Source column C. There are more descriptions in either but I only track those 4 per product code.

    'Loop through the range of PRODUCT CODEs to build report.
    Set orderRange = sSheet.Range("O2", sSheet.Cells(Rows.Count, "O").End(xlUp))
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange.Rows
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For Each d In orderRange.Rows
             rowCounterS = orderRange.Row + 1
             If sSheet.Cells(rowCounterS, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(rowCounterS, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(rowCounterS, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(rowCounterS, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If

        Next d
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounter + 1
    Next c

This iteration does not count or populate correctly, but it does compile. It only populates the row of B7 with 0s and gives up. I am trying to accomplish:

    For Each "product code" in "range of product codes" on Report
        For Each row on Source starting at 2
            If "that row" contains a matching "product code" from Report
                And If "that row" also contains "desired status1"
                    Add 1 to counter for "desired status1"
                And If "that row" also contains "desired status2"
                    Add 1 to a counter for "desired status2"
                etc...
    Populate Report column C with status 1 from the counter
    Populate Report column D with status 2 from the counter
    etc...
    Next "product code"

How did I mess this up? Trying all day with variations on that syntax once got all the fields to populate with status numbers, but they were all 0s like the first row. Currently only getting top row populating 0s. I don't understand why the dynamic range worked once to get the unique product code list once but not in the next step to loop.

EDIT: Caught a typo with rowCounterW at the bottom that stopped it from looping more than once. Also replaces some variables to count rows on the Source sheet better. Working as follows:

    'Loop through the range of PRODUCT CODEs to build report.
    rowCounterW = 7 'Starting offset for populating the report.
    For Each c In nameRange
        pediCounter = 0 'Counter for pedigree column.
        adhoCounter = 0 'Counter for ad-hoc column.
        workCounter = 0 'Counter for working column.
        holdCounter = 0 'Counter for hold column.
        cellName = c.Value

        For i = 2 To sSheet.Cells(Rows.Count, 2).End(xlUp).Row
            If sSheet.Cells(i, "O") = cellName Then 'If the program name matches on both sheets.
                If sSheet.Cells(i, "Z") = "Plant" Then
                    pediCounter = pediCounter + 1 'Counts for pedigree column.
                End If
                If sSheet.Cells(i, "Z") = "Storage" Then
                    adhoCounter = adhoCounter + 1 'Counts for ad-hoc column.
                End If
                If sSheet.Cells(i, "C") = "Working" Then
                    workCounter = workCounter + 1 'Counts for working column.
                End If
                If sSheet.Cells(i, "C") = "Holding" Then
                    holdCounter = holdCounter + 1 'Counts for hold column.
                End If
            End If
        Next i
        'Populates the report after parsing every row.
        wSheet.Cells(rowCounterW, "C") = pediCounter
        wSheet.Cells(rowCounterW, "D") = adhoCounter
        wSheet.Cells(rowCounterW, "E") = wSheet.Cells(rowCounterW, "C") + wSheet.Cells(rowCounterW, "D")
        wSheet.Cells(rowCounterW, "F") = workCounter
        wSheet.Cells(rowCounterW, "G") = holdCounter
        wSheet.Cells(rowCounterW, "H") = wSheet.Cells(rowCounterW, "E") + wSheet.Cells(rowCounterW, "F") + wSheet.Cells(rowCounterW, "G")
        rowCounterW = rowCounterW + 1
    Next c


来源: stackexchange

问:
Data does not make it into Coldbox handler from AJAX call
I have a page that is making an $.ajax call to a handler method in Coldbox.  I've done this many times, but in this current project, more than once, if I dump the rc scope at the start of the handler, there's nothing in it other than my usual stuff I add elsewhere on each request.

What's even more weird is that if I don't interrupt the flow of execution it will go from the handler into the model and through the query and back out and return a SUCCESS, even though none of the required values are there.  If I dump the arguments scope in the model, nothing is there either.  This sounds like either a coldbox bug or a misconfiguration or something, but at this point I'll hope it's something I'm doing wrong.

So, first up, here's the AJAX call:

```<code>function deleteAgendaItem(agendaid, eventid) {

var data = {},
    url = "<cfoutput>#event.buildLink('agenda.delete')#</cfoutput>";

data.eventid = eventid;
data.agendaid = agendaid;

var xhr = $.ajax({type: "post", data: data, url: url, async: false, dataType : "json", contentType: "application/json; charset=utf-8"});

return JSON.parse(xhr.responseText);

}
</code>```

I've dumped my data structure to ensure the values are in there.

Here's the handler in coldbox:

```<code><cffunction name="delete">
    <cfargument name="event">
    <cfargument name="rc">
    <cfargument name="prc">

    <cfscript>
    param rc.agendaid = 0;
    param rc.eventid = 0;
    var modelObj = getModel('agenda');
    var data = modelObj.delete(agendaid=rc.agendaid, eventid=rc.eventid, clientid=rc.userInfo.currentClientID);

    event.renderData(format="json", data=SerializeJSON(data));
    </cfscript>

</cffunction>
</code>```

This is where stuff gets weird.  If I dump rc, there's nothing in it other than my rc.userInfo.* stuff which is added in the prehandler (it's the contents of the user's cookie).

For completeness, here's the model:

```<code><cffunction name="delete" output="false" access="public" returntype="struct">
    <cfargument name="agendaid" type="numeric" required="yes">
    <cfargument name="eventid" type="numeric" required="yes">
    <cfargument name="clientid" type="numeric" required="yes">

    <cfset var ret = StructNew()>
    <cfset ret.success = true>

    <cfquery datasource="#variables.dsn#">
        update agenda
        set active = 0
        where agendaid = <cfqueryparam value="#arguments.agendaid#" cfsqltype="cf_sql_integer">
        and eventid = <cfqueryparam value="#arguments.eventid#" cfsqltype="cf_sql_integer">
        and clientid = <cfqueryparam value="#arguments.clientid#" cfsqltype="cf_sql_integer">
    </cfquery>

    <cfreturn ret>

</cffunction>
</code>```

Like I said earlier, if I let everything run, it will pass on through the model and return ret, which is success=true.  No errors thrown.  VERY weird.  And if I dump arguments, there's nothing in it.

I've dumped both event.getHTTPContent() and getHttpRequestData() and they too are empty when it comes to the data I'm sending over.

I'm running on CF2016 on a Mac, but I've run the same code on a Windows server running Lucee and the same issue occurs.  My Coldbox verion is v4.3.0.

Another thing worth mentioning... I've had this same problem with other calls in this project, with one difference... while I can't see any of the values being passed in (they too are blank), if I let it run through the model, IT WORKS FINE.  I still can't dump them in the model either.  That is beyond bizarre...note that while I do param the values going into the model, the fact that when I dump the arguments scope in the model and nothing appears is weird.

21 years doing ColdFusion and eight years doing Coldbox and this is the weirdest thing I've seen...

So... maybe another set of eyes will help.  Am I doing something wrong?  I must be.  Thanks. :)

答:
Coldbox 4.x will not de-serialize a JSON payload body in the request, by default - which your $.ajax call is sending.  This changes in the upcoming 5.0 release.  In the meantime, though, you will need to deserialize the inbound JSON payload - preferrably using a preHandler or aroundHandler method.

```<code>if( isJSON( event.getHTTPContent() ) ){
    structAppend( rc, event.getHTTPContent( json=true ), true );
}
</code>```

Alternately, you can either change your content type of the ajax request to use multipart/form-data and those values will populate the request collection, as you would expect or develop off the BE release of Coldbox 5 ( CommandBox install box install coldbox@be )

ContentLicense: CC BY-SA 3.0

Body:
I have a page that is making an $.ajax call to a handler method in Coldbox.  I've done this many times, but in this current project, more than once, if I dump the rc scope at the start of the handler, there's nothing in it other than my usual stuff I add elsewhere on each request.

What's even more weird is that if I don't interrupt the flow of execution it will go from the handler into the model and through the query and back out and return a SUCCESS, even though none of the required values are there.  If I dump the arguments scope in the model, nothing is there either.  This sounds like either a coldbox bug or a misconfiguration or something, but at this point I'll hope it's something I'm doing wrong.

So, first up, here's the AJAX call:

function deleteAgendaItem(agendaid, eventid) {

var data = {},
    url = "<cfoutput>#event.buildLink('agenda.delete')#</cfoutput>";

data.eventid = eventid;
data.agendaid = agendaid;

var xhr = $.ajax({type: "post", data: data, url: url, async: false, dataType : "json", contentType: "application/json; charset=utf-8"});

return JSON.parse(xhr.responseText);

}

I've dumped my data structure to ensure the values are in there.

Here's the handler in coldbox:

<cffunction name="delete">
    <cfargument name="event">
    <cfargument name="rc">
    <cfargument name="prc">

    <cfscript>
    param rc.agendaid = 0;
    param rc.eventid = 0;
    var modelObj = getModel('agenda');
    var data = modelObj.delete(agendaid=rc.agendaid, eventid=rc.eventid, clientid=rc.userInfo.currentClientID);

    event.renderData(format="json", data=SerializeJSON(data));
    </cfscript>

</cffunction>

This is where stuff gets weird.  If I dump rc, there's nothing in it other than my rc.userInfo.* stuff which is added in the prehandler (it's the contents of the user's cookie).

For completeness, here's the model:

<cffunction name="delete" output="false" access="public" returntype="struct">
    <cfargument name="agendaid" type="numeric" required="yes">
    <cfargument name="eventid" type="numeric" required="yes">
    <cfargument name="clientid" type="numeric" required="yes">

    <cfset var ret = StructNew()>
    <cfset ret.success = true>

    <cfquery datasource="#variables.dsn#">
        update agenda
        set active = 0
        where agendaid = <cfqueryparam value="#arguments.agendaid#" cfsqltype="cf_sql_integer">
        and eventid = <cfqueryparam value="#arguments.eventid#" cfsqltype="cf_sql_integer">
        and clientid = <cfqueryparam value="#arguments.clientid#" cfsqltype="cf_sql_integer">
    </cfquery>

    <cfreturn ret>

</cffunction>

Like I said earlier, if I let everything run, it will pass on through the model and return ret, which is success=true.  No errors thrown.  VERY weird.  And if I dump arguments, there's nothing in it.

I've dumped both event.getHTTPContent() and getHttpRequestData() and they too are empty when it comes to the data I'm sending over.

I'm running on CF2016 on a Mac, but I've run the same code on a Windows server running Lucee and the same issue occurs.  My Coldbox verion is v4.3.0.

Another thing worth mentioning... I've had this same problem with other calls in this project, with one difference... while I can't see any of the values being passed in (they too are blank), if I let it run through the model, IT WORKS FINE.  I still can't dump them in the model either.  That is beyond bizarre...note that while I do param the values going into the model, the fact that when I dump the arguments scope in the model and nothing appears is weird.

21 years doing ColdFusion and eight years doing Coldbox and this is the weirdest thing I've seen...

So... maybe another set of eyes will help.  Am I doing something wrong?  I must be.  Thanks. :)

Body:
Coldbox 4.x will not de-serialize a JSON payload body in the request, by default - which your $.ajax call is sending.  This changes in the upcoming 5.0 release.  In the meantime, though, you will need to deserialize the inbound JSON payload - preferrably using a preHandler or aroundHandler method.

if( isJSON( event.getHTTPContent() ) ){
    structAppend( rc, event.getHTTPContent( json=true ), true );
}

Alternately, you can either change your content type of the ajax request to use multipart/form-data and those values will populate the request collection, as you would expect or develop off the BE release of Coldbox 5 ( CommandBox install box install coldbox@be )


问:
wcf serialization and nhibernate lazy loading
I'm using .net 2.0 with NHibernate/ActiveRecord and WCF.

I haven't been using NH Lazy load so far, but the performance penalties are too big to ignore, so I'm starting to use it.

From what I've read so far, it's not an easy subject, using NH entities with lazy loading and serializing to WCF, but the benefits are too great to ignore.

Using code I've found here: WCF Serialization With NHibernate, I've been able to get WCF to recognize the basic types.

I'm also creating the DataContractSerializer like this:

```<code>public override XmlObjectSerializer CreateSerializer(Type standard, XmlDictionaryString name, XmlDictionaryString NS, IList<Type> knownTypes)
{
    return new DataContractSerializer(standard, name, NS, knownTypes, 0x989680, false, true /* Preserve References*/, new HibernateDataContractSurrogate());
}
</code>```

My problem is when I have something like this:

```<code>[DataContract, ActiveRecord("POS_POSCUSTOMERS",Lazy = true)]
public class POSCustomer : ActiveRecordForPOS<POSCustomer>
{
    private Branch belongsToBranch;

    [DataMember,BelongsTo("BRANCH")]
    public virtual Branch BelongsToBranch
    {
        get { return belongsToBranch; }
        set { belongsToBranch = value; }
    }
}
</code>```

and

```<code>[DataContract, ActiveRecord("BRANCHES",Lazy = true)]
public class Branch : ActiveRecordForPOS<Branch>
{
    private POSCustomer defaultPOSCustomer;

    [DataMember, BelongsTo("POS_POSCUSTNUM", Cascade= CascadeEnum.None)]
    public virtual POSCustomer DefaultPOSCustomer
    {
        get { return defaultPOSCustomer; }
        set { defaultPOSCustomer = value; }
    }
}
</code>```

Branch.DefaultPOSCustomer and POSCustomer.BelongsToBranch are two unrelated entities, but they're the same entities, for example Branch 200 has DefaultPOSCustomer 100, and POSCustomer has BelongsToBranch 200.

The problem is that when WCF tries to serialize the object graph, it bounces between DefaultPOSCustomer and BelongsToBranch, as if doesn't recognize that they're the same entities and that it has already serialized them, until it runs into stack overflow.

If I turn off the Lazy = true on these classes, the serialization works just fine.

How does DataContractSerializer decides that an entity has already been serialized?

How can I stop this behaviour?

Is there perhaps some other way to serialize lazy loading entities with WCF ?

p.s. I've been considering another solution, of creating something similar to NHibernate Proxy, but replace the properties that are related to other classes with the raw key, so instead of having a property of type Branch, I'd have a property of type int with the value 200. This way I might be able to avoid the cycle problem I've ran into, but i'd try this as a last resort, as it would be pretty complicated to maintain.

edit: I've got a lot of entities, so creating a dto for each one is out of the question, and creating it dynamically would be complicated, so i'd rather avoid that or use it as last resort. I also need to do business logic on the server side, so I'll be needing the entities rather than the raw data.

edit: well, no luck going the direct NH/AR/WCF way. I'll go with creating the DTO which seems to be easier.

答: We have been using this solution and have found it to be easier/better than the DTO solution.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm using .net 2.0 with NHibernate/ActiveRecord and WCF.

I haven't been using NH Lazy load so far, but the performance penalties are too big to ignore, so I'm starting to use it.

From what I've read so far, it's not an easy subject, using NH entities with lazy loading and serializing to WCF, but the benefits are too great to ignore.

Using code I've found here: WCF Serialization With NHibernate, I've been able to get WCF to recognize the basic types.

I'm also creating the DataContractSerializer like this:

public override XmlObjectSerializer CreateSerializer(Type standard, XmlDictionaryString name, XmlDictionaryString NS, IList<Type> knownTypes)
{
    return new DataContractSerializer(standard, name, NS, knownTypes, 0x989680, false, true /* Preserve References*/, new HibernateDataContractSurrogate());
}

My problem is when I have something like this:

[DataContract, ActiveRecord("POS_POSCUSTOMERS",Lazy = true)]
public class POSCustomer : ActiveRecordForPOS<POSCustomer>
{
    private Branch belongsToBranch;

    [DataMember,BelongsTo("BRANCH")]
    public virtual Branch BelongsToBranch
    {
        get { return belongsToBranch; }
        set { belongsToBranch = value; }
    }
}

and

[DataContract, ActiveRecord("BRANCHES",Lazy = true)]
public class Branch : ActiveRecordForPOS<Branch>
{
    private POSCustomer defaultPOSCustomer;

    [DataMember, BelongsTo("POS_POSCUSTNUM", Cascade= CascadeEnum.None)]
    public virtual POSCustomer DefaultPOSCustomer
    {
        get { return defaultPOSCustomer; }
        set { defaultPOSCustomer = value; }
    }
}

Branch.DefaultPOSCustomer and POSCustomer.BelongsToBranch are two unrelated entities, but they're the same entities, for example Branch 200 has DefaultPOSCustomer 100, and POSCustomer has BelongsToBranch 200.

The problem is that when WCF tries to serialize the object graph, it bounces between DefaultPOSCustomer and BelongsToBranch, as if doesn't recognize that they're the same entities and that it has already serialized them, until it runs into stack overflow.

If I turn off the Lazy = true on these classes, the serialization works just fine.

How does DataContractSerializer decides that an entity has already been serialized?

How can I stop this behaviour?

Is there perhaps some other way to serialize lazy loading entities with WCF ?

p.s. I've been considering another solution, of creating something similar to NHibernate Proxy, but replace the properties that are related to other classes with the raw key, so instead of having a property of type Branch, I'd have a property of type int with the value 200. This way I might be able to avoid the cycle problem I've ran into, but i'd try this as a last resort, as it would be pretty complicated to maintain.

edit: I've got a lot of entities, so creating a dto for each one is out of the question, and creating it dynamically would be complicated, so i'd rather avoid that or use it as last resort. I also need to do business logic on the server side, so I'll be needing the entities rather than the raw data.

edit: well, no luck going the direct NH/AR/WCF way. I'll go with creating the DTO which seems to be easier.


问:
How to make a Menu that goes from the header to the footer?
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>
    <body>
      <header>
        <h1>This is my header</h1>
      </header>

      <nav>
        <h2>Navigation</h2>
        <ul>
          <li>Google</li>
          <li>Bing</li>
          <li>Yahoo</li>
          <li>AOL</li>
          <li>Facebook</li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>

            email@gmail.com

        </address>
      </footer>

    </body>
  </head>
</html></code>```

答:
Ok, I figured it out. So I wasn't paying attention to where the  tag was. For some reason on my file, the header was below the  tags. So after putting the  tag before the

Thank you for trying to help me tho. :)

header {
  text-align: center;
  border-bottom: 3px double black;
}

/*BODY*/

nav {
  float: left;
  clear: left;
  width: 15%;
  min-height: 400px;
  border-right: 1px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border-top: 3px double black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>
    <body class="nav">
      <header>
        <h1>This is my header</h1>
      </header>
      <nav>
        <h2>Navigation</h2>
        <ul>
          <li>Google</li>
          <li>Bing</li>
          <li>Yahoo</li>
          <li>AOL</li>
          <li>Facebook</li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>

            Email@gmail.com

        </address>
      </footer>

    </body>
  </head>
</html></code>```

Body:
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>

This is my header

Navigation

Google

Bing

Yahoo

AOL

Facebook

          Section 1

          Section Body

          Section 2

          Section Body

          Article

          Article Body

footer

        <address>
          DreamRiskers

            email@gmail.com

        </address>

Body:
Ok, I figured it out. So I wasn't paying attention to where the <header> tag was. For some reason on my file, the header was below the <nav> tags. So after putting the <header> tag before the <nav>

Thank you for trying to help me tho. :)

header {
  text-align: center;
  border-bottom: 3px double black;
}

/*BODY*/

nav {
  float: left;
  clear: left;
  width: 15%;
  min-height: 400px;
  border-right: 1px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border-top: 3px double black;
}

<!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>
    <body class="nav">
      <header>
        <h1>This is my header</h1>
      </header>
      <nav>
        <h2>Navigation</h2>
        <ul>
          <li><a href="google.com">Google</a></li>
          <li><a href="Bing.com">Bing</a></li>
          <li><a href="Yahoo.com">Yahoo</a></li>
          <li><a href="Aol.com">AOL</a></li>
          <li><a href="Facebook.com">Facebook</a></li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>
          <a href="mailto:Email@gmail.com">
            Email@gmail.com
          </a>
        </address>
      </footer>

    </body>
  </head>
</html>


问:
Spring Cloud Consul /refresh endpoint missing
I'm using Spring Cloud Consul for Distributed Configuration with Consul and all goes fine. All configuration is currently and successfully read from Consul server on startup of the application. But I can't reload this configuration for my app when some data on Consul changed because there is not /refresh endpoint. But here says "Sending a HTTP POST to /refresh will cause the configuration to be reloaded." As I understand it should be like for Spring Cloud Config Client but it doesn't. What did I miss?

答:
Or add @RefreshScope on your bean for e.g.

```<code>@Component
@RefreshScope
public class MyConsulConfig  {

@Value("${consul.base.url}")
private String baseUrl;
}
</code>```

Body:
Or add @RefreshScope on your bean for e.g.

@Component
@RefreshScope
public class MyConsulConfig  {

@Value("${consul.base.url}")
private String baseUrl;
}


问:
Django - many-to-one relationship - how to select parent models that have children only
Say I have this model relationship in Django 1.2...

```<code>class Section(models.Model):
    title = models.CharField(max_length=200)

class Page(models.Model):
    section = models.OneToOneField(Section)
    title = models.CharField(max_length=200)
</code>```

I want to select Sections that have one or more Pages associated with them, how would I achieve this in a query? Or would I have to select all sections and then filter out one's that do not have pages manually?

答:
I would second sza's answer if was 100% sure that isnull works in all such cases - but I haven't checked that so I'm not sure (even though I occasionaly use it for such purposes) :-)

What I'm sure of is this:

```<code>from django.db import models
Section.objects.annotate(page_num=models.Count('page')).filter(page_num__gt=0)
</code>```

-- and while counting might be an overkill for your case wih OneToOneField relationship, it definitely works.

Body:
Say I have this model relationship in Django 1.2...

class Section(models.Model):
    title = models.CharField(max_length=200)

class Page(models.Model):
    section = models.OneToOneField(Section)
    title = models.CharField(max_length=200)

I want to select Sections that have one or more Pages associated with them, how would I achieve this in a query? Or would I have to select all sections and then filter out one's that do not have pages manually?

Body:
I would second sza's answer if was 100% sure that isnull works in all such cases - but I haven't checked that so I'm not sure (even though I occasionaly use it for such purposes) :-)

What I'm sure of is this:

from django.db import models
Section.objects.annotate(page_num=models.Count('page')).filter(page_num__gt=0)

-- and while counting might be an overkill for your case wih OneToOneField relationship, it definitely works.


问:
Install iOS App onto Multiple Devices with Free Developer Account
Fledgling iOS hobbyist here. I have a demo app I plan on presenting to a group of people in about a month. It is a simple app, and I am still on the free tier of the Apple Developer Program for now. For this presentation, I'm being provided loaner iPhones, iPads, and MacBooks to demo my app and its code on.

I do know that I am able to load my app onto at least two devices, but they are my own personal iPhone and iPad.

My question is this: With a free developer account, will I be able to 1) load my app onto multiple iPhones and iPads (that I do not own) to demo for the duration of this presentation; and 2) load the code into Xcode on multiple Macs (that I do not own) so that I can show the code to those present. Or will I have to take the plunge and purchase the full $99/year developer account.

This isn't a code question, I know - but the Apple Developer forums are not nearly as active, and I would like a clear answer on this.

答: The quick workaround is you change the identifiers and install it on various phones. com.company.app1 and com.componay.app2 and install the same app on different device. Although with this push notifications and all services connected to identifier does not works.  </p>


问:
jQuery Mobile breaks my site
I load jQuery Mobile on my site when I am only on a mobile touchscreen device. When I do though. It messes up everything. For example, select menus don't work quite right, as well, the words "loading, loading, undefined" appear at the bottom of the page. I know I am missing something but do not know what.

Any ideas on what I could be missing?

Thanks

EDIT: Okay, So I took out all scripts that I am running except for jQuery and jQuery Mobile. I call jQuery first, then jQuery Mobile. It still breaks aspects of the site.

What it breaks:
 - I cannot navigate to any other page via the navbar, if I click on a nav item, and look in the url, the correct url appears (with a # in it) like: /#/about-us/ Then, it just redirects to the home page and the page goes white

Select menus have weird results. It prints out whatever is in the select right beside it. And if you in landscape mode on the ipad and you click on the select, it sends you to the bottom of the page (weird).

it prints out 'loading' twice and 'undefined' once at the bottom of the page

All I have for scripts are jQuery and jQuery Mobile. I should also mention that I am using wordpress so it might have enqueued some other scripts (I have deregistered Wordpress' version of jquery and enqueued my own)

Anyone else experiencing these problems?

答:
Same happened to me by mixing mobile with other frameworks. Fixed issue but getting custom build of jQuery.mobile.  My case was that I needed swipe for touch devices only so used custom min file and nothing was broken after that.

It really depends if you need jQuery.mobile or you need just a certain functionality, Widgets, events? Use custom version that you can build yourself.

You can make and download yours here : http://jquerymobile.com/download-builder/

I hope it worked for you too guys!

Title: jQuery Mobile breaks my site


问:
Excel Search Date formats
I am using Excels 2013 mid and search function to get the date from a comment column but I don't know how to do this to cover the 8 date formats(dd/mm/yyyy, dd/mm/yy and so on). Three of my formulas are below although I would need to join them all together to capture all the date formats.The comment column can be any text with a date anywhere within it.

```<code>=MID(A6, SEARCH("??/??/????", A6, 1), 10)
=MID(A7, SEARCH("?/??/????", A7, 1), 9)
=MID(A8, SEARCH("??/?/????", A8, 1), 9)
</code>```

There must be a better way of doing this as the only way I can think of is to put each formula on a separate column and then use an if statement to show the date.
Any help would be much appreciative. thanks

Sample Column data

```<code>Paid on 01/01/2017
Paid on 1/01/2017, Reference AAA123
Reference BBB456 Paid on  01/1/2017
</code>```

答:
This array formula works if there are no other numbers before the date in the string:

```<code>=INDEX(--TRIM(CLEAN(MID(SUBSTITUTE(SUBSTITUTE(A1," ",REPT(" ",999)),",",""),(ROW(INDIRECT("1:" & LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1))-1)*999+1,999))),MATCH(TRUE,ISNUMBER(--TRIM(CLEAN(MID(SUBSTITUTE(SUBSTITUTE(A1," ",REPT(" ",999)),",",""),(ROW(INDIRECT("1:" & LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1))-1)*999+1,999)))),0))
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

It parses the string by the space and iterates through each "word" till it finds the first that can be converted to a number, which a date is.

This will require that the output be formatted into the date format desired.

Title: Excel Search Date formats

Body:
I am using Excels 2013 mid and search function to get the date from a comment column but I don't know how to do this to cover the 8 date formats(dd/mm/yyyy, dd/mm/yy and so on). Three of my formulas are below although I would need to join them all together to capture all the date formats.The comment column can be any text with a date anywhere within it.

=MID(A6, SEARCH("??/??/????", A6, 1), 10)
=MID(A7, SEARCH("?/??/????", A7, 1), 9)
=MID(A8, SEARCH("??/?/????", A8, 1), 9)

There must be a better way of doing this as the only way I can think of is to put each formula on a separate column and then use an if statement to show the date.
Any help would be much appreciative. thanks

Sample Column data

Paid on 01/01/2017
Paid on 1/01/2017, Reference AAA123
Reference BBB456 Paid on  01/1/2017

Body:
This array formula works if there are no other numbers before the date in the string:

=INDEX(--TRIM(CLEAN(MID(SUBSTITUTE(SUBSTITUTE(A1," ",REPT(" ",999)),",",""),(ROW(INDIRECT("1:" & LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1))-1)*999+1,999))),MATCH(TRUE,ISNUMBER(--TRIM(CLEAN(MID(SUBSTITUTE(SUBSTITUTE(A1," ",REPT(" ",999)),",",""),(ROW(INDIRECT("1:" & LEN(A1)-LEN(SUBSTITUTE(A1," ",""))+1))-1)*999+1,999)))),0))

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

It parses the string by the space and iterates through each "word" till it finds the first that can be converted to a number, which a date is.

This will require that the output be formatted into the date format desired.


问:
How slicing in Python works
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? Please include references where appropriate.

See Why are slice and range upper-bound exclusive? for more discussion of the design decisions behind the notation.

See Pythonic way to return list of every nth item in a larger list for the most common practical usage of slicing (and other ways to solve the problem): getting every Nth element of a list. Please use that question instead as a duplicate target where appropriate.

For more specific answers about slice assignment, see How does assignment work with list slices? (although this is also addressed here).

答:
The answers above don't discuss slice assignment. To understand slice assignment, it's helpful to add another concept to the ASCII art:

```<code>                +---+---+---+---+---+---+
                | P | y | t | h | o | n |
                +---+---+---+---+---+---+
Slice position: 0   1   2   3   4   5   6
Index position:   0   1   2   3   4   5

>>> p = ['P','y','t','h','o','n']
# Why the two sets of numbers:
# indexing gives items, not lists
>>> p[0]
 'P'
>>> p[5]
 'n'

# Slicing gives lists
>>> p[0:1]
 ['P']
>>> p[0:2]
 ['P','y']
</code>```

One heuristic is, for a slice from zero to n, think: "zero is the beginning, start at the beginning and take n items in a list".

```<code>>>> p[5] # the last of six items, indexed from zero
 'n'
>>> p[0:5] # does NOT include the last item!
 ['P','y','t','h','o']
>>> p[0:6] # not p[0:5]!!!
 ['P','y','t','h','o','n']
</code>```

Another heuristic is, "for any slice, replace the start by zero, apply the previous heuristic to get the end of the list, then count the first number back up to chop items off the beginning"

```<code>>>> p[0:4] # Start at the beginning and count out 4 items
 ['P','y','t','h']
>>> p[1:4] # Take one item off the front
 ['y','t','h']
>>> p[2:4] # Take two items off the front
 ['t','h']
# etc.
</code>```

The first rule of slice assignment is that since slicing returns a list, slice assignment requires a list (or other iterable):

```<code>>>> p[2:3]
 ['t']
>>> p[2:3] = ['T']
>>> p
 ['P','y','T','h','o','n']
>>> p[2:3] = 't'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
</code>```

The second rule of slice assignment, which you can also see above, is that whatever portion of the list is returned by slice indexing, that's the same portion that is changed by slice assignment:

```<code>>>> p[2:4]
 ['T','h']
>>> p[2:4] = ['t','r']
>>> p
 ['P','y','t','r','o','n']
</code>```

The third rule of slice assignment is, the assigned list (iterable) doesn't have to have the same length; the indexed slice is simply sliced out and replaced en masse by whatever is being assigned:

```<code>>>> p = ['P','y','t','h','o','n'] # Start over
>>> p[2:4] = ['s','p','a','m']
>>> p
 ['P','y','s','p','a','m','o','n']
</code>```

The trickiest part to get used to is assignment to empty slices. Using heuristic 1 and 2 it's easy to get your head around indexing an empty slice:

```<code>>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
 ['P','y','t','h']
>>> p[1:4]
 ['y','t','h']
>>> p[2:4]
 ['t','h']
>>> p[3:4]
 ['h']
>>> p[4:4]
 []
</code>```

And then once you've seen that, slice assignment to the empty slice makes sense too:

```<code>>>> p = ['P','y','t','h','o','n']
>>> p[2:4] = ['x','y'] # Assigned list is same length as slice
>>> p
 ['P','y','x','y','o','n'] # Result is same length
>>> p = ['P','y','t','h','o','n']
>>> p[3:4] = ['x','y'] # Assigned list is longer than slice
>>> p
 ['P','y','t','x','y','o','n'] # The result is longer
>>> p = ['P','y','t','h','o','n']
>>> p[4:4] = ['x','y']
>>> p
 ['P','y','t','h','x','y','o','n'] # The result is longer still
</code>```

Note that, since we are not changing the second number of the slice (4), the inserted items always stack right up against the 'o', even when we're assigning to the empty slice. So the position for the empty slice assignment is the logical extension of the positions for the non-empty slice assignments.

Backing up a little bit, what happens when you keep going with our procession of counting up the slice beginning?

```<code>>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
 ['P','y','t','h']
>>> p[1:4]
 ['y','t','h']
>>> p[2:4]
 ['t','h']
>>> p[3:4]
 ['h']
>>> p[4:4]
 []
>>> p[5:4]
 []
>>> p[6:4]
 []
</code>```

With slicing, once you're done, you're done; it doesn't start slicing backwards. In Python you don't get negative strides unless you explicitly ask for them by using a negative number.

```<code>>>> p[5:3:-1]
 ['n','o']
</code>```

There are some weird consequences to the "once you're done, you're done" rule:

```<code>>>> p[4:4]
 []
>>> p[5:4]
 []
>>> p[6:4]
 []
>>> p[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code>```

In fact, compared to indexing, Python slicing is bizarrely error-proof:

```<code>>>> p[100:200]
 []
>>> p[int(2e99):int(1e99)]
 []
</code>```

This can come in handy sometimes, but it can also lead to somewhat strange behavior:

```<code>>>> p
 ['P', 'y', 't', 'h', 'o', 'n']
>>> p[int(2e99):int(1e99)] = ['p','o','w','e','r']
>>> p
 ['P', 'y', 't', 'h', 'o', 'n', 'p', 'o', 'w', 'e', 'r']
</code>```

Depending on your application, that might... or might not... be what you were hoping for there!

Below is the text of my original answer. It has been useful to many people, so I didn't want to delete it.

```<code>>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]
</code>```

This may also clarify the difference between slicing and indexing.

OwnerDisplayName: Simon

ContentLicense: CC BY-SA 4.0

Title: How slicing in Python works

Body:
The answers above don't discuss slice assignment. To understand slice assignment, it's helpful to add another concept to the ASCII art:

                +---+---+---+---+---+---+
                | P | y | t | h | o | n |
                +---+---+---+---+---+---+
Slice position: 0   1   2   3   4   5   6
Index position:   0   1   2   3   4   5

>>> p = ['P','y','t','h','o','n']
# Why the two sets of numbers:
# indexing gives items, not lists
>>> p[0]
 'P'
>>> p[5]
 'n'

# Slicing gives lists
>>> p[0:1]
 ['P']
>>> p[0:2]
 ['P','y']

One heuristic is, for a slice from zero to n, think: "zero is the beginning, start at the beginning and take n items in a list".

>>> p[5] # the last of six items, indexed from zero
 'n'
>>> p[0:5] # does NOT include the last item!
 ['P','y','t','h','o']
>>> p[0:6] # not p[0:5]!!!
 ['P','y','t','h','o','n']

Another heuristic is, "for any slice, replace the start by zero, apply the previous heuristic to get the end of the list, then count the first number back up to chop items off the beginning"

>>> p[0:4] # Start at the beginning and count out 4 items
 ['P','y','t','h']
>>> p[1:4] # Take one item off the front
 ['y','t','h']
>>> p[2:4] # Take two items off the front
 ['t','h']
# etc.

The first rule of slice assignment is that since slicing returns a list, slice assignment requires a list (or other iterable):

>>> p[2:3]
 ['t']
>>> p[2:3] = ['T']
>>> p
 ['P','y','T','h','o','n']
>>> p[2:3] = 't'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable

The second rule of slice assignment, which you can also see above, is that whatever portion of the list is returned by slice indexing, that's the same portion that is changed by slice assignment:

>>> p[2:4]
 ['T','h']
>>> p[2:4] = ['t','r']
>>> p
 ['P','y','t','r','o','n']

The third rule of slice assignment is, the assigned list (iterable) doesn't have to have the same length; the indexed slice is simply sliced out and replaced en masse by whatever is being assigned:

>>> p = ['P','y','t','h','o','n'] # Start over
>>> p[2:4] = ['s','p','a','m']
>>> p
 ['P','y','s','p','a','m','o','n']

The trickiest part to get used to is assignment to empty slices. Using heuristic 1 and 2 it's easy to get your head around indexing an empty slice:

>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
 ['P','y','t','h']
>>> p[1:4]
 ['y','t','h']
>>> p[2:4]
 ['t','h']
>>> p[3:4]
 ['h']
>>> p[4:4]
 []

And then once you've seen that, slice assignment to the empty slice makes sense too:

>>> p = ['P','y','t','h','o','n']
>>> p[2:4] = ['x','y'] # Assigned list is same length as slice
>>> p
 ['P','y','x','y','o','n'] # Result is same length
>>> p = ['P','y','t','h','o','n']
>>> p[3:4] = ['x','y'] # Assigned list is longer than slice
>>> p
 ['P','y','t','x','y','o','n'] # The result is longer
>>> p = ['P','y','t','h','o','n']
>>> p[4:4] = ['x','y']
>>> p
 ['P','y','t','h','x','y','o','n'] # The result is longer still

Note that, since we are not changing the second number of the slice (4), the inserted items always stack right up against the 'o', even when we're assigning to the empty slice. So the position for the empty slice assignment is the logical extension of the positions for the non-empty slice assignments.

Backing up a little bit, what happens when you keep going with our procession of counting up the slice beginning?

>>> p = ['P','y','t','h','o','n']
>>> p[0:4]
 ['P','y','t','h']
>>> p[1:4]
 ['y','t','h']
>>> p[2:4]
 ['t','h']
>>> p[3:4]
 ['h']
>>> p[4:4]
 []
>>> p[5:4]
 []
>>> p[6:4]
 []

With slicing, once you're done, you're done; it doesn't start slicing backwards. In Python you don't get negative strides unless you explicitly ask for them by using a negative number.

>>> p[5:3:-1]
 ['n','o']

There are some weird consequences to the "once you're done, you're done" rule:

>>> p[4:4]
 []
>>> p[5:4]
 []
>>> p[6:4]
 []
>>> p[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

In fact, compared to indexing, Python slicing is bizarrely error-proof:

>>> p[100:200]
 []
>>> p[int(2e99):int(1e99)]
 []

This can come in handy sometimes, but it can also lead to somewhat strange behavior:

>>> p
 ['P', 'y', 't', 'h', 'o', 'n']
>>> p[int(2e99):int(1e99)] = ['p','o','w','e','r']
>>> p
 ['P', 'y', 't', 'h', 'o', 'n', 'p', 'o', 'w', 'e', 'r']

Depending on your application, that might... or might not... be what you were hoping for there!

Below is the text of my original answer. It has been useful to many people, so I didn't want to delete it.

>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]

This may also clarify the difference between slicing and indexing.


问:
Should I be worried if someone has my app keystore?
I had my game ported from iOS to Android and I know absolutely nothing about Android. The developer I hired used his keystore file for the app. Should I be worried? And is there anything I can do about it?</p>

答:
so first is to understand your keystore
Your keystore is used to generate your APK with a password and upload to the Market.

Once you have uploaded to the market that keystore and password are locked for that app. If the developer has a copy of your keystore and password, they could create an identical bundle id application and sign it with same keystore and password and steal your spot on the market.

You would get an email of course, so you could catch that they did it.
Google would likely work with you on this to get it recovered and replaced.

However, you can simply opt-in for app signing on the market now to allow uploading of your current keystore to the app store. This allows you to recover if you ever lose your password or keystore info. This is a nice new feature, but won't stop you from having it stolen obviously.

Now, if the app has NOT been released to the market yet, simply create a new keystore and password and go from there.

If it is on the store, you can change the bundle id if you don't have a large user base yet, and delete the old app and create a new keystore and password for the same app with your new bundle id.

example
com.mysite.myapp
could become
com.mysite.mynewapp

now for future reference. Please do not allow engineers to have your production password. They can help you create a keystore and then you type the password. Then move the keystore either into the repo as part of the signing or to your CI build machine for generating builds.

The password should be secure, a common way to do this is in an environment variable on the build server so only the build server assembleRelease would work as the rest would not find the local environment variable value of MY_SIGNING_KEY.

Hope that helps.


问:
How to fix app crash due to Thread 0 error
Now I know how to figure out why my app is crashing, could someone help me in fixing this crash please.

Would this do the job ? THank you

```<code> switch tempDayHolder
                    {
                    case "Monday":
                        outputWeekdays.append(2)
                    case "Tuesday":
                        outputWeekdays.append(3)
                    case "Wednesday":
                        outputWeekdays.append(4)
                    case "Thursday":
                        outputWeekdays.append(5)
                    case "Friday":
                        outputWeekdays.append(6)
                    case "Saturday":
                        outputWeekdays.append(7)
                    case "Sunday":
                        outputWeekdays.append(1)
                    default :
                        outputWeekdays.append(1)
                    }
</code>```

Apologies if this is a basic question. I am a newbie and learning things from online tutorials and is the first time I've encountered this issue.

Ok so I connected the phone where the crash is happening, went into xcode>Devices and this is the crash log. Any pointers from here would be highly appreciated :

https://pastebin.com/mhTteSBC

答:
(let's ignore your programming style.. as you say you are a newbie)

source misses some types.

So:

1) suppose the complete code is:

```<code>import Foundation

var outputWeekdays = [Int]()

class Days {

    init() {
    }
    var daysSelected: String?{
        get{
            if let returnValue  = UserDefaults.standard.object(forKey: "SELECTED_DAY") as? String{
                return returnValue
            }
            else{
                return nil
            }
        }
    }
}
func foo(days: Days){

    let tempDayHolder = days.daysSelected as? String  ?? ""
    switch tempDayHolder
    {
    case "Monday":
        outputWeekdays.append(2)
    case "Tuesday":
        outputWeekdays.append(3)
    case "Wednesday":
        outputWeekdays.append(4)
    case "Thursday":
        outputWeekdays.append(5)
    case "Friday":
        outputWeekdays.append(6)
    case "Saturday":
        outputWeekdays.append(7)
    case "Sunday":
        outputWeekdays.append(1)
    default :
        outputWeekdays.append(1)
    }
}

var days = Days()
foo(days: days)
</code>```

code does work (we suppose we got for example for prefs....)
I got a waring of unnecessary  casting..

2) doing:

```<code>    var daysSelected: NSString?{
..
</code>```

and:

```<code>let tempDayHolder = days.daysSelected as String? ?? ""
</code>```

It does work.

So we need your full code.

Body:
Now I know how to figure out why my app is crashing, could someone help me in fixing this crash please.

Would this do the job ? THank you

 switch tempDayHolder
                    {
                    case "Monday":
                        outputWeekdays.append(2)
                    case "Tuesday":
                        outputWeekdays.append(3)
                    case "Wednesday":
                        outputWeekdays.append(4)
                    case "Thursday":
                        outputWeekdays.append(5)
                    case "Friday":
                        outputWeekdays.append(6)
                    case "Saturday":
                        outputWeekdays.append(7)
                    case "Sunday":
                        outputWeekdays.append(1)
                    default :
                        outputWeekdays.append(1)
                    }

Apologies if this is a basic question. I am a newbie and learning things from online tutorials and is the first time I've encountered this issue.

Ok so I connected the phone where the crash is happening, went into xcode>Devices and this is the crash log. Any pointers from here would be highly appreciated :

https://pastebin.com/mhTteSBC

Body:
(let's ignore your programming style.. as you say you are a newbie)

source misses some types.

So:

1) suppose the complete code is:

import Foundation

var outputWeekdays = [Int]()

class Days {

    init() {
    }
    var daysSelected: String?{
        get{
            if let returnValue  = UserDefaults.standard.object(forKey: "SELECTED_DAY") as? String{
                return returnValue
            }
            else{
                return nil
            }
        }
    }
}
func foo(days: Days){

    let tempDayHolder = days.daysSelected as? String  ?? ""
    switch tempDayHolder
    {
    case "Monday":
        outputWeekdays.append(2)
    case "Tuesday":
        outputWeekdays.append(3)
    case "Wednesday":
        outputWeekdays.append(4)
    case "Thursday":
        outputWeekdays.append(5)
    case "Friday":
        outputWeekdays.append(6)
    case "Saturday":
        outputWeekdays.append(7)
    case "Sunday":
        outputWeekdays.append(1)
    default :
        outputWeekdays.append(1)
    }
}

var days = Days()
foo(days: days)

code does work (we suppose we got for example for prefs....)
I got a waring of unnecessary  casting..

2) doing:

    var daysSelected: NSString?{
..

and:

let tempDayHolder = days.daysSelected as String? ?? ""

It does work.

So we need your full code.


问:
Side by side display of two sections
I'm a beginner, and, as it is in case of most beginners, I'm struggling with something I feel should be simpler than it is for me at the moment.

As a part of my task, I am to create a layout for a blog entry, whereby the date and the author would be represented in the column to the left (roundel-container in the code below), whereas the content itself (articlebody) and the footer with "read more" button and links to comments (readmore-footer) would form the second, wider column to the right. This image represents a simplified vision of what I want to achieve.

I've been playing around with position:, left:, right: and float:, but to mediocre results (which I might well owe to lack of practice). Here's how the code looks like now:

HTML

```<code><section class="articlebox">
    <section class="roundel-container">
        <div class="roundel left"><span class="bold">11 Nov 2013</span></div>
        <div class="roundel left"><span class="bold">by John Doe</span></div>
    </section>
    <section class="articlebody">
        <p class="readable">Lorem ipsum ...</p>
    </section>
    <footer id="readmore-footer">
        <div class="button bold white" id="readmore-button">Read More</div>
        <section class="right">
            <p><a class="darkblue">10 likes</a> <a class="darkblue">22 comments</a></p>
        </section>
    </footer>
</section>
</code>```

CSS

```<code>.articlebody {
    position: relative;
    left: 0;
    padding: 0px 15px 10px 15px;
}

.articlebox {
    position: relative;
    width: 100%;
    overflow: hidden;
}

.roundel {
    height: 80px;
    width: 80px;
    border-radius: 40px;
    margin: 10px;
    color: white;
    background-color: #22aaec;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    align-items: center;
}

.roundel-container {
    position: relative;
    left: 0;
    min-width: 220px;
}

#readmore-footer {
    margin-top: 25px;
    position: relative;
    left: 0;
}

.left {
    float: left;
    width: 45%;
}

.button {
    padding: 5px 15px;
    margin-left: 12px;
    margin-right: 12px;
}

.right {
    float: right;
    width: 45%;
}
</code>```

I'd appreciate help with this one, as well as any tips and tricks you might give regarding the above. Thanks!

答:
write your code like this:

 <!DOCTYPE html>

roundel container

article body

      readmore footer

    ```

note: this is just demo that will give you idea. Hope it will helps you. Cheers!

Title: Side by side display of two sections

Body:
I'm a beginner, and, as it is in case of most beginners, I'm struggling with something I feel should be simpler than it is for me at the moment.

As a part of my task, I am to create a layout for a blog entry, whereby the date and the author would be represented in the column to the left (roundel-container in the code below), whereas the content itself (articlebody) and the footer with "read more" button and links to comments (readmore-footer) would form the second, wider column to the right. This image represents a simplified vision of what I want to achieve.

I've been playing around with position:, left:, right: and float:, but to mediocre results (which I might well owe to lack of practice). Here's how the code looks like now:

HTML

11 Nov 2013

by John Doe

Lorem ipsum ...

Read More

10 likes 22 comments

CSS

.articlebody {
    position: relative;
    left: 0;
    padding: 0px 15px 10px 15px;
}

.articlebox {
    position: relative;
    width: 100%;
    overflow: hidden;
}

.roundel {
    height: 80px;
    width: 80px;
    border-radius: 40px;
    margin: 10px;
    color: white;
    background-color: #22aaec;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    align-items: center;
}

.roundel-container {
    position: relative;
    left: 0;
    min-width: 220px;
}

#readmore-footer {
    margin-top: 25px;
    position: relative;
    left: 0;
}

.left {
    float: left;
    width: 45%;
}

.button {
    padding: 5px 15px;
    margin-left: 12px;
    margin-right: 12px;
}

.right {
    float: right;
    width: 45%;
}

I'd appreciate help with this one, as well as any tips and tricks you might give regarding the above. Thanks!

Body:
write your code like this:

 <!DOCTYPE html>
    <html>
    <head>
    <style>
    div.container {
        width: 100%;
        border: 1px solid gray;
    }

    header, footer {
        padding: 1em;
        border-top: 1px solid black;
        clear: left;
    }

    nav {
        float: left;
        max-width: 160px;
        margin: 0;
        padding: 1em;
    }

    nav ul {
        list-style-type: none;
        padding: 0;
    }

    nav ul a {
        text-decoration: none;
    }

    article {
        margin-left: 170px;
        border-left: 1px solid gray;

        overflow: hidden;
    }
    </style>
    </head>
    <body>
    <div class="container">
    <nav>
      <p>roundel container</p>
    </nav>
    <article>
      <p>article body</p>
      <footer>readmore footer</footer>
    </article>
    </div>
    </body>
    </html>

note: this is just demo that will give you idea. Hope it will helps you. Cheers!


问:
Check if user is authenticated for the first time in Firebase Google Authentication in Android
I am using Firebase Authentication in an Android application, and I am using Google account authentication as an option to sign in to the application.

How can I know if the user is signed in to the application for the first time or not?

答:
A solution when you use Firebase Auth together with Firestore

The root architecture of the Firestore Database would look like this

Use the Firebase Auth currentUser.uid to create a root document for each user. Start by adding a field called registered_at to the root document as soon as the user is created the first time and then add your specific collections to your root document depending on your use case.

When logging in or signing in you can then check if the document with the registered_at field already exists. If it doesn't exist yet, then you can treat the user as a new user (assuming the user can not delete or alter the registered_at field later)

```<code>import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore

fun rootDocument(): DocumentReference? = rootPath()?.let {
    return fireStore().document(it)
}

fun rootPath(): String? {
    val loggedInUser = loggedInUser()
    if (loggedInUser != null) {
        return "users/${loggedInUser.uid}"
    }
    return null
}

fun fireStore() = FirebaseFirestore.getInstance()

fun createWriteBatch() = fireStore().batch()

fun loggedInUser() = fireAuth().currentUser

fun fireAuth(): FirebaseAuth = FirebaseAuth.getInstance()

fun afterSignIn() {

    val rootDocument = rootDocument()
            ?: throw IllegalStateException("root document not found")

    rootDocument.get().addOnCompleteListener {
        val isNewUser = it.result.exists().not()

        if (isNewUser) {
            val batch = createWriteBatch()

            batch.set(rootDocument, HashMap<Any, Any>().apply {
                put("registered_at", System.currentTimeMillis())
            })

            batch.commit().addOnCompleteListener {
                println("this is a new user")
            }

        } else {
            println("this is not a new user")
        }
    }
}
</code>```

Body:
A solution when you use Firebase Auth together with Firestore

The root architecture of the Firestore Database would look like this

Use the Firebase Auth currentUser.uid to create a root document for each user. Start by adding a field called registered_at to the root document as soon as the user is created the first time and then add your specific collections to your root document depending on your use case.

When logging in or signing in you can then check if the document with the registered_at field already exists. If it doesn't exist yet, then you can treat the user as a new user (assuming the user can not delete or alter the registered_at field later)

import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore

fun rootDocument(): DocumentReference? = rootPath()?.let {
    return fireStore().document(it)
}

fun rootPath(): String? {
    val loggedInUser = loggedInUser()
    if (loggedInUser != null) {
        return "users/${loggedInUser.uid}"
    }
    return null
}

fun fireStore() = FirebaseFirestore.getInstance()

fun createWriteBatch() = fireStore().batch()

fun loggedInUser() = fireAuth().currentUser

fun fireAuth(): FirebaseAuth = FirebaseAuth.getInstance()

fun afterSignIn() {

    val rootDocument = rootDocument()
            ?: throw IllegalStateException("root document not found")

    rootDocument.get().addOnCompleteListener {
        val isNewUser = it.result.exists().not()

        if (isNewUser) {
            val batch = createWriteBatch()

            batch.set(rootDocument, HashMap<Any, Any>().apply {
                put("registered_at", System.currentTimeMillis())
            })

            batch.commit().addOnCompleteListener {
                println("this is a new user")
            }

        } else {
            println("this is not a new user")
        }
    }
}


问:
Android support library v7 Searchview bug
My App uses ActionBar tabs with Fragments and as a first step I used only the v4 library.
but now I implemented the v7 appcompat as well.
and on devices with API>11 it worked fine, Because I just use          ActivityCompat.invalidateOptionsMenu(this.getActivity());
but with devices with API<11 the App seemed to crash every time getActivity().supportInvalidateOptionsMenu(); gets called saying there is an inflate exception : android.view.InflateException: Binary XML file line #85: Error inflating class
and in the dalvikvm : Could not find class 'android.support.v7.widget.SearchView$5', referenced from method android.support.v7.widget.SearchView.addOnLayoutChangeListenerToDropDownAnchorSDK11.

I searched online for the last 3 weeks and here is stuff I managed to find:

first there is this.

which wasn't really enough to solve the problem but then I also found this.

Now I use eclipse but after reading Issue 67388 from the link above I downloaded android studio 0.5.4 in order to see if it will work for me as well.
I needed to set the Build gradle to version 0.9.0 and the android.support.v4/android.support.v7 to version 19.0.1 because with 19.1.0 the App still crashes.

now the app runs okay on devices API>11 like android 2.2.3 2.3 etc but will crash if you rotate the device from NullPointerException

the code that causes the exception according to the logcat is :

mSearchView = new MySearchView(getActivity());
```

<p>on 4.4 works fine, but when I run the App on android 3.0 or 4.0/4.1/4.2.1 etc the App crashes again with <strong>android.view.InflateException: Binary XML file line #85: Error inflating class</strong>
and will crash when I rotate the device.</p>

<p>is there anyway I could solve this problem?how?
I am really stuck and don't know what to do any more
Thanks in advance.</p>

<p>here is the full log cat: </p>

<p><strong>InflateException</strong></p>

<pre class="lang-js prettyprint-override"><code>E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #85: Error inflating class <unknown>
            at android.view.LayoutInflater.createView(LayoutInflater.java:513)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:262)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:254)
            at com.samer.deutschwordbookapp.Words$MySearchView.<init>(Words.java:459)
            at com.samer.deutschwordbookapp.Words.onCreateOptionsMenu(Words.java:94)
            at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
            at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1967)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
            at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:617)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
</code>```

NullPointerException

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.view.ViewConfiguration.get(ViewConfiguration.java:211)
            at android.view.View.<init>(View.java:1814)
            at android.view.View.<init>(View.java:1856)
            at android.view.View.<init>(View.java:1834)
            at android.view.ViewGroup.<init>(ViewGroup.java:285)
            at android.widget.LinearLayout.<init>(LinearLayout.java:115)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:258)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:254)
            at com.samer.deutschwordbookapp.Expressions$MySearchView.<init>(Expressions.java:432)
            at com.samer.deutschwordbookapp.Expressions.onCreateOptionsMenu(Expressions.java:89)
            at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
            at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1956)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
            at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
            at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:70)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:4627)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:521)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
            at dalvik.system.NativeStart.main(Native Method)
```

答:
I ended up solving it with a workaround but forgot to post the answer.

The problem was caused due to the fragments manipulating the nav bar to display different possible actions for the different fragments, and sometimes, when navigating between the fragments, the app would crash with the above described error on the above described devices, in essence this should work, but again, it's a really weird android bug that I didn't fully understand.
So Implemented an interface on the activity level that had the nav bar and added the interface in the fragments, then each fragment simply asked the activity to change the actions based on it's needs, which prevented the crash and worked as it should

Body:
My App uses ActionBar tabs with Fragments and as a first step I used only the v4 library.
but now I implemented the v7 appcompat as well.
and on devices with API>11 it worked fine, Because I just use          ActivityCompat.invalidateOptionsMenu(this.getActivity());
but with devices with API<11 the App seemed to crash every time getActivity().supportInvalidateOptionsMenu(); gets called saying there is an inflate exception : android.view.InflateException: Binary XML file line #85: Error inflating class
and in the dalvikvm : Could not find class 'android.support.v7.widget.SearchView$5', referenced from method android.support.v7.widget.SearchView.addOnLayoutChangeListenerToDropDownAnchorSDK11.

I searched online for the last 3 weeks and here is stuff I managed to find:

first there is this.

which wasn't really enough to solve the problem but then I also found this.

Now I use eclipse but after reading Issue 67388 from the link above I downloaded android studio 0.5.4 in order to see if it will work for me as well.
I needed to set the Build gradle to version 0.9.0 and the android.support.v4/android.support.v7 to version 19.0.1 because with 19.1.0 the App still crashes.

now the app runs okay on devices API>11 like android 2.2.3 2.3 etc but will crash if you rotate the device from NullPointerException

the code that causes the exception according to the logcat is :

mSearchView = new MySearchView(getActivity());

on 4.4 works fine, but when I run the App on android 3.0 or 4.0/4.1/4.2.1 etc the App crashes again with android.view.InflateException: Binary XML file line #85: Error inflating class
and will crash when I rotate the device.

is there anyway I could solve this problem?how?
I am really stuck and don't know what to do any more
Thanks in advance.

here is the full log cat:

InflateException

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #85: Error inflating class <unknown>
            at android.view.LayoutInflater.createView(LayoutInflater.java:513)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:262)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:254)
            at com.samer.deutschwordbookapp.Words$MySearchView.<init>(Words.java:459)
            at com.samer.deutschwordbookapp.Words.onCreateOptionsMenu(Words.java:94)
            at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
            at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1967)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
            at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:617)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)
            at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:1998)
            at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:481)
            at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
            at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:644)
            at android.support.v7.app.ActionBarActivityDelegateBase.supportInvalidateOptionsMenu(ActionBarActivityDelegateBase.java:421)
            at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:172)
            at com.samer.deutschwordbookapp.Words.onPrepareOptionsMenu(Words.java:117)
            at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1596)

NullPointerException

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.view.ViewConfiguration.get(ViewConfiguration.java:211)
            at android.view.View.<init>(View.java:1814)
            at android.view.View.<init>(View.java:1856)
            at android.view.View.<init>(View.java:1834)
            at android.view.ViewGroup.<init>(ViewGroup.java:285)
            at android.widget.LinearLayout.<init>(LinearLayout.java:115)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:258)
            at android.support.v7.widget.SearchView.<init>(SearchView.java:254)
            at com.samer.deutschwordbookapp.Expressions$MySearchView.<init>(Expressions.java:432)
            at com.samer.deutschwordbookapp.Expressions.onCreateOptionsMenu(Expressions.java:89)
            at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
            at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1956)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
            at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
            at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:70)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:123)
            at android.app.ActivityThread.main(ActivityThread.java:4627)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:521)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
            at dalvik.system.NativeStart.main(Native Method)


问:
g++ compiler "redefinition…previously defined"
I know there are similar questions but none of these work in my case. Hi I cannot find why I have this issue.
Here is my individual.h file:

```<code>#ifndef INDIVIDUAL_H
#define INDIVIDUAL_H

#include <vector>
#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;

class Individual{
    private:
        vector<unsigned int> chromosome;
        unsigned int n_genes;
        unsigned int N_colours_used = 0;
        unsigned int fitness = 0;

    public:
        Individual(unsigned int ngenes){};

};

#endif
</code>```

And this is my individual.cpp file:

```<code>#include "individual.h"

Individual :: Individual(unsigned int ngenes){
    cout << "something" << endl;
}
</code>```

The error looks like this

```<code>src/individual.cpp:4:1: error: redefinition of ‘Individual::Individual(unsigned int)’
Individual :: Individual(unsigned int ngenes){
 ^
In file included from src/individual.cpp:1:0:
include/individual.h:24:13: note: ‘Individual::Individual(unsigned int)’ previously defined here
             Individual(unsigned int ngenes){};
</code>```

I tried everything thats in stackoverflow but I still don't know how to solve this problem. Also

"#pragma once" does not work.

答:
```<code>    Individual(unsigned int ngenes){};
</code>```

As you can see you have { } after your function declaration, which is a definition of an empty body.

Then you are trying to redefine the body of the function in the .cpp file. Remove { }.

Body:
I know there are similar questions but none of these work in my case. Hi I cannot find why I have this issue.
Here is my individual.h file:

#ifndef INDIVIDUAL_H
#define INDIVIDUAL_H

#include <vector>
#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;

class Individual{
    private:
        vector<unsigned int> chromosome;
        unsigned int n_genes;
        unsigned int N_colours_used = 0;
        unsigned int fitness = 0;

    public:
        Individual(unsigned int ngenes){};

};

#endif

And this is my individual.cpp file:

#include "individual.h"

Individual :: Individual(unsigned int ngenes){
    cout << "something" << endl;
}

The error looks like this

src/individual.cpp:4:1: error: redefinition of ‘Individual::Individual(unsigned int)’
Individual :: Individual(unsigned int ngenes){
 ^
In file included from src/individual.cpp:1:0:
include/individual.h:24:13: note: ‘Individual::Individual(unsigned int)’ previously defined here
             Individual(unsigned int ngenes){};

I tried everything thats in stackoverflow but I still don't know how to solve this problem. Also

"#pragma once" does not work.

Body:
    Individual(unsigned int ngenes){};

As you can see you have { } after your function declaration, which is a definition of an empty body.

Then you are trying to redefine the body of the function in the .cpp file. Remove { }.