VBA static time stamp only when cell data has changed--NOT when data refreshes. Standard VBA not working

Question: I'm very new to VBA and will do my best to explain my issue.
I have a workbook that syncs a list of tasks bidirectionally with Outlook Tasks, and that's working just fine.
I also have a macro that creates a static times tamp every time the "Status" column (Column D) changes.
The problem is, every time I open the worksheet and it syncs with Outlook, it refreshes Column D (along with the rest of the worksheet) and the time stamp updates even if the Status text has remained the same.
Below is the macro I'm using to create the time stamp: is there a way to modify so it only time stamps when the actual text in the cell (Column D) changes (i.e. "In Progress" becomes "Waiting"), and not just when the workbook syncs and refreshes all the data?
Thank you so much!!!
REVISED CODE BELOW--This is the code that syncs with Outlook from "ThisWorkbook" in the "Microsoft Excel Objects" folder.
'--> Declare some constants
'Edit the constants below as needed so they correctly reflect the column number they appear in in the spreadsheet'
Const EXC_CLIENT = 1
Const EXC_SUBJECT = 2
Const EXC_START = 5
Const EXC_STATUS = 4
Const EXC_DUE = 8
Const EXC_EID = 26
Const PROC_NAME = "Outlook Synchronization"
'Do not change any constants from this point on
Const olTaskNotStarted = 0
Const olTaskInProgress = 1
Const olTaskComplete = 2
Const olTaskWaiting = 3
Const olTaskDeferred = 4
Const olText = 1
Const olYesNo = 6
Const olFolderTasks = 13
Const DESKTOP_READOBJECTS = &H1&

'--> Declare some variables
Dim olkApp As Object, _
    olkSes As Object, _
    olkFld As Object, _
    olkTsk As Object, _
    olkPrp As Object, _
    excWks As Excel.Worksheet, _
    lngRow As Long, _
    strRun As String, _
    bolSkp As Boolean

Private Sub InitializeExcel()
    Set excWks = Application.ActiveWorkbook.Sheets(1)
    lngRow = 2
    strRun = Format(Now, "yyyy-mm-dd-hh-nn-ss")
End Sub

Private Sub DeactivateExcel()
    Set excWks = Nothing
End Sub

Private Sub InitializeOutlook()
    Set olkApp = CreateObject("Outlook.Application")
    Set olkSes = olkApp.GetNamespace("MAPI")
    olkSes.Logon olkApp.DefaultProfileName
    Set olkFld = olkSes.GetDefaultFolder(olFolderTasks)
End Sub

Private Sub DeactivateOutlook()
    olkSes.Logoff
    Set olkFld = Nothing
    Set olkSes = Nothing
    Set olkApp = Nothing
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    '--> On saving the workbook you will be given an opportunity to synchronize from Excel to Outlook
    InitializeExcel     'Prep Excel for a sync
    InitializeOutlook   'Prep Outlook for a sync
    Excel2Outlook       'Sync from Excel to Outlook
    DeactivateExcel     'Clean-up Excel
    DeactivateOutlook   'Clean-up Outlook
End Sub

Private Sub Workbook_Open()
    '--> On opening the workbook you will be given an opportunity to syncronize data from Outlook to Excel
    bolSkp = False      'Set this to True if you don't want to be prompted to run the sync when opening/closing the spreadsheet.
    InitializeExcel     'Prep Excel for a sync
    InitializeOutlook   'Prep Outlook for a sync
    Outlook2Excel       'Sync from Outlook to Excel
    DeactivateExcel     'Clean-up Excel
    DeactivateOutlook   'Clean-up Outlook
End Sub

Private Sub Excel2Outlook()
    If Not bolSkp Then
        If MsgBox("Should I sync the tasks to Outlook?", vbQuestion + vbYesNo, PROC_NAME) = vbYes Then
            Do Until excWks.Cells(lngRow, 1) = ""
                Select Case excWks.Cells(lngRow, EXC_EID)
                    Case ""
                        Set olkTsk = olkFld.Items.Add()
                        With olkTsk
                            .UserProperties.Add "ExcelTaskList", olYesNo, True
                            .UserProperties.Item("ExcelTaskList").Value = True
                            .UserProperties.Add "Synced", olText
                            .UserProperties.Item("Synced").Value = strRun
                            .Save
                        End With
                        excWks.Cells(lngRow, EXC_EID) = olkTsk.EntryID
                    Case Else
                        Set olkTsk = olkSes.GetItemFromID(excWks.Cells(lngRow, EXC_EID))
                End Select
                With olkTsk
                    .Subject = excWks.Cells(lngRow, EXC_CLIENT) & "/" & excWks.Cells(lngRow, EXC_SUBJECT)
                    If IsDate(excWks.Cells(lngRow, EXC_START)) Then .StartDate = excWks.Cells(lngRow, EXC_START)
                    If IsDate(excWks.Cells(lngRow, EXC_DUE)) Then .DueDate = excWks.Cells(lngRow, EXC_DUE)
                    Select Case excWks.Cells(lngRow, EXC_STATUS)
                        Case "Complete"
                            .Status = olTaskComplete
                        Case "Deferred"
                            .Status = olTaskDeferred
                        Case "In Progress"
                            .Status = olTaskInProgress
                        Case "Not Started"
                            .Status = olTaskNotStarted
                        Case "Waiting"
                            .Status = olTaskWaiting
                    End Select
                    olkTsk.UserProperties.Item("Synced").Value = strRun
                    .Save
                End With
                lngRow = lngRow + 1
            Loop
            For lngRow = olkFld.Items.Count To 1 Step -1
                Set olkTsk = olkFld.Items(lngRow)
                Set olkPrp = olkTsk.UserProperties.Find("ExcelTaskList", True)
                If TypeName(olkPrp) <> "Nothing" Then
                    If olkTsk.UserProperties.Item("Synced").Value < strRun Then
                        olkTsk.Delete
                    End If
                End If
            Next
        End If
    End If
End Sub

Private Sub Outlook2Excel()
    Dim excRng As Excel.Range, arrTmp As Variant, intCnt As Integer
    If Not bolSkp Then
        If MsgBox("Should I sync tasks from Outlook?", vbQuestion + vbYesNo, PROC_NAME) = vbYes Then
            For intCnt = olkFld.Items.Count To 1 Step -1
                Set olkTsk = olkFld.Items(intCnt)
                Set olkPrp = olkTsk.UserProperties.Find("ExcelTaskList", True)
                If TypeName(olkPrp) = "Nothing" Then
                    'The task does not exist in the spreadsheet.  Add it.
                    lngRow = excWks.UsedRange.Rows.Count + 1
                    With olkTsk
                        If InStr(1, .Subject, "/") > 0 Then
                            arrTmp = Split(.Subject, "/")
                            excWks.Cells(lngRow, EXC_CLIENT) = arrTmp(0)
                            excWks.Cells(lngRow, EXC_SUBJECT) = arrTmp(1)
                        Else
                            excWks.Cells(lngRow, EXC_CLIENT) = "Select Client"
                            excWks.Cells(lngRow, EXC_SUBJECT) = .Subject
                        End If
                        If .StartDate <> #1/1/4501# Then
                            excWks.Cells(lngRow, EXC_START) = .StartDate
                            excWks.Cells(lngRow, EXC_START).NumberFormat = "[$-409]d-mmm;@"
                        End If
                        Select Case .Status
                            Case olTaskComplete
                                excWks.Cells(lngRow, EXC_STATUS) = "Complete"
                            Case olTaskDeferred
                                excWks.Cells(lngRow, EXC_STATUS) = "Deferred"
                            Case olTaskInProgress
                                excWks.Cells(lngRow, EXC_STATUS) = "In Progress"
                            Case olTaskNotStarted
                                excWks.Cells(lngRow, EXC_STATUS) = "Not Started"
                            Case olTaskWaiting
                                excWks.Cells(lngRow, EXC_STATUS) = "Waiting"
                        End Select
                        If .DueDate <> #1/1/4501# Then
                            excWks.Cells(lngRow, EXC_DUE) = .DueDate
                            excWks.Cells(lngRow, EXC_DUE).NumberFormat = "[$-409]ddd, mmm. d;@"
                        End If
                        excWks.Cells(lngRow, EXC_EID) = .EntryID
                        .UserProperties.Add "ExcelTaskList", olYesNo, True
                        .UserProperties.Item("ExcelTaskList").Value = True
                        .UserProperties.Add "Synced", olText
                        .UserProperties.Item("Synced").Value = strRun
                        .Save
                    End With
                Else
                    If olkTsk.UserProperties.Item("Synced").Value > olkTsk.LastModificationTime Then
                        For lngRow = 2 To excWks.UsedRange.Rows.Count
                            If excWks.Cells(lngRow, EXC_EID) = olkTsk.EntryID Then Exit For
                        Next
                        If lngRow >= 2 And lngRow <= excWks.UsedRange.Rows.Count Then
                            With olkTsk
                                If InStr(1, .Subject, "/") > 0 Then
                                    arrTmp = Split(.Subject, "/")
                                    excWks.Cells(lngRow, EXC_CLIENT) = arrTmp(0)
                                    excWks.Cells(lngRow, EXC_SUBJECT) = arrTmp(1)
                                Else
                                    excWks.Cells(lngRow, EXC_CLIENT) = "Select Client"
                                    excWks.Cells(lngRow, EXC_SUBJECT) = .Subject
                                End If
                                If .StartDate <> #1/1/4501# Then excWks.Cells(lngRow, EXC_START) = .StartDate
                                Select Case .Status
                                    Case olTaskComplete
                                        excWks.Cells(lngRow, EXC_STATUS) = "Complete"
                                    Case olTaskDeferred
                                        excWks.Cells(lngRow, EXC_STATUS) = "Deferred"
                                    Case olTaskInProgress
                                        excWks.Cells(lngRow, EXC_STATUS) = "In Progress"
                                    Case olTaskNotStarted
                                        excWks.Cells(lngRow, EXC_STATUS) = "Not Started"
                                    Case olTaskWaiting
                                        excWks.Cells(lngRow, EXC_STATUS) = "Waiting"
                                End Select
                                If .DueDate <> #1/1/4501# Then excWks.Cells(lngRow, EXC_DUE) = .DueDate
                                .UserProperties.Item("Synced").Value = strRun
                                .Save
                            End With
                        Else
                            MsgBox "Critical problem.  There was no match in the spreadsheet for the task" & vbCrLf & vbTab & olkTsk.Subject, vbCritical + vbOKOnly, PROC_NAME
                        End If
                    End If
                End If
            Next
            On Error Resume Next
            For lngRow = excWks.UsedRange.Rows.Count To 2 Step -1
                If excWks.Cells(lngRow, EXC_EID) <> "" Then
                    Set olkTsk = olkSes.GetItemFromID(excWks.Cells(lngRow, EXC_EID))
                    Debug.Print excWks.Cells(lngRow, EXC_SUBJECT)
                    If (TypeName(olkTsk) = "Nothing") Or (olkTsk.Parent.Name = "Deleted Items") Then
                        Set excRng = excWks.Range("A" & lngRow, "Z" & lngRow)
                        excRng.Delete xlShiftUp
                    End If
                End If
                Set olkTsk = Nothing
            Next
            On Error GoTo 0
        End If
    End If
End Sub

Public Sub ForceExcel2Close()
    Dim varDesktop As Variant
    varDesktop = OpenInputDesktop(0, False, DESKTOP_READOBJECTS)
    'varDesktop will be 0 if the screen is locked, non-zero if it is not.
    If varDesktop = 0 Then
        bolSkp = True
        ThisWorkbook.Save
        CreateScriptFile
        RunScriptFile
    End If
