text:
Q: OleDbDataAdapter Fill and OleDbDataReader takes 3-5 minutes to fill This is a really strange problem as it only happens on random brand new Windows 10 pc's. It will take anywhere from 1-5 minutes to fill the data adapter or data reader. This is the 3rd pc it has happened to when upgrading from a Windows 7 old pc to a brand new windows 10 pc. The first time it happened a year ago, the problem only occurred for 1 day. The second time we could not fix it and just put them back on their old Windows 7 pc. And now it is happening again. We have replaced 4 other pc's that run this program with the same model Nuc 10i7 computer and they work just fine only taking 1-5 seconds to get through all the routines.
I don't think it is the connection string or the SQL statement since it works fine on other pc's.
I isolated the delay to when the OleDbDataAdapter or the OleDbDataReader are being filled which is evident in the screenshots below using a logging function before and after the fill.
This is on Nuc10i7 pc, VB.Net program calling one row of data from an Access db.
Public Sub PrintSwatLoad(SwatKey As String)
    didPrint = True
    Try
        Dim sBarcode As String = ""
        Dim cn As New OleDbConnection(MDBConnect)
        Dim sSql As String = "" &
          "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
                "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
          "FROM Swatlog INNER JOIN tblTempCert " &
            "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
         "WHERE [tblTempCert].[SwatDate] = #" & SwatKey & "#"

        cn.Open()
        Dim cmd As New OleDbCommand(sSql, cn)
        'Dim da As New OleDbDataAdapter(cmd)
        'Dim ds As New DataSet
        Dim dt As New DataTable

        ''''''''right here is where it hangs'''''''''''''''''''
        Dim myreader As OleDbDataReader = cmd.ExecuteReader()
        ''''''''above this is where it hangs. deleted all my logging methods for clarity''''''''''
        '''
        While myreader.Read()
            If myreader.HasRows = True Then     'ds.Tables(0).Rows.Count
                'Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
                If IsTareout = True Then
                    sBarcode = Trim(myreader("Trucker")) & myreader("TruckNo")
                End If

                Dim rSwatLaserCert As New XRSwatLaserCert
                rSwatLaserCert.DataSource = dt
                Dim rpt As New DevExpress.XtraReports.UI.ReportPrintTool(rSwatLaserCert)
                With rSwatLaserCert
                    .XrBCTareOut.Text = sBarcode
                    If Not (myreader("ManualWeight") = 1 Or myreader("ManualWeight") = 3) Then
                        .XrLabelManualGross1.Visible = False
                        .XrLabelManualGross2.Visible = False
                        .XrLabelManualGross3.Visible = False
                    End If

                    If Not (myreader("ManualWeight") = 2 Or myreader("ManualWeight") = 3) Then
                        .XrLabelManualTare1.Visible = False
                        .XrLabelManualTare2.Visible = False
                        .XrLabelManualTare3.Visible = False
                    End If

                    If myreader("CertStatus") = 1 Then
                    ElseIf myreader("CertStatus") = 2 Then
                        .XrLabelCertStatus1.Text = "VOID"
                        .XrLabelCertStatus2.Text = "VOID"
                        .XrLabelCertStatus3.Text = "VOID"
                    Else
                        .XrLabelCertStatus1.Visible = False
                        .XrLabelCertStatus2.Visible = False
                        .XrLabelCertStatus3.Visible = False
                    End If

                    If IsDBNull(myreader("DeputyName")) = True Then
                        .XrLabelDeputy1.Text = myreader("Weighmaster")
                        .XrLabelDeputy2.Text = myreader("Weighmaster")
                        .XrLabelDeputy3.Text = myreader("Weighmaster")
                    Else
                        .XrLabelDeputy1.Text = myreader("DeputyName")
                        .XrLabelDeputy2.Text = myreader("DeputyName")
                        .XrLabelDeputy3.Text = myreader("DeputyName")
                    End If

                    If NoNull(myreader("ReplacedCert")) = "" Then                 'Replaced this line: If IsDBNull(myreader("ReplacedCert")) = True Then
                        .XrLabelReplacesLabel1.Visible = False
                        .XrLabelReplacesLabel2.Visible = False
                        .XrLabelReplacesLabel3.Visible = False

                        .XrLabel174.Visible = False                             ' Replaces cert 1
                        .XrLabel113.Visible = False                             ' Replaces cert 2
                        .XrLabel178.Visible = False                             ' Replaces cert 3

                        .XrLabel174.BorderWidth = 0                             ' Replaces cert 1
                        .XrLabel113.BorderWidth = 0                             ' Replaces cert 2
                        .XrLabel178.BorderWidth = 0                             ' Replaces cert 3
                    Else
                        .XrLabel174.Text = myreader("ReplacedCert")               ' Replaces cert 1
                        .XrLabel113.Text = myreader("ReplacedCert")               ' Replaces cert 2
                        .XrLabel178.Text = myreader("ReplacedCert")               ' Replaces cert 3
                    End If
                End With
                rpt.Print()
            End If
        End While
        cn.Close()

Please note ****** this code works perfectly fine on certain PC's which is why I didn't provide the code originally. I am on a Lenovo thinkpad right now and the code runs fine with either the datareader or adapter methods. It will run fine on intel's Nuc 10 i7 sometimes and then sometimes it doesn't as I described above.*********
Here is the code using the dataAdapter and datatable method:
 Public Sub PrintSwatLoad(SwatKey As String)
    didPrint = True
    Try
        Dim sBarcode As String = ""
        Dim cn As New OleDbConnection(MDBConnect)
        Dim sSql As String = "" &
          "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
                "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
          "FROM Swatlog INNER JOIN tblTempCert " &
            "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
         "WHERE [tblTempCert].[SwatDate] = #" & SwatKey & "#"

        Dim cmd As New OleDbCommand(sSql, cn)
        Dim da As New OleDbDataAdapter(cmd)
        Dim ds As New DataSet
        Dim dt As New DataTable

        cn.Open()

        ''''''''''This is where it hangs using the dataAdapter fill'''''''''''
        da.Fill(dt)
        ''''''''''Above is where it hangs''''''''''''''''''''''''''''

        ds.Tables.Add(dt) ' added this to dataset
        dt.TableName = "dataset"
        cn.Close()

        If dt.Rows.Count > 0 Then     'ds.Tables(0).Rows.Count
            Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
            If IsTareout = True Then
                sBarcode = Trim(WrkRow("Trucker")) & WrkRow("TruckNo")
            End If

            Dim rSwatLaserCert As New XRSwatLaserCert
            rSwatLaserCert.DataSource = dt

            Dim rpt As New DevExpress.XtraReports.UI.ReportPrintTool(rSwatLaserCert)
            With rSwatLaserCert
                .XrBCTareOut.Text = sBarcode
                If Not (WrkRow("ManualWeight") = 1 Or WrkRow("ManualWeight") = 3) Then
                    .XrLabelManualGross1.Visible = False
                    .XrLabelManualGross2.Visible = False
                    .XrLabelManualGross3.Visible = False
                End If

                If Not (WrkRow("ManualWeight") = 2 Or WrkRow("ManualWeight") = 3) Then
                    .XrLabelManualTare1.Visible = False
                    .XrLabelManualTare2.Visible = False
                    .XrLabelManualTare3.Visible = False
                End If

                If WrkRow("CertStatus") = 1 Then
                ElseIf WrkRow("CertStatus") = 2 Then
                    .XrLabelCertStatus1.Text = "VOID"
                    .XrLabelCertStatus2.Text = "VOID"
                    .XrLabelCertStatus3.Text = "VOID"
                Else
                    .XrLabelCertStatus1.Visible = False
                    .XrLabelCertStatus2.Visible = False
                    .XrLabelCertStatus3.Visible = False
                End If

                If IsDBNull(WrkRow("DeputyName")) = True Then
                    .XrLabelDeputy1.Text = WrkRow("Weighmaster")
                    .XrLabelDeputy2.Text = WrkRow("Weighmaster")
                    .XrLabelDeputy3.Text = WrkRow("Weighmaster")
                Else
                    .XrLabelDeputy1.Text = WrkRow("DeputyName")
                    .XrLabelDeputy2.Text = WrkRow("DeputyName")
                    .XrLabelDeputy3.Text = WrkRow("DeputyName")
                End If

                If NoNull(WrkRow("ReplacedCert")) = "" Then                 'Replaced this line: If IsDBNull(WrkRow("ReplacedCert")) = True Then
                    .XrLabelReplacesLabel1.Visible = False
                    .XrLabelReplacesLabel2.Visible = False
                    .XrLabelReplacesLabel3.Visible = False

                    .XrLabel174.Visible = False                             ' Replaces cert 1
                    .XrLabel113.Visible = False                             ' Replaces cert 2
                    .XrLabel178.Visible = False                             ' Replaces cert 3

                    .XrLabel174.BorderWidth = 0                             ' Replaces cert 1
                    .XrLabel113.BorderWidth = 0                             ' Replaces cert 2
                    .XrLabel178.BorderWidth = 0                             ' Replaces cert 3
                Else
                    .XrLabel174.Text = WrkRow("ReplacedCert")               ' Replaces cert 1
                    .XrLabel113.Text = WrkRow("ReplacedCert")               ' Replaces cert 2
                    .XrLabel178.Text = WrkRow("ReplacedCert")               ' Replaces cert 3
                End If
            End With
            rpt.Print()
        End If
        ds.Tables.Remove("dataset")
        da.Dispose()
        Catch ex As Exception
        RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)

    End Try
    didPrint = False
