问:
Vuejs not loading image completely from backend API
Context:
I've got a WebApp (frontend: Vue3, backend: node.js + express) with a single vue, and a button. When clicking on a button it triggers a script in the backend, downloading an image, and storing it locally. This image should be rendered on the Vue side.

My Issue:
Everything seems to work, except that Vue is not displaying the image completely. I only have a small share of the file displayed.

Backend Controller (images.controller.js):

```<code>const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const downloadImage = async(fileUrl, fileName) => {
    let isDownloaded = false
    const downloadFolder = './images';

    const localFilePath = path.resolve(__dirname, downloadFolder, fileName);

    try {
        const response = await axios({
            method: 'GET',
            url: fileUrl,
            responseType: 'stream',
        });

        if(response.status === 200){
            isDownloaded = true;
            await response.data.pipe(fs.createWriteStream(localFilePath));
        }

    } catch (error) {
        console.log(error)
    }

    return isDownloaded;
}

const readImage = async(req, res) => {
    try {
        const fileName = `${uuidv4()}.jpeg`;
        const fileUrl = 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg';
        const isDownloaded = await downloadImage(fileUrl, fileName);

        if(isDownloaded){
            const img = fs.readFile(__dirname + '/images/' + fileName, async(err, data) => {
                var contenType = 'image/jpeg';
                var base64 = await Buffer.from(data).toString('base64');
                base64 = 'data:image/jpeg;base64,' + base64;
                res.status(200).send(base64)
            })
        }
    } catch (error) {
        console.log(error)
    }
}

module.exports = {
    readImage: readImage,
}
</code>```

Frontend side, my Home.vue:

```<code><template>
  <div class="home">
    <button @click="readImage">TEST</button>
    <div v-if="img">
      <img :src="img">
    </div>
  </div>
</template>

<script>
import ImagesService from '../services/images.service'
export default {
  name: 'Home',
  data(){
    return {
      img: ''
    }
  },

  methods: {
    async readImage(){
      const temp = await ImagesService.readImages({name: 'dog.jpeg'})
      this.img = temp.data
    }
  },
}
</script>
</code>```

images.service.js:

```<code>import api from '../../http-common';

export default new class ImagesService {
    //Read Screenshot
    readImages(imageName){
        return api.post('read/image', imageName)
    }
}
</code>```

http-common.js:

```<code>import axios from 'axios'

export default axios.create({
    baseURL: 'http://localhost:3003/api',
    headers: {
        "Content-type": "application/json",
    }
})
</code>```

答:
it's because stream is not a promise: image is read and downloaded before the stream is finished saving it

Try wrapping data.pipe in a promise and resolve when the saving is done:

```<code>const downloadImage = (fileUrl, fileName) => {
    return new Promise(async(resolve, reject) => {
        let isDownloaded = false
        const downloadFolder = './images';

        const localFilePath = path.resolve(__dirname, downloadFolder, fileName);

        const imgStream = fs.createWriteStream(localFilePath);

        try {
            const response = await axios({
                method: 'GET',
                url: fileUrl,
                responseType: 'stream',
            });

            if (response.status === 200) {

                response.data.pipe(imgStream);
            }

        } catch (error) {
            console.log(error)
            reject(error);
        }

        imgStream.on('finish', () => {
            resolve(true);
        });
    })
};
</code>```

Body:
Context:
I've got a WebApp (frontend: Vue3, backend: node.js + express) with a single vue, and a button. When clicking on a button it triggers a script in the backend, downloading an image, and storing it locally. This image should be rendered on the Vue side.

My Issue:
Everything seems to work, except that Vue is not displaying the image completely. I only have a small share of the file displayed.

Backend Controller (images.controller.js):

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const downloadImage = async(fileUrl, fileName) => {
    let isDownloaded = false
    const downloadFolder = './images';

    const localFilePath = path.resolve(__dirname, downloadFolder, fileName);

    try {
        const response = await axios({
            method: 'GET',
            url: fileUrl,
            responseType: 'stream',
        });

        if(response.status === 200){
            isDownloaded = true;
            await response.data.pipe(fs.createWriteStream(localFilePath));
        }

    } catch (error) {
        console.log(error)
    }

    return isDownloaded;
}

const readImage = async(req, res) => {
    try {
        const fileName = `${uuidv4()}.jpeg`;
        const fileUrl = 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg';
        const isDownloaded = await downloadImage(fileUrl, fileName);

        if(isDownloaded){
            const img = fs.readFile(__dirname + '/images/' + fileName, async(err, data) => {
                var contenType = 'image/jpeg';
                var base64 = await Buffer.from(data).toString('base64');
                base64 = 'data:image/jpeg;base64,' + base64;
                res.status(200).send(base64)
            })
        }
    } catch (error) {
        console.log(error)
    }
}

module.exports = {
    readImage: readImage,
}

Frontend side, my Home.vue:

<template>

    <button @click="readImage">TEST</button>

</template>

images.service.js:

import api from '../../http-common';

export default new class ImagesService {
    //Read Screenshot
    readImages(imageName){
        return api.post('read/image', imageName)
    }
}

http-common.js:

import axios from 'axios'

export default axios.create({
    baseURL: 'http://localhost:3003/api',
    headers: {
        "Content-type": "application/json",
    }
})

Body:
it's because stream is not a promise: image is read and downloaded before the stream is finished saving it

Try wrapping data.pipe in a promise and resolve when the saving is done:

const downloadImage = (fileUrl, fileName) => {
    return new Promise(async(resolve, reject) => {
        let isDownloaded = false
        const downloadFolder = './images';

        const localFilePath = path.resolve(__dirname, downloadFolder, fileName);

        const imgStream = fs.createWriteStream(localFilePath);

        try {
            const response = await axios({
                method: 'GET',
                url: fileUrl,
                responseType: 'stream',
            });

            if (response.status === 200) {

                response.data.pipe(imgStream);
            }

        } catch (error) {
            console.log(error)
            reject(error);
        }

        imgStream.on('finish', () => {
            resolve(true);
        });
    })
};


来源: stackexchange

问:
How Can I Do Peach Math Number Switcher Program Like This?
Here's The Program I Want To Do.
Program

[x,y,z]

X = The Largest Number Of Position X, By Start From Number Zero

Y = The Largest Number Of Position Y, By Start From Number Zero

Z = The Largest Number Of Position Z, By Start From Number Zero

C = The Sum Number Of Position (x, y, z), It Must Not Equal To C.

ContentLicense: CC BY-SA 4.0

Body:
X = int(input("X:"))
Y = int(input("Y:"))
Z = int(input("Z:"))
C = int(input("C:"))
array = []

def add_one(max_array):
    for i in range(max_array[0]+1):
        if len(max_array) != 1:
            for j in add_one(max_array[1:]):
                yield [i] + j
        else:
            yield [i]

for i in add_one([X,Y,Z]):
    if sum(i) == C:
        continue
    array.append(i)

print(array)

#input
X:1
Y:1
Z:2
C:3
#output
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]

#input
X:0
Y:2
Z:1
C:2
#output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 2, 1]]


问:
I have troubles with counting the list elements equal to a given value K
I used the command list.count, but it just doesn't work.
Here's the code:</p>
```<code>import random

a = [random.randint (1, 10) for c in range (20) ]
print (a)

d = int (input ('Input a number') )
a.count(d)

while d in a:
    list.remove (d)
print(a)
</code>```

答:
you have to remove d from a so you would do a.remove(d) and not list.remove(d)

list is an object of a class and not an instance of it, the list you are searching for is not list, but a:

```<code>import random
a = [random.randint (1, 10) for c in range (20) ]
print (a)
d = int (input ('Input a number') )
# a.count(d) #doesn't do anything
while d in a:
    a.remove(d) #remove d from a
print(a)
</code>```

Body:
I used the command list.count, but it just doesn't work.
Here's the code:

import random

a = [random.randint (1, 10) for c in range (20) ]
print (a)

d = int (input ('Input a number') )
a.count(d)

while d in a:
    list.remove (d)
print(a)

Body:
you have to remove d from a so you would do a.remove(d) and not list.remove(d)

list is an object of a class and not an instance of it, the list you are searching for is not list, but a:

import random
a = [random.randint (1, 10) for c in range (20) ]
print (a)
d = int (input ('Input a number') )
# a.count(d) #doesn't do anything
while d in a:
    a.remove(d) #remove d from a
print(a)


问:
System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.' in VB
Apologies if my post doesn't follow common practice/rules for coding forums as this is my second question.

I have a button that once clicked, performs a search in an MS Access database for items based on the selected values in combo boxes and adds these items to a data grid. It creates a parameter for each value and adds the relevant combo box item to that parameter.

The CreateSQLStr() function forms the SQL command text based on what combo boxes have a selected value (i.e. if a combo box doesn't have a selected value then it won't specify a condition for that field in the table but if it does it will add AND (TableField = @Parameter) onto the SQL command text).

I've tried changing the "ACTIVE" to a pre-defined string and the same error and I can't think of anything else.

My error is `System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.'

Details:

```<code>System.Data.OleDb.OleDbException
  HResult=0x80040E10
  Message=Parameter @Status has no default value.
  Source=System.Data
  StackTrace:
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.OleDb.OleDbCommand.ExecuteReader()
   at WindowsApplication1.frmEmployee.vehiclesearch_Click(Object sender, EventArgs e) in C:\Users\aawad\OneDrive\Documents\QHP\QHP\QHP\frmEmployee.vb:line 79
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
   at WindowsApplication1.My.MyApplication.Main(String[] Args) in :line 81

  This exception was originally thrown at this call stack:
    [External Code]
    WindowsApplication1.frmEmployee.vehiclesearch_Click(Object, System.EventArgs) in frmEmployee.vb
    [External Code]