End Sub

Sub CreateScriptFile()
    Dim objFSO As Object, objFil As Object
    Set objFSO = CreateObject("Scripting.FileSystemobject")
    Set objFil = objFSO.CreateTextFile(Environ("TMP") & "\CloseExcel.vbs", True)
    With objFil
        .WriteLine "WScript.Sleep 5000"
        .WriteLine "Set excApp = GetObject(,""Excel.Application"")"
        .WriteLine "excApp.Quit"
        .WriteLine "Set excApp = Nothing"
        .Close
    End With
    Set objFSO = Nothing
    Set objFil = Nothing
End Sub

Sub RunScriptFile()
    Dim objShl As Object
    Set objShl = CreateObject("WScript.Shell")
    objShl.Run Environ("TMP") & "\CloseExcel.vbs", 0, False
    Set objShl = Nothing
End Sub

Comment: From the described behavior, a "refresh" without changing the content triggers a `Change` event. To circumvent this you might consider reading the status (col D) on `workbook_open`, and store it in a variable. Then allow the refresh, and look for differences with the initial value. It's a hack. Would it help?
Comment: Hi Floris, thanks for the comment. I'm open to anything at this point, but I don't have enuogh savvy to fully follow what you're saying. How do I store the data in Column D as a variable?
Comment: I have created a small working example - see my answer below.
Comment: In the process of updating, you have "lost" the original `Workbook_SheetChange()` event code. Consider putting it back for completeness...
Answer: The following code implements the idea I talked about in my comment:

Keep a copy of the data that you consider "unchanged", and when the
  SheetChange event fires, compare the actual new value against the
  reference. If the two values are not the same, take the action you
  wanted to take.

EDITED Based on the first version of the code not working for your, I suspect that the refresh happens before the workbook_open event fires. To get around this, I have created a new variant, initialized, which will initially be empty (no value assigned to it). When the SheetChange event fires, it checks the state of this variable: if it is empty, it knows to do the initializing of the colStore before running the rest of the code. That ought to solve the problem. Otherwise the way this macro works is unchanged:
By keeping a copy of the data "before we messed with it" in memory, you prevent "updates" of the time stamp if the value didn't actually change.
It worked for a simple test case - when I "edit" a cell but put the same value back in, the "change" event is fired, but the date stamp is not updated.
Let me know if any of this needs further explanation.
Option Explicit
Dim colStore
Dim initialized
Const colOfInterest = "D2:D1000" ' make this the column you want to be active on
Dim rowOne As Integer

Private Sub Workbook_Open()
  If IsEmpty(initialized) Then
    MsgBox "opening workbook. Nothing has been initialized yet"
    initializeIt
  End If
End Sub

Private Sub initializeIt()
  colStore = Range(colOfInterest).Value
  rowOne = Range(colOfInterest).Cells(1).Row
  initialized = True
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim tempAddress
On Error GoTo leaveSub

If IsEmpty(initialized) Then
  MsgBox "fired sheet_change before workbook_open!"
  initializeIt
End If

With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(Range(colOfInterest), .Cells) Is Nothing Then
            Application.EnableEvents = False
            If IsEmpty(.Value) Then
                .Offset(0, 2).ClearContents
            Else
                ' see if value actually changed
                tempAddress = .Row
                If .Value = colStore(.Row - rowOne + 1, 1) Then
                Else
                  colStore(.Row - rowOne + 1, 1) = .Value ' update the store
                  ' update the date:
                  With .Offset(0, 2)
                    .NumberFormat = "mmm, d, h:mm:ss AM/PM"
                    .Value = Now
                  End With
                End If
            End If
        End If
    End With
leaveSub:
  Application.EnableEvents = True

End Sub

SECOND EDIT Based on the code you have given, I think the following "code merge" should produce something that works. I cannot test it - but let me know if this works for you, or if you still have problems. There are some TEST MESSAGEs in here - take them out after everything works (they just help confirm that program flow is correct). Put all this code in the Workbook module:
Option Explicit
Dim colStore
Dim initialized
Const colOfInterest = "D2:D1000" ' make this the column you want to be active on
Dim rowOne As Integer

'--> Declare some constants
'Edit the constants below as needed so they correctly reflect the column number they appear in in the spreadsheet'
Const EXC_CLIENT = 1
Const EXC_SUBJECT = 2
Const EXC_START = 5
Const EXC_STATUS = 4
Const EXC_DUE = 8
Const EXC_EID = 26
Const PROC_NAME = "Outlook Synchronization"
'Do not change any constants from this point on
Const olTaskNotStarted = 0
Const olTaskInProgress = 1
Const olTaskComplete = 2
Const olTaskWaiting = 3
Const olTaskDeferred = 4
Const olText = 1
Const olYesNo = 6
Const olFolderTasks = 13
Const DESKTOP_READOBJECTS = &H1&

'--> Declare some variables
Dim olkApp As Object, _
    olkSes As Object, _
    olkFld As Object, _
    olkTsk As Object, _
    olkPrp As Object, _
    excWks As Excel.Worksheet, _
    lngRow As Long, _
    strRun As String, _
    bolSkp As Boolean

Private Sub InitializeExcel()
    Set excWks = Application.ActiveWorkbook.Sheets(1)
    lngRow = 2
    strRun = Format(Now, "yyyy-mm-dd-hh-nn-ss")
End Sub

Private Sub DeactivateExcel()
    Set excWks = Nothing
End Sub

Private Sub InitializeOutlook()
    Set olkApp = CreateObject("Outlook.Application")
    Set olkSes = olkApp.GetNamespace("MAPI")
    olkSes.Logon olkApp.DefaultProfileName
    Set olkFld = olkSes.GetDefaultFolder(olFolderTasks)
End Sub

Private Sub DeactivateOutlook()
    olkSes.Logoff
    Set olkFld = Nothing
    Set olkSes = Nothing
    Set olkApp = Nothing
End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    '--> On saving the workbook you will be given an opportunity to synchronize from Excel to Outlook
    InitializeExcel     'Prep Excel for a sync
    InitializeOutlook   'Prep Outlook for a sync
    Excel2Outlook       'Sync from Excel to Outlook
    DeactivateExcel     'Clean-up Excel
    DeactivateOutlook   'Clean-up Outlook
End Sub

Private Sub Workbook_Open()
'--> Adding a few lines of code to capture the "current status"
'--> before anything gets updated / refreshed
If IsEmpty(initialized) Then
    MsgBox "TEST MESSAGE. Opening workbook. Nothing has been initialized yet."
    initializeIt
  End If
'--> On opening the workbook you will be given an opportunity to syncronize data from Outlook to Excel
    bolSkp = False      'Set this to True if you don't want to be prompted to run the sync when opening/closing the spreadsheet.
    InitializeExcel     'Prep Excel for a sync
    InitializeOutlook   'Prep Outlook for a sync
    Outlook2Excel       'Sync from Outlook to Excel
    DeactivateExcel     'Clean-up Excel
    DeactivateOutlook   'Clean-up Outlook
End Sub

Private Sub Excel2Outlook()
    If Not bolSkp Then
        If MsgBox("Should I sync the tasks to Outlook?", vbQuestion + vbYesNo, PROC_NAME) = vbYes Then
            Do Until excWks.Cells(lngRow, 1) = ""
                Select Case excWks.Cells(lngRow, EXC_EID)
                    Case ""
                        Set olkTsk = olkFld.Items.Add()
                        With olkTsk
                            .UserProperties.Add "ExcelTaskList", olYesNo, True
                            .UserProperties.Item("ExcelTaskList").Value = True
                            .UserProperties.Add "Synced", olText
                            .UserProperties.Item("Synced").Value = strRun
                            .Save
                        End With
                        excWks.Cells(lngRow, EXC_EID) = olkTsk.EntryID
                    Case Else
                        Set olkTsk = olkSes.GetItemFromID(excWks.Cells(lngRow, EXC_EID))
                End Select
                With olkTsk
                    .Subject = excWks.Cells(lngRow, EXC_CLIENT) & "/" & excWks.Cells(lngRow, EXC_SUBJECT)
                    If IsDate(excWks.Cells(lngRow, EXC_START)) Then .StartDate = excWks.Cells(lngRow, EXC_START)
                    If IsDate(excWks.Cells(lngRow, EXC_DUE)) Then .DueDate = excWks.Cells(lngRow, EXC_DUE)
                    Select Case excWks.Cells(lngRow, EXC_STATUS)
                        Case "Complete"
                            .Status = olTaskComplete
                        Case "Deferred"
                            .Status = olTaskDeferred
                        Case "In Progress"
                            .Status = olTaskInProgress
                        Case "Not Started"
                            .Status = olTaskNotStarted
                        Case "Waiting"
                            .Status = olTaskWaiting
                    End Select
                    olkTsk.UserProperties.Item("Synced").Value = strRun
                    .Save
                End With
                lngRow = lngRow + 1
            Loop
            For lngRow = olkFld.Items.Count To 1 Step -1
                Set olkTsk = olkFld.Items(lngRow)
                Set olkPrp = olkTsk.UserProperties.Find("ExcelTaskList", True)
                If TypeName(olkPrp) <> "Nothing" Then
                    If olkTsk.UserProperties.Item("Synced").Value < strRun Then
                        olkTsk.Delete
                    End If
                End If
            Next
        End If
    End If
End Sub