End Sub

   Public Sub GetKeyAndReason(ByRef sKey As String, ByRef sReason As String)
    Dim sSql As String = "SELECT SwatDate, Reason FROM tblTempCert"
    Dim cn As New OleDbConnection(MDBConnect)
    Dim da As New OleDbDataAdapter(sSql, cn)
    Dim ds As New DataSet

    Dim dt As New DataTable
    da.Fill(dt)
    If dt.Rows.Count > 0 Then
        Dim WorkRow1 As DataRow = dt.Rows(0)
        sKey = WorkRow1("SwatDate").ToString
        sReason = WorkRow1("Reason").ToString
    End If
    dt.Dispose()
    da.Dispose()
    cn.Dispose()
End Sub

A: It's possible that your Access database is corrupt. The code below contains a variety of methods that may be useful, including CompactAccessDatabase and CompactAccessDatabaseMDBOnly - compacting also repairs the database, if needed. Since the data types weren't provided for the tables mentioned in the OP, the data types in "CreateTblSwatLog" and "CreateTblTempCert" may need to be updated.
Add references to your project:
VS 2019:

*

*Click Project

*Select Add Reference

*Click COM

*Check Microsoft Jet and Replication Objects 2.6 Library

*Check Microsoft ADO Ext. 6.0 for DDL and Security

*Check Microsoft DAO 3.6 Object Library

*Check Microsoft Access xx.x Object Library

*Click Assemblies

*Check System.Data (if not already checked)

Create a module (name: Helper)
Imports System.IO
Imports System.Data.OleDb