</code>```

`

```<code>Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    If DbConnect() Then 'This fucntions returns boolean for whether or not database is connecyed
        Dim SQLcmd As New OleDbCommand
        With SQLcmd
            .Connection = cn
            .CommandText = CreateSQLStr() 'Creates command text based on selected combo box items, see below
            .Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
            .Parameters.AddWithValue("@Model", ModelCBox.SelectedItem)
            .Parameters.AddWithValue("@ClassV", ClassCBox.SelectedItem)
            .Parameters.AddWithValue("@VSeats", SeatsCBox.SelectedItem)
            .Parameters.AddWithValue("@GrBox", GrboxCBox.SelectedItem)
            .Parameters.AddWithValue("@Branch", BranchCBox.SelectedItem)
            .Parameters.AddWithValue("@Status", "ACTIVE")
            Dim rs As OleDbDataReader = .ExecuteReader 'Error occurs at this point
            While rs.Read 'Adding data to data grid
                Dim make, model, year, fuel, vclass, body As String
                make = rs("VMake")
                model = rs("VModel")
                year = rs("VRegYear")
                fuel = rs("VFuel")
                vclass = rs("VClass")
                body = rs("VBody")
                VehDGrid.Rows.Add(make, model, year, fuel, vclass, body)
            End While
            rs.Close()
            cn.Close()
        End With
    Else 'Error message when no vehicle found
        MessageBox.Show("Could not find any vehicles with the selected details. ", "Find vehicle", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End If
End Sub

Function CreateSQLStr() As String
    Dim SQLStr As String
    SQLStr = "Select * FROM Vehicles WHERE (VStatus = @Status)"
    If MakeCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr + " AND (VMake = @Make)"
    End If
    If ModelCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VModel = @Model)"
    End If
    If ClassCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VClass = @ClassV)"
    End If
    If SeatsCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VSeats = @Seats)"
    End If
    If GrboxCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VGearbox = @GrBox)"
    End If
    If BranchCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (BranchID = @Branch)"
    End If
    Return SQLStr
End Function

</code>```

EDIT: reply to comment

```<code> Dim rs As OleDbDataReader = SQLcmd.ExecuteReader

                While rs.Read
                    VehDGrid.Rows.Add(rs("VehicleID"), rs("VMake"), rs("VModel"), rs("VRegYear"),
                                      rs("VFuel"), rs("VClass"), rs("VBody"), rs("VSeats"),
                                      rs("VGearbox"), rs("VReg"), rs("PPDay"), rs("VColour"))
                End While
</code>```

答:
With MS Access, the order of the parameters is important not the names. I use the ? placeholder within my SQL command when using parameters. I also specify the data type so consider using the OleDbParameter Constructor (String, OleDbType) constructor. In my example I have used VarChar which you may want to change accordingly.

I would also consider implementing Using:

Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.

Lastly, if you want to conditional update the WHERE based on a value being selected, you should do the same for your parameters to ensure they too are not being added when they are not required:

```<code>If MakeCBox.SelectedItem IsNot Nothing Then
    SQLcmd.Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
End If
</code>```

This should help to ensure your SQL command is what you want it to be.

As a courtesy note it would also be good to look into taking the time to name your variables, methods, and anything else to be a bit more descriptive, for example CreateSQLStr becomes GetSelectVehicleCommandString.

Also I try to abstract away repetitive code behind a method so that you can call that and pass in parameters. It makes it a little easier to maintain and if you wanted to, you could write a unit test for those methods to ensure they do exactly what you expect them to do. These are just my thoughts. I've thrown together an example to help you on your way. Hopefully this has all been useful to you:

Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    Dim selectVehicleCommandString = "SELECT * FROM Vehicles WHERE (VStatus = @Status)"

    Using connection As New OleDbConnection(connectionString),
          command As New OleDbCommand(selectVehicleCommandString, connection)

        command.Parameters.Add(CreateParameter("@Status", OleDbType.VarChar, "ACTIVE"))

        If MakeCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VMake")
            command.Parameters.Add(CreateParameter("@Make", OleDbType.VarChar,MakeCBox.SelectedItem))
        End If

        If ModelCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VModel")
            command.Parameters.Add(CreateParameter("@Model", OleDbType.VarChar,ModelCBox.SelectedItem))
        End If

        If ClassCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VClass")
            command.Parameters.Add(CreateParameter("@ClassV", OleDbType.VarChar,ClassCBox.SelectedItem))
        End If

        If SeatsCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VSeats")
            command.Parameters.Add(CreateParameter("@VSeats", OleDbType.VarChar,SeatsCBox.SelectedItem))
        End If

        If GrboxCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VGearbox")
            command.Parameters.Add(CreateParameter("@GrBox", OleDbType.VarChar,GrboxCBox.SelectedItem))
        End If

        If BranchCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "BranchID")
            command.Parameters.Add(CreateParameter("@Branch", OleDbType.VarChar,BranchCBox.SelectedItem))
        End If

        command.CommandText = selectVehicleCommandString

        connection.Open()

        Dim results As New DataTable
        results.Load(command.ExecuteReader())

        VehDGrid.DataSource = results
    End Using
End Sub

Private Function AppendToWhereClause(commandString As String, columnName As String) As String
    Return commandString + $" AND ({columnName} = ?)"
End Function

Private Function CreateParameter(parameterName As String, dataType As OleDbType, value As String)
    Dim parameter As New OleDbParameter(parameterName, dataType) With {
        .Value = value
    }
    Return parameter
End Function
```

Please note that this code is completely untested as I haven't got the capabilities of running this against an MS Access database. if I've missed something, let me know and I'll look to correct accordingly

My attempt here is to try and give you some thoughts on how to approach the code:

Implement "Using" when given the opportunity

If conditionally appending to the WHERE clause if a value exists, do the same with the parameter itself

Provide more descriptive names to your variable names, methods, form objects

Remove the use of unnecessary variables and simplifying code for example, when adding rows to VehDGrid for example

Body:
Apologies if my post doesn't follow common practice/rules for coding forums as this is my second question.

I have a button that once clicked, performs a search in an MS Access database for items based on the selected values in combo boxes and adds these items to a data grid. It creates a parameter for each value and adds the relevant combo box item to that parameter.

The CreateSQLStr() function forms the SQL command text based on what combo boxes have a selected value (i.e. if a combo box doesn't have a selected value then it won't specify a condition for that field in the table but if it does it will add AND (TableField = @Parameter) onto the SQL command text).

I've tried changing the "ACTIVE" to a pre-defined string and the same error and I can't think of anything else.

My error is `System.Data.OleDb.OleDbException: 'Parameter @Status has no default value.'

Details:

System.Data.OleDb.OleDbException
  HResult=0x80040E10
  Message=Parameter @Status has no default value.
  Source=System.Data
  StackTrace:
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.OleDb.OleDbCommand.ExecuteReader()
   at WindowsApplication1.frmEmployee.vehiclesearch_Click(Object sender, EventArgs e) in C:\Users\aawad\OneDrive\Documents\QHP\QHP\QHP\frmEmployee.vb:line 79
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
   at WindowsApplication1.My.MyApplication.Main(String[] Args) in :line 81

  This exception was originally thrown at this call stack:
    [External Code]
    WindowsApplication1.frmEmployee.vehiclesearch_Click(Object, System.EventArgs) in frmEmployee.vb
    [External Code]