Private Sub Outlook2Excel()
    Dim excRng As Excel.Range, arrTmp As Variant, intCnt As Integer
    If Not bolSkp Then
        If MsgBox("Should I sync tasks from Outlook?", vbQuestion + vbYesNo, PROC_NAME) = vbYes Then
            For intCnt = olkFld.Items.Count To 1 Step -1
                Set olkTsk = olkFld.Items(intCnt)
                Set olkPrp = olkTsk.UserProperties.Find("ExcelTaskList", True)
                If TypeName(olkPrp) = "Nothing" Then
                    'The task does not exist in the spreadsheet.  Add it.
                    lngRow = excWks.UsedRange.Rows.Count + 1
                    With olkTsk
                        If InStr(1, .Subject, "/") > 0 Then
                            arrTmp = Split(.Subject, "/")
                            excWks.Cells(lngRow, EXC_CLIENT) = arrTmp(0)
                            excWks.Cells(lngRow, EXC_SUBJECT) = arrTmp(1)
                        Else
                            excWks.Cells(lngRow, EXC_CLIENT) = "Select Client"
                            excWks.Cells(lngRow, EXC_SUBJECT) = .Subject
                        End If
                        If .StartDate <> #1/1/4501# Then
                            excWks.Cells(lngRow, EXC_START) = .StartDate
                            excWks.Cells(lngRow, EXC_START).NumberFormat = "[$-409]d-mmm;@"
                        End If
                        Select Case .Status
                            Case olTaskComplete
                                excWks.Cells(lngRow, EXC_STATUS) = "Complete"
                            Case olTaskDeferred
                                excWks.Cells(lngRow, EXC_STATUS) = "Deferred"
                            Case olTaskInProgress
                                excWks.Cells(lngRow, EXC_STATUS) = "In Progress"
                            Case olTaskNotStarted
                                excWks.Cells(lngRow, EXC_STATUS) = "Not Started"
                            Case olTaskWaiting
                                excWks.Cells(lngRow, EXC_STATUS) = "Waiting"
                        End Select
                        If .DueDate <> #1/1/4501# Then
                            excWks.Cells(lngRow, EXC_DUE) = .DueDate
                            excWks.Cells(lngRow, EXC_DUE).NumberFormat = "[$-409]ddd, mmm. d;@"
                        End If
                        excWks.Cells(lngRow, EXC_EID) = .EntryID
                        .UserProperties.Add "ExcelTaskList", olYesNo, True
                        .UserProperties.Item("ExcelTaskList").Value = True
                        .UserProperties.Add "Synced", olText
                        .UserProperties.Item("Synced").Value = strRun
                        .Save
                    End With
                Else
                    If olkTsk.UserProperties.Item("Synced").Value > olkTsk.LastModificationTime Then
                        For lngRow = 2 To excWks.UsedRange.Rows.Count
                            If excWks.Cells(lngRow, EXC_EID) = olkTsk.EntryID Then Exit For
                        Next
                        If lngRow >= 2 And lngRow <= excWks.UsedRange.Rows.Count Then
                            With olkTsk
                                If InStr(1, .Subject, "/") > 0 Then
                                    arrTmp = Split(.Subject, "/")
                                    excWks.Cells(lngRow, EXC_CLIENT) = arrTmp(0)
                                    excWks.Cells(lngRow, EXC_SUBJECT) = arrTmp(1)
                                Else
                                    excWks.Cells(lngRow, EXC_CLIENT) = "Select Client"
                                    excWks.Cells(lngRow, EXC_SUBJECT) = .Subject
                                End If
                                If .StartDate <> #1/1/4501# Then excWks.Cells(lngRow, EXC_START) = .StartDate
                                Select Case .Status
                                    Case olTaskComplete
                                        excWks.Cells(lngRow, EXC_STATUS) = "Complete"
                                    Case olTaskDeferred
                                        excWks.Cells(lngRow, EXC_STATUS) = "Deferred"
                                    Case olTaskInProgress
                                        excWks.Cells(lngRow, EXC_STATUS) = "In Progress"
                                    Case olTaskNotStarted
                                        excWks.Cells(lngRow, EXC_STATUS) = "Not Started"
                                    Case olTaskWaiting
                                        excWks.Cells(lngRow, EXC_STATUS) = "Waiting"
                                End Select
                                If .DueDate <> #1/1/4501# Then excWks.Cells(lngRow, EXC_DUE) = .DueDate
                                .UserProperties.Item("Synced").Value = strRun
                                .Save
                            End With
                        Else
                            MsgBox "Critical problem.  There was no match in the spreadsheet for the task" & vbCrLf & vbTab & olkTsk.Subject, vbCritical + vbOKOnly, PROC_NAME
                        End If
                    End If
                End If
            Next
            On Error Resume Next
            For lngRow = excWks.UsedRange.Rows.Count To 2 Step -1
                If excWks.Cells(lngRow, EXC_EID) <> "" Then
                    Set olkTsk = olkSes.GetItemFromID(excWks.Cells(lngRow, EXC_EID))
                    Debug.Print excWks.Cells(lngRow, EXC_SUBJECT)
                    If (TypeName(olkTsk) = "Nothing") Or (olkTsk.Parent.Name = "Deleted Items") Then
                        Set excRng = excWks.Range("A" & lngRow, "Z" & lngRow)
                        excRng.Delete xlShiftUp
                    End If
                End If
                Set olkTsk = Nothing
            Next
            On Error GoTo 0
        End If
    End If
End Sub

Public Sub ForceExcel2Close()
    Dim varDesktop As Variant
    varDesktop = OpenInputDesktop(0, False, DESKTOP_READOBJECTS)
    'varDesktop will be 0 if the screen is locked, non-zero if it is not.
    If varDesktop = 0 Then
        bolSkp = True
        ThisWorkbook.Save
        CreateScriptFile
        RunScriptFile
    End If
End Sub

Sub CreateScriptFile()
    Dim objFSO As Object, objFil As Object
    Set objFSO = CreateObject("Scripting.FileSystemobject")
    Set objFil = objFSO.CreateTextFile(Environ("TMP") & "\CloseExcel.vbs", True)
    With objFil
        .WriteLine "WScript.Sleep 5000"
        .WriteLine "Set excApp = GetObject(,""Excel.Application"")"
        .WriteLine "excApp.Quit"
        .WriteLine "Set excApp = Nothing"
        .Close
    End With
    Set objFSO = Nothing
    Set objFil = Nothing
End Sub

Sub RunScriptFile()
    Dim objShl As Object
    Set objShl = CreateObject("WScript.Shell")
    objShl.Run Environ("TMP") & "\CloseExcel.vbs", 0, False
    Set objShl = Nothing
End Sub

'--> And the other functions (that initialize the data store, and update status
Private Sub initializeIt()
  colStore = Range(colOfInterest).Value
  rowOne = Range(colOfInterest).Cells(1).Row
  initialized = True
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim tempAddress
On Error GoTo leaveSub

If IsEmpty(initialized) Then
  MsgBox "fired sheet_change before workbook_open!"
  initializeIt
End If

With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(Range(colOfInterest), .Cells) Is Nothing Then
            Application.EnableEvents = False
            If IsEmpty(.Value) Then
                .Offset(0, 2).ClearContents
            Else
                ' see if value actually changed
                tempAddress = .Row
                If .Value = colStore(.Row - rowOne + 1, 1) Then
                Else
                  colStore(.Row - rowOne + 1, 1) = .Value ' update the store
                  ' update the date:
                  With .Offset(0, 2)
                    .NumberFormat = "mmm, d, h:mm:ss AM/PM"
                    .Value = Now
                  End With
                End If
            End If
        End If
    End With
leaveSub:
  Application.EnableEvents = True

End Sub

Third (and last?) edit Updated code to allow multiple columns to be "tracked". This is quite a bit more general; in order to keep things simple I am posting just the functions that changed - replace them in the above code, and it should work for both columns D and J. If you look at the comments it's easy to see what you would have to modify if you want different behavior.
Option Explicit
Dim colStore
Dim initialized
' two strings that contain the columns and range of rows we want to track:
' columnsOfInterest_string could contain any number of comma-separated columns
' but rowsOfInterest_string must contain just two: first and last row
Const columnsOfInterest_string = "D,J"
Const rowsOfInterest_string = "2,1000"

' a few variables that get initialized when workbook is first opened
Dim rowsOfInterest
Dim colLookupTable
Dim rangeOfInterest As Range

Private Sub Workbook_Open()
  If IsEmpty(initialized) Then
'    MsgBox "opening workbook. Nothing has been initialized yet"
    initializeIt
  End If
End Sub

Private Sub testIt()
  Dim r1, r2, ra, rd, rad
  Dim vals, valUnion, valBlock
  ra = "A1:A5"
  rd = "D1:D5"
  rad = ra & "," & rd
  Debug.Print rad
  Set r1 = Range("A1:A5")
  Set r2 = Range("D1:D5")
  vals = Range(rad).Value
  valUnion = Union(r1, r2).Value
  valBlock = Range("A1:D5").Value
End Sub

Private Sub initializeIt()
' copy the data from the relevant ranges to a variable
' if the cell contents don't change, don't update the time stamp
  Dim thisCol, rangeAddress, cList, rRange
  Dim nRows, nCols, c, ci, ri

  ' create a "dictionary" to go from "column name" to "column index in stored array"
  Set colLookupTable = CreateObject("Scripting.Dictionary")
  ' get the list of columns as an array:
  cList = Split(columnsOfInterest_string, ",")
  nCols = UBound(cList) + 1 ' since Option Base 0

  rowsOfInterest = Split(rowsOfInterest_string, ",") ' should be just two numbers
  nRows = Val(rowsOfInterest(1)) - Val(rowsOfInterest(0)) + 1

  ' create a string with the address of the entire range of interest:
  rangeAddress = ""
  ci = 1
  For Each c In cList
    thisCol = c & rowsOfInterest(0) & ":" & c & rowsOfInterest(1)
    colLookupTable.Add c, ci    ' create lookup for index into the array
    rangeAddress = rangeAddress & thisCol & ","
    ci = ci + 1
  Next c
  rangeAddress = Left(rangeAddress, Len(rangeAddress) - 1)
  Set rangeOfInterest = Range(rangeAddress)
  ' get all the data from the complete range and store it
  colStore = ToArray(rangeOfInterest)
  initialized = True
End Sub

Function ToArray(rng) As Variant()
' With thanks to Tim Williams of StackOverflow.com
' answer http://stackoverflow.com/a/18994211/1967396

Dim arr() As Variant, r As Long, nr As Long
    Dim ar As Range, c As Range, cnum As Long, rnum As Long
    Dim col As Range

    nr = rng.Areas(1).Rows.Count
    ReDim arr(1 To nr, 1 To rng.Cells.Count / nr)
    cnum = 0
    For Each ar In rng.Areas
        For Each col In ar.Columns
        cnum = cnum + 1
        rnum = 1
        For Each c In col.Cells
            arr(rnum, cnum) = c.Value
            rnum = rnum + 1
        Next c
        Next col
    Next ar

    ToArray = arr
End Function

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim tempAddress, colOfInterest
On Error GoTo leaveSub

If IsEmpty(initialized) Then
'  MsgBox "fired sheet_change before workbook_open!"
  initializeIt
End If

With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(rangeOfInterest, .Cells) Is Nothing Then
            Application.EnableEvents = False
            If IsEmpty(.Value) Then
                .Offset(0, 2).ClearContents
            Else
                ' see if value actually changed
                tempAddress = Split(Target.Address, "$")
                colOfInterest = colLookupTable(tempAddress(1))
                If .Value = colStore(.Row - rowsOfInterest(0) + 1, colOfInterest) Then
                Else
                  colStore(.Row - rowsOfInterest(0) + 1, colOfInterest) = .Value ' update the store
                  ' update the date:
                  With .Offset(0, 2)
                    .NumberFormat = "mmm, d, h:mm:ss AM/PM"
                    .Value = Now
                  End With
                End If
            End If
        End If
    End With
leaveSub:
  Application.EnableEvents = True

End Sub