Module HelperAccess

    Private didPrint As Boolean = False
    'Private MDBConnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SWAT\Pclogs.mdb;User Id=admin;Password=;"
    Private MDBConnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SWAT\Pclogs.mdb;Mode=Share Exclusive;User Id=admin;Password=;"
    'Private MDBConnect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SWAT\Pclogs.mdb;Persist Security Info=False;"

    Public Property IsTareOut As Boolean = True

    Public Sub CompactAccessDatabase(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft Access xx.x Object Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method works with both .mdb and .accdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            Dim dbe As New Microsoft.Office.Interop.Access.Dao.DBEngine

            'invoke CompactDatabase - compacts database to temp file
            dbe.CompactDatabase(filename, tempFilename)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dbe)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub CompactAccessDatabaseMDBOnly(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft DAO 3.6 Object Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method works with only .mdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            Dim dbe As New DAO.DBEngine

            'invoke CompactDatabase - compacts database to temp file
            dbe.CompactDatabase(filename, tempFilename)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dbe)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub CompactAccessDatabaseMDBOnly2(filename As String)
        'Add reference
        'Project => Add Reference => COM => Microsoft Jet and Replication Objects 2.6 Library

        'compacts Access database by copying the database to a new file and replacing the original file
        'Note: this method is only for .mdb files

        Try
            If String.IsNullOrEmpty(filename) OrElse Not System.IO.File.Exists(filename) Then
                Throw New Exception("Error: Access database '" & filename & "' doesn't exist.")
            End If

            Dim fileExt As String = Path.GetExtension(filename).ToLower()

            'must be .mdb to compact
            If fileExt <> ".mdb" Then
                Throw New Exception("Error: Compacting database with '" & fileExt & "' isn't supported.")
            End If

            Dim connectionString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Mode=Share Exclusive;User Id=admin;Password=;", filename)
            Dim tempFilename As String = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) & "_temp" & Path.GetExtension(filename))
            'Dim connectionStringTemp As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", tempFilename)
            Dim connectionStringTemp As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", tempFilename)

            'Debug.WriteLine("connectionString: " & connectionString)
            'Debug.WriteLine("tempFilename: " & tempFilename)
            'Debug.WriteLine("connectionStringTemp: " & connectionStringTemp)

            'create instance of Jet Replication Object
            Dim objJRO = Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"))

            'Engine Type:
            '1: JET10
            '2: JET11
            '3: JET2x
            '4: JET3x
            '5: JET4x
            'Dim oParams = {connectionString, String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", tempFilename)}
            Dim oParams = {connectionString, connectionStringTemp}

            Debug.WriteLine("Info: Compacting '" & filename & "'...")

            'invoke CompactDatabase - compacts database to temp file
            objJRO.GetType().InvokeMember("CompactDatabase", System.Reflection.BindingFlags.InvokeMethod, Nothing, objJRO, oParams)

            'delete original database file
            System.IO.File.Delete(filename)

            System.IO.File.Move(tempFilename, filename)

            'release COM object
            'System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO)
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objJRO)

            Debug.WriteLine("Info: Database compacted: '" & filename & "'")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Function CreateDatabase() As String
        'Add reference
        'Project => Add Reference => COM => Microsoft ADO Ext. 6.0 for DDL and Security

        Dim result As String = String.Empty

        Dim cat As ADOX.Catalog = Nothing

        Try
            'create New instance
            cat = New ADOX.Catalog()

            'create Access database
            cat.Create(MDBConnect)

            'set value
            result = String.Format("Status: Database created.")

            Return result
        Catch ex As Exception
            'set value
            result = String.Format("Error (CreateDatabase): {0}(Connection String: {1})", ex.Message, MDBConnect)
            Return result
        Finally
            If cat IsNot Nothing Then
                'close connection
                cat.ActiveConnection.Close()

                'release COM object
                System.Runtime.InteropServices.Marshal.ReleaseComObject(cat)

                cat = Nothing
            End If
        End Try
    End Function

    Public Function CreateTblSwatLog() As String
        Dim result As String = String.Empty

        Dim tableName As String = "SwatLog"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE SwatLog "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [WeightCert] varchar(50),"
        sqlText += " [SwatDate] DateTime,"
        sqlText += " [TareDate] DateTime,"
        sqlText += " [SaleCode] varchar(50),"
        sqlText += " [Species] varchar(50),"
        sqlText += " [Qual] varchar(50),"
        sqlText += " [SaleDesc] varchar(50),"
        sqlText += " [Trucker] varchar(50),"
        sqlText += " [TruckNo] varchar(50),"
        sqlText += " [TruckState] varchar(50),"
        sqlText += " [TruckLic] varchar(50),"
        sqlText += " [TrlState] varchar(50),"
        sqlText += " [TrlLic] varchar(50),"
        sqlText += " [TruckType] varchar(50),"
        sqlText += " [Comments] varchar(150),"
        sqlText += " [TareLoad] varchar(50),"
        sqlText += " [ScaleLoad] varchar(50),"
        sqlText += " [LoadNo] integer,"
        sqlText += " [Logger] varchar(50),"
        sqlText += " [LogMethod] varchar(50),"
        sqlText += " [Block] varchar(50),"
        sqlText += " [Gross] varchar(25),"
        sqlText += " [Tare] varchar(25),"
        sqlText += " [Weight] numeric(18,2),"
        sqlText += " [PrintAvg] numeric(18,2),"
        sqlText += " [Brand] varchar(50),"
        sqlText += " [Commodity] varchar(50),"
        sqlText += " [SortCode] varchar(50),"
        sqlText += " [Deck] varchar(50),"
        sqlText += " [UserInfo1] varchar(50),"
        sqlText += " [UserInfo2] varchar(50),"
        sqlText += " [EmergencyLevel] integer,"
        sqlText += " [ReprintCount] integer,"
        sqlText += " [Reason] varchar(75),"
        sqlText += " [LocationName] varchar(50),"
        sqlText += " [Addr1] varchar(50),"
        sqlText += " [Addr2] varchar(50),"
        sqlText += " [OwnerName] varchar(50),"
        sqlText += " [LoggerName] varchar(75),"
        sqlText += " [Contract] varchar(50),"
        sqlText += " [Weighmaster] varchar(50),"
        sqlText += " [TT] varchar(50),"
        sqlText += " [Reprint] bit,"
        sqlText += " [TareoutBarcode] Longbinary,"
        sqlText += " [PrintTare] bit,"
        sqlText += " [TruckName] varchar(50),"
        sqlText += " [ManualWeight] varchar(50),"
        sqlText += " [DeputyName] varchar(50),"
        sqlText += " [CertStatus] varchar(50),"
        sqlText += " [ReplacedCert] varchar(50));"

        Try
            Debug.WriteLine(sqlText)

            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Public Function CreateTblSwatLog2() As String
        Dim result As String = String.Empty

        Dim tableName As String = "SwatLog"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE SwatLog "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [WeightCert] varchar(50),"
        sqlText += " [SwatDate] DateTime,"
        sqlText += " [TareDate] DateTime,"
        sqlText += " [SaleCode] varchar(50),"
        sqlText += " [Species] varchar(50),"
        sqlText += " [Qual] varchar(50),"
        sqlText += " [SaleDesc] varchar(50),"
        sqlText += " [Trucker] varchar(50),"
        sqlText += " [TruckNo] varchar(50),"
        sqlText += " [TruckState] varchar(50),"
        sqlText += " [TruckLic] varchar(50),"
        sqlText += " [TrlState] varchar(50),"
        sqlText += " [TrlLic] varchar(50),"
        sqlText += " [TruckType] varchar(50),"
        sqlText += " [Comments] varchar(150),"
        sqlText += " [TareLoad] varchar(50),"
        sqlText += " [ScaleLoad] varchar(50),"
        sqlText += " [LoadNo] integer,"
        sqlText += " [Logger] varchar(50),"
        sqlText += " [LogMethod] varchar(50),"
        sqlText += " [Block] varchar(50),"
        sqlText += " [Gross] numeric(18,2),"
        sqlText += " [Tare] numeric(18,2),"
        sqlText += " [Weight] numeric(18,2),"
        sqlText += " [PrintAvg] numeric(18,2),"
        sqlText += " [Brand] varchar(50),"
        sqlText += " [Commodity] varchar(50),"
        sqlText += " [SortCode] varchar(50),"
        sqlText += " [Deck] varchar(50),"
        sqlText += " [UserInfo1] varchar(50),"
        sqlText += " [UserInfo2] varchar(50),"
        sqlText += " [EmergencyLevel] integer,"
        sqlText += " [ReprintCount] integer,"
        sqlText += " [Reason] varchar(75),"
        sqlText += " [LocationName] varchar(50),"
        sqlText += " [Addr1] varchar(50),"
        sqlText += " [Addr2] varchar(50),"
        sqlText += " [OwnerName] varchar(50),"
        sqlText += " [LoggerName] varchar(75),"
        sqlText += " [Contract] varchar(50),"
        sqlText += " [Weighmaster] varchar(50),"
        sqlText += " [TT] varchar(50),"
        sqlText += " [Reprint] bit,"
        sqlText += " [TareoutBarcode] Longbinary,"
        sqlText += " [PrintTare] bit,"
        sqlText += " [TruckName] varchar(50),"
        sqlText += " [ManualWeight] varchar(50),"
        sqlText += " [DeputyName] varchar(50),"
        sqlText += " [CertStatus] varchar(50),"
        sqlText += " [ReplacedCert] varchar(50));"

        Try
            Debug.WriteLine(sqlText)

            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Public Function CreateTblTempCert() As String
        Dim result As String = String.Empty

        Dim tableName As String = "tblTempCert"

        Dim sqlText = String.Empty
        sqlText = "CREATE TABLE tblTempCert "
        sqlText += "(ID AUTOINCREMENT not null primary key,"
        sqlText += " [SwatDate] DateTime);"

        Try
            'create database table
            ExecuteNonQuery(sqlText)

            result = String.Format("Table created: '{0}'", tableName)

        Catch ex As OleDbException
            'result = String.Format("Error (CreateTblSwatLog - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        Catch ex As Exception
            'result = String.Format("Error (CreateTblSwatLog): Table creation failed: '{0}'; {1}", tableName, ex.Message)
            Throw ex
        End Try

        Return result
    End Function

    Private Function ExecuteNonQuery(sqlText As String) As Integer
        Dim rowsAffected As Integer = 0

        'used for insert/update

        'create new connection
        Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
            'open
            cn.Open()

            'create new instance
            Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
                'execute
                rowsAffected = cmd.ExecuteNonQuery()
            End Using
        End Using

        Return rowsAffected
    End Function

    Public Sub PrintSwatLoad(SwatKey As String)
        'set value
        didPrint = True

        'create new instance
        Dim dt As New DataTable

        'create new instance
        Dim ds As New DataSet

        Try
            Dim sBarcode As String = ""

            Dim sSql As String = String.Empty

            'sSql = "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
            '        "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
            '        "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
            '        "ScaleLoad, LoadNo, Logger, LogMethod, Block, Val(Gross) as GrossWt, " &
            '        "Val(Tare) as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
            '        "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
            '        "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
            '        "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
            '        "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
            '        "FROM Swatlog INNER JOIN tblTempCert " &
            '        "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
            '        "WHERE [tblTempCert].[SwatDate] = ?;"

            sSql = "SELECT WeightCert, [SwatLog].[SwatDate], TareDate, SaleCode, " &
                    "Species, Qual, SaleDesc, Trucker, TruckNo, TruckState, " &
                    "TruckLic, TrlState, TrlLic, TruckType, Comments, TareLoad, " &
                    "ScaleLoad, LoadNo, Logger, LogMethod, Block, Gross as GrossWt, " &
                    "Tare as TareWt, Weight, PrintAvg, Brand, Commodity, SortCode, " &
                    "Deck, UserInfo1, UserInfo2, EmergencyLevel, ReprintCount, " &
                    "Reason, LocationName, Addr1, Addr2, OwnerName, LoggerName," &
                    "Contract, Weighmaster, TT, Reprint, TareoutBarcode, PrintTare, TruckName, " &
                    "ManualWeight, DeputyName, CertStatus, ReplacedCert  " &
                    "FROM Swatlog INNER JOIN tblTempCert " &
                    "ON [SwatLog].[SwatDate] = [tblTempCert].[SwatDate] " &
                    "WHERE [tblTempCert].[SwatDate] = ?;"

            Using cn As New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                Dim swatDate As DateTime = DateTime.MaxValue

                'try to convert to DateTime
                DateTime.TryParse(SwatKey, swatDate)

                Using cmd As New OleDbCommand(sSql, cn)
                    'add parameters
                    cmd.Parameters.Add("!swatDate", OleDbType.DBDate).Value = swatDate

                    'ToDo: remove the following code that is for debugging
                    For Each p As OleDbParameter In cmd.Parameters
                        Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    Next

                    Debug.WriteLine(cmd.CommandText)

                    Using da As New OleDbDataAdapter(cmd)

                        'fill DataTable
                        da.Fill(dt)

                        'add to DataSet
                        ds.Tables.Add(dt) ' added this to dataset
                        dt.TableName = "dataset"

                        'Debug.WriteLine("table count: " & ds.Tables.Count)

                        'For i As Integer = 0 To ds.Tables.Count - 1 Step 1
                        'Debug.WriteLine("table: " & ds.Tables(i).TableName)
                        'Next
                    End Using
                End Using
            End Using

            If dt.Rows.Count > 0 Then     'ds.Tables(0).Rows.Count
                Dim WrkRow As DataRow = dt.Rows(0)    'ds.Tables(0).Rows(0)
                If IsTareOut = True Then
                    'sBarcode = Trim(WrkRow("Trucker")) & WrkRow("TruckNo")
                    sBarcode = Trim(WrkRow("Trucker")) & " - " & WrkRow("TruckNo")

                    Debug.WriteLine("sBarcode: " & sBarcode)
                End If

                'ToDo: add desired code

            End If
        Catch ex As OleDbException
            'ToDo: add desired code
            'RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)
            Throw ex
        Catch ex As Exception
            'ToDo: add desired code
            'RecordEvent("Cert error:   " & SwatKey & " - " & Reason & " (" & ex.Message & ")", True)
            Throw ex
        End Try

        'set value
        didPrint = False
    End Sub

    Public Function TblSwatLogInsert(swatDate As DateTime, trucker As String, truckNo As String, weight As String, tare As String, comments As String) As Integer
        Dim rowsAffected As Integer = 0

        Dim sqlText As String = String.Empty
        sqlText = "INSERT INTO SwatLog ([SwatDate], [Trucker], [TruckNo], [Weight], [Tare], [Comments]) VALUES (?, ?, ?, ?, ?, ?);"

        Try
            'insert data to database
            'create new connection
            Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                'create new instance
                Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)

                    'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
                    'However, specifying names in the parameter 'Add' statement can be useful for debugging
                    'Since OLEDB uses anonymous names, the order which the parameters are added is important
                    'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
                    'parameters must be added in the order that they are specified in the SQL
                    'if a value is null, the value must be assigned as: DBNull.Value

                    'add parameters
                    With cmd.Parameters
                        .Add("!swatDate", OleDbType.DBDate).Value = swatDate
                        .Add("!trucker", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(trucker), DBNull.Value, trucker)
                        .Add("!truckNo", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(truckNo), DBNull.Value, truckNo)
                        .Add("!weight", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(weight), 0, weight)
                        .Add("!tare", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(tare), 0, tare)
                        .Add("!comments", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(comments), DBNull.Value, comments)
                    End With

                    'ToDo: remove the following code that is for debugging
                    'For Each p As OleDbParameter In cmd.Parameters
                    'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    'Next

                    'execute
                    rowsAffected = cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch ex As OleDbException
            Debug.WriteLine("Error (TblSwatLogInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
            Throw ex
        Catch ex As Exception
            Debug.WriteLine("Error (TblSwatLogInsert) - " & ex.Message & "(" & sqlText & ")")
            Throw ex

        End Try

        Return rowsAffected
    End Function

    Public Function TblTempCertInsert(swatDate As DateTime) As Integer
        Dim rowsAffected As Integer = 0

        Dim sqlText As String = String.Empty
        sqlText = "INSERT INTO tblTempCert ([SwatDate]) VALUES (?);"

        Try
            'insert data to database
            'create new connection
            Using cn As OleDbConnection = New OleDbConnection(MDBConnect)
                'open
                cn.Open()

                'create new instance
                Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)

                    'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
                    'However, specifying names in the parameter 'Add' statement can be useful for debugging
                    'Since OLEDB uses anonymous names, the order which the parameters are added is important
                    'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
                    'parameters must be added in the order that they are specified in the SQL
                    'if a value is null, the value must be assigned as: DBNull.Value

                    'add parameters
                    With cmd.Parameters
                        .Add("!swatDate", OleDbType.DBDate).Value = swatDate
                    End With

                    'ToDo: remove the following code that is for debugging
                    'For Each p As OleDbParameter In cmd.Parameters
                    'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
                    'Next

                    'execute
                    rowsAffected = cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch ex As OleDbException
            Debug.WriteLine("Error (TblTempCertInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
            Throw ex
        Catch ex As Exception
            Debug.WriteLine("Error (TblTempCertInsert) - " & ex.Message & "(" & sqlText & ")")
            Throw ex

        End Try

        Return rowsAffected
    End Function
End Module

Resources

*

*Converting Access OLE object image to show in Datagridview vb.net

*Compact and Repair Access Database using C# ?

*How do I compact and repair an ACCESS 2007 database by .NET code?

*jro.jetengine not being recognised..

*Compact and Repair Access Database using C# and Late Binding


text:
Q: how to (check)know auto start permission allowed or not? Hello I used this code for start Autostart permission in android mi,oppo,vivo device.this perfect running, but how to know autostart permission allowed by user.
private void addAutoStartup() {

    try {
        Intent intent = new Intent();
        String manufacturer = android.os.Build.MANUFACTURER;
        if ("xiaomi".equalsIgnoreCase(manufacturer)) {
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
        } else if ("oppo".equalsIgnoreCase(manufacturer)) {
            intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
        } else if ("vivo".equalsIgnoreCase(manufacturer)) {
            intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
        } else if ("Letv".equalsIgnoreCase(manufacturer)) {
            intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
        } else if ("Honor".equalsIgnoreCase(manufacturer)) {
            intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
        }

        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0) {
            startActivityForResult(intent, 1);
            startActivity(intent);
        }
    } catch (Exception e) {
        Log.e("exc", String.valueOf(e));
    }
}