`

Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    If DbConnect() Then 'This fucntions returns boolean for whether or not database is connecyed
        Dim SQLcmd As New OleDbCommand
        With SQLcmd
            .Connection = cn
            .CommandText = CreateSQLStr() 'Creates command text based on selected combo box items, see below
            .Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
            .Parameters.AddWithValue("@Model", ModelCBox.SelectedItem)
            .Parameters.AddWithValue("@ClassV", ClassCBox.SelectedItem)
            .Parameters.AddWithValue("@VSeats", SeatsCBox.SelectedItem)
            .Parameters.AddWithValue("@GrBox", GrboxCBox.SelectedItem)
            .Parameters.AddWithValue("@Branch", BranchCBox.SelectedItem)
            .Parameters.AddWithValue("@Status", "ACTIVE")
            Dim rs As OleDbDataReader = .ExecuteReader 'Error occurs at this point
            While rs.Read 'Adding data to data grid
                Dim make, model, year, fuel, vclass, body As String
                make = rs("VMake")
                model = rs("VModel")
                year = rs("VRegYear")
                fuel = rs("VFuel")
                vclass = rs("VClass")
                body = rs("VBody")
                VehDGrid.Rows.Add(make, model, year, fuel, vclass, body)
            End While
            rs.Close()
            cn.Close()
        End With
    Else 'Error message when no vehicle found
        MessageBox.Show("Could not find any vehicles with the selected details. ", "Find vehicle", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End If
End Sub

Function CreateSQLStr() As String
    Dim SQLStr As String
    SQLStr = "Select * FROM Vehicles WHERE (VStatus = @Status)"
    If MakeCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr + " AND (VMake = @Make)"
    End If
    If ModelCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VModel = @Model)"
    End If
    If ClassCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VClass = @ClassV)"
    End If
    If SeatsCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VSeats = @Seats)"
    End If
    If GrboxCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (VGearbox = @GrBox)"
    End If
    If BranchCBox.SelectedItem IsNot Nothing Then
        SQLStr = SQLStr & " AND (BranchID = @Branch)"
    End If
    Return SQLStr
End Function

EDIT: reply to comment

 Dim rs As OleDbDataReader = SQLcmd.ExecuteReader

                While rs.Read
                    VehDGrid.Rows.Add(rs("VehicleID"), rs("VMake"), rs("VModel"), rs("VRegYear"),
                                      rs("VFuel"), rs("VClass"), rs("VBody"), rs("VSeats"),
                                      rs("VGearbox"), rs("VReg"), rs("PPDay"), rs("VColour"))
                End While

Body:
With MS Access, the order of the parameters is important not the names. I use the ? placeholder within my SQL command when using parameters. I also specify the data type so consider using the OleDbParameter Constructor (String, OleDbType) constructor. In my example I have used VarChar which you may want to change accordingly.

I would also consider implementing Using:

Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.

Lastly, if you want to conditional update the WHERE based on a value being selected, you should do the same for your parameters to ensure they too are not being added when they are not required:

If MakeCBox.SelectedItem IsNot Nothing Then
    SQLcmd.Parameters.AddWithValue("@Make", MakeCBox.SelectedItem)
End If

This should help to ensure your SQL command is what you want it to be.

As a courtesy note it would also be good to look into taking the time to name your variables, methods, and anything else to be a bit more descriptive, for example CreateSQLStr becomes GetSelectVehicleCommandString.

Also I try to abstract away repetitive code behind a method so that you can call that and pass in parameters. It makes it a little easier to maintain and if you wanted to, you could write a unit test for those methods to ensure they do exactly what you expect them to do. These are just my thoughts. I've thrown together an example to help you on your way. Hopefully this has all been useful to you:

Private Sub vehiclesearch_Click(sender As Object, e As EventArgs) Handles VehicleSearch.Click
    Dim selectVehicleCommandString = "SELECT * FROM Vehicles WHERE (VStatus = @Status)"

    Using connection As New OleDbConnection(connectionString),
          command As New OleDbCommand(selectVehicleCommandString, connection)

        command.Parameters.Add(CreateParameter("@Status", OleDbType.VarChar, "ACTIVE"))

        If MakeCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VMake")
            command.Parameters.Add(CreateParameter("@Make", OleDbType.VarChar,MakeCBox.SelectedItem))
        End If

        If ModelCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VModel")
            command.Parameters.Add(CreateParameter("@Model", OleDbType.VarChar,ModelCBox.SelectedItem))
        End If

        If ClassCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VClass")
            command.Parameters.Add(CreateParameter("@ClassV", OleDbType.VarChar,ClassCBox.SelectedItem))
        End If

        If SeatsCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VSeats")
            command.Parameters.Add(CreateParameter("@VSeats", OleDbType.VarChar,SeatsCBox.SelectedItem))
        End If

        If GrboxCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "VGearbox")
            command.Parameters.Add(CreateParameter("@GrBox", OleDbType.VarChar,GrboxCBox.SelectedItem))
        End If

        If BranchCBox.SelectedItem IsNot Nothing Then
            selectVehicleCommandString = AppendToWhereClause(selectVehicleCommandString, "BranchID")
            command.Parameters.Add(CreateParameter("@Branch", OleDbType.VarChar,BranchCBox.SelectedItem))
        End If

        command.CommandText = selectVehicleCommandString

        connection.Open()

        Dim results As New DataTable
        results.Load(command.ExecuteReader())

        VehDGrid.DataSource = results
    End Using
End Sub

Private Function AppendToWhereClause(commandString As String, columnName As String) As String
    Return commandString + $" AND ({columnName} = ?)"
End Function

Private Function CreateParameter(parameterName As String, dataType As OleDbType, value As String)
    Dim parameter As New OleDbParameter(parameterName, dataType) With {
        .Value = value
    }
    Return parameter
End Function

Please note that this code is completely untested as I haven't got the capabilities of running this against an MS Access database. if I've missed something, let me know and I'll look to correct accordingly

My attempt here is to try and give you some thoughts on how to approach the code:

Implement "Using" when given the opportunity

If conditionally appending to the WHERE clause if a value exists, do the same with the parameter itself

Provide more descriptive names to your variable names, methods, form objects

Remove the use of unnecessary variables and simplifying code for example, when adding rows to VehDGrid for example


问:
Disabling dependabot alerts for a repository on GitHub
GitHub dependabot security alerts may sometimes become a chore especially when an abandoned project that is no longer in active use receives frequent security advisories. Is there an option to disable the active security monitoring?

答:
Open you repo and go to Settings. Click on Code security and analysis in the Security subsection. There you will find dependabot settings with a Disable button for turning off the automated advisories.

The page is also available through direct link https://github.com/<USERNAME>/<REPO>/settings/security_analysis by replacing placeholders <USERNAME> and <REPO> with the corresponding identifiers.

Note that disabling the advisories will negatively impact the security of your software and should be avoided for any software with production deployments.


问:
localhost prints .php file instead of executing it
I am running macOS 12.2.1 and I have installed php via brew install php@7.4. I have also added the following to my http.conf:

```<code><IfModule dir_module>
    DirectoryIndex index.php index.html
</IfModule>
</code>```

But instead of executing my index.php, the browser just prints its code <?php echo 'hello world'; ?>

Now, I know that I'm supposed to add LoadModule php7_module /usr/local/Cellar/php@7.4/7.4.27/lib/httpd/modules/libphp7.so to my httpd.conf as well, but if I do, I get a ERR_CONNECTION_REFUSED.

I have noticed that all the other LoadModules point to a path libexec/apache2/.

Is my path incorrect? The file /usr/local/Cellar/php@7.4/7.4.27/lib/httpd/modules/libphp7.so does exist though... And I cannot find the directory /libexec/apache2/ on my system..

答:
The answer was missing Code signing, I followed this guide and after a lot of trial and error now it works:
https://www.simplified.guide/macos/keychain-ca-code-signing-create

People who work at Apple are horrible people.

Body:
I am running macOS 12.2.1 and I have installed php via brew install php@7.4. I have also added the following to my http.conf:

<IfModule dir_module>
    DirectoryIndex index.php index.html
</IfModule>

But instead of executing my index.php, the browser just prints its code <?php echo 'hello world'; ?>

Now, I know that I'm supposed to add LoadModule php7_module /usr/local/Cellar/php@7.4/7.4.27/lib/httpd/modules/libphp7.so to my httpd.conf as well, but if I do, I get a ERR_CONNECTION_REFUSED.

I have noticed that all the other LoadModules point to a path libexec/apache2/.

Is my path incorrect? The file /usr/local/Cellar/php@7.4/7.4.27/lib/httpd/modules/libphp7.so does exist though... And I cannot find the directory /libexec/apache2/ on my system..


问:
Get request url in feign client interceptor
I am using spring feign client for making http requests.

Fiegn configuration class

```<code>DefaultConfig.class
public class DefaultConfig {

    @Bean
    public OkHttpClient client() {
        return new OkHttpClient();
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public Decoder feignDecoder() {
        return new JacksonDecoder();
    }

    @Bean
    public Encoder feignEncoder() {
        return new JacksonEncoder();
    }
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            template.header(Authorization, apiKey);
        };
    }
}
</code>```

My client interface:

```<code>@FeignClient(name = "default", url = "${base-url}",
        configuration = DefaultConfig.class)
public interface {

    @PostMapping(value = "/users/")
   Response createUser(@RequestBody Map<String, ?> requestBody);

    @GetMapping(value = "/users/{id}")
   Response getUserDetails(@PathVariable String id);

}
</code>```

The thing is now I need to use different authorization key for GET and POST request. In the configuration class I need to differentiate the request by url called. How can we get the url the requester interceptor or any other way we can achieve this. We can create separate interceptor for this but I try to use the same interceptor for both cases.

答:
Everything you need seems to be in the code below.

@Bean.
public RequestInterceptor requestInterceptor() {
    return template -> {
        template.request().url() // this is request url which is from feign!
        template.requsst().httpMethod() // this is request method!
    };
}
```

Body:
I am using spring feign client for making http requests.

Fiegn configuration class

DefaultConfig.class
public class DefaultConfig {

    @Bean
    public OkHttpClient client() {
        return new OkHttpClient();
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public Decoder feignDecoder() {
        return new JacksonDecoder();
    }

    @Bean
    public Encoder feignEncoder() {
        return new JacksonEncoder();
    }
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            template.header(Authorization, apiKey);
        };
    }
}

My client interface:

@FeignClient(name = "default", url = "${base-url}",
        configuration = DefaultConfig.class)
public interface {

    @PostMapping(value = "/users/")
   Response createUser(@RequestBody Map<String, ?> requestBody);

    @GetMapping(value = "/users/{id}")
   Response getUserDetails(@PathVariable String id);

}

The thing is now I need to use different authorization key for GET and POST request. In the configuration class I need to differentiate the request by url called. How can we get the url the requester interceptor or any other way we can achieve this. We can create separate interceptor for this but I try to use the same interceptor for both cases.


问:
How can I list the Kafka consumer lag and latest offset per partition and consumer group using the Kafka .NET client API?
I'm trying to get the consumer lag using the .NET Confluent.Kafka 1.4.0-RC1 (for Net472).
I can get the desired result using this script:

```<code>$ bin/kafka-run-class.sh kafka.admin.ConsumerGroupCommand --bootstrap-server localhost:9092 --group Grp1 --describe
</code>```

Resulting:

```<code>GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                  HOST            CLIENT-ID
Grp1            test3           1          15              15              0               rdkafka-ca76855f-7b66-4bf1-82bc-73e9a1c1cf71 /10.186.129.93  rdkafka
Grp1            test3           2          13              13              0               rdkafka-d64379dc-881a-4f6f-a793-51e832cc2f5a /10.186.129.93  rdkafka
Grp1            test3           0          9               9               0               rdkafka-a25bdb80-3b70-4e42-963e-d41ad9e2a99a /10.186.129.93  rdkafka
Grp1            test            0          68              68              0               -                                            -               -
</code>```