Comment: Wait! I removed my original time stamp code from the worksheet (Page 1), and now it seems to be working! By Jove, Floris--I think you've done it! 1000 thank you's!
Comment: Thank you very much for your help, but it's not yet working, though it could be a problem with my implementation. Below is the code for the worksheet, including a calendar module I'm using:
Comment: Hmmm, it won't let me post my code in the comment section due to character limit, and it won't let me post by "Answering my own question". Apologies, this is my first time working with stackoverflow and I am bumbling a bit!
Comment: it's still refreshing/overwriting the timestamp when I open the workbook (which automatically syncs it with Outlook). If there was a way for me to attach my file to present a better understanding I would but it doesn't seem to be an option on StackOverflow. I appreciate your willingness to help but I have a feeling my abilities are too nascent to take your help and implement it! Thank you nonetheless.
Comment: Don't worry! You can add your code by editing your own question. I suspect (this was my worry) that Excel does the refresh before firing the "workbook_open" event. I have modified my code above - you should see one of two messages when the workbook first opens. It you get the "fired sheet_change before workbook_open" message we will know we found (and fixed...?) the issue. Let me know how it goes.  PS - this code needs to be in the Workbook code module, but I think you already know that (otherwise you would not get any event processing).
Comment: Eeek! I was not aware it belongs in the workbook code. When I said my abilities were nascent I was being charitable. When I add your code to the bottom of the existing code in the Workbook, the Option Explicit becomes nested in the Private Sub above it and separated from your code above; when I add it to the top, it seems to interfere with the pre-existing "Declaration of constants". I will revise my original post with the pre-existing code from the workbook. Please let me know if this is where your code belongs, and if it should go above or below it. Apologies for my ineptitude!
Comment: "Option Explicit" is good programming practice and belongs at the top of every module. It ensures that you declare all your variables - and will warn you (sometimes) about mistyped variable names (since they were probably not declared). Recognize that you can only have one Workbook_Open and Workbook_SheetChange sub in this module - so if you are doing other things as well you need to do some merging. Once you post your code I can help more.
Comment: Updated code - can't test this now since I don't have your data etc; let me know if this works.
Comment: The empty-check approach is better anyway, as it will also correctly handle a code reset.
Comment: @RBarryYoung thanks. Right now the challenge is to get the code into OP's workbook correctly...
Comment: @Floris so appreciative of the help. I wiped out the code in the Workbook module and pasted in your modified code above. When I open the file, I get your Test Message first, then I'm prompted to sync, and when I do it still cascades the time stamp column with the current date/time overwriting the time stamp from before. One quick question--you keep referencing the workbook "module". To be clear, I am posting this in the "ThisWorkbook" page under Excel Objects. I do have another folder called "Modules", and in it is "Module1", but that only contains a small piece of code for my pop-up calendar
Comment: Two little questions then I will close this case and, if I may, send you an Amazon gift card. 1) to remove the Test Message, what line should I delete from the code? 2) If i wanted the time stamp to fire not just when the data changed in column D, but when the data changed in columns B, D or J--is that a matter of adding a range to the Option Explicit at the top of the code? If I'm pressing my luck just send me packing and I will be quite happy.
Comment: No worries. The `const colOfInterest` describes the range you look for; but right now the code thinks it is all in one column. If you want to look at multiple columns it will take a little bit more work - especially when they are not contiguous. Can't update the code with that tonight, sorry. As for the messages - just put an apostrophe in front of the line that starts `MsgBox` and it will go away. You can't send me a gift card - but you can "pay it forward" by looking at other questions and seeing if there are any you can answer. Appreciate the positive feedback! Glad to help.
Comment: Understood. I will expand my macro knowledge (VBA for Dummies, maybe) and try to return the favor to another in need. And in terms of my request, forget Column B. Columns D and J and the ones. I know I'm asking a lot so I will try to keep my promise to pay it forward...
Comment: I noticed that you had declared some constants that correspond to specific column numbers - `EXC_STATUS = 4` for example, corresponding to column `D`. I don't see a constant corresponding to column `J` (would be `10`). If the columns you want to "track" have an associated number I know a way to extend this solution. I could hard code the number - it would be better to use the defined constants. What would column `J` be called?
Comment: I would call Column J "Notes" to keep things simple.
Comment: I have made an edit that shows how to extend this to multiple columns. Let me know how that goes!
Comment: Implemented your new code. Going well. Only hitch is when I update column J it time-stamps in column L instead of Column F (looking to have both triggers timestamp in same column). So just need to offset time stamp target for Column J by -4...trying to figure out how to do it...
Comment: Instead of `with .Offset(0,2)` using `with Cells(.Row, 6)` ought to work. I think- on iPhone can't check.
Comment: All seems to be working well. Thank you @Floris Truly appreciative of your help.
Comment: Glad to hear it. You might want to mark the answer as "accepted" using the check mark alongside it. Good luck on your learning journey!


Tuning SVM parameters in R

Question: I am training an SVM model for the classification of the variable V19 within my dataset.
I have done a pre-processing of the data, in particular I have used MICE to impute some missing data.
Anyway a part of the training dataset I use is this one:

Through the "tune" function I tried to train looking for the best parameters through cross-validation;
tune.out <- tune(svm, hard~., data=train, kernel="sigmoid",type="C",decision.values =TRUE,scaled =TRUE, ranges=list(cost=2^(-3:2),gamma=2^(-25:1),coef0=1^(-15:5)),tunecontrol = tune.control(nrepeat = 5, sampling = "cross", cross = 5))

I tried many combinations of parameters and different kernels, but what I get is always a model that can not predict correctly even the same training data, always returns all outputs to FALSE.
I really don't know if it's just a problem of tuning parameters or if I managed wrong the dataset.
Thanks for any advice.
EDIT : @Alex H I tried your code and what I obtain is :
Support Vector Machines with Radial Basis Function Kernel
1094 samples
  18 predictor
   2 classes: 'X1', 'X2'

Pre-processing: centered (18), scaled (18)
Resampling: Cross-Validated (10 fold, repeated 5 times)
Summary of sample sizes: 985, 985, 985, 985, 984, 984, ...
Resampling results across tuning parameters:

  C     ROC        Sens    Spec
  0.25  0.5241539  0.9996  0
  0.50  0.5320540  1.0000  0
  1.00  0.5066151  0.9994  0
  2.00  0.5225485  1.0000  0
  4.00  0.5130391  1.0000  0

Tuning parameter 'sigma' was held constant at a value of 0.04595822
ROC was used to select the optimal model using the largest value.
The final values used for the model were sigma = 0.04595822 and C = 0.5.

Answer: Try using the caret package.
library(caret)
set.seed(12345)

#Create simulation data
topxdata = matrix(rnorm(200, mean=0, sd=1), nrow = 20, ncol = 10)
botxdata = matrix(rnorm(200, mean=1, sd=1), nrow = 20, ncol = 10)
xdata = rbind(topxdata, botxdata)
colnames(xdata) = 1:10

ydata = c(rep("Top", 20), rep("Bottom", 20) )
ydata = as.factor(ydata)

# Setup for cross validation
ctrl <- trainControl(method="repeatedcv",   # 10fold cross validation
                     repeats=5,         # do 5 repetitions of cv
                     summaryFunction=twoClassSummary,   # Use AUC to pick the best model
                     classProbs=TRUE)

#Train and Tune the SVM
svm.tune <- train(x=xdata,
                  y= ydata,
                  method = "svmRadial",   # Radial kernel
                  tuneLength = 5,                   # 5 values of the cost function
                  preProc = c("center","scale"),  # Center and scale data
                  metric="ROC",
                  trControl=ctrl)

svm.tune

Post your result
Support Vector Machines with Radial Basis Function Kernel

40 samples
10 predictors
 2 classes: 'Bottom', 'Top'

Pre-processing: centered (10), scaled (10)
Resampling: Cross-Validated (10 fold, repeated 5 times)
Summary of sample sizes: 36, 36, 36, 36, 36, 36, ...
Resampling results across tuning parameters:

  C     ROC    Sens  Spec
  0.25  0.980  0.85  0.91
  0.50  0.975  0.85  0.90
  1.00  0.955  0.83  0.88
  2.00  0.945  0.82  0.84
  4.00  0.945  0.81  0.77