How to find out if this permission allowed or not?

A: Short answer you can't
As of now it can be done via root but it is not recommended and can potentially harm user's device .
As for me i tend to create a dialog and redirect user to autostart screen.
If user click on "do not show again(checkbox)" simply stop showing that dialog but consider this as a liable option but bad practice
Permission Dialog

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Can IBM Bluemix Node-RED Iotout node be set up correctly to send command to Device (Arduino)? I have an Arduino Uno that is successfully registered as a device with IBM IoTF. It can send information to the Bluemix Node-RED app without any issues now.
Now, I would like the Node-RED app to send commands to the device (the Arduino Uno). The Arduino is subscribed to the MQTT without any error. But, it is not receiving any commands from the Node-RED. I followed the directions at the link below to create another flow in Node-RED to show when a command is published and the commands are being shown, so they seem to be going to the MQTT broker. But, the device (Arduino) is not receiving them.
How can I figure out how to get this working?
Node-RED, IOT Foundation Out Node Not Sending Commands
I have the IBM IoT Out Node parameters set as follows:
Authentication: Bluemix Service
Output type: Device command
Device type: Arduino-tempsensor (this is the same string I used for the device type (name) when I registered it in IoTF)
Device ID: I put the MAC address here, should it be more
Command Type: status (I used the word "status" here. Does capitalization matter? Where should I get this value from?  I used "status" because it is in the topic:  "iot-2/cmd/status/fmt/json" is that correct?)
Format: json (does capitalization matter here?)
data: {"d":{"myName":"Arduino Uno", "temperature":989}}   (I used this because it's JSON and I wanted to just see anything at the device)
Name: IBM IoT App Out

A: I typed up this whole question and then it occurred to me that the test flow to look for the published command should have all of the parameters set to exactly the same as the output. When I tried that, I was not getting the command message coming back. Then, I realized that my mac address (device ID) was capitalized in one place, but not the other. The MAC address (Device ID) I used to register the device was all in caps, so I make the Iot-out node for the command so that it was all capitalized and made the Iot-in node to test for the message so that it was all capitalized. Now it works!  Then, I looked back at the device (which was printing to the serial monitor so I could see what was happening) and I am now seeing the messages! So, make sure your parameters follow the same capitaliztion!


text:
Q: Как в SQLite3 узнать какие даты присутствуют в столбце содержащим и дату и время? Работаю с SQLite3 из под Node.JS
В таблице присутствует столбец с датой-временем в текстовом формате 'Feb 18 2021 11:06:37 GMT+0700'.
Так же в базе есть столбец utime - числовой, где тоже время представлено в unix-формате.
Может быть много (сотни) строк с одной датой, но разным временем.
Для фронтенда, мне надо:

*

*узнать какие даты ('Feb 18 2021') присутствуют в таблице (чтобы знать сколько карточек будет)

*Далее, получать строки принадлежащие одной дате, для заполнения карточек.
Какими путями это достигается? параллельно RTFM-лю

Чтоб не терять времени на фронтЕ, пока я привязался к Unix времени:

*

*получить список уникальных дат:

SELECT DISTINCT date(datetime(utime/1000, 'unixepoch','localtime')) AS dates
FROM events
ORDER BY utime

*Подучить строки для указанной даты:

SELECT *
FROM events
WHERE date(datetime(utime/1000, 'unixepoch','localtime')) = '2021-02-18'

Как бы теперь прикрутить GMT - часовой пояс юзера?

A: Для начала определимся что есть что. Timestamp (метка времени) -- это точка на временной оси, когда произошло или произойдёт некое событие. Дата (и дата-и-время) -- это не совсем время, это интерпретация времени. В один и тот же момент времени (timestamp) даты могут быть разные в зависимости от часового пояса, используемого календаря и других условностей.
Дальше. Вас интересуют даты в часовом поясе пользователя? Чтобы их получить вам надо использовать функции дат, указав смещение часового пояса пользователя. Допустим есть некое событие в 1613692799, здесь нет никакого часового пояса, это просто точка на оси времени. Если интерпретировать эту точку как UTC дату, то получится select date(1613692799, 'unixepoch') -- 2021-02-18. А чтобы взглянуть на эту же точку из UTC+3 (московское время, например) надо накинуть эти 3 часика select date(1613692799, 'unixepoch', '+3 hours') -- 2021-02-19. Для жителя Лондона это 18-е, а для меня 19-е. Всё очень просто.
Хранить часовой пояс пользователя в большинстве случаев не нужно. Во-первых, дата может зависеть не от часового пояса пользователя, а от других факторов (например на авиабилетах мы хотим видеть дату-время в часовом поясе аэропорта на день вылета). Во-вторых, обычно пользователь может изменить таймзону по разным причинам (летом у жителя Лондона станет UTC+1), и тогда сохранённая зона возможно потеряет смысл.
Если вам надо создать объект даты у себя в коде, то вы можете так же использовать timestamp. То, что у вас в результате sql date(...) нет строчки "GMT+0700" не должно вас останавливать, для создания даты вам нужна метка времени.


text:
Q: Calling update_user_meta inside of another function doesn't work I have a function that does updates a db outside of wordpress and then I'd like it to take that information and update the user_meta table in wordpress.  The print statement prints all the appropriate information, but the update doesn't happen.
add_action('edit_user_profile_update', 'EditUsertoSF_Admin');

function EditUsertoSF_Admin($user_id) {
   global $SFUserID;

  $query = "SELECT Id, COUNT(Email) from Contact where Email='" . $_POST['email'] . "' GROUP BY ID";

            $createResponse3 = $mySforceConnection->query(($query));

            foreach ($createResponse3->records as $record) {
                foreach($record as $records) {
                    }
            }
                if($records > 0) {
                    $sObject->Id = $record->Id[0];
                    $createResponse = $mySforceConnection->update(array($sObject), 'Contact');

                    $SFUserID = $record->Id[0];
                    //print 'SF inside function Edit' . 'WP' . $user_id . 'SF' .$record->Id[0];
                    update_user_meta( $user_id, 'SF_User_ID', $SFUserID );
                }
}


text:
Q: Avoiding copy when passing an Eigen::Ref to another function I have a throughout my codebase functions that take arguments of type const Eigen::ArrayXd & and in order to efficiently wrap these functions with pybind11 and/or nanobind, I need to instead have Eigen::Ref<const Eigen::ArrayXd>& at the python <-> C++ boundary for data exchange. But what I have learned through experimentation, is that passing a const Eigen::Ref<const Eigen::ArrayXd> & to a function that wants a const Eigen::ArrayXd & always creates a copy. I have some timing results below (the copying code is many orders of magnitude slower). I don't see why the copy is required, and I would like to be able to throw (or at least be warned) if such a copy is being made.
More generally, I would like this code to not copy, and recommendations for how to avoid the copy without modifying the function foo. Is it a bug that copies are being made? It seems to me that if the memory block is not being modified (everything is const), no copy should in principle be required.
#include <catch2/catch_test_macros.hpp>
#include <catch2/benchmark/catch_benchmark_all.hpp>

#include <Eigen/Dense>

TEST_CASE("Time Eigen copying"){
    auto foo = [](const Eigen::ArrayXd &x){
        return x[3];
    };
    auto bar = [&foo](const Eigen::Ref<const Eigen::ArrayXd> &x){
        return foo(x);
    };

    Eigen::ArrayXd a = Eigen::ArrayXd::LinSpaced(1000000, 1, 2);
    const Eigen::Ref<const Eigen::ArrayXd> b = a;

    BENCHMARK("foo(a)"){
        return foo(a);
    };
    BENCHMARK("foo(ref(a))"){
        return foo(b);
    };
    BENCHMARK("bar"){
        return bar(b);
    };
}

yielding the results:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bench_EigenRef is a Catch2 v3.0.0-preview.4 host application.
Run with -? for options

Randomness seeded to: 3293564162

-------------------------------------------------------------------------------
Time Eigen copying
-------------------------------------------------------------------------------
/Users/ihb/Documents/Code/xxx/bench_EigenRef.cpp:6
...............................................................................

benchmark name                       samples       iterations    estimated
                                     mean          low mean      high mean
                                     std dev       low std dev   high std dev
-------------------------------------------------------------------------------
foo(a)                                         100          1070      2.889 ms
                                        26.4022 ns    26.0969 ns    27.1884 ns
                                        2.28764 ns   0.684344 ns    4.19932 ns

foo(ref(a))                                    100             1    384.512 ms
                                        3.89065 ms    3.87928 ms    3.90858 ms
                                        71.3259 us    49.9853 us    126.239 us

bar                                            100             1    380.192 ms
                                        3.87231 ms    3.85994 ms    3.89631 ms
                                        84.5487 us    53.4453 us    157.822 us

===============================================================================


text:
Q: SharedPreferences getStringSet method not available Very strange issue - I'm using the latest version of Android Development. Here is my code:
public static final String MY_PREFS_NAME = "MyPrefsFile";

   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

          final SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();

Set<String> savedCityFare = editor.getStringSet(whatever);

Funny part is none of the getter methods are available for editor. What am I doing wrong?

A:
Funny part is none of the getter methods are available for editor

The getter methods are on the SharedPreferences. Only the setter methods are on the SharedPreferences.Editor. Think of the SharedPreferences.Editor as being a builder-style class for creating and executing a "transaction" to update the shared preferences.

A: If you take a look at the documentation at http://developer.android.com/reference/android/content/SharedPreferences.Editor.html you'll see that the SharedPreferences.Editor class only has putX() methods defined. If you want to use the getters, you don't need an Editor but only a SharedPreferences object.
SharedPreferences preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Set<String> savedCityFare = preferences.getStringSet(whatever);

I would also suggest using PreferenceManager.getDefaultSharedPreferences() to obtain a SharedPreferences object.
JUST AN EDIT
To add value in SharedPreferences:
PreferenceManager.getDefaultSharedPreferences(YOUR_CONTEXT).edit().putXXX(YOURKEY,YOURVALUE).commit();//This will directly save value in your SharedPreferences.
When you want to fetch the value from your Preferences:
PreferenceManager.getDefaultSharedPreferences(YOUR_CONTEXT).getXXX(YOUR_KEY);//THIS WILL Returned you the stored value.
Default Preferences are used when you want to maintain a single instance of SharedPreferences throughout the app.


text:
Q: Read JavaScript Array into Apex List This question is related to what I have asked here
I'm getting this output in my apex controller and I'm looking a way to extract or parse this output string into List or Class?
18:59:48:001 USER_DEBUG [21]|DEBUG|--debuglogbranch:
{attributes={type=Account, url=/services/data/v38.0/sobjects/Account/0014100000BNrJEAA1},
   Id=0014100000BNrJEAA1, Name=test2, ParentId=00141000009mTavAAE,
   children=[
    {
       attributes={type=Account,
       url=/services/data/v38.0/sobjects/Account/0014100000BNrLIAA1},
       Id=0014100000BNrLIAA1, Name=test2.2,
       ParentId=0014100000BNrJEAA1,
       level=3,
       expanded=false,
       uid=0.7055100027498606,
       parent_uid=0.11747820325450764,
       children=[]
     }
    ],
    level=2,
    expanded=true,
    uid=0.11747820325450764,
    parent_uid=0.33335628016211594,
    selected=true
}

I have tried something like this:
@RemoteAction
public static void mymethod(String branch){
Map<String, Object> root = (Map<String, Object>)JSON.deserializeUntyped(branch);
    List<Object> items = (List<Object>)root.get('attributes'); //ERROR
    for (Object item : items) {
        Map<String, Object> i = (Map<String, Object>)item;
        System.debug(i.get('id'));
    }
}

got this error:
> Visualforce Remoting Exception: , column 1: Invalid conversion
> from runtime type String to Map<String,ANY>

A: I hit a very similar issue to this the other day, I didn't bother trying to establish why this works but I found that going via an intermediate variable helped, but I was indexing the list directly because I only cared about the first entry:
List<Object> messageResults = (List<Object>)resBody.get('messages');
Map<String, Object> messageResult = (Map<String, Object>)messageResults[0];

A sub-standard workaround for your scenario might be to use a regular for loop:
for (Integer i = 0; i < items.size(); i++)
    Map<String, Object> item = (Map<String, Object>)items[i];
    System.debug(item.get('id'));
}