I'm not able to get similar report using the .NET client code. Here's the code I've been trying - but getting nothing as the consumer.Assignment property has an empty collection.

```<code>private string WriteConsumerGroupLags(string bootstrapServers, string consumerGroupName) {
    // kafka-console-consumer.bat --zookeeper MW45670117:2380 --topic powertelemetry --consumer-property group.id=test123 --consumer-property enable.auto.commit=true

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("\n");
    sb.AppendLine("Consumer Group Lag Report");
    sb.AppendLine("-------------------------");
    ConsumerConfig config = new ConsumerConfig {
        BootstrapServers = bootstrapServers,
        GroupId = consumerGroupName,
        AutoOffsetReset = AutoOffsetReset.Earliest
    };

    using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build()) {
        foreach (TopicPartition tp in consumer.Assignment) {
            string topic = tp.Topic;
            int partitionID = tp.Partition.Value;
            // gets the current position (offset) for the specific topic/partition
            Offset offset = consumer.Position(new TopicPartition(topic, new Partition(partitionID)));
            sb.AppendLine($"Offset value is: {offset.Value}");

            // returns current commited offset for the current assignment
            List<TopicPartitionOffset> tpos = consumer.Committed(TimeSpan.FromSeconds(4));
            foreach (TopicPartitionOffset tpo in tpos) {
                sb.AppendLine($"Commited offset for partition {tpo.TopicPartition} is {tpo.Offset}");
            }
        }
    }

    return sb.ToString();
}
</code>```

Looking for both consumer lag and latest offset per partition/consumer-group.

答:
I have expanded on your answer to include generating the model for topic partitions.</p>
```<code>public class Offsets
{
   public string WriteConsumerGroupLags(string bootstrapServers, string consumerGroupName)
   {
      var sb = new StringBuilder();
      sb.AppendLine("\n");
      sb.AppendLine("Consumer Group Lag Report");
      sb.AppendLine("-------------------------");

      var config = new ConsumerConfig
      {
         BootstrapServers = bootstrapServers,
         GroupId = consumerGroupName,
         SecurityProtocol = SecurityProtocol.Ssl
      };

      using var adminClient = new AdminClientBuilder(config).Build();
      using var consumer = new ConsumerBuilder<Ignore, string>(config).Build();

      var meta = adminClient.GetMetadata(TimeSpan.FromSeconds(20));

      var topicPartitions = new List<TopicPartition>();

      foreach (var topicMeta in meta.Topics.Where(x => !x.Topic.Contains("__")))
      {
         topicPartitions.AddRange(topicMeta.Partitions.Select(topicMetaPartition => new TopicPartition(topicMeta.Topic, new Partition(topicMetaPartition.PartitionId))));
      }

      consumer.Assign(topicPartitions);

      List<TopicPartitionOffset> tpos = consumer.Committed(TimeSpan.FromSeconds(40));
      foreach (TopicPartitionOffset tpo in tpos)
      {
         WatermarkOffsets w = consumer.QueryWatermarkOffsets(tpo.TopicPartition, TimeSpan.FromSeconds(40));
         long commited = tpo.Offset.Value;
         long log_end_offset = w.High.Value;
         long lag = log_end_offset - commited;
         sb.AppendLine(
            $"Commited offset for Topic {tpo.TopicPartition.Topic} Partition {tpo.TopicPartition.Partition} is {commited} out of Wantermark end offset {log_end_offset} Lag is: {lag}");
      }

      sb.AppendLine();

      return sb.ToString();
   }
}
</code>```

Body:
I'm trying to get the consumer lag using the .NET Confluent.Kafka 1.4.0-RC1 (for Net472).
I can get the desired result using this script:

$ bin/kafka-run-class.sh kafka.admin.ConsumerGroupCommand --bootstrap-server localhost:9092 --group Grp1 --describe

Resulting:

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                  HOST            CLIENT-ID
Grp1            test3           1          15              15              0               rdkafka-ca76855f-7b66-4bf1-82bc-73e9a1c1cf71 /10.186.129.93  rdkafka
Grp1            test3           2          13              13              0               rdkafka-d64379dc-881a-4f6f-a793-51e832cc2f5a /10.186.129.93  rdkafka
Grp1            test3           0          9               9               0               rdkafka-a25bdb80-3b70-4e42-963e-d41ad9e2a99a /10.186.129.93  rdkafka
Grp1            test            0          68              68              0               -                                            -               -

I'm not able to get similar report using the .NET client code. Here's the code I've been trying - but getting nothing as the consumer.Assignment property has an empty collection.

private string WriteConsumerGroupLags(string bootstrapServers, string consumerGroupName) {
    // kafka-console-consumer.bat --zookeeper MW45670117:2380 --topic powertelemetry --consumer-property group.id=test123 --consumer-property enable.auto.commit=true

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("\n");
    sb.AppendLine("Consumer Group Lag Report");
    sb.AppendLine("-------------------------");
    ConsumerConfig config = new ConsumerConfig {
        BootstrapServers = bootstrapServers,
        GroupId = consumerGroupName,
        AutoOffsetReset = AutoOffsetReset.Earliest
    };

    using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build()) {
        foreach (TopicPartition tp in consumer.Assignment) {
            string topic = tp.Topic;
            int partitionID = tp.Partition.Value;
            // gets the current position (offset) for the specific topic/partition
            Offset offset = consumer.Position(new TopicPartition(topic, new Partition(partitionID)));
            sb.AppendLine($"Offset value is: {offset.Value}");

            // returns current commited offset for the current assignment
            List<TopicPartitionOffset> tpos = consumer.Committed(TimeSpan.FromSeconds(4));
            foreach (TopicPartitionOffset tpo in tpos) {
                sb.AppendLine($"Commited offset for partition {tpo.TopicPartition} is {tpo.Offset}");
            }
        }
    }

    return sb.ToString();
}

Looking for both consumer lag and latest offset per partition/consumer-group.

Body:
I have expanded on your answer to include generating the model for topic partitions.

public class Offsets
{
   public string WriteConsumerGroupLags(string bootstrapServers, string consumerGroupName)
   {
      var sb = new StringBuilder();
      sb.AppendLine("\n");
      sb.AppendLine("Consumer Group Lag Report");
      sb.AppendLine("-------------------------");

      var config = new ConsumerConfig
      {
         BootstrapServers = bootstrapServers,
         GroupId = consumerGroupName,
         SecurityProtocol = SecurityProtocol.Ssl
      };

      using var adminClient = new AdminClientBuilder(config).Build();
      using var consumer = new ConsumerBuilder<Ignore, string>(config).Build();

      var meta = adminClient.GetMetadata(TimeSpan.FromSeconds(20));

      var topicPartitions = new List<TopicPartition>();

      foreach (var topicMeta in meta.Topics.Where(x => !x.Topic.Contains("__")))
      {
         topicPartitions.AddRange(topicMeta.Partitions.Select(topicMetaPartition => new TopicPartition(topicMeta.Topic, new Partition(topicMetaPartition.PartitionId))));
      }

      consumer.Assign(topicPartitions);

      List<TopicPartitionOffset> tpos = consumer.Committed(TimeSpan.FromSeconds(40));
      foreach (TopicPartitionOffset tpo in tpos)
      {
         WatermarkOffsets w = consumer.QueryWatermarkOffsets(tpo.TopicPartition, TimeSpan.FromSeconds(40));
         long commited = tpo.Offset.Value;
         long log_end_offset = w.High.Value;
         long lag = log_end_offset - commited;
         sb.AppendLine(
            $"Commited offset for Topic {tpo.TopicPartition.Topic} Partition {tpo.TopicPartition.Partition} is {commited} out of Wantermark end offset {log_end_offset} Lag is: {lag}");
      }

      sb.AppendLine();

      return sb.ToString();
   }
}


问:
NodeJS - Two same I2C address BME280 sensors connected through TCA9548A multiplexer (clashing results)
Good evening everyone!

For some reason there are a lot information on TCA9548A in Python, but not much on NodeJS.

I was trying to use this library from Github TCA9548A with this library BME280

Both BME280 sensors have address 0x76.

TCA9548A - 0x70.

The final code I was running was this:

```<code>const tca9548a_1 = new TCA9548A({addr: 0x70, bus: 1});

//as an example, if using two bme280 temp sensors (sensor1 and sensor2)
//that have the same address need to enable the specific
//multiplexer port each time you want to read from a certain device
//singlePortOn activates the port of the argument and
//disables all other ports
//argument has to be a number 0-7
//
//use a callback to ensure that the port is enabled
//before proceeding with other processing
//
//for example, sensor1 is attached to port 2 on the multiplexer
//
tca9548a_1.singlePortOn(2, doSomethingWithSensor());

//then read from sensor2 attached to port 6 on the multiplexer
//
tca9548a_1.singlePortOn(7, doSomethingWithSensor());

function doSomethingWithSensor () {
  //process sensor data magic
const bme280 = require('bme280');

const format = number => (Math.round(number * 100) / 100).toFixed(2);
const delay = millis => new Promise(resolve => setTimeout(resolve, millis));

const reportContinuous = async _ => {
  const sensor = await bme280.open({
    i2cBusNumber: 1,
    i2cAddress: 0x76,
    humidityOversampling: bme280.OVERSAMPLE.X1,
    pressureOversampling: bme280.OVERSAMPLE.X16,
    temperatureOversampling: bme280.OVERSAMPLE.X2,
    filterCoefficient: bme280.FILTER.F16
  });

  for (let i = 1; i <= 250; ++i) {
    const reading = await sensor.read();
    console.log(
      `${i} ` +
      `${format(reading.temperature)}°C, ` +
      `${format(reading.pressure)} hPa, ` +
      `${format(reading.humidity)}%`
    );
    await delay(1000); // 1 second
  }

  await sensor.close();
};

reportContinuous().catch(console.log);

}
</code>```