Tuning parameter 'sigma' was held constant at a value of 0.06064355
ROC was used to select the optimal model using the largest value.
The final values used for the model were sigma = 0.06064355 and C = 0.25.
```

Comment: Thanks for the advice.
Comment: Even with this solution I always obtain FALSE as prediction
Comment: @Marts your ROC values are basically 0.5, and your specificity=0. This means the classifier isn't able to distinguish the two classes. Try a different classifier (e.g. change to method = "rf"). If that doesn't work you might have to collect more data.
Comment: thanks. I tried svmRadialWeights and I obtain some results, now I'm playing with parameters. I have to use SVM for this homework, maybe I will try sigmoid kernel, but in Caret I didn't find it as method.

Tuning SVM parameters in R


Python: Finding files in directory but ignoring folders and their contents

Question: So my program search_file.py is trying to look for .log files in the directory it is currently placed in. I used the following code to do so:
import os

# This is to get the directory that the program is currently running in
dir_path = os.path.dirname(os.path.realpath(__file__))

# for loop is meant to scan through the current directory the program is in
for root, dirs, files in os.walk(dir_path):
    for file in files:
        # Check if file ends with .log, if so print file name
        if file.endswith('.log')
            print(file)

My current directory is as follows:
search_file.py
sample_1.log
sample_2.log
extra_file (this is a folder)
And within the extra_file folder we have:
extra_sample_1.log
extra_sample_2.log
Now, when the program runs and prints the files out it also takes into account the .log files in the extra_file folder. But I do not want this. I only want it to print out sample_1.log and sample_2.log. How would I approach this?
Answer: Try this:
import os

files = os.listdir()

for file in files:
    if file.endswith('.log'):
        print(file)

The problem in your code is os.walk traverses the whole directory tree and not just your current directory. os.listdir returns a list of all filenames in a directory with the default being your current directory which is what you are looking for.
os.walk documentation
os.listdir documentation
Answer: By default, os.walk does a root-first traversal of the tree, so you know the first emitted data is the good stuff. So, just ask for the first one. And since you don't really care about root or dirs, use _ as the "don't care" variable name
# get root files list.
_, _, files = next(os.walk(dir_path))
for file in files:
    # Check if file ends with .log, if so print file name
    if file.endswith('.log')
        print(file)

Its also common to use glob:
from glob import glob
dir_path = os.path.dirname(os.path.realpath(__file__))
for file in glob(os.path.join(dir_path, "*.log")):
    print(file)

This runs the risk that there is a directory that ends in ".log", so you could also add a testing using os.path.isfile(file).


How to open Visual Studio Code from the command line on RHEL?

Question: I would like to open VSCode from my RHEL terminal using the code command but when I try to type Shell Command: Install 'code' command in PATH directly in VSCode Command Palette, it indicates that No matching command is found. Is there a way to configure $PATH directly via the command line to make code work?
Comment: Does this answer your question? [How to permanently set $PATH on Linux/Unix](https://stackoverflow.com/questions/14637979/how-to-permanently-set-path-on-linux-unix)
Comment: Try `/usr/local/bin/code`. if it working, set PATH: `PATH="$PATH:/usr/local/bin"`. To make it permanently, write is to your `.bash_profile`
Comment: @ExDoors I tried to see ```/usr/local/bin/code``` and its does not exist
Answer: Finally what worked for me was to run the following commands :
sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc

dnf check-update

sudo dnf install code


Is the rational span countable?

Question: Let $\{x_n\}_{n\in\mathbb{N}}$ be a subset of an arbitrary vector space. Is the $span_\mathbb{Q} \{x_n\}_{n\in\mathbb{N}}$ countable?
I know that unions over countable index sets are countable and tried to write:
$$span_\mathbb{Q} \{x_n\}_{n\in\mathbb{N}} = \left\{ \sum_{i=1}^m \lambda_ix_i | m\in \mathbb{N}, x_i\in\{x_n\}_{n\in\mathbb{N}}, \lambda_i\in \mathbb{Q}  \right\}\\
= \bigcup_{n\in\mathbb{N}} \bigcup_{\{x_i\}_{i=1}^m \subset\{x_n\}_{n\in\mathbb{N}}} \bigcup_{\{\lambda_j\}_{j=1}^m \subset \mathbb{Q}} \left\{ \sum_{i=1}^m \lambda_ix_i\right\}.$$
I don't know if the last two unions are formed over a countable index sets. Does may be anyone has an idea or can give me reference for this? Thanks in advance.
Edit: For completeness: We need a theorem which states that all finite sequences with entries form a countable set are countable. This is Theorem V.2.8, P.171 in Kazimierz Kuratowski and Andrzej Mostowski, Set theory: with an introduction to descriptive set theory, 2., compl. rev. ed., Studies in Logicand the Foundations of Mathematics V. 86, North-Holland PublishingCompany, Amsterdam, New York, Oxford, 1976 (eng)
Answer: Each of your unions is indeed over a countable index set

the naturals, naturally
the finite subsets (in your case, of fixed cardinality $m$) of $\{x_i\}_{i\in \Bbb N}$, or equivalently of $\Bbb N$
$\Bbb Q^m$
Answer: Yes. First, note that $\mathbb{Q}[x]$ is a $\mathbb{Q}$-vector space with a countable basis $\{x^n : n \in \mathbb{N}\}$ (here $0 \in \mathbb{N}$). We also know that $\mathbb{Q}[x]$ is countable (since there are countably many elements of degree $\leq k$ for all $k \in \mathbb{N}$). Now, for any countable subset $\{v_n\}_{n \in \mathbb{N}}$ of a $\mathbb{Q}$-vector space, there is a unique surjective linear transformation
$$T : \mathbb{Q}[x] \to \operatorname{span}_{\mathbb{Q}}\{v_n\}_{n \in \mathbb{N}}$$
such that $T(x^n) = v_n$ for all $n \in \mathbb{N}$. This shows that $\lvert \operatorname{span}_{\mathbb{Q}}\{v_n\}_{n \in \mathbb{N}} \rvert \leq \lvert \mathbb{Q}[x] \rvert = \aleph_0$, as desired.

Is the rational span countable?


Which statistics test should I use?

Question: Group High is a year in which there was a high temperature change and group Low is a year in which there was a low temperature change. The classes represent an the percentage of coverage for a species on a plate. E.g. class 0 = 0% growth, class 4 = 50-75% growth, class 6 = >75% growth.  (I will not compare an amount of temperature change to an amount of growth)
I need to know if there is a significant difference between group High and group Low. Which statistical test can I use?
Both of my variables are categorical, right?
I use R studio and Excel.
Comment: A chi-square test.
Comment: Even so, the assumptions of a chi-squared test are violated with such a small dataset no?
Comment: Perhaps an exact test would be more appropriate than a $\chi^2$ test in this case.
Answer: Comment:
A suggestion has been made to do a chi-squared
test on your $2 \times 6$ table of counts to see if the distributions for High and Low are
different. That is one reasonable possibility  among several.
H = c(6, 4,14, 3, 3, 2)
L = c(0, 3,15,10, 6, 1)
TBL = rbind(H,L);  TBL

  [,1] [,2] [,3] [,4] [,5] [,6]
H    6    4   14    3    3    2
L    0    3   15   10    6    1

chisq.test(TBL)

        Pearson's Chi-squared test

data:  TBL
X-squared = 11.168, df = 5, p-value = 0.04815

Warning message:
In chisq.test(TBL) :
 Chi-squared approximation may be incorrect

It has also been commented that the counts in some
of the cells are too sparse for a reliable P-value. Hence
the 'Warning'. (Some of the expected counts are less than 5.)
chisq.test(TBL)$exp
      [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
H 2.865672 3.343284 13.85075 6.208955 4.298507 1.432836
L 3.134328 3.656716 15.14925 6.791045 4.701493 1.567164
Warning message:
In chisq.test(TBL) : Chi-squared approximation may be incorrect

You could try combining Classes 0 & 1 and Classes 4 & 5 to get a $2 \times 4$ table of counts and then do a chi-squared test on that table.
Alternatively, as implemented in R, it is possible to obtain a
more useful P-value by simulation, which is marginally
significant at the 5% level.
chisq.test(TBL, sim=T)

        Pearson's Chi-squared test
        with simulated p-value
        (based on 2000 replicates)

data:  TBL
X-squared = 11.168, df = NA, p-value = 0.04698

Moreover, as you suggest, your six 'Classes' are ordinal. So, you might want to consider looking here. Also, you might look at the
links in the margin of this page noted as 'Related'.
Your strategy should be to select the one test that you think
best matches the nature of your data and your objectives. (You should not try all
possible tests and pick the one with the smallest P-value.)

Which statistics test should I use?


ProgressBar usando Threads e SceneBiulder

Question: Estou fazendo um trabalho, e eu queria saber de uma maneira simples como eu resolvo isso, eu estou fazendo um programa simples em que é quase que um jogo, basicamente, você aperta um botão, a barra de progresso começa a crescer, e adiciona 1 ponto em uma Label. só que quando eu coloco pra funcionar, ele realiza os dois ao mesmo tempo e o ponto vai antes da barra de progresso se concluir, alguém poderia me ajudar?
Método no Controller:
@FXML Label lb$;
int dinheiro = 0;

@FXML
    public void botão() {
        BarraDeProgresso b = new BarraDeProgresso(100, 90, barra);
        new Thread(b).start();
        dinheiro++;
        lb$.setText(String.valueOf(dinheiro));

    }

Classe BarraDeProgresso:
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.control.ProgressBar;

public class BarraDeProgresso extends Task<Void>{

private int qt;
private int tempo;
private ProgressBar barra;

public BarraDeProgresso(int qt, int tempo, ProgressBar barra) {
    this.qt = qt;
    this.tempo = tempo;
    this.barra = barra;
    barra.setProgress(0);
}

public void inicia() {
    double incremento = 1.0/qt;
    for(int i=0; i<qt; i++){
        try {
            Thread.sleep(tempo);
            barra.setProgress(barra.getProgress()+incremento);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

//gets e sets implementados

Comment: Boa tarde otavio, sugiro que poste o que você já conseguiu fazer, dê uma olhada nesse link sobre [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve)
Comment: Atente-se para certos padrões sobre perguntas, pois é difícil saber como ajudar se você não nos der um rumo, e bem vindo à comunidade
Comment: Coloquei os códigos, melhorou?
Answer: A forma correta de marcar o progresso em JavaFX é utilizando um bind em conjunto com os métodos updateProgress/updateMessage. Veja o exemplo abaixo:
Task<Void> tarefa = new Task<Void>() {

    @Override
    protected Void call() throws Exception {
        for(int i = 0; i < 10; i++) {
            updateMessage("Pontos: " + i);
            updateProgress(i, 9); // (trabalho atual, total)
            Thread.sleep(1000);
        }
        return null;
    }
};

Label label = new Label("0");
label.textProperty().bind(tarefa.messageProperty());

ProgressBar pg = new ProgressBar();
pg.progressProperty().bind(tarefa.progressProperty());

O método setProgress do ProgressBar apenas coloca o muda o valor da propriedade mas não serve para incrementar.


Linear regression parameters that vary with periodic time

Question: I am looking to predict the suitability of weather conditions (a rating out of 10) for an outdoor activity. My plan was to use linear regression with features such as maximum temperature, chance of rain etc. My problem is that I need to make the model account for the time of the year, for example an almost perfect winter day (rated 10) would probably only be a mediocre summer day (rated 5/6).
My idea is to introduce a function that is dependent on time. Hopefully this would also account for climate variations, for example, Country A may have a temperature difference of 40 degrees C from summer to winter whereas Country B may have a more consistent temperature year-round with a difference of only 5 degrees C.
The model would then have a formula like
$y_i = w_0 + w_1*x_{i1} + w_2*x_{i2} + ... + w_k*z_1(t)*x_{i1} + w_{k+1}*z_2(t)*x_{i2} + ...$
where we have the standard linear regression model plus terms which have a weight function $z$ that depends on time $t$ to account for variability of the features throughout the year. My thinking is that $z_i(t)$ would be approximately zero for all $t$ if the feature does not vary throughout year and would vary with $t$ if the feature varies with $t$.
Firstly, is this a (statistically) valid model?
Secondly, I'm struggling to think of the form of the function $z$. It can't be linear in $t$ as $t=1$ and $t=365$ probably have the same value if $t$ is the day of the year. Also different areas of the world have different times for peak weather. Obviously the seasons are reversed in the hemispheres, but also two places in the same hemisphere may have their dry or warm period (for example) at different times of the year. Maybe a sine or cosine function?
Thirdly, is there a completely different model that I should be using? i.e. this one is not appropriate.
Comment: Gaussian process regression seems appropriate.
Answer: If I understand what you have in mind, I think this can be accomplished by interacting geography with pairs of $\cos(2 \pi \cdot j \cdot t)$ and $\sin(2 \pi \cdot j \cdot t)$ terms, where $j$ depends on time unit $t$. For example, with hourly data, $j=\frac{1}{24}$, and daily requires $j=\frac{1}{365}$ This can deal with smoothly varying seasonality. It will not handle abrupt events, like the joy of fireworks on the fourth of July, which can best be handled with dummies.
Comment: I have now changed my model but this was along the lines of my thinking and I think is correct approach.


Set a property that updates information on display on a VC swift

Question: I have 2 view controllers, VC1 displays all the users on my apps basic info, when you press a more info button in a certain cell it segues to a new VC that displays the users full profile that was in the cell that you previously pressed.
With help I have everything working except for how to display the results on VC2. I am trying to set a property in the VC2.  I also tried for
This code is returning no errors but displays nothing on the VC2.
I've tried set, get willSet, everything and can't crack it:
var userToShowDetail: PFUser? {
    willSet {
        self.configureView()
    }
}

func configureView() {
    // Update the user interface for the detail item.
    if let userToShowDetail: PFUser = self.userToShowDetail {
        if let label = self.userName {
            userName.text = userToShowDetail["name"] as! String?

        }
    }
}

override func viewDidLoad() {

I tried this one but it returns nothing but an empty VC:
var userToShowDetail: PFUser?

override func viewDidLoad() {
    super.viewDidLoad()

    if let appUsers = userToShowDetail as PFUser? {

    self.userName.text = appUsers["name"] as? String

    self.userInstrument.text = appUsers["instrument"] as? String

    self.userAge.text = appUsers["age"] as? String

    self.userProfile.file = appUsers["image"] as? PFFile

    self.userProfile.layer.cornerRadius = self.userProfile.frame.size.width/2

    self.userProfile.clipsToBounds = true

    self.userProfile.loadInBackground()
    }

I have researched didSet and willSet but I am still at a loss. Any help would be greatly appreciated. What is the next step can someone point me to a tutorial or advise me please.
willSet and DidSet purpose
Apple properties
View Controller 1 segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "userProfileDetailsSegue" {
//get the index path for the row that was selected
let indexPath = self.resultsPageTableView.indexPathForSelectedRow!
//get the PFUser object for that particular row
let userToShow = self.appUsers[indexPath.row]
//create your new view controller
let newVc = segue.destinationViewController as! UserProfileDetailsViewController
//assign the new vc's property to your object
newVc.userToShowDetail = userToShow
}
}

Comment: Try an [exception breakpoint](https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_an_exception_breakpoint.html) it might help you figure out where the problem is
Comment: can you show the code where you set `userToShowDetail` when pushing from vc1 to vc2 please?
Comment: @AndreSlotta sorry I updated my code there.
Answer: This is a common mistake when you are newer to swift.
 - When you segue to VC2, and pass a value to "userToShowDetail".The "didSet" method of "userToShowDetail" will be called.
 - Unfortunately, at this point, your VC2's views are still nil.So you will get this error.
 - The solution is simple,add a "?" after each view in your "didSet" func.
And don't forget to call "didSet" func in VC2's viewDidload.
func configureView() {
if let userToShowDetail: PFUser = self.userToShowDetail {
    if let label == self.userName? {//add "?" to VC2's subviews
        userName?.text = userToShowDetail["name"] as! String?//add "?" to VC2's subviews
    }
  }
}

override func viewDidLoad() {
  super.viewDidLoad()
  configureView()//call mothed in didSet()
  // other thing you need to do
}

Comment: I don't think I get you. Is my code correct above in my didSet method? Where do I add the "?" in my didSet code above? Sorry complete novice at didSet etc.
Comment: @Grace I added some snippet.
Comment: Now it is getting an error on "if let label = self.userName?"            The error is on the ? inserted.  The error is: '?' must be followed by a call, member lookup, or subscript
Comment: change this line of code to "if let label == self.userName?"
Comment: New error "variable binding in a condition requires an initializer" on the { after "if let label == self.userName?"
Comment: In your case you should just get rid of this line of code.func configureView() {
if let userToShowDetail: PFUser = self.userToShowDetail {
        userName?.text = userToShowDetail["name"] as! String?//add "?" to VC2's subviews
  }
}
Comment: Okay so now I have no errors, it doesn't crash or return any errors but it still is not updating the label called 'username' with the user info?
Comment: Did you add configureView() to viewDidload() ??


Getting error while trying to install watir

Question: I am having trouble install Watir. I am guessing that I am missing some C libraries.
Here is what I did:

Installed Rubyinstaller
Installed devkit
gem update --system
gem install watir --platform x86-mingw32

and here is my output:
<code>C:\>gem install watir --platform x86-mingw32
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
ERROR:  Error installing watir:
    ERROR: Failed to build gem native extension.

C:/Ruby200/bin/ruby.exe extconf.rb
checking for ffi.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers.  Check the mkmf.log file for more details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=C:/Ruby200/bin/ruby
    --with-ffi_c-dir
    --without-ffi_c-dir
    --with-ffi_c-include
    --without-ffi_c-include=${ffi_c-dir}/include
    --with-ffi_c-lib
    --without-ffi_c-lib=${ffi_c-dir}/
    --with-libffi-config
    --without-libffi-config
    --with-pkg-config
    --without-pkg-config
C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:430:in `try_do': The compiler failed to generate an executable file. (RuntimeError) You have to install development tools first.
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:561:in `try_cpp'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:1040:in `block in have_header'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:891:in `block in checking_for'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:336:in `block (2 levels) in postpone'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:306:in `open'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:336:in `block in postpone'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:306:in `open'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:332:in `postpone'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:890:in `checking_for'
    from C:/Ruby200/lib/ruby/2.0.0/mkmf.rb:1039:in `have_header'
    from extconf.rb:16:in `<main>'