Although you'd expect Object to be a pure reference to any object there is definitely some funkiness around how it's been implemented; I've hit a scenario before where some code just wouldn't work as expected when using it.


text:
Q: Google Map Does not appear in Modal Popup I want to show google maps in modal popup, but it doesn't seem to be appeared. Need Help.
Here is the HTML -

JS -
function initialize() {
    var myloc = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 17,
        center: myloc,
        scrollwheel: false
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        animation: google.maps.Animation.BOUNCE
    });
    var contentString = '
'+
            '
'+
            '
'+
            '

title here
'+
            '
'+
            '
description here
'+
            '
'+
            '
';
    var infowindow = new google.maps.InfoWindow({
        content: contentString,
        maxWidth: 250
    });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
}
google.maps.event.addDomListener(window, 'load', initialize);

Here is the Popup preview image -
  Image Preview

A: You should use resize on modal shown to refresh your map:
$('modal-id').on('shown.bs.modal', function ()
{
    google.maps.event.trigger(map, "resize");
});

Hope this helps.

A: I have added this for a static map load which is in the modal popup.
google.maps.event.addListener(map, "idle", function()
{
   google.maps.event.trigger(map, 'resize');
});


text:
Q: Creating Neutral network for line detection - is it possible? So I want to detect lines on grayscale images. I have a lot of data 9x9 matrices of pixel ints 1 to 256 and 1*4 matrices of ponnts coords X ,Y, X,Y We have 1 line per 9x9 image or non lines. So what structure should have my NN?

A: Detecting simple lines on a grayscale image is a well known problem. A Hough transform would be suffice for the job. See http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html?highlight=hough%20line#cv-houghlines for a function that implement finding lines using Hough Transform.
Can you try the above function and see if it works?
If it doesn't, please update your question with a sample image.

A: Assuming that you're using the most common variety of neural networks, multillayer perceptrons, you'll have exactly as many input nodes as there are features.
The inputs may include transformed variables, in addition to the raw variables.  The number of hidden nodes is selected by you, but you should have enough to permit the neural network to adequately make the mapping.
The number of output nodes will be determined by the number of classes and the representation you choose.  Assuming two classes ("line", "not line" seems likely), you may use 1 output node, which indicates the estimated probability of one class (the probability of the remaining class being 1 minus the probability of the first class).


text:
Q: Colour Plotly table based on value with index I have a dataframe

How do I plot this as Plotly table, color its cells based on the cell value, were 1 should be replaced with green color and 0 with grey.
Also while plotting the table, the column names and row index should be maintained in table without color.
The resultant table should be

Above visualization can be achieved using pandas style configurations, but how do I achieve the same in Plotly-Dash
The examples provided here https://plotly.com/python/table/#cell-color-based-on-variable,
dont show how to preserve the row and column index names/values without coloring them

A: *

*it's really included in plotly table pandas documentation

*just need to extend to include index in data that is provided to header* and cells

*plus a simple colour matrix which matches your styling requirements

import pandas as pd
import numpy as np
import plotly.graph_objects as go

df = pd.DataFrame(
    {
        **{"index": [f"a{i+1}" for i in range(3)]},
        **{
            d: np.random.randint(0, 2, 3)
            for d in pd.date_range("18-jul-2021", periods=4)
        },
    }
).set_index("index")

fig = go.Figure(
    go.Table(
        header={"values": [df.index.name] + df.columns.tolist()},
        cells=dict(
            values=df.reset_index().T.values,
            fill_color=np.select(
                [df.reset_index().T.values == 1, df.reset_index().T.values == 0],
                ["green", "red"],
                "white",
            ),
            align="center",
        ),
    )
)
fig


text:
Q: How to displaying all data from all file_get_contents & search one of them I have some txt files, and show only one file using the function file_get_contents ().
if I want to find an object within each file, then I have to open the file one by one and search it using ctrl + f.
I think it's not an effective way to search for an object from all the existing files.
Can anyone suggest me how to create a "search feature" to search for an object on some of the txt files?
i use php script.
this is txt file

A: make a scandir to list files, then use file_get_contents to find the content and search into with