Output and the problem: Only one sensor is being read and is outputting information that is doubled. This code is not reading information from them both, but just from one.

I am not very strong in JavaScript, but really want to learn.
Seems like I need to create a callback - from this comment in the code:

//use a callback to ensure that the port is enabled before proceeding with other processing

Will greatly appreciate any help on this subject.

答:
Code that worked for me:

```<code>const TCA9548A = require('tca9548a');
const i2c = require('i2c-bus');

const tca9548a_1 = new TCA9548A({ addr: 0x70, bus: 1 });

function two(callback) {
    tca9548a_1.singlePortOn(2);
    console.log("Two")
    const bme280 = require('bme280');
    bme280.open().then(async sensor => {
        console.log(await sensor.read());
        await sensor.close();
    }).catch(console.log);
    callback()
}

function seven(callback) {
    return setTimeout(() => {
        tca9548a_1.singlePortOn(7);
        console.log("Seven")
        const bme280 = require('bme280');
        bme280.open().then(async sensor => {
            console.log(await sensor.read());
            await sensor.close();
        }).catch(console.log);
        callback()
    }, 1000);
}

function run() {
    two(() => {
        seven(() => { })
    })
}

run();
</code>```

OUTPUT:

```<code>Two
{
  temperature: 28.303820903622544,
  pressure: 991.7407636221005,
  humidity: 39.50036416630162
}
Seven
{
  temperature: 24.77324210727238,
  pressure: 991.0048461479205,
  humidity: 25.391542980733707
}
</code>```

Body:
Good evening everyone!

For some reason there are a lot information on TCA9548A in Python, but not much on NodeJS.

I was trying to use this library from Github TCA9548A with this library BME280

Both BME280 sensors have address 0x76.

TCA9548A - 0x70.

The final code I was running was this:

const tca9548a_1 = new TCA9548A({addr: 0x70, bus: 1});

//as an example, if using two bme280 temp sensors (sensor1 and sensor2)
//that have the same address need to enable the specific
//multiplexer port each time you want to read from a certain device
//singlePortOn activates the port of the argument and
//disables all other ports
//argument has to be a number 0-7
//
//use a callback to ensure that the port is enabled
//before proceeding with other processing
//
//for example, sensor1 is attached to port 2 on the multiplexer
//
tca9548a_1.singlePortOn(2, doSomethingWithSensor());

//then read from sensor2 attached to port 6 on the multiplexer
//
tca9548a_1.singlePortOn(7, doSomethingWithSensor());

function doSomethingWithSensor () {
  //process sensor data magic
const bme280 = require('bme280');

const format = number => (Math.round(number * 100) / 100).toFixed(2);
const delay = millis => new Promise(resolve => setTimeout(resolve, millis));

const reportContinuous = async _ => {
  const sensor = await bme280.open({
    i2cBusNumber: 1,
    i2cAddress: 0x76,
    humidityOversampling: bme280.OVERSAMPLE.X1,
    pressureOversampling: bme280.OVERSAMPLE.X16,
    temperatureOversampling: bme280.OVERSAMPLE.X2,
    filterCoefficient: bme280.FILTER.F16
  });

  for (let i = 1; i <= 250; ++i) {
    const reading = await sensor.read();
    console.log(
      `${i} ` +
      `${format(reading.temperature)}°C, ` +
      `${format(reading.pressure)} hPa, ` +
      `${format(reading.humidity)}%`
    );
    await delay(1000); // 1 second
  }

  await sensor.close();
};

reportContinuous().catch(console.log);

}

Output and the problem: Only one sensor is being read and is outputting information that is doubled. This code is not reading information from them both, but just from one.

I am not very strong in JavaScript, but really want to learn.
Seems like I need to create a callback - from this comment in the code:

//use a callback to ensure that the port is enabled before proceeding with other processing

Will greatly appreciate any help on this subject.

Body:
Code that worked for me:

const TCA9548A = require('tca9548a');
const i2c = require('i2c-bus');

const tca9548a_1 = new TCA9548A({ addr: 0x70, bus: 1 });

function two(callback) {
    tca9548a_1.singlePortOn(2);
    console.log("Two")
    const bme280 = require('bme280');
    bme280.open().then(async sensor => {
        console.log(await sensor.read());
        await sensor.close();
    }).catch(console.log);
    callback()
}

function seven(callback) {
    return setTimeout(() => {
        tca9548a_1.singlePortOn(7);
        console.log("Seven")
        const bme280 = require('bme280');
        bme280.open().then(async sensor => {
            console.log(await sensor.read());
            await sensor.close();
        }).catch(console.log);
        callback()
    }, 1000);
}

function run() {
    two(() => {
        seven(() => { })
    })
}

run();

OUTPUT:

Two
{
  temperature: 28.303820903622544,
  pressure: 991.7407636221005,
  humidity: 39.50036416630162
}
Seven
{
  temperature: 24.77324210727238,
  pressure: 991.0048461479205,
  humidity: 25.391542980733707
}


问:
Query large volume of data for web page display
I am new to Oracle (know some basic SQL), but the task is somehow assigned to me.

My task is to optimize a query. It joins some large tables (query is time consuming) and returns the result to a webpage (paging can be used).

My question is what direction should I look into? It would be better if links can be provided.

Here is some details:

Optimized methods taken

```<code>index on dayNum, timeNum, entityID columns
</code>```

Number of rows:

time_seq:  100,000

indicator_set: 50,000,000

tity amount: 1,000

Query:

```<code>select *
  from time_seq seq,
       (
        select entityID,
               dayNum,
               timeNum,
               sum(ind1) sum_ind1,
               avg(ind2) avg_ind2,
               max(ind3) max_ind3
          from indicator_set
         group by entityID, dayNum, timeNum
         -- the dayNum timeNum are grouped to the time sequence standard
         -- in time_seq table
        ) sum
where seq.entityID=sum.entityID
  and seq.dayNum=sum.dayNum
  and seq.timeNum=sum.timeNum
</code>```

Table time_seq

```<code>entityID, dayNum, timeNum
--------------------------------
object1, 20110818, 220000
object1, 20110818, 223000
object1, 20100818, 230000
object1, 20110819, 220000
object1, 20110819, 223000
object1, 20100819, 230000
object2, 20110818, 220000
object2, 20110818, 223000
object2, 20100818, 230000
object2, 20110819, 220000
object2, 20110819, 223000
object2, 20100819, 230000
</code>```

Table indicator_set

```<code>entityID, dayNum, timeNUm, ind1, ind2, ind3
--------------------------------------------
object1, 20110818, 220000, 23,34,23
object1, 20110818, 220500, 23,54,543
object1, 20110818, 220530, 23,54,543
object1, 20110818, 220610, 23,54,543
object1, 20110818, 222900, 23,54,543
...
</code>```

PS: sorry I didn't provide exact format/detail of the table and query. Just too complicated.

cheers~

答:
What are you doing with the results of this query?  Assuming that the query returns on the order of 100,000 rows (I assume that the join does not eliminate a substantial number of the rows in TIME_SEQ), the query doesn't make a lot of sense.  You're returning 100,000 unordered rows to a user via a web page-- there is no way that a human would ever page through 100,000 rows and there is no way that it makes sense to present those rows unordered (or to order them in the middle tier).

It would very rarely make sense to try to aggregate 50 million rows of data on the fly in order to populate a web page.  That's going to be an inherently slow operation-- if users are expecting a response in a second or two, you don't have time to read and aggregate 50 million rows.  You could potentially create a materialized view on INDICATOR_SET that could be used to pre-aggregate the data.  That will make inserts and updates slower but should speed up your query.

Of course, even if you pre-aggregate the 50 million rows down to just 100,000 rows, you're still trying to join two 100,000 row tables and send 100,000 unordered rows to the client which is unlikely to be reasonable.  You could potentially add an ORDER BY clause so that the rows come in a reasonable order but that is generally going to add time to the query since you're introducing an extra sort.  There may be ways to optimize that depending on what you intend to sort by.  However, I'd still come back to the fundamental problem that returning 100,000 rows to a human client is fundamentally not the right approach.

ContentLicense: CC BY-SA 3.0

Body:
I am new to Oracle (know some basic SQL), but the task is somehow assigned to me.

My task is to optimize a query. It joins some large tables (query is time consuming) and returns the result to a webpage (paging can be used).

My question is what direction should I look into? It would be better if links can be provided.

Here is some details:

Optimized methods taken

index on dayNum, timeNum, entityID columns

Number of rows:

time_seq:  100,000

indicator_set: 50,000,000

tity amount: 1,000

Query:

select *
  from time_seq seq,
       (
        select entityID,
               dayNum,
               timeNum,
               sum(ind1) sum_ind1,
               avg(ind2) avg_ind2,
               max(ind3) max_ind3
          from indicator_set
         group by entityID, dayNum, timeNum
         -- the dayNum timeNum are grouped to the time sequence standard
         -- in time_seq table
        ) sum
where seq.entityID=sum.entityID
  and seq.dayNum=sum.dayNum
  and seq.timeNum=sum.timeNum

Table time_seq

entityID, dayNum, timeNum
--------------------------------
object1, 20110818, 220000
object1, 20110818, 223000
object1, 20100818, 230000
object1, 20110819, 220000
object1, 20110819, 223000
object1, 20100819, 230000
object2, 20110818, 220000
object2, 20110818, 223000
object2, 20100818, 230000
object2, 20110819, 220000
object2, 20110819, 223000
object2, 20100819, 230000