Gem files will remain installed in C:/Ruby200/lib/ruby/gems/2.0.0/gems/ffi-1.9.3 for inspection. Results logged to C:/Ruby200/lib/ruby/gems/2.0.0/gems/ffi-1.9.3/ext/ffi_c/gem_make.out
</code>
Comment: What operating system are you working on?
Comment: What Ruby are you using? 32bit or 64 bit? Did you install proper version of Devkit for your Ruby? One way would be to delete Devkit directory and download the proper version and install it again with `--force` flag.
Answer: You shell install headers for FFI for the MINGW platform. If you are using MINGW for CYGWIN, you should run CYGWIN installer and install the libffi-devel/libffi-dev package. Otherwise, you should install external development package for MINGW like this to support development headers for ffi.
Additionally, please see here on how to use FFI on mingw here.


Finding the equation whose roots are $\pm \tan(\pi/7)$, $\pm\tan(2\pi/7)$ and $\pm\tan(3\pi/7)$ using De Moivre's Theorem

Question:
Find the equation whose roots are $\pm \tan(\pi/7)$, $\pm\tan(2\pi/7)$ and $\pm\tan(3\pi/7)$ using De Moivre's Theorem.

I tried converting $y=\cos x + i\sin x$ in terms of $\tan$ but it didn't work out. Please HELP . PLEASE USE DE MOIVRE'S THEOREM.
Comment: Can you use a polynomial?
Comment: You have to prove using De Moivre Theorem that's it..
Answer: What about $$ f(x) = (x^2- \tan ^2 (\pi /7))(x^2- \tan ^2 (2\pi /7))(x^2- \tan ^2 (3\pi /7))$$
Comment: Plz solve using De Moivre Theorem
Answer: To build a polynomial equation whose roots are $(r_1,\ldots,r_n)$, you can easily build the following equation: $\prod_k (x-r_k) = 0$.
With your example, you get the following equation:
 $(x-\tan(\pi/7))\cdot(x+\tan(\pi/7))\cdot(x-\tan(2\pi/7))\cdot(x+\tan(2\pi/7))\cdot(x-\tan(3\pi/7))\cdot(x+\tan(3\pi/7))=0$
Using the identity following identity:
 $(a+b)\cdot(a-b) = a^2 - b^2$, the equation becomes:
$(x^2 - \tan^2(\pi/7))(x^2 - \tan^2(2\pi/7))(x^2 - \tan^2(3\pi/7)) = 0$
Unfortunately, $\tan(\pi/7)$ doesn't have a nice way to be written.


Commutative diagram in the Category ( Ex in GTM 211 , Serge Lang )

Question: There is a example in the book Algebra written by Serge Lang , page 57.

Choose a object B in category $\mathbb A$ , define $\mathbb A_B$ as
  the category of morphisms $Mor(A,B) \in \mathbb A$
Suppose $f \in Mor(C,B) , g\in Mor(D,B)$ , then the morphism of
  $\mathbb A_B$ is simply a morphism $h \in Mor(C,D)$ such that $gh=f$ . i.e three
  morphisms form a commutative diagram.

If $h$ doesn't exist , then $\mathbb A_B$ can't be a category since there no morphisms.
However , why does $h$ always exist ? I can't derive it from any axioms of category.
Thanks for your time.
Comment: If $x,y$ are two objects in a category $C$, it may very well happen that there is no morphism from $x$ to $y$ (for instance in Sets with $y=\emptyset$ and $x$ not empty). In your category, the set of morphism from $f$ to $g$ may as well be empty (and this is the case if there is no $h:C\rightarrow D$ such that $f=gh$.)
Answer: As Roland comments, it may happen that the homset $Mor(A,B)$ is an empty set.
A more direct example for that is any discrete category, which is defined on any set/class of objects with just the property that $Mor(A,B)=\emptyset$ whenever $A\ne B\ $ (and $Mor(A,A)=\{1_A\}$).


Windows Server 2012 R2 Powershell IP Interfaces Compartments

Question: If I run Get-NetIPInterface -ifIndex 29 -IncludeAllCompartments, I get one Interface back.
There are only 2 Compartments I checked this via @(Get-NetCompartment).Count.
The Compartment IDs are 1 and 2. This information is also printed by Get-NetCompartment.
But If I run Get-NetIPInterface -CompartmetId 2 I get this error:
PS C:\Users\Administrator> Get-NetIPInterface -ifIndex 29 -CompartmentId 1
Get-NetIPInterface : No matching MSFT_NetIPInterface objects found by CIM query for instances of the
ROOT/StandardCimv2/MSFT_NetIPInterface class on the  CIM server: SELECT * FROM MSFT_NetIPInterface  WHERE
((InterfaceIndex = 29)) AND ((CompartmentId = 1)). Verify query parameters and retry.
At line:1 char:1
+ Get-NetIPInterface -ifIndex 29 -CompartmentId 1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (MSFT_NetIPInterface:String) [Get-NetIPInterface], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound,Get-NetIPInterface

or this
PS C:\Users\Administrator> Get-NetIPInterface -ifIndex 29 -CompartmentId 2
Get-NetIPInterface : No matching MSFT_NetIPInterface objects found by CIM query for instances of the
ROOT/StandardCimv2/MSFT_NetIPInterface class on the  CIM server: SELECT * FROM MSFT_NetIPInterface  WHERE
((InterfaceIndex = 29)) AND ((CompartmentId = 2)). Verify query parameters and retry.
At line:1 char:1
+ Get-NetIPInterface -ifIndex 29 -CompartmentId 2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (MSFT_NetIPInterface:String) [Get-NetIPInterface], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound,Get-NetIPInterface

PS C:\Users\Administrator>

Why do I get this error?
If the Interface is not in Compartment 1 and not in Compartment 2, where it is?
More Information:
PS C:\Users\Administrator>  Get-NetIPInterface -ifIndex 29 -IncludeAllCompartments

ifIndex InterfaceAlias                  AddressFamily NlMtu(Bytes) InterfaceMetric Dhcp     ConnectionState PolicyStore
------- --------------                  ------------- ------------ --------------- ----     --------------- -----------
29      NIC_INTERN_CONTOSO              IPv4                  1500               5 Disabled Connected       ActiveStore

PS C:\Users\Administrator> Get-NetCompartment

CompartmentId          : 1
CompartmentDescription : Default Compartment
CompartmentGuid        : !SOME NUMBERS!

CompartmentId          : 2
CompartmentDescription : COMPARTMENT2
CompartmentGuid        : !SOME NUMBERS"

Answer: You should be able to use something like this to find out what CompartmentId it is in:
Get-NetIPInterface -ifIndex 29 -IncludeAllCompartments | ForEach-Object { "$($_.InterfaceAlias) - $($_.CompartmentId)" }

Use that to check that it actually is in one of those compartments.


evaluate relationship between 1 independent variable and multiple dependent variables.

Question: To evaluate the relationship between variables coefficient of correlation and coefficient of determination obtained from regression are used. But what is the procedure if I have 1 Independent variable (IV), let's call it $X$, and multiple dependent variables $Y_1,Y_2,Y_3,Y_4,Y_5$? All my variables are continuous.
I am trying to evaluate the relationship of GPA with the total test score of an entry exam. The dependent variables will be probably strongly correlated and they do measure the same construct: GPA in fist semester, GPA in second semester, GPA for history course, GPA for technical courses.
Which technique can I use in this case?
I was thinking of reverse regression, as every correlation matrix will be symmetric because of $cov(x,y)=cov(y,x)$.
Answer: Turn the model around. Usually you can turn the model around. Then you can also use all sorts of regression and looking at your example, this seems to be satisfying. You can also solve the dependency between the tests with interaction, found from correlation for groupwise variables/ or identified via testing.
Comment: so you mean to use reverse regression?
Comment: I mean show that your entry exam test score can be correctly modeled by your GPA's. So Exam_Test_Score=GPA_History+GPA_TechCourse+GPA_second_semester+GPA_First_semester + \epsilon.
The only thing that changes in this model is the side of \epsilon which is the error residual. If you choose this model, you can still evaluate if it is a reasonable model by R² and you can also implement interaction terms for interdependency of your GPA_i's .
To me there is no reason, why you could not evaluate this model, instead of the other way around, math doesn't care for the direction of your equation.
Comment: My bad, did not look up reverse regression. Yeah that's the way to go.


LINQ to XML: How to clone nodes while retaining annotations?

Question: Try this:
var doc1 = XDocument.Load(@"C:\any.xml", LoadOptions.SetLineInfo);
var doc2 = new XDocument(doc1);

doc2 no longer has any line number information. Digging in with Reflector, I can see that when the nodes are cloned from doc1 to doc2 this does not preserve the annotations on the XObject base type, which includes the line number information accessible via IXmlLineInfo. Nor does it retain the BaseUri, which I also need.
Any ideas how I can clone the document while preserving line numbers? I found this but it doesn't preserve BaseUri and is a bit of a hack.
Comment: I have gotten around this in my particular case by keeping a reference to the original XDocument which is never modified and just used to look up line numbers and BaseUris.
Answer: This retains the LineInfo at least (I didn't try the BaseUri as I didn't need it):
using (var xmlReader = doc1 .CreateReader())
   doc2 = XDocument.Load(xmlReader, LoadOptions.SetLineInfo);