text:
Q: Finding Consecutive day Excluding Weekends So my work manages different parts(screws, nuts...). We have these buckets that these parts fall into because they qualify as a part that needs to be ordered (low inventory). When the parts fall in the bucket they need to be ordered and resolved, if not they reappear in the bucket the next day(EXPEID_DESK).
The goal is to find the consecutive days that these parts have been in the bucket but skipping over Sunday and Monday (system isn't running those days) and count consecutively again
This is the code:
With a as (
    SELECT
        ITEM_ID,
        SUGGESTION_DT,
        PDC,EXPID_DESC,
        PLNR_CD,
        DATEADD(DAY,
                - ROW_NUMBER() OVER(PARTITION BY Item_ID,PDC,EXPID_DESC,PLNR_CD
                                    ORDER BY SUGGESTION_DT),
                SUGGESTION_DT) as GroupingSet
    FROM jda.m_suggested_versus_ordered
    where SUGGESTION_DT >= '2022-01-01'and EXPID_DESC ='Inside Leads'
)
select
    ITEM_ID,
    PDC,
    EXPID_DESC,
    count(*)as consec,
    PLNR_CD,
    MAX(SUGGESTION_DT) as day_end,
    MIN(SUGGESTION_DT) as day_start
from a
group by ITEM_ID, PDC, EXPID_DESC, PLNR_CD, GroupingSet
order by consec desc;

This is the output:
Output


text:
Q: How to access the menu item within a frame using Selenium Webdriver or Cypress? I am having some trouble clicking a menu button on a webpage for work. The error occurs whether I am using Selenium or Cypress. While using cypress I get an uncaught exception error, and an error stating the (html) document cannot be read - while using selenium the element cannot be found.
After I login to the application I can't access anything.
driver.switchTo().defaultContent();
driver.switchTo().frame(driver.findElement(By.tagName("frameset")).findElements(By.tagName("frame")).get(1));
driver.findElement(By.cssSelector("body > table.section > tbody > tr > td > table > tbody > tr > td:nth-child(1)")).click();

I have tried to find it using the xpath as well. I'll also provide a snip of the html. Any help or guidance would be greatly appreciated.

A: To click on the <td> element you need to switchTo() the iframe ignoring the iframeset using either of the following locator strategies:

*

*Using cssSelector:
driver.switchTo().defaultContent();
driver.switchTo().frame(driver.findElement(By.cssSelector("frame#1[src^='displayMenu']")));
driver.findElement(By.cssSelector("table.menubutton > tr > td")).click();

*Using xpath:
driver.switchTo().defaultContent();
driver.switchTo().frame(driver.findElement(By.xpath("//frame[@id='1' and starts-with(@src, 'displayMenu')]")));
driver.findElement(By.xpath("table[@class='menubutton']//tr/td")).click();


text:
Q: PHP - fread() function I have simple file ...i got the code from w3schools
When i tried to execute the code
fread() function doesn't return anything
first.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$file = fopen("test.php","r");
fread($file,filesize("test.php"));

?>

test.php
<?php
echo "Hello world";
?>

when i open localhost/first.php
the result is blank page

A: You never capture what you read to display it on the page. Do
$contents = fread(...);
if($contents===false):
    //there was an error
else:
    echo $contents;
endif;


text:
Q: ImageView emptied on subsequent activity launches I'm using this AsyncTask to load an image from a URL and populate an ImageView with that image:
new DownloadImageTask((ImageView) findViewById(R.id.headerIV)).execute(imageURL);

and
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {

        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

I noticed that whenever I background my app and relaunch the activity, the ImageViews are emptied. Various checks on the ImageViews show that they are null in onCreate(), and so if I want to show images again, I have to call the AsyncTask again, which eventually leads to out-of-memory exceptions. So, I'm wondering: Does the activity recycle/empty my ImageViews for some reasons on onPause() based on that code block I'm using?

A: Try this !!!!
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

ImageView bmImage;
Bitmap mIcon11;

public DownloadImageTask(ImageView bmImage) {
    this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {

    try {
            mIcon11 = BitmapFactory.decodeStream((InputStream) new URL(urls[0]).getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
    return mIcon11;
}

protected void onPostExecute(Bitmap result) {
    if (result != null) {
            bmImage.setImageBitmap(result);

        } else {

            Toast.makeText(TestActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();

        }
}
}

A: Whenever your app comes to foreground the onResume() is called and the views are generated again, so that can be the reason for the null values.
You can use onResume() for the same. (For more info check out Activity life cycle)
Also as suggested by others, you can use Picasso or Universal Image Loader or other libraries for ease.
To start with you can refer below links:
https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/
http://javatechig.com/android/how-to-use-picasso-library-in-android
http://javatechig.com/android/universal-image-loader-library-in-android


text:
Q: extracting unique values from a column with multiple criteria I have data where im trying to extract unique values from one column for each set of my customers. i want to use the data to do a mail merge . for instance column A has multiple entries for each customer name. so in column A cells a1:a6 all say "abc company" the cells a7:a11 all say "X company". in column B it has a recommended part number list. so b1:b3 all say "01-ssc-011" then b3:b5 all say 01-ssc-044 then b5:b8 all say "01-ssc-011" and finally b8:b11 all say 01-ssc-044"
how would i extract the unique part numbers for each set of customers. I want to essentially delete duplicate instances of part number PER CUSTOMER and leave only unique part numbers for each customer.
enter image description here

A: Assuming there is no other data in other cell/column.
Select column A&B > Data > Remove duplicates.
Please share if it works/not. ( :


text:
Q: Aggregation does not working in Mongoose with Match and Group i'm coding an application using AngularJS, NodeJS and Mongoose.
Now, i'm doing a chart and I need to return some data passsing some parameters.
But the aggregation does not work. I have this query working in MongoDB:

var user = db.getCollection('users').find(
{profile: "SUPERVISOR"},{_id: 1}).map(function(u){return u._id;}
)

db.getCollection("visitas").aggregate(
    { '$match':
     { createdAt:
       { '$gte': ISODate('2015-01-10T00:00:00.000Z'),
         '$lt': ISODate('2015-07-01T00:00:00.000Z') } } }, { '$group':
     { _id: { usuario: user, dia: [Object] },
      visitas: { '$sum': 1 } } }
)

When I try to run the same query in my application using Mongoose, the query does not work. The problem i've seen is that the comma between MATCH and GROUP is disapearing. When i try to search with only group or match, the query works. Someone can help me? This is the application code:

 .then(function (listaUsuarios){
           var argsVisit;
          console.log({ $match : { "createdAt" : { $gte: "2015-01-10T00:00:00.000Z", $lt: "2015-07-01T00:00:00.000Z"  }} },
                  { $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } }, "visitas" : { $sum : 1 } } });

          Visita.aggregate({ $match : { "createdAt" : { $gte: "2015-01-10T00:00:00.000Z", $lt: "2015-07-01T00:00:00.000Z"  }} },
                  { $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } }, "visitas" : { $sum : 1 } } })
            .exec(function (err, results) {
                    if (err) {
                        console.log("Erro!!!");
                        deferredDados.reject({
                            error: 500,
                            message: 'Erro buscando Visita, erro: '+err
                        });
                    } else {
                        if (!results || results.length == 0) {
                            console.log("Sem retorno!!!");
                            deferredDados.resolve( [0,0,0,0,0,0,0] ); //Tudo zerado poruqe não há retorno.
                            //deferredDados.resolve(0);

                            deferredDados.reject({
                                error: 500,
                                message: 'Erro buscando Visitas, não achou resultados'

                            });
                        } else {
                            console.log("Dados"+results);
                            deferredDados.resolve( results );
                            //deferredDados.resolve( results.data] );
                        }

                    }

                });
          return deferredDados.promise;
      })

A: SOLVED!!!
A member of my team found the error! \o/
Maybe this can help someone who will have the same problem.
To solve, you just have to convert the date, in string, to the date type.
The solved code is below:
.then(function (listaUsuarios){
       var argsVisit;

      if (tipoVisita == 'N'){
            argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2001","2002"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
        } else if (tipoVisita == 'R'){
            argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2005"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
        } else if (tipoVisita == 'I'){
            argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2003"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
        }

        var initDate = new Date('2015-04-02T00:00:00.000Z');
        var endDate = new Date('2015-05-09T00:00:00.000Z');

       argsMatch = [{ $match : { "createdAt" : { $gte: initDate, $lt: endDate  }} },
                   { $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } },  "visitas" : {$sum : { $cond: [ {$or : [ { $eq: [ "$tipo", "2001"] },{ $eq: [ "$tipo","2002"] }] },1,0 ]}}}
                    }]

      Visita.aggregate(argsMatch)
        .exec(function (err, results) {
                if (err) {
                    console.log("Erro!!!");
                    deferredDados.reject({
                        error: 500,
                        message: 'Erro buscando Visita, erro: '+err
                    });
                } else {
                    if (!results || results.length == 0) {
                        console.log("Sem retorno!!!");
                        deferredDados.resolve( [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ); //Tudo zerado poruqe não há retorno.
                        //deferredDados.resolve(0);

                        deferredDados.reject({
                            error: 500,
                            message: 'Erro buscando Visitas, não achou resultados'

                        });
                    } else {
                        deferredDados.resolve( results );
                    }

                }

            });
      return deferredDados.promise;
  })
  .then(function(dados) {
        res.json(dados);

    })
   .catch(function(fallback) {
    console.log('Erro no retorno dos usuarios!!!');
    console.log(fallback);
  });

I hope this can help someone.


text:
Q: widget based web framework for scala I am trying to move from java to scala . I am basically a web developer where i use zkoss, vaadin as my framework. Do scala has widget based framework.Fully ajax based? I haven't tried lift and play need some advice is that fully ajax based?

A: Try Scala+GWT with one of web frameworks (Lift, Play and etc.)

A: The Vaadin framework can be used with Scala. There is even a project called Scaladin to help you with that. Since you already know it, I suggest you try learning scala with that framework. After you have a good understand of scala you should have a better base for what framework to choose in case you want to leave Vaadin.
Here are some resources:

*

*Scala and Vaadin HOWTO

*Scaladin wiki

*Develop Vaadin apps with Scala


text:
Q: How do you determine if a list of of points in 3D space are in clock-wise order? point[0] = (0,1,1)
point[1] = (1,1,1)
point[2] = (0,0,1)
point[3] = (1,0,1)

For examples below, each point above maps to an index in the visualization below.
0----------1
|          |
|          |
|          |
3----------2

A: You can't.
If the points are not coplanar, it is even impossible to define an orientation.
If the points are coplanar, you can look at their plane from both sides.

If you want this information with respect to an observer, project the vertices to the viewing plane (to reduce to 2D) and compute the algebraic area by the shoelace formula. The sign tells you the orientation.

A: You can but only in respect to some direction ...
taking your example if you are looking on it as is its CW however if you look at it from behind its CCW ... if you look from sides (perpendicularly so the face is projected to line) we can not tell.
So the usual approach is to do a cross product of the vertices. This will give you normal vector of the face but the direction is determined by the CW/CCW. Now the result compare to reference direction by dot product. So:
vec3 p0,p1,p2; // 3 vertexes of your face not on single line
vec3 dir;      // reference direction
float winding = dot( cross( p1-p0 , p2-p1 ) , dir )

Now the winding sign tells you if the face is CW or CCW in respect to dir. Which one it is depends on your notations. However this works only for convex polygons (or in convex part of concave ones) !!!
In computer graphics the reference direction is usually camera view direction. So once in camera local space coordinate system the direction is z axis so inspecting the z coordinate of the cross product is enough. This is known as face culling (skipping polygons with wrong winding in GL set by GL_CULL_FACE)...
You can look at the reference dir as an axis of rotation aorund which you are determining if the points are CW or CCW ...


text:
Q: Use the Shell Method to compute the volume of the solid obtained by rotating the region bound by the graph y=4^2-x^2 Use the Shell Method to compute the volume of the solid obtained by rotating the region bound by the graph  $4y=4^2-x^2$ and the $x$-axis about the line $x=6$.
Hello, I've been having a lot of problems with this question. I feel fairly certain about what I am doing, but the answer is not correct. I'm not really looking for the answer, but rather help in determining where I am going wrong. Currently I'm working with the idea that the radius is $(6-x)$ and the height is $16-x^2$. I'm using the shell method so my area before integrating is $2\pi(6-x)(16-x^2)$, and the bounds being $0$ and $4$.
The answer I keep getting is $384\pi$, which is incorrect.
My guess is I'm making a mistake with the radius, but everything I'm reading points to it being correct. Any help would be appreciated.

A: Your radius function is correct:  $r = 6-x$.  Your height should be $f(x) = y = \frac{1}{4}(16-x^2)$.  The interval of integration is $x \in [-4,4]$, because these are the solutions to $0 = y = 16-x^2 = (4-x)(4+x)$.  Therefore, the volume integral is $$V = \int_{x=-4}^4 2\pi r f(x) \, dx = \int_{x=-4}^4 \frac{\pi}{2} (6-x)(16-x^2) \, dx.$$