Table indicator_set

entityID, dayNum, timeNUm, ind1, ind2, ind3
--------------------------------------------
object1, 20110818, 220000, 23,34,23
object1, 20110818, 220500, 23,54,543
object1, 20110818, 220530, 23,54,543
object1, 20110818, 220610, 23,54,543
object1, 20110818, 222900, 23,54,543
...

PS: sorry I didn't provide exact format/detail of the table and query. Just too complicated.

cheers~


问:
How do I echo different content for each product tag on a category page in WooCommerce?
I am using URL parameters to filter my categories like so: https://example.com/collections/trousers/?product_tag=male

I want to echo different HTML depending on the tag used. Here's my code which should be pretty self explanatory:

```<code>add_action('bs_after_primary', 'custom_product_category_descriptions');

function custom_product_category_descriptions() {

if ( is_product_category( 'trousers' ) && ! is_product_tag( array( 'male', 'female' ) ) ) {
echo '<h1>Checkout these trousers for men and women</h1>';
  } elseif ( is_product_category( 'trousers' ) && is_product_tag ( 'male' ) && ! is_product_tag ( 'female' ) ) {
echo '<h1>Checkout out these trousers for Men</h1>';
  }
    elseif ( is_product_category( 'trousers' ) && ! is_product_tag ( 'male' ) && is_product_tag ( 'female' ) ) {
echo '<h1>Checkout out these trousers for Women</h1>';
  }
}
</code>```

The above code echo's
Checkout these trousers for men and women
 on all trouser category pages:

https://example.com/collections/trousers/

https://example.com/collections/trousers/?product_tag=male

https://example.com/collections/trousers/?product_tag=female

Why does the code echo on all URL's above ignoring my ! is not conditional statements?

答: Woo's is_product_tag() function detects whether you are viewing a product tag page. But you are viewing a product category page, not a tag page, so is_product_tag( anything ) always returns false.

Body:
I am using URL parameters to filter my categories like so: https://example.com/collections/trousers/?product_tag=male

I want to echo different HTML depending on the tag used. Here's my code which should be pretty self explanatory:

add_action('bs_after_primary', 'custom_product_category_descriptions');

function custom_product_category_descriptions() {

if ( is_product_category( 'trousers' ) && ! is_product_tag( array( 'male', 'female' ) ) ) {
echo '
Checkout these trousers for men and women
';
  } elseif ( is_product_category( 'trousers' ) && is_product_tag ( 'male' ) && ! is_product_tag ( 'female' ) ) {
echo '
Checkout out these trousers for Men
';
  }
    elseif ( is_product_category( 'trousers' ) && ! is_product_tag ( 'male' ) && is_product_tag ( 'female' ) ) {
echo '
Checkout out these trousers for Women
';
  }
}

The above code echo's
Checkout these trousers for men and women
 on all trouser category pages:

https://example.com/collections/trousers/

https://example.com/collections/trousers/?product_tag=male

https://example.com/collections/trousers/?product_tag=female

Why does the code echo on all URL's above ignoring my ! is not conditional statements?


问:
What do curly braces around a variable in a function parameter mean
I saw this code on a package:

```<code>const SortableList = SortableContainer(({items}) => {
 return (
     <ul>
        {items.map((value, index) =>
            <SortableItem key={`item-${index}`} index={index} value={value} />
        )}
    </ul>
 );
});
</code>```

What is happening to items by putting curly braces around it in the function parameters?

答:
This is Destructuring Assignment.

In this example below, the variables "name", "sex" and "age" in curly braces "{}" extract the values "John", "Male" and "24" from "data" respectively:

*The variable names in curly braces "{}" must be same as the key names in "data"

const data = { name: "John", sex: "Male", age: 24 };

const { name, sex, age } = data;

console.log(name); // John
console.log(sex);  // Male
console.log(age);  // 24```
</div>
</div>
</p>
<p>If the variable names in <strong>curly braces "{}"</strong> are not same as the key names in <strong>"data"</strong>, the values of <strong>"undefined"</strong> are assigned:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = { name: "John", sex: "Male", age: 24 };

const { myName, mySex, age } = data;

console.log(myName); // undefined
console.log(mySex);  // undefined
console.log(age);    // 24</code>```

The order of the variables in curly braces "{}" doesn't matter:

const data = { name: "John", sex: "Male", age: 24 };

const { age, sex, name } = data;

console.log(name); // John
console.log(sex);  // Male
console.log(age);  // 24```
</div>
</div>
</p>
<p>You can rename the variables in <strong>curly braces "{}"</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = { name: "John", sex: "Male", age: 24 };

const { name: firstName, sex: gender, age } = data;

console.log(firstName); // John
console.log(gender);    // Male
console.log(age);       // 24</code>```

After renaming the variables in curly braces "{}", the original variables don't work and give error:

const data = { name: "John", sex: "Male", age: 24 };

const { name: firstName, sex: gender, age } = data;

console.log(name);
console.log(sex);
console.log(age);```

Body:
I saw this code on a package:

const SortableList = SortableContainer(({items}) => {
 return (

        {items.map((value, index) =>
            <SortableItem key={`item-${index}`} index={index} value={value} />
        )}

 );
});

What is happening to items by putting curly braces around it in the function parameters?

Body:
This is Destructuring Assignment.

In this example below, the variables "name", "sex" and "age" in curly braces "{}" extract the values "John", "Male" and "24" from "data" respectively:

*The variable names in curly braces "{}" must be same as the key names in "data"

const data = { name: "John", sex: "Male", age: 24 };

const { name, sex, age } = data;

console.log(name); // John
console.log(sex);  // Male
console.log(age);  // 24

If the variable names in curly braces "{}" are not same as the key names in "data", the values of "undefined" are assigned:

const data = { name: "John", sex: "Male", age: 24 };

const { myName, mySex, age } = data;

console.log(myName); // undefined
console.log(mySex);  // undefined
console.log(age);    // 24

The order of the variables in curly braces "{}" doesn't matter:

const data = { name: "John", sex: "Male", age: 24 };

const { age, sex, name } = data;

console.log(name); // John
console.log(sex);  // Male
console.log(age);  // 24

You can rename the variables in curly braces "{}":

const data = { name: "John", sex: "Male", age: 24 };

const { name: firstName, sex: gender, age } = data;

console.log(firstName); // John
console.log(gender);    // Male
console.log(age);       // 24

After renaming the variables in curly braces "{}", the original variables don't work and give error:

const data = { name: "John", sex: "Male", age: 24 };

const { name: firstName, sex: gender, age } = data;

console.log(name);
console.log(sex);
console.log(age);


问:
How to ignore the error in Discord.js V12
I made a command for DM the role.

You can see my code here:

```<code>const { Client, Message, MessageEmbed } = require('discord.js');
// const { join } = require('path');

module.exports = {
    name: 'dm-role',
    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    run: async(client, message, args) => {
        if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")

        if (!args[0]) return message.channel.send("where's the role?")
        const role = message.mentions.roles.first()

        message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))

        if(!role) return message.channel.send("where's the role?")

        const reason = args.slice(1).join(" ")
        if(!reason) return message.channel.send("the message ?");

        try {
            await role.send(reason);
            return message.channel.send("done");
        } catch {
            return message.channel.send("failed");
        }
    }
}
</code>```

Someone in the role has blocked my bot, so I got an error like this

```<code>throw new DiscordAPIError(request.path, data, request.method, res.status);
            ^

DiscordAPIError: Cannot send messages to this user
</code>```

I just want to know how I can get past the error, and the bot still keeps sending DMs to people who haven't blocked the bot.

答:
You can use the .catch(...) method on the .send(...) function.

Example:

role.send(reason).catch((error) => console.log(error));
```
<p>Full Example:</p>
<pre class="lang-js prettyprint-override"><code>run: async(client, message, args) => {
    if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")

    if (!args[0]) return message.channel.send("where's the role?")
    const role = message.mentions.roles.first()

    message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))

    if (!role) return message.channel.send("where's the role?")

    const reason = args.slice(1).join(" ")
    if (!reason) return message.channel.send("the message ?");

    try {
        // Attempt to send the message, if failed log the error and continue
        await role.send(reason).catch(error => console.log(error))
        return message.channel.send("done");
    } catch {
        return message.channel.send("failed");
    }
}
</code>```

Body:
I made a command for DM the role.

You can see my code here:

const { Client, Message, MessageEmbed } = require('discord.js');
// const { join } = require('path');

module.exports = {
    name: 'dm-role',
    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    run: async(client, message, args) => {
        if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")

        if (!args[0]) return message.channel.send("where's the role?")
        const role = message.mentions.roles.first()

        message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))

        if(!role) return message.channel.send("where's the role?")

        const reason = args.slice(1).join(" ")
        if(!reason) return message.channel.send("the message ?");

        try {
            await role.send(reason);
            return message.channel.send("done");
        } catch {
            return message.channel.send("failed");
        }
    }
}

Someone in the role has blocked my bot, so I got an error like this

throw new DiscordAPIError(request.path, data, request.method, res.status);
            ^

DiscordAPIError: Cannot send messages to this user

I just want to know how I can get past the error, and the bot still keeps sending DMs to people who haven't blocked the bot.

Body:
You can use the .catch(...) method on the .send(...) function.

Example:

role.send(reason).catch((error) => console.log(error));

Full Example:

run: async(client, message, args) => {
    if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("admin only lol")

    if (!args[0]) return message.channel.send("where's the role?")
    const role = message.mentions.roles.first()

    message.guild.roles.cache.get(role.id).members.forEach(member => member.send(args.slice(1).join(" ")))

    if (!role) return message.channel.send("where's the role?")

    const reason = args.slice(1).join(" ")
    if (!reason) return message.channel.send("the message ?");

    try {
        // Attempt to send the message, if failed log the error and continue
        await role.send(reason).catch(error => console.log(error))
        return message.channel.send("done");
    } catch {
        return message.channel.send("failed");
    }
}


问:
One view for multiple sub-domains using django-hosts
I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains.

hosts file:

```<code>127.0.0.1       localhost
127.0.0.1       myproject.io
127.0.0.1       www.myproject.io
127.0.0.1       company1.myproject.io
127.0.0.1       company2.myproject.io
</code>```

settings.py:

```<code>ROOT_URLCONF = 'core.urls'
ROOT_HOSTCONF = 'core.hosts'
DEFAULT_HOST = 'www'
DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000"
</code>```

core/hosts.py:

```<code>from hostsconf import urls as redirect_urls
host_patterns = [
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'(?!www).*', redirect_urls, name='wildcard'),
]
</code>```

hostsconf/urls.py:

```<code>from .views import wildcard_redirect