Answer: You could save it into a memory stream and then reload it into a new instance of XDocument.
Comment: That would still lose the original BaseUri and line number information, I'm afraid.
Comment: Hmm, that's a shame, but yes, of course it would. Could you get away with wrapping the new instance with something that can hold the original BaseUri?


Supervised dimensionality reduction

Question: I have a data set consisting of 15K labeled samples (of 10 groups). I want to apply dimensionality reduction into 2 dimensions, that would take into consideration the knowledge of the labels.
When I use "standard" unsupervised dimensionality reduction techniques such as PCA, the scatter plot seems to have nothing to do with the known labels.
Does what I am looking for have a name? I would like to read some references of solutions.
Comment: If you are looking for linear methods, then linear discriminant analysis (LDA) is what you should be using.
Comment: One possibility would be to first reduce to the nine-dimensional space spanning the class centroids, and then use PCA to further reduce to two dimensions.
Comment: @amoeba: Thanks. I used it and it performed much better!
Comment: Glad that it helped. I provided a brief answer with some further references.
Comment: Related: https://stats.stackexchange.com/questions/16305 (possibly duplicate, though perhaps the other way round. I will come back to this after I update my answer below.)
Answer: The most standard linear method of supervised dimensionality reduction is called linear discriminant analysis (LDA). It is designed to find low-dimensional projection that maximizes class separation. You can find a lot of information about it under our discriminant-analysis tag, and in any machine learning textbook such as e.g. freely available The Elements of Statistical Learning.
Here is a picture that I found here with a quick google search; it shows one-dimensional PCA and LDA projections when there are two classes in the dataset (origin added by me):

Another approach is called partial least squares (PLS). LDA can be interpreted as looking for projections having highest correlation with the dummy variables encoding group labels (in this sense LDA can be seen as a special case of canonical correlation analysis, CCA). In contrast, PLS looks for projections having highest covariance with group labels. Whereas LDA only yields 1 axis for the case of two groups (like on the picture above), PLS will find many axes ordered by the decreasing covariance. Note that when there are more than two groups present in the dataset, there are different "flavours" of PLS that will produce somewhat different results.
Update (2018)
I should find time to expand this answer; this thread seems to be popular but my original answer above is very short and not detailed enough.
In the meantime, I will mention Neighbourhood Components Analysis -- a linear method that finds the projection maximizing $k$-nearest-neighbours classification accuracy. There is a nonlinear generalization using neural networks, see Learning a Nonlinear Embedding by Preserving Class Neighbourhood Structure. One can also use neural network classifiers with a bottleneck, see Deep Bottleneck Classifiers in Supervised
Dimension Reduction.
Comment: nice graphic, explains much

Supervised dimensionality reduction


What are the broadest class of distributions for which the range statistic is ancillary to the expectation of the random variable?

Question: Let $X_1,X_2,X_3$ be  iid random variables such that $E(X_1)=\mu$
Define $X_{(3)}$ and $X_{(1)}$ as the maximum and minimum order statistics respectively.
I know that if $X$ is normal, $R=X_{(3)}-X_{(1)}$ is ancillary to $\mu$
What is the biggest family of distributions for which this is true?
Comment: Could you tell us how "biggest" is supposed to be determined?  Cardinality, number of parameters, set inclusion, or maybe something else?
Comment: This would be true for symmetric distributions, but maybe also some others ...
Comment: Thank you. I guess biggest is somewhat vague. I was I meant biggest as in most general. Symmetric is pretty broad which helps a lot.
Answer: This will be true for all symmetric distributions. But as the linked post makes clear, distributions might be symmetric in different senses, and you didn't specify which. But in statistics, the most used sense is symmetry with respect so some point of symmetry, usually the expectation (when exists.) So I will assume that definition.
So, the result will hold for the family of all symmetric distributions (with existing expectation.) But: Let $X \sim F$ for some distribution $F$ (with existing expectation. Will not repeat that.) Then define a distribution family by $ Y = X+\theta; X \sim F$ for $\theta \in \mathbf{R}$. Then obviously the distribution of $R$ will be free of $\theta$, so will be ancillary for the expectation. One could maybe/probably construct more such families. And this families will not be ordered by inclusion ... so it is not possible to tell which is largest (in the sense of set inclusion.) Now you can understand the comment by @whuber.
Comment: The correctness of this answer depends on what definition of "ancillary" you are using.  As you point out, any given *location family* generated by a *single* symmetric distribution will work.  But consider, say, the Normal$(\mu,\sigma)$ family: the range *does* give information about its parameter and--according to [this definition](https://en.wikipedia.org/wiki/Ancillary_statistic)--is *not* ancillary.  Accordingly, the family of all symmetric distributions that you name at the outset doesn't work.
Comment: @whuber: The question says *ancillary to $\mu$*, that is the sense I am using. This corresponds to the concept of *S-nonformation* given on page 47 of [Barndorff-Nielsen](https://www.amazon.com/Information-exponential-families-statistical-mathematical/dp/0471995452/ref=sr_1_12?keywords=barndorff-Nielsen&qid=1575332593&sr=8-12) which I have also linked [here](https://stats.stackexchange.com/questions/410867/why-arent-error-in-x-models-more-widely-used/412772#412772).
Comment: Thanks for the clarification, +1.
Comment: Any density $f$ such that$$\int xf(x)\text{d}x=0$$leads to a family$$f_\mu(x)=f(x-\mu)$$that makes $R$ ancillary in $\mu$.
Comment: @Xi'an: That is included in my answer ...


How to override handleMethodArgumentNotValid properly in Spring Boot

Question: I'm trying to override the handleMethodArgumentNotValid method. But I'm still getting the error:
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]
I've overridden the method as suggested in various posts (for example in Spring Rest ErrorHandling @ControllerAdvice / @Valid) like this:
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
        String message = errorMessageBuilder(ex);
        return handleExceptionInternal(ex, message, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, webRequest);
    }
}

What am I doing wrong?
Sincerely,
Marcel
Comment: The error message mentions ambiguity. That sounds like there are multiple exception handlers for the same exception class and the compiler won't pick a random one. I have no idea about a solution though.
Comment: I know what the message means, Spring handles it internally as well, that's why I'm overriding it (Extending the class at first, then override it.)
Comment: @MarcelOostebring please check my answer, this will help you https://stackoverflow.com/a/57961101/10426557 if this helps upvote please...
Comment: @One guy that unfortunately did not help me. I'm still getting the ambigious exception handler method mapped error.
Comment: May help someone, I got it working with this : https://stackoverflow.com/a/68888906/3412696
Comment: I think the Spring boot version is causing the problem. Unfortunately, in some of tutorials the versions are not mentioned and the speed of change is insane these days.
Answer: If you want to create your own response, then try with the below code.
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
        Map<String, Object> body = new HashMap<>();
        body.put("error", ex);
        return new ResponseEntity<>(body, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}

You can change the Map to your customize object and set the error pieces of information you want. I hope it will work.
Comment: Yes, I've found a working way by now. Either not extending the ResponseEntityExceptionHandler, or if you do extend that class, remove @ExceptionHandler(MethodArgumentNotValidException.class) worked too.


Somar modelos em VueJS com model.number

Question: Estava a experimentar vuejs e deparei-me com algumas dificuldades, basicamente estava a somar 3 inputs e colocar o resultado em um 4º.
Problema, vamos supor que insiro:

t.valor1 => 1
  t.valor1 => 0 ( preciso apagar e colocar o 0 de novo)
  t.valor1 => 3

ou

t.valor1 => 0
   t.valor1 => 1 ( preciso apagar e colocar o 0 de novo)
   t.valor1 => 3

O total é de 13 e não 4, o vuejs esta a tratar os resultados como texto apesar de ter colocado a opção model.number. Eu penso que a causa aqui é da diretiva input-noempty que está a alterar o valor do input diretamente invez do valor do modelo, mas seria o método mais correto?

Vue.directive('input-noempty', {
  update: function(el, binding) {
   // sem zeros a esquerda
    el.value = el.value.replace(/(^|[^0-9])0+/g, "");
    // evita que o campo fique vazio
    el.value = el.value.length == 0 ? 0 : el.value;
  },
});

new Vue({
  el: "#app",
  data: {
   t:{
     valor1:0, valor2: 0, valor3:0, total: function(){return this.valor1 + this.valor2 + this.valor3;}
    }
  }
})
.total{ border-color: lightblue; }

<input v-input-noempty  type="test" v-model.number="t.valor1" />
<input v-input-noempty  type="test" v-model.number="t.valor2" />
<input v-input-noempty  type="test" v-model.number="t.valor3" />

<input class="total" type="test" v-model.number="t.total()" />

Answer: À partida seria de esperar que o v-model.number só retornasse números, mas não é o caso... há um issue no Github sobre isso onde um dos membros da equipa diz que talvez na V.3 esse novo comportamento seja considerado. Assim isto é um problema clássico de concatenação de strings. Tu pensas que estás a somar números mas estás a concatenar strings. Usa Number() para converter de string para numero e já vai funcionar como esperas.
Deixo um exemplo, ligeiramente modificado como sugestão. Uso computed porque parece-me mais correto aqui.

new Vue({
  el: "#app",
  data: {
    t: {
      valor1: 0,
      valor2: 0,
      valor3: 0,
    }
  },
  computed: {
    total() {
      const {valor1, valor2, valor3} = this.t;
      return [valor1, valor2, valor3]
        .map(Number)
        .reduce((input, sum) => input + sum, 0);
    }
  }
})
.total {
  border-color: lightblue;
}

  <input v-input-noempty type="test" v-model.number="t.valor1" />
  <input v-input-noempty type="test" v-model.number="t.valor2" />
  <input v-input-noempty type="test" v-model.number="t.valor3" />

  <input class="total" type="test" v-model.number="total" />

Comment: @lazyFox fiz mais uma melhoria no código se quiseres usar.
Comment: Por fim consegui arranjar um solução, também fui forcado a usar `meunumero || 0` e no meu caso estou usando um componente agora. Depois de ler sobre watchers, diretives, components, ao menos já aprendi algo novo. Mas desmotivou bastante o vuejs, porque tinha uma tabela para construir, e pensei que o vuejs ia-me facilitar a vida e só me atrasou.

Somar modelos em VueJS com model.number


Extending a controller in Rails

Question: I have a controller which calls out to another class.
class BlahController < ActionController
  def index
    OtherClass.get_stuff
  end
end

In this class I want to be able to write controller style code.
for instance:
class OtherClass
  def self.get_stuff
    @foo = bar
  end
end

However, I would also like @foo to exist when inside my view, but as it's a separate class those variables aren't making it back through into the controller assigns - so question is, how I can make this so?
(Ignore why I'm having to call out to a separate class, I'm trying to get this code fitting in with a legacy codebase without too much butchery)
Comment: Does OtherClass has to be a class? What if you change OtherClass to a module and mix in it into the controller?
Comment: are you dealing with lots of instance variables, if not simple return from your class and storing it in instance variable should be good to go
Comment: I don't want to return stuff as it limits what I can do with the class later on
Comment: How about you move your method - OtherClass.getStuff to a helper class so that it is accessible from view ?
Comment: Helpers are primarily view helpers, not controller and I don't really want to dirty those waters.
Comment: You are confused. There is no such thing as "controller style code". A controller is just a class. You're asking to set an instance variable from the return value of a method in another class. See my answer.
Answer: class BlahController < ActionController
  def index
    OtherClass.get_stuff(self)
  end