text:
Q: Kubernetes exposed pod connection refused - one time works, sometime not I have a kubernetes instalation with master and 1 node.
It is configured and everything is working very good.
$ kubectl get pods

NAME          READY     STATUS    RESTARTS   AGE
mantis-gfs    1/1       Running   1          22h
mongodb-gfs   1/1       Running   0          14h

I exposed the pod mongodb-gfs:
$ kubectl expose pod mongodb-gfs --port=27017 --external-ip=10.9.8.100 --name=mongodb --labels="env=development"

The extrnal IP 10.9.8.100 is the IP of the kubernetes master node
The service was created successfully.
$ kubectl get services

NAME                TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)     AGE
glusterfs-cluster   ClusterIP   10.111.96.254   <none>        1/TCP       23d
kubernetes          ClusterIP   10.96.0.1       <none>        443/TCP     29d
mongodb             ClusterIP   10.100.149.90   10.9.8.100    27017/TCP   1m

Now i am able to access the mongo using:
mongo 10.9.8.100:27017

And here is the problem. It works some time, but some time not.
I connect once and i get the shell, i connect second time and get:
$ mongo 10.9.8.100:27017

MongoDB shell version v3.4.17
connecting to: mongodb://10.9.8.100:27017/test
2018-11-01T09:27:23.524+0100 W NETWORK  [thread1] Failed to connect to 10.9.8.100:27017, in(checking socket for error after poll), reason: Connection refused
2018-11-01T09:27:23.524+0100 E QUERY    [thread1] Error: couldn't connect to server 10.9.8.100:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:240:13
@(connect):1:6
exception: connect failed

Then i try again and it works, try again it works, try again it not works...
Any clues what may cause the problem?

A: I found the problem and the solution. The problem was, the pod definition. For both pods: mongodb-gfs and mantis-gfs i have the same label settings. Then i exposed services with the same label="env=development". In this case the traffic that i expected to go always to one pod was "loadbalanced" to one or other pod (they have the same label) of different types.
Changing the label in the mongodb-gfs pod definition solved the problem with connection issues.

A: Had the same issue and przemas led me in the right direction with the selectors. When different pods have the same selector labels k8s selects the wrong one sometimes. You have to choose unique names for the selectors. Weird that this is not logged anywhere which pod is selected.
apiVersion: v1
kind: Service
metadata:
 name: revproxy-svc
spec:
 selector:
   role: app
 type: NodePort

---

apiVersion: v1
kind: Service
metadata:
 name: loadbalance-svc
spec:
 selector:
   role: app
 type: NodePort

---

apiVersion: apps/v1
kind: Deployment
metadata:
 name: loadbalancer-python
spec:
 replicas: 1
 selector:
   matchLabels:
     role: app
 template:
   metadata:
     labels:
       role: app

---

apiVersion: apps/v1
kind: Deployment
metadata:
 name: revproxy
spec:
 replicas: 2
 selector:
   matchLabels:
     role: app
 template:
   metadata:
     labels:
       role: app


text:
Q: How do I send tempo or timing information to AVAudioUnitMIDIInstrument in Mac OS swift using AVFoundation I have a Mac OS desktop app which hosts virtual instrument plugins as AVAudioUnitMIDIInstrument. My app is basically a music sequencer. I would like to trigger instruments that use drum loops and/or arpeggiators. This requires sending some sort of timing information to the AVAudioUnitMIDIInstrument. How do I do this? My guess is that I need to send either a MidiMetaEvent, or perhaps regular MidiTimestamp info. How do I do this? I don't see any methods on AVAudioUnitMidiInstrument that do this. Here are the methods I see:
func sendController(UInt8, withValue: UInt8, onChannel: UInt8)
Send a MIDI controller event to the instrument.

func sendMIDIEvent(UInt8, data1: UInt8)
Sends a MIDI event which contains one data byte to the instrument.

func sendMIDIEvent(UInt8, data1: UInt8, data2: UInt8)
Sends a MIDI event which contains two data bytes to the instrument.

func sendMIDISysExEvent(Data)
Sends a MIDI System Exclusive event to the instrument.

func sendPitchBend(UInt16, onChannel: UInt8)
Sends a MIDI Pitch Bend event to the instrument.

func sendPressure(UInt8, onChannel: UInt8)
Sends a MIDI channel pressure event to the instrument.

func sendPressure(forKey: UInt8, withValue: UInt8, onChannel: UInt8)
Sends a MIDI Polyphonic key pressure event to the instrument.

func sendProgramChange(UInt8, bankMSB: UInt8, bankLSB: UInt8, onChannel: UInt8)
Sends MIDI Program Change and Bank Select events to the instrument.

func sendProgramChange(UInt8, onChannel: UInt8)
Sends MIDI Program Change and Bank Select events to the instrument.

func startNote(UInt8, withVelocity: UInt8, onChannel: UInt8)
Sends a MIDI Note On event to the instrument.

func stopNote(UInt8, onChannel: UInt8)
Sends a MIDI Note Off event to the instrument

A: The way that audio plugins get timing information is by setting a callback function that calls your host and retrieves information such as time signature, tempo and position.
import Foundation
import AVFoundation
import AudioToolbox
import CoreAudioKit
class AudioNodeFactory{
    class func instrument(description: AudioComponentDescription, context: AUHostMusicalContextBlock?) -> AVAudioUnitMIDIInstrument{
        let plugin = AVAudioUnitMIDIInstrument(audioComponentDescription: description)
        plugin.auAudioUnit.musicalContextBlock = context
        return plugin
    }
}

A musical context block looks something like this:

func getMusicalContext(currentTempo : UnsafeMutablePointer<Double>?,
                        timeSignatureNumerator : UnsafeMutablePointer<Double>?,
                        timeSignatureDenominator : UnsafeMutablePointer<Int>?,
                        currentBeatPosition: UnsafeMutablePointer<Double>?,
                        sampleOffsetToNextBeat : UnsafeMutablePointer<Int>?,
                        currentMeasureDownbeatPosition: UnsafeMutablePointer<Double>?) -> Bool {
     if self.delegate == nil { return false }
     let context = self.delegate!.musicalContext
     currentTempo?.pointee = context.currentTempo
     timeSignatureNumerator?.pointee = context.timeSignatureNumerator
     timeSignatureDenominator?.pointee = context.timeSignatureDenominator
     currentBeatPosition?.pointee = context.currentBeatPosition
     sampleOffsetToNextBeat?.pointee = context.sampleOffsetToNextBeat
     currentMeasureDownbeatPosition?.pointee = context.currentMeasureDownbeatPosition
     return true
 }


text:
Q: Starting Up SQL Server 2008 in IIS I'm a complete noob at windows servers and IIS so please be patient with me.
I originally set up a website using php/mysql.  I have the website running PHP with FastCGI through IIS already, but the SQL Server part is tripping me up.  I'm shocked that there are no instructions about this that I can find anywhere.
I installed a bunch of SQL Server options through the Web Platform Installer (WPI).  I can't connect using sqlcmd or the Microsoft SQL Server Management Studio.  I get the same error for both ("A network related or instance-specific error has occurred...")  I know I'm missing a vital step to start up the server and connect to it, but I can't find what I need to do anywhere.  SQL Server (SQLEXPRESS) is displaying as running in my services list.  In the SQL Server Configuration manager, SQL Server (SQLEXPRESS) is shown as running in the SQL Server Services list.  SQL Server Browser and SQL Server Agent are listed, but stopped, and the option to start them is grayed out.
I need to be able to create my DB on this machine through something and connect to the server through php with the sqlsrv driver. The sqlsrv_* functions work, but I can't connect to localhost with sqlsrv_connect() either.  I'm sure I'm just missing some important step to get the server actually running.
I'd love to use LAMP, but a lot of the other application software relies on SQL Server and windows.

A: You sayed something about php/mysql, be aware that SQL Server (Express) is not MySql.
First of all, I guess you want to at lest get a connection using Management Studio so you at least can 'see' a database? You first need to configure the SQL Server Client. Try this:

*

*Hold down the windows key and press "R" (or click the start button and use the search box).

*type "cliconfg" (without the quotes) and hit enter

*Enable Named pipes or TCP/IP and check shared memory

Now you have to do the same on the server: In the start menu you should have a "SQL Server 2008 R2" entyr with "Configuration tools" under it. From there click on "SQL Server Configuration Manager". If you can't find the "SQL Server Configuration Manager" in your start menu (it might not be installed for "all users") try this:

*

*Hold down the windows key and press "R" (or click the start button and use the search box).

*type "mmc" (without the quotes) and hit enter

*Go to File -> Add or Remove Snap-In

*Locate "SQL Server Configuration Manager" and add it to the right "Selected Snap-Ins"

*

*If you still could not find it, you need to install it, download from here: http://www.microsoft.com/downloads/details.aspx?familyid=56AD557C-03E6-4369-9C1D-E81B33D8026B

*Click Ok

From there you should be able to enable the server-side protocols.
After this, you should be able to connect to the server using SQL Server Management Studio. Now you can run your SQL installation scripts (you might need to do some tweaking if the original ones were for MySql).
This is not a full answer since you're not done yet. You'll have to tweak the PHP site to use the correct client and set the correct connection-string(s). Hope that helps.