urlpatterns = [
    url(r'^(?P<path>.*)', wildcard_redirect)
]
</code>```

hostsconf/views.py:

```<code>DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000")

def wildcard_redirect(request, path=None):
    new_url = DEFAULT_REDIRECT_URL
    if path is not None:
        new_url = DEFAULT_REDIRECT_URL + "/" + path
    return HttpResponseRedirect(new_url)
</code>```

I have a few problems now:

When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS
Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong?

How to implement a single view for all sub-domains where will be dynamic context for each company. Basically I need to make queries into the db by sub domain name. Example:

```<code>def home_page(request):
    subdomain = 'somehow get sub domain (company1 or company2)'
    comp = User.objects.get(domain_name=subdomain)
    return redirect(request, 'tpl.html', {"company": comp})
</code>```

UPDATE:
Figured out how to handle ALLOWED_HOSTS and get a subdomain. But I still don't get how to implement single view for my sub domains. Do I need to create another pattern in hosts.py?

答:
This question seems to be vert old but I think it will be helpfull for anyone who is still searching for this.

For wildcard subdomain, adding the domain in a list does not work for me. I have to add it as a tuple.

```<code>ALLOWED_HOSTS = ['.domain.com'] - This does not work for me

ALLOWED_HOSTS = ('.domain.com',) - This works for me.
</code>```

I tested it on Django 2.2.5 and Django 3.6

Body:
I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains.

hosts file:

127.0.0.1       localhost
127.0.0.1       myproject.io
127.0.0.1       www.myproject.io
127.0.0.1       company1.myproject.io
127.0.0.1       company2.myproject.io

settings.py:

ROOT_URLCONF = 'core.urls'
ROOT_HOSTCONF = 'core.hosts'
DEFAULT_HOST = 'www'
DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000"

core/hosts.py:

from hostsconf import urls as redirect_urls
host_patterns = [
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'(?!www).*', redirect_urls, name='wildcard'),
]

hostsconf/urls.py:

from .views import wildcard_redirect

urlpatterns = [
    url(r'^(?P<path>.*)', wildcard_redirect)
]

hostsconf/views.py:

DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000")

def wildcard_redirect(request, path=None):
    new_url = DEFAULT_REDIRECT_URL
    if path is not None:
        new_url = DEFAULT_REDIRECT_URL + "/" + path
    return HttpResponseRedirect(new_url)

I have a few problems now:

When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS
Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong?

How to implement a single view for all sub-domains where will be dynamic context for each company. Basically I need to make queries into the db by sub domain name. Example:

def home_page(request):
    subdomain = 'somehow get sub domain (company1 or company2)'
    comp = User.objects.get(domain_name=subdomain)
    return redirect(request, 'tpl.html', {"company": comp})

UPDATE:
Figured out how to handle ALLOWED_HOSTS and get a subdomain. But I still don't get how to implement single view for my sub domains. Do I need to create another pattern in hosts.py?

Body:
This question seems to be vert old but I think it will be helpfull for anyone who is still searching for this.

For wildcard subdomain, adding the domain in a list does not work for me. I have to add it as a tuple.

ALLOWED_HOSTS = ['.domain.com'] - This does not work for me

ALLOWED_HOSTS = ('.domain.com',) - This works for me.

I tested it on Django 2.2.5 and Django 3.6


问:
What does the operand of this mov instruction underlined in this image mean?

The above image along with the title fully encapsulates my question :-)

Extra details (if necessary):
I assume the above is enough information to answer the question, so if you know the answer and you wish to stop reading the rest of the question, that's totally fine.

I'm trying to understand what happens when a struct is returned by a C function. This is an example from the ``Reverse Engineering for Beginners'' by Dennis Yurichev page 139 (Returning a struct).

I understand that _a$ and $T3853 are macros, but I don't understand what the instruction actually does after the macros are replaced by their values.

答:
See above, _a$ and $T3853 are symbols defined to value 12 and 8 respectively.  So

```<code>mov ecx, DWORD PTR _a$[esp-4]
</code>```

is the same as

```<code>mov ecx, DWORD PTR 12[esp-4]
</code>```

or

```<code>mov ecx, DWORD PTR [esp-4+12]
</code>```

or

```<code>mov ecx, DWORD PTR [esp+8]
</code>```

Body:
See above, _a$ and $T3853 are symbols defined to value 12 and 8 respectively.  So

mov ecx, DWORD PTR _a$[esp-4]

is the same as

mov ecx, DWORD PTR 12[esp-4]

or

mov ecx, DWORD PTR [esp-4+12]

or

mov ecx, DWORD PTR [esp+8]


问:
__path__ attribute not found
I got this error when trying to deploy my function on gcloud functions. The function runs smoothly on my local machine FYI. I've browsed some posts but none have the solution

答:
As mentioned in the similar thread1 and thread2:

For anyone else that had this problem :
Removing the .py suffix on the python -m command fixes this problem, it appears -m only requires module names whereas running it directly as a python file (no -m option) requires the .py suffix

To learn more about the path attribute , you can refer to the documentation

Title: __path__ attribute not found


问:
Transparent status bar (with visible navigation bar)
I know this question has been asked many times, but all of the answers either not working, or use deprecated code:

Android Completely transparent Status Bar?

Transparent status bar - before Android 4.4 (KitKat)

Lollipop : draw behind statusBar with its color set to transparent

I want to achieve the same effect as latest google maps app:

Fully transparent status bar (Only status bar. not navigation bar!)

Non deprecated solution

WindowCompat.setDecorFitsSystemWindows(window, false) partially working as it also hides the navigation bar also

答:
Add this to your theme

<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar" ns1:targetApi="23">true</item>
```
<p>And use this method</p>
<pre class="lang-kotlin prettyprint-override"><code>     private fun handleStatusBar() {
        //set fullScreen (draw under statusBar and NavigationBar )
            WindowCompat.setDecorFitsSystemWindows(window, false)

            container.setOnApplyWindowInsetsListener { view, insets ->
            val navigationBarHeight = WindowInsetsCompat.toWindowInsetsCompat(insets)
                .getInsets(WindowInsetsCompat.Type.navigationBars()).bottom

            view.updatePadding(bottom = navigationBarHeight)
            WindowInsetsCompat.CONSUMED.toWindowInsets()
        }

        //make statusBar content dark
        WindowCompat.getInsetsController(window, window.decorView)?.isAppearanceLightStatusBars =
            true

        window.statusBarColor = Color.TRANSPARENT
    }
</code>```

Body:
Add this to your theme

<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar" ns1:targetApi="23">true</item>

And use this method

     private fun handleStatusBar() {
        //set fullScreen (draw under statusBar and NavigationBar )
            WindowCompat.setDecorFitsSystemWindows(window, false)

            container.setOnApplyWindowInsetsListener { view, insets ->
            val navigationBarHeight = WindowInsetsCompat.toWindowInsetsCompat(insets)
                .getInsets(WindowInsetsCompat.Type.navigationBars()).bottom

            view.updatePadding(bottom = navigationBarHeight)
            WindowInsetsCompat.CONSUMED.toWindowInsets()
        }

        //make statusBar content dark
        WindowCompat.getInsetsController(window, window.decorView)?.isAppearanceLightStatusBars =
            true

        window.statusBarColor = Color.TRANSPARENT
    }


问:
International notation for input time format
I have a page that tells the user to input a time in the format hh:mm:ss.  This is obviously fine for English speaking audiences, but is this an acceptable international notation?

If not, could you give me some examples of how other countries display this kind of information to the user.

答:
In terms of time, it is usually either in format hh:mm:ss or h:mm:ss, that is you either do zero-padding or no zero padding for single digits hours.

Another thing is, the format - distinction between 12 hours and 24 hours, that also varies from Locale to Locale.

Lastly, you should take into account local user's time zone - it is natural to enter the time in relation to current time zone.

How would you go about these options? Basically, it depends on what your UI look like. If you have just one text box where user can enter free-form text, you should actually parse the text according to valid Locale format. In that case you can give an example of the format, by formatting current day, so the label would say something like "Enter the time (for example: 16:36:11):".

Other approach is to have two (hour/minute) or more text fields (seconds) separated by time separator (":") and possibly conditional AM/PM radio button group (or drop down). In that case it would be a bit harder, because to do that correctly, you should actually analyze the localized pattern (on what is and what is not supported) and dynamically create UI elements (I don't want to see AM/PM stuff as I am using 24 hours time naturally) as well as validation rules...


问:
Can we use RobotFramework to automate MacOsx application?
Can we use RobotFramework to automate MacOSx application?
I could not find any documentation on this. Can you share some example on this.</p>

答: I went ahead with Appium. It is working fine for me so far.</p>


问:
I have troubles with counting the list elements equal to a given value K
I used the command list.count, but it just doesn't work.
Here's the code:</p>
```<code>import random