end

class OtherClass
  def self.get_stuff(that)
    that.instance_variable_set(:@foo, bar)
  end
end

Please note that I don't agree with this method.  I am just answering the question as you stated it.
I would prefer to accomplish this functionality through mixins and thereby decrease parameter coupling that is present within the code above.
Answer: Code structured like this will be difficult to read and maintain.  Whenever you can, let the controller directly set all of the variables that the view needs:
class BlahController < ActionController
  def index
    @foo = OtherClass.get_stuff
  end
end

class OtherClass
  def self.get_stuff
    # return the value that should be assigned to @foo
  end
end

Extending a controller in Rails


How to prepare to play bowed vibraphone?

Question: The UK brass band I play in is preparing a test piece that features a bowed vibraphone amongst the percussion parts.
We've been using a cello bow, well rosined. But sometimes when you start bowing, nothing happens.
I'd like to know:

What is the most successful bowing technique to use?
Is there anything we need to do to mechanically prepare the vibraphone for being played with a bow?
Comment: Check the bar edges are clean - they may get handled and grease from hands will stop the bow gripping.
Comment: Indeed there are some notes about the percussion parts  - http://faber-product-media.s3.amazonaws.com/b0842969-eb6f-4251-a0e6-e84af5c3a77a   but nothing that answers my original questions.
Comment: Does the composer of this rather oddball piece have any instructions in the score?
Comment: I came across this old question while searching for something else.  How did this turn out?  I also wondered whether a wooden "bow" would work, in a similar fashion to the stick used with a singing bowl.
Answer: I'd like to add some experience to the existing answer as an orchestral percussionist with some (controversial) background as a violinist.
Vibraphone bowing is a wide term that is often underestimated by both percussionists and composers. While the basic technique is well known, its practical application requires important knowledge and experience, especially considering the following aspects:

the width of the bow hair (cello and double bass bows normally have a wider contact surface);
the length of the bow (opposite to the above, violas and violins normally are much longer);

Now, a double bass bow is normally the preferred choice: due to its hair width, it normally makes it easier to actually start the sound, even for inexperienced players. Note, though, that there is no absolute standard size for bows. For instance, double bass bows can have very different lengths depending on the generic style, or their playing philology (for instance, jazz, German classical symphony, or Italian opera) possibly ranging between 60 and 75 centimetres. That's a lot of difference both in length and, then, in mass.
But that's not enough: sometimes you have to play long sustained notes (possibly for multiple bars), and even if you are experienced enough, lots of things may work against you: effective note length, dynamics (possibly to be kept constant and without interruptions), instrument capabilities and overall acoustics.
While the target material (a metal bar, opposed to a string) may be different, the basic concept remains: string players literally spend years learning about bowing techniques, and even if we, as percussionists, rarely need those skills, we cannot ignore the shortcomings of such underestimations.
Interestingly enough, we have a further difficulty; string players normally take aid (hopefully with some awareness) from the weight of their playing: the arm, the bow, and even other aspects related to body movements; lots of important aspects of the bow movements are from top to bottom: gravity (and its awareness) helps a lot, and makes it easier to "add" proper sound to your playing.
Ask a violinist to play the same difficult piece when they're upside down.
Similarly, none of this helps when bowing a vibraphone bar: you have no bow/arm weight to help you, because the bow is always vertical.

There are two main aspects to consider about all this:

note attack (when the note can be actually perceived);
legato ("slurred") effects, a long note that is consistent in its dynamics and not affected by technique limitations;

For vibraphone bowing, the former is normally a simpler objective: you have to understand the mass of your movements and of the bow, along with the bow "hair width". If you can, take your time to know the instruments (the vibraphone and the bow) and learn how to get the most from them. This will also create further experience and eventually help you in the long run.
As usual, spending time is what you need: studying and experience are your only friends.
Note that, similarly to strings, there's almost nothing you can do to "prepare" the instrument: if the instrument or its strings are cheap and poorly sounding, that's what you get, similarly to a cheap/student/practice percussion instrument.
The "attack" only depends on physical friction capabilities of the material and construction fineness, which is not an aspect that is normally considered fundamental for such percussion instruments. A vibraphone has to primarily "play well" when struck, not when bowed.
For long sustained notes, the problem is still about experience and practice.
A well trained string player is able to almost seamlessly "slur" a very long note even between bow changes, and a percussionist should at least try to do so as well.
You have to learn how to begin a new bow change, meaning that you have to know or understand how you should eventually touch the bar again, in order to avoid its damping and, instead, take advantage of its current vibration in the shortest amount of time possible, so that your new bowing will not break the current sound, but continue it instead.

All of the above requires lots of time and efforts.
If this is the first time you're doing this, don't worry too much, but also take the experience as an important learning point.
If you have enough time, do your studying.
Do experiments. Try different bow grips and body positions. Experience the differences you can apply when starting the bow movement from the tip or the heel.
Sometimes you have to use one bow per hand, but, if you don't, use the free arm as a body lever to apply a better grip, "weight" and control.
If you only need to play one sustained note, consider using two bows (one for each hand).
Based on your experience and capabilities, decide the bow type: as said above, double bass bows are the preferred choice, but if the piece (or playing acoustics) doesn't require too much dynamics, a longer and slimmer bow may be a better choice.
Answer: I am a cellist and do not have experience with vibraphone, but from this video and this website, the following techniques seem to be important:
1: Use a bass bow instead of a cello bow.  Bass bows are larger and have more hair, so they will give you more sound.
2: Press hard.  The bow needs to be pressing into the metal to grip it— it's not enough just slide it over.  Rosin helps with this.


Solving functional equation $\sin f = f^2-3if+\pi$

Question: I want to find all (entire) solutions to the equation $$\sin f = f^2-3if+\pi.$$ Using the identity theorem, I was able to show that if a solution exists, it must be constant. Therefore, all that is left to do is to show that there is some $a\in\mathbb{C}$ such that $$\sin a = a^2-3ia+\pi.$$ By plugging the above equation into WolframAlpha, I know that there must exist a unique solution (namely $a\approx .19+.78i$), but I could not prove so. Any help in showing the existence (or the uniqueness) of $a$ would be appreciated.
Answer: $\sin a = a^2-3ia+\pi$ has infinitely many solutions $a \in \Bbb C$.
More generally, for any polynomial $p$, $\sin z - p(z)$ has infinitely
many zeros in the complex plane.
This can be shown in the same way as Antonio Vargas did it in Solve $\sin(z) = z$ in complex numbers for the special case $\sin z - z$:
Assume that $\sin z - p(z)$ has only finitely many zeros. The function is entire and of order $1$,
therefore the Hadamard factorization theorem gives that
$$
 \sin z - p(z) = q(z) e^{az+b}
$$
with a polynomial $q$, and complex numbers $a, b$. For $z = iy$, $y \to +\infty$,
the left-hand side is asymptotically
$$
 \frac{e^{-y} - e^y}{2i} + O(y^{\deg p}) \sim \frac 12 i e^y
$$
and that is only possible if $\operatorname{Im} a = -1$.
On the other hand, for $z = -iy$, $y \to +\infty$,
the left-hand side is asymptotically
$$
 \frac{e^{y} - e^{-y}}{2i} + O(y^{\deg p}) \sim -\frac 12 i e^y
$$
which is only possible if  $\operatorname{Im} a = +1$.


Separate image name from image path

Question: views.py
def index(request):
     profile = profiles.objects.all()
     for person in persons:
         images = profile.image
         image = 'uploads/no-img.jpg'
         if images:
             [x.strip() for x in images.split('/')]
             image = images[-1:]
         p = image_name(image = image,activated = 1)
         p.save()

models.py
class profiles(models.Model):
     image = models.ImageField(blank=True,upload_to='%Y/%m/%d')
     user = models.OneToOneField(User)

2012/09/08/4f31063d985c97b64e930917b456083c.jpg I want to separate the image name from this link.
Comment: http://docs.python.org/2/library/os.path.html#os.path.basename
Comment: The argument to `basename` must be a string.
Comment: 'ImageFieldFile' object has no attribute 'rfind
I got this error when i did this.**image =os.path.basename(images)**.
Comment: Now i convert my images to string 'str(image)' and got the result.
Answer: Use os.path.basename(path) : Returns the base name of pathname path passed as string.
>> os.path.basename('2012/09/08/4f31063d985c97b64e930917b456083c.jpg')
   4f31063d985c97b64e930917b456083c.jpg

Read more about it here.
Comment: Now i convert my images to string 'str(image)' and got the result.

Separate image name from image path


How can I solve the folowing Diophantine equation with two unknowns?

Question:
Find one integer solution to the following Diophantine equation:
  \begin{equation*}
\\\forall \,x,y \in \mathbb{Z}\\
6xy + x - y = 274
\end{equation*}

The resultat ist $x = 9$, $y = 5$ (Obtained with wolframalpha )
I need to know a method that allows me to reach such a result. How can I calculate the value of these two variables in a Diophantine equation?
For example: 6xy + x - y = 458
Comment: But, the equation is not linear.
Comment: you can use this site. It does a step-by-step solution or just a solution but it also provides the method Bill Dubuque mentioned in his answer. so you basically have everything in one neat package.

https://www.alpertron.com.ar/QUAD.HTM
Answer: Hint $\ $ This type of diophantine equation is solvable by a generalization of completing the square. Namely, completing a square generalizes to completing a product, using the AC-method, viz.
$$\begin{eqnarray} &&axy + bx + cy\, =\, d,\ \ a\ne 0\\
\overset{\times\,a}\iff\, &&\!\! (ax+c)(ay+b)\, =\, ad+bc\end{eqnarray}\qquad\qquad$$
So the problem reduces to checking which factors of $\,ad+bc\,$ have above form, a finite process.
Answer: $\dfrac{274+y}{6y+1}=x$
As $x$is an integer, if integer $d$ divides both $274+y,6y+1;d$  must divide $6(274+y)-(6y+1)=1643$
For integer $x,6y+1$ must divide $1643=31\cdot53$ whose divisors are $\pm1\pm31,\pm53$
Comment: In case anyone wonders, solving it this way ends up being essentially equivalent to the method in my answer using the AC method to complete the product.
Answer: This is @Bill Dubuque's answer in more detail.
I don't know what you mean by $\mathbb Z_0$.
$$ \forall x,y \in \mathbb Z_0, \quad 6xy + x - y = 274 $$
\begin{align}
   6xy + x - y        &= 274 \\
   36xy + 6x - 6y     &= 1644 \\
   36xy + 6x - 6y - 1 &= 1643 \\
   6x(6y+1) -1(6y+1)  &= 1643 \\
   (6x-1)(6y+1)       &= 1643
\end{align}
\begin{array}{|cc|cc|}
\hline
   6x-1 & 6y+1 & x &y \\
\hline
   1    & 1643   & \ast & \ast\\
   31   &   53   & \ast & \ast\\
   53   &   31   &    9 &    5\\
   1643 &    1   &  274 &   0\\
\hline
\end{array}
Comment: @DaríoA.Gutiérrez  Listed is the four ways of multiplying two integers to get the product 1643. I got it by going to Wolfram Alpha and typing in Divisors[1643].
Comment: Thank you for your answer. I do not quite understand the table
How do you get on the numbers 31 and 53?
Comment: Know you what an algorithm used Wolfram Alpha by Divisors[1643] to extract the integer solutions (9, 5)?
Comment: @DaríoA.Gutiérrez - You solve 6x-1=53 and 6y+1=31.