text:
Q: how to insert multiple rows into sqllite3 database I am trying to select rows and fetch them from the DB table and then insert them into a list so I can insert all of the rows at once into the database, but I got an error.
def paid_or_returned_buyingchecks(self):
    date = datetime.now()
    now = date.strftime('%Y-%m-%d')
    self.tenlistchecks=[]

    self.con = sqlite3.connect('car dealership.db')
    self.cursorObj = self.con.cursor()

    self.dashboard_buying_checks_dates = self.cursorObj.execute("select id, paymentdate , paymentvalue, car ,sellername from cars_buying_checks where nexttendays=?",(now,))
    self.dashboard_buying_checks_dates_output = self.cursorObj.fetchall()
    self.tenlistchecks.append(self.dashboard_buying_checks_dates_output)
    print(self.tenlistchecks)

    self.dashboard_buying_checks_dates = self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])

    self.con.commit()

but I got an error :
[[(120, '21-08-2022', '1112', 'Alfa Romeo', 'james'), (122, '21-08-2022', '465', 'Buick', 'daniel '), (123, '21-08-2022', '789', 'Buick', 'daniel ')]]
self.dashboard_buying_checks_dates = self.cursorObj.executemany(
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 1 supplied.

A: self.cursorObj.fetchall() returns a list of tuples, which is what you need to feed to executemany, so
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",self.tenlistchecks)

not
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])


text:
Q: graphql-redis-subscriptions on Heroku not working consistently We are using subscriptions on a node graphql server. Recently I added the cluster ability and used Redis for pubsub. On my local environment all works great. When I upload to heroku and use their Redis addon the first time I fire a mutation I see it show but the next time it does not. After a few attempts it works again (50% work).
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';

let REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:6379';

const options = {
  retryStrategy: times => {
    // reconnect after
    return Math.min(times * 50, 2000);
  }
};

const pubsub = new RedisPubSub({
  publisher: new Redis(REDIS_URL, options),
  subscriber: new Redis(REDIS_URL, options)
});

Here is the error I get in the log
Aug 22 16:06:11 service-staging app[web] Error (node:76) UnhandledPromiseRejectionWarning: Error: Connection in subscriber mode, only subscriber commands may be used
Aug 22 16:06:11 service-staging app[web] info     at Redis.sendCommand (/app/node_modules/ioredis/built/redis/index.js:570:24)
Aug 22 16:06:11 service-staging app[web] info     at DatastoreShim.applySegment (/app/node_modules/newrelic/lib/shim/shim.js:1424:20)
Aug 22 16:06:11 service-staging app[web] info     at _applyRecorderSegment (/app/node_modules/newrelic/lib/shim/shim.js:1015:20)
Aug 22 16:06:11 service-staging app[web] info     at Redis._doRecord (/app/node_modules/newrelic/lib/shim/shim.js:994:17)
Aug 22 16:06:11 service-staging app[web] info     at Redis.wrapper [as sendCommand] (/app/node_modules/newrelic/lib/shim/shim.js:965:24)
Aug 22 16:06:11 service-staging app[web] info     at Redis.publish (/app/node_modules/ioredis/built/commander.js:124:21)
Aug 22 16:06:11 service-staging app[web] info     at RedisPubSub.<anonymous> (/app/node_modules/graphql-redis-subscriptions/src/redis-pubsub.ts:64:31)
Aug 22 16:06:11 service-staging app[web] info     at step (/app/node_modules/graphql-redis-subscriptions/dist/redis-pubsub.js:32:23)
Aug 22 16:06:11 service-staging app[web] info     at Object.next (/app/node_modules/graphql-redis-subscriptions/dist/redis-pubsub.js:13:53)
Aug 22 16:06:11 service-staging app[web] info     at /app/node_modules/graphql-redis-subscriptions/dist/redis-pubsub.js:7:71
Aug 22 16:06:11 service-staging app[web] info     at new Promise (<anonymous>)
Aug 22 16:06:11 service-staging app[web] info     at __awaiter (/app/node_modules/graphql-redis-subscriptions/dist/redis-pubsub.js:3:12)
Aug 22 16:06:11 service-staging app[web] info     at RedisPubSub.publish (/app/node_modules/graphql-redis-subscriptions/dist/redis-pubsub.js:76:16)
Aug 22 16:06:11 service-staging app[web] info     at publish (/app/src/resolvers/action.js:435:18)
Aug 22 16:06:11 service-staging app[web] info (node:76) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 9)

When I run the mutation I should see it show up for the listening subscription.
Also, on a side note if I set the number of instances to 1 or 2 I always get the error. 3 or more I at least get the first mutation and half of the following mutations.

A: After much personal pain and anguish I got it running. I removed the Heroku Redis add on and replaced it with the Redis Cloud add on. All works just as expected!


text:
Q: CFArrayGetValueAtIndex not returning aything I have an extremely simple code snippet to get the application support directory of a use. Problem is, it doesn't work! I get the values in a CFArrayRef (because I want to use C code since I will use this snippet in a C++ application later) and try to get the first string in there using CFArrayGetValueAtIndex(). I convert the returned void* to a char* using a C-style cast and attempt to output it using printf(), but nothing gets outputted! Can anyone explain why? I've looked online through the documentation for CFArray and tried to google the issue, but came up with nothing. Any help would be really appreciated!
Code:
#include <Foundation/Foundation.h>
#include <typeinfo>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    CFArrayRef array = \
      (CFArrayRef)NSSearchPathForDirectoriesInDomains(
                        NSApplicationSupportDirectory,
                        NSUserDirectory,
                        YES);
    char* string = (char*)CFArrayGetValueAtIndex(array, 0);
    printf("string: %s\n", string);
    [pool drain];
}

A: Why are you converting it to a char*? The resulting array from NSSearchPathForDirectoriesInDomains() contains CFStringRefs, not char*s.
Try using CFShow((CFTypeRef)CFArrayGetValueAtIndex(array, 0));


text:
Q: How to display detail informations from firestore in another activity when I click a listView item? I'm making app and I use firestore as database. I made a listView consisting of movies(just names). And I want to display details in another activity when I click one of them. I did something for this but I just get the last movie I added. When I click the another one, the result is the last movie I added. All movie details are same. I couldn't fix this. How can I fix it?
this is how I made the listView part
public class Izlediklerim extends AppCompatActivity {
    private FirebaseAuth firebaseAuth;
    private FirebaseFirestore firebaseFirestore;
    ArrayList<String> adArray;
    ListView listView;
    ArrayAdapter arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_izlediklerim);

        firebaseFirestore=FirebaseFirestore.getInstance();
        adArray=new ArrayList<>();
        listView=findViewById(R.id.listView);
        arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,adArray);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent=new Intent(Izlediklerim.this,FilmiGoster.class);
                startActivity(intent);
            }
        });
        filmleriAl();
    }
    public void filmleriAl(){
        CollectionReference collectionReference = firebaseFirestore.collection("Filmler");
        collectionReference.orderBy("filmtarih").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Toast.makeText(Izlediklerim.this, e.getLocalizedMessage().toString(), Toast.LENGTH_LONG).show();
                }

                if (queryDocumentSnapshots != null) {

                    for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {

                        Map<String, Object> data = snapshot.getData();
                        String name = (String) data.get("filmadi");

                        adArray.add(name);
                        arrayAdapter.notifyDataSetChanged();
                    }
                }

            }
        });
    }
}

and this is the detail part
public class FilmiGoster extends AppCompatActivity {
    ImageView fr;
    TextView fa,ft,fh;
    private FirebaseAuth firebaseAuth;
    private FirebaseFirestore firebaseFirestore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filmi_goster);

        fr=findViewById(R.id.fr);
        fa=findViewById(R.id.fa);
        ft=findViewById(R.id.ft);
        fh=findViewById(R.id.fh);

        firebaseFirestore=FirebaseFirestore.getInstance();
        firebaseAuth=FirebaseAuth.getInstance();

        CollectionReference collectionReference = firebaseFirestore.collection("Filmler");
        collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Toast.makeText(FilmiGoster.this,e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();
                }

                if (queryDocumentSnapshots != null) {
                    for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {

                        Map<String, Object> data = snapshot.getData();

                        String hakkinda = (String) data.get("filmdusunce");
                        String ad = (String) data.get("filmadi");
                        String downloadUrl = (String) data.get("downloadurl");
                        String zaman = (String) data.get("filmtarih");

                        fa.setText(ad);
                        Picasso.get().load(downloadUrl).into(fr);
                        fh.setText(hakkinda);
                        ft.setText(zaman);

                    }
                }
            }
        });
    }

}

A: Have 2 more array lists in Izlediklerim
public class Izlediklerim extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;
    private FirebaseFirestore firebaseFirestore;
    ArrayList<String> adArray;

    //here..
    ArrayList<String> hakkindaArray = new ArrayList<>();
    ArrayList<String> zamanArray = new ArrayList<>();

    ListView listView;
    ArrayAdapter arrayAdapter;
    .......
    .......

Now in filmleriAl() method of Izlediklerim:
for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {

 Map<String, Object> data = snapshot.getData();

String name = (String) data.get("filmadi");

//add these too
String hakkinda = (String) data.get("filmdusunce");
String zaman = (String) data.get("filmtarih");

adArray.add(name);

//add these too
hakkindaArray.add(hakkinda);
zamanArray.add(zaman);
....
....

Pass the movie details as an intent extra:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

Intent intent=new Intent(Izlediklerim.this,FilmiGoster.class);
//here..
intent.putExtra("movie_name" , adArray.get(position));
intent.putExtra("movie_hakkinda" , hakkindaArray.get(position));
intent.putExtra("movie_zaman" , zamanArray.get(position));
startActivity(intent);
....
....

Now in your onCreate() of FilmiGoster get the details passed:
public class FilmiGoster extends AppCompatActivity {
ImageView fr;
TextView fa,ft,fh;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;

//add these

private String movieName;
private String movieHakkinda;
private String movieZaman;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filmi_goster);

//here get the passed movie details and use directly in textViews
movieName = getIntent().getStringExtra("movie_name");
movieHakkinda = getIntent().getStringExtra("movie_hakkinda");
movieZaman = getIntent().getStringExtra("movie_zaman");

......
......