a = [random.randint (1, 10) for c in range (20) ]
print (a)

d = int (input ('Input a number') )
a.count(d)

while d in a:
    list.remove (d)
print(a)
</code>```

答:
The count method works properly and if you are asking why still your code isn't working then

Replace list.remove(d) with a.remove(d)

Print the value of a.count(d) to check whether the count method is working.

Body:
I used the command list.count, but it just doesn't work.
Here's the code:

import random

a = [random.randint (1, 10) for c in range (20) ]
print (a)

d = int (input ('Input a number') )
a.count(d)

while d in a:
    list.remove (d)
print(a)


问:
Does tdengine supports create index on normal columns?
I used tdengine for a few weeks, since our table have more than 30 million record for a table, however I want to filter with a nchar column. I have built a cluster with three nodes. But the filter response speed is not as fast as MySQL.I thought that if I can create index on this column the speed will be faster. Since i filtered with timestamp which is the primary key and tdengine automatically create index on this column. So I want to ask if tdengine supports create index ? If so, how to create? Can some help?</p>

答: TDengine not support create index on other columns till now.BUt it automatically create index for ts(the first column timestamp type). It will support create index on normal column in the furture.</p>


问:
Does the compiler automatically add an "extern" to a global variable that is not assigned a value in Programe language C?
So far I have understood the following:
A variable declaration is the declaration of a type and name of a variable without allocating memory space for it.
A variable definition means that the variable is declared and memory space is allocated for it.
So it has nothing to do with the initialization of the variable, whether you speak of a definition or a declaration.
In C, a declaration is always a definition e.g. if one write int i;.
But there is one exception. If you write extern int i; no memory space is allocated, only the variable is declared.
So int i; is always declaration and definition at the same time. But extern int i; is just declaration.

Is it true that in C you can declare a variable as often as you want, but you can only define the variable once?
I ask because I've tried the following and the compiler results confuse me. I use gcc and don't set the -std flag.
Neither this program:

```<code>int i;
int i;

void main(void){
i = 2;
}
</code>```

nor this program:

```<code>int i=0;
int i;
void main(void){
i = 2;
}
</code>```

lead to problems. The compiler compiles both without error. I would have expected since I didn't use the "extern" keyword here that the compiler would say something like "error: multiple definition".
But it doesn't give an error message. Is it possible that the compiler automatically writes an "extern" before all global defined "int i;" if I don't initialize them at the same time?
Isn't it then superfluous for the programmer to ever use the extern keyword for variables since the compiler will do that automatically anyway?

I think my considerations are confirmed by the following behavior. The following programs return errors:

```<code>int i;
i=0;
void main(void){
i = 2;
}
</code>```

leads to:

```<code>"warning: data definition has no type or storage class
 i=0;
warning: type defaults to 'int' in declaration of 'i' [-Wimplicit-int]"
</code>```

and

```<code>float i;
i=0;
void main(void){
i = 2;
}
</code>```

leads to:

```<code>"warning: data definition has no type or storage class
 i=0;
 warning: type defaults to 'int' in declaration of 'i' [-Wimplicit-int]
 error: conflicting types for 'i'
 note: previous declaration of 'i' was here
 float i;"
</code>```

So to me again it looks like there is an implicit "extern" before the first int i; respectively float i; is written because they are not assigned a value. As a result, no storage space is allocated for i.
But there is no other file in which storage space is allocated for i. Therefore there is no definition for i and the compiler therefore thinks in the 2nd line that i should be defined here.
Therefore there are no problems with the 1st program because the automatic type assignment fits, but with the 2nd program it no longer fits, which is why an error is returned.

The following program also throws an error:

```<code>void main(void){
int i;
int i;
}
</code>```

If I write the declaration (and thus also the definition) in a scope, the compiler returns the following error message.

```<code>"error: redeclaration of 'i' with no linkage int i;
 note: previous declaration of 'i' was here int i;"
</code>```

I can only explain it again with the fact that the compiler does not automatically set an "extern" before a variable that is not a global variable and therefore there are 2 definitions here.
But then I ask myself why is it called redeclaration and not redefinition or multiple definition?

It would be very nice if someone could confirm my assumptions or enlighten me on how to understand it correctly. Many Thanks!

答:
A variable declaration is the declaration of a type and name of a variable without allocating memory space for it.

Even if memory is reserved for an object, it a declaration. We do not exclude definitions from declarations; there are declarations that are definitions and declarations that are not definitions.

The declaration x = 3; causes memory to be reserved for x, but it also makes the name and type of x known, so it declares x.

So int i; is always declaration and definition at the same time.

Not quite. Inside a function, int i; is a definition. Outside of a function, int i; is a tentative definition. This is a special category that was necessary due to the history of C development. The language was not designed all at once with foresight about how it would be used. Different implementors tried different things. When a standard for the C language was developed, the committee working on it had to accommodate diverse existing uses.

When there is a tentative definition, the program can still supply a regular definition later in the translation unit. (The translation unit is the source file being compiled along with all the files included in it.) If the program does not supply a regular definition by the end of the translation unit, then the tentative definition becomes a regular definition as if it had an initializer of zero, as in int i = 0;.

Some C implementations treat multiple tentative definitions of an identifier in different translation units as referring to the same object. Some C implementations treat them as errors. Both behaviors are allowed by the C standard.

Is it true that in C you can declare a variable as often as you want, but you can only define the variable once?

Not always. Variables with no linkage (declared inside a function without static or extern) may not be declared more than once. (An identical declaration can appear inside a nested block, but this declares a new variable with the same name.)

Repeated declarations must have compatible types, and there are additional rules about which repeated declarations are allowed. For example, an identifier may not be declared with static after it has been declared with extern.

The compiler compiles both without error.

As described above, int i; outside a function is a tentative definition. Initially, it acts only as a non-definition declaration. So it may be repeated, and it may be replaced by a regular definition.

So to me again it looks like there is an implicit "extern" before the first int i;

No, there is not. int i; is a tentative definition, and it has nothing to do with the error messages you are getting. The error messages “data definition has no type or storage class” and “type defaults to 'int' in declaration of 'i'” are from the i=0;. This is a statement, not a declaration, but the C grammar does not provide for statements outside of functions. Outside of functions, the compiler is looking for only declarations. So it expects to see a type, as in int i=0;. The first message tells you the compiler does not see a type or a storage class. The second message tells you that, since it did not see a type, it is assuming int. This is a relic of old behavior in C where the int type would be taken as a default, so it could be left off. (Do not use that in new C code.)

The following program also throws an error:

Inside a function, int i; is a definition, so two of them causes multiple definitions of i.

Body:
So far I have understood the following:
A variable declaration is the declaration of a type and name of a variable without allocating memory space for it.
A variable definition means that the variable is declared and memory space is allocated for it.
So it has nothing to do with the initialization of the variable, whether you speak of a definition or a declaration.
In C, a declaration is always a definition e.g. if one write int i;.
But there is one exception. If you write extern int i; no memory space is allocated, only the variable is declared.
So int i; is always declaration and definition at the same time. But extern int i; is just declaration.

Is it true that in C you can declare a variable as often as you want, but you can only define the variable once?
I ask because I've tried the following and the compiler results confuse me. I use gcc and don't set the -std flag.
Neither this program:

int i;
int i;

void main(void){
i = 2;
}

nor this program:

int i=0;
int i;
void main(void){
i = 2;
}

lead to problems. The compiler compiles both without error. I would have expected since I didn't use the "extern" keyword here that the compiler would say something like "error: multiple definition".
But it doesn't give an error message. Is it possible that the compiler automatically writes an "extern" before all global defined "int i;" if I don't initialize them at the same time?
Isn't it then superfluous for the programmer to ever use the extern keyword for variables since the compiler will do that automatically anyway?

I think my considerations are confirmed by the following behavior. The following programs return errors:

int i;
i=0;
void main(void){
i = 2;
}

leads to:

"warning: data definition has no type or storage class
 i=0;
warning: type defaults to 'int' in declaration of 'i' [-Wimplicit-int]"

and

float i;
i=0;
void main(void){
i = 2;
}

leads to:

"warning: data definition has no type or storage class
 i=0;
 warning: type defaults to 'int' in declaration of 'i' [-Wimplicit-int]
 error: conflicting types for 'i'
 note: previous declaration of 'i' was here
 float i;"

So to me again it looks like there is an implicit "extern" before the first int i; respectively float i; is written because they are not assigned a value. As a result, no storage space is allocated for i.
But there is no other file in which storage space is allocated for i. Therefore there is no definition for i and the compiler therefore thinks in the 2nd line that i should be defined here.
Therefore there are no problems with the 1st program because the automatic type assignment fits, but with the 2nd program it no longer fits, which is why an error is returned.

The following program also throws an error:

void main(void){
int i;
int i;
}

If I write the declaration (and thus also the definition) in a scope, the compiler returns the following error message.

"error: redeclaration of 'i' with no linkage int i;
 note: previous declaration of 'i' was here int i;"

I can only explain it again with the fact that the compiler does not automatically set an "extern" before a variable that is not a global variable and therefore there are 2 definitions here.
But then I ask myself why is it called redeclaration and not redefinition or multiple definition?

It would be very nice if someone could confirm my assumptions or enlighten me on how to understand it correctly. Many Thanks!