问:
Looping through an Array of objects in Javascript sent by socket.emit
So I am making a blockchain in Node.js and am trying to print generated blocks in html. I am using socket. io to emit data to html, but am having issues with sending an object array of blocks that are in the blockchain.

So far my code looks like this:

Client.js

```<code>const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const myArgs = process.argv.slice(2);
const port = myArgs[0];
const SHA256 = require("crypto-js/sha256");

class Block {
    constructor(index, timestamp, data, previousHash) {
        this.index = index;
        this.timestamp = timestamp;
        this.data = data;
        this.previousHash = previousHash;
        this.hash = this.generateHash();
    }
    generateHash() {
        return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString();
    }
}

class Blockchain {
    constructor() {
        this.blockchain = [this.createGenesisBlock()];
    }

    createGenesisBlock() {
        return new Block(0, Date.now(), "prvi blok verige", "0");
    }

    getTheLatestBlock() {
        return this.blockchain[this.blockchain.length - 1];
    }

    addNewBlock(newBlock) {
        newBlock.previousHash = this.getTheLatestBlock().hash;
        newBlock.hash = newBlock.generateHash();
        this.blockchain.push(newBlock);
    }

    validateBlock(newBlock) {
        const latestBlock = this.getTheLatestBlock();
        if (newBlock.previousHash !== latestBlock.hash)
            return false;
        if (newBlock.index <= latestBlock.index)
            return false;
        if (newBlock.hash !== newBlock.generateHash())
            return false;
        return true;
    }

    validateChain() {
        for (let i = 1; i < this.blockchain.length; i++) {
            const currentBlock = this.blockchain[i];
            const previousBlock = this.blockchain[i - 1];
            if (currentBlock.hash !== currentBlock.generateHash()) {
                return false;
            }
            if (currentBlock.previousHash !== previousBlock.hash) {
                return false;
            }
            if (currentBlock.index <= previousBlock.index)
                return false;
            return true;

        }
    }
}
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('GUI connected on port: ' + port);
    socket.emit('onConnection', port);

    let logCoin = new Blockchain();
    console.log("mining logcoin in progress...");
    logCoin.addNewBlock(
        new Block(1, Date.now(),"Block 1")
    );

    logCoin.addNewBlock(
        new Block(2, Date.now(), "Block 2")
    );

    logCoin.addNewBlock(
        new Block(3, Date.now(),"Block 3")
    );
    console.log(logCoin);
    socket.emit('blockLedger', JSON.stringify(logCoin,null));

    socket.on('disconnect', () => {
        console.log("Client has disconnected");
    });
});

server.listen(port, () => {
    console.log('listening on port ' + port + ':');
});

</code>```

index.html

```<code>
<!DOCTYPE html>
<html>

<style>
    body {
        margin: 10px;
        padding-bottom: 3rem;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    }

    #header {
        display: flex;
        flex-direction: row;
    }

    #contentWrap {
        display: flex;
        width: 100%;
        flex-direction: row;
        align-items: stretch;
        justify-content: space-between;
        margin-top: 10px;
    }

    #contentWrap>div {
        flex: 1;
        border: 1px solid black;
    }

    #blocks {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }

    #blocks>li {
        padding: 0.5rem 1rem;
    }

    #blocks>li:nth-child(odd) {
        background: #efefef;
    }

    #minedBlocks {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }

    #minedBlocks>li {
        padding: 0.5rem 1rem;
    }

    #minedBlocks>li:nth-child(odd) {
        background: #efefef;
    }

    #port {
        position: absolute;
        right: 10px;
    }
</style>

<body>
    <div id="header">
        <div id="element1">
            <h1>Blockchain</h1>
            <p id="connectionStatus">Status: Offline</p>
            <form id="form" action="">
                <button id="mine">Mine</button>
            </form>
        </div>
        <div id="element2" style="align-self: center;">
            <form id="form" action="">
                <div id="port">
                    <input id="portInput" autocomplete="off" /><button>Connect port</button>
                </div>
            </form>
        </div>
    </div>
    <div id="contentWrap">
        <div id="ledger">
            <ul id="blocks">
                <li>Blockchain ledger</li>
            </ul>
        </div>
        <div id="mined">
            <ul id="minedBlocks">
                <li>Mining...</li>
            </ul>
        </div>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io();
        socket.on('onConnection', function (msg) {
            document.getElementById('connectionStatus').innerText = "Status: Online: PORT " + msg;
        });
        socket.on('blockLedger', function (msg) {
            var index;
            var data;
            var timeStamp;
            var previousHash;
            var hash;
            var blocks = document.getElementById('blocks');
            var obj = JSON.parse(msg);
            obj.forEach(function (arrayItem) {          // here is where i try to loop throught //the array
                let item = document.createElement("li");
                item.textContent = arrayItem.index;
                blocks.appendChild(item);
                window.scrollTo(0, document.body.scrollHeight);
            })

        })

    </script>
</body>

</html>

</code>```

I am trying to add all block indexes to a list, but nothing is added to the list. I dont think the forEach loop even works.

The array looks like this

And like this when i send it to html stringified

What am I doing wrong?

Edit
I used the solution from @ZackNewsham and it works, thanks!

Body:
So I am making a blockchain in Node.js and am trying to print generated blocks in html. I am using socket. io to emit data to html, but am having issues with sending an object array of blocks that are in the blockchain.

So far my code looks like this:

Client.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const myArgs = process.argv.slice(2);
const port = myArgs[0];
const SHA256 = require("crypto-js/sha256");

class Block {
    constructor(index, timestamp, data, previousHash) {
        this.index = index;
        this.timestamp = timestamp;
        this.data = data;
        this.previousHash = previousHash;
        this.hash = this.generateHash();
    }
    generateHash() {
        return SHA256(this.index + this.timestamp + this.previousHash + JSON.stringify(this.data)).toString();
    }
}

class Blockchain {
    constructor() {
        this.blockchain = [this.createGenesisBlock()];
    }

    createGenesisBlock() {
        return new Block(0, Date.now(), "prvi blok verige", "0");
    }

    getTheLatestBlock() {
        return this.blockchain[this.blockchain.length - 1];
    }

    addNewBlock(newBlock) {
        newBlock.previousHash = this.getTheLatestBlock().hash;
        newBlock.hash = newBlock.generateHash();
        this.blockchain.push(newBlock);
    }

    validateBlock(newBlock) {
        const latestBlock = this.getTheLatestBlock();
        if (newBlock.previousHash !== latestBlock.hash)
            return false;
        if (newBlock.index <= latestBlock.index)
            return false;
        if (newBlock.hash !== newBlock.generateHash())
            return false;
        return true;
    }

    validateChain() {
        for (let i = 1; i < this.blockchain.length; i++) {
            const currentBlock = this.blockchain[i];
            const previousBlock = this.blockchain[i - 1];
            if (currentBlock.hash !== currentBlock.generateHash()) {
                return false;
            }
            if (currentBlock.previousHash !== previousBlock.hash) {
                return false;
            }
            if (currentBlock.index <= previousBlock.index)
                return false;
            return true;

        }
    }
}
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('GUI connected on port: ' + port);
    socket.emit('onConnection', port);

    let logCoin = new Blockchain();
    console.log("mining logcoin in progress...");
    logCoin.addNewBlock(
        new Block(1, Date.now(),"Block 1")
    );

    logCoin.addNewBlock(
        new Block(2, Date.now(), "Block 2")
    );

    logCoin.addNewBlock(
        new Block(3, Date.now(),"Block 3")
    );
    console.log(logCoin);
    socket.emit('blockLedger', JSON.stringify(logCoin,null));

    socket.on('disconnect', () => {
        console.log("Client has disconnected");
    });
});

server.listen(port, () => {
    console.log('listening on port ' + port + ':');
});

index.html

<!DOCTYPE html>

Blockchain

Status: Offline

            <form id="form" action="">
                <button id="mine">Mine</button>
            </form>

            <form id="form" action="">

                    <input id="portInput" autocomplete="off" /><button>Connect port</button>

            </form>

Blockchain ledger

Mining...

I am trying to add all block indexes to a list, but nothing is added to the list. I dont think the forEach loop even works.

The array looks like this

And like this when i send it to html stringified

What am I doing wrong?

Edit
I used the solution from @ZackNewsham and it works, thanks!


来源: stackexchange

问:
how to import a Cmake Project which used .sh scripts for build to Vscode?
I have a legacy code base which has CMake configuration and .sh files which calls build commands with respect to build type ( release, relwithdebinfo etc.) as well as does a lot of things.

I have to work over codebase. So far I used STM32CubeIDe. I imported the project as existing Makefile project and then I changed C/C++ Build directory to where makefile outputs converted.

So whenever I did a change on the code, I hit the build command over UI and it calls make command at where I modifed the path above.
This is working but In case of a need of debug then I had to use .elf outputs and OZONE J link Debug program.
I have to do build+debug in same environment but eclipse is slow and making me struggle.
How can I make VSCode host to my legacy code in order to build and debug and also navigate in code i.e go to the definition of code in VSCode, not only building.

Please navigate me if anything needs to share from existing code base, if there is still unclear.

ContentLicense: CC BY-SA 4.0


问:
Java EE, JBoss: @Asynchronous does not allow method overloading
Does anybody has an idea why method overloading in combination with the @Asynchronous annotation does not work (I tested only on JBoss 6.0).

Example:

```<code>@Stateless
@LocalBean
public interface AsyncBean {

    @Asynchronous
    public void test(int a){
        // a lot of time-consuming calculations with a
    }

    @Asynchronous
    public void test(int a, int b) {
        // a lot of time-consuming calculations with a and b
    }
}
</code>```

Calls to any of the overloaded test() methods of the AsyncBean are not asynchronous. Howewer, giving up overloading (renaming one of the methods) results in asynchronous processing of the method calls.

Is there a reason why this does not work?

ContentLicense: CC BY-SA 3.0

Body:
Does anybody has an idea why method overloading in combination with the @Asynchronous annotation does not work (I tested only on JBoss 6.0).

Example:

@Stateless
@LocalBean
public interface AsyncBean {

    @Asynchronous
    public void test(int a){
        // a lot of time-consuming calculations with a
    }

    @Asynchronous
    public void test(int a, int b) {
        // a lot of time-consuming calculations with a and b
    }
}

Calls to any of the overloaded test() methods of the AsyncBean are not asynchronous. Howewer, giving up overloading (renaming one of the methods) results in asynchronous processing of the method calls.

Is there a reason why this does not work?


问:
Cmocka: How to get a list of all failed tests at the end of the session?
I would like to print a list of all the tests that have failed to be used at the end of the session. In CMocka framework failed tests are shown after each cmocka_run_group_tests call. Is there a standard solution to show all failed tests after running all test groups?

I suppose that I can use all CMUnitTest arrays after running all tests. They should keep all information about filed tests. But is there a better solution to do it?


问:
What is the best of passing taskHandle to another class in freeRTOS with pointers
OK it was not wise to ask question with some assumptions. Here is the detailed version.

I have 2 task, 1 for MQTT and 1 for LED. I want to read a data over MQTT and take an action to turn on an LED.

Here is my task declarations:

```<code>void taskMqtt(void *param);
xTaskHandle handleTaskMqtt;

void taskLed(void *param);
xTaskHandle handleTaskLed;
</code>```

Here is the task creation part

```<code>status = xTaskCreate(taskMqtt, "taskMqtt", 4096, NULL, 2, handleTaskMqtt);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "taskMqtt CREATED");

status = xTaskCreate(taskLed, "taskLed", 4096, NULL, 2, &handleTaskLed);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "taskLed CREATED");
</code>```

I created my Mqtt object like this and it works fine.

```<code>Mqtt mqtt("192.168.137.212", move(uptrWifi), handleTaskLed);
</code>```

Here is the Mqtt.h file to observe class declaration

```<code>class Mqtt
{
private:
std::unique_ptr<Wifi> uptrWifi;
static xTaskHandle handlerTask;

static const char *subscribeTopic;
static const char *publishTopic;

static esp_mqtt_client_config_t _mqttCfg;
static esp_mqtt_client_handle_t _clientCfg;

static void mqttEventHandler(void *arg, esp_event_base_t eventBase, int32_t eventId, void *eventData);

public:
Mqtt(const char *brokerIp, std::unique_ptr<Wifi> uptrToWifi, xTaskHandle taskToNotify);
void init(void);
void sendDataOverMqtt(std::string title, int data);
void sendDataOverMqtt(std::string title, int data, std::string pubTopic);
static void getDataOverMqtt(char *data, int dataLen);

void setTopics(std::string subTopic, std::string pubTopic);
};
</code>```

In Mqtt.cpp file I defined

```<code>xTaskHandle Mqtt::handlerTask;
</code>```

and constructor

```<code>Mqtt::Mqtt(const char *brokerIp, std::unique_ptr<Wifi> uptrToWifi,
xTaskHandle taskToNotify)
{
_mqttCfg.host = brokerIp;
ESP_LOGI("MQTT_H", "MQTT BROKER IP SET\n");

uptrWifi = move(uptrToWifi);
handlerTask = taskToNotify;
}
</code>```

and here is my function for read data and forward to the LED task.

```<code>void Mqtt::getDataOverMqtt(char *data, int dataLen)
{
static uint32_t valueToSend = 1;

if (strncmp(data, "Led ON", 6) == 0)
{
    ESP_LOGI(TAG, "\nDATA COMES \n");

    if (handlerTask != NULL)
    {
        xTaskNotify(handlerTask, valueToSend, eSetValueWithOverwrite);
    }
    else
    {
        printf("\nNULL pointer\n");
        fflush(stdout);
    }

    printf("\nCMD=%.*s\n\n", dataLen, data);
}
else if (strncmp(data, "Led OFF", 7) == 0)
{
    printf("\nCMD=%.*s\n\n", dataLen, data);
}
}
</code>```

And here is the LED task

```<code>void taskLed(void *param)
{
uint32_t ulNotifiedValue = false;

while (1)
{
    ESP_LOGI(TAG, "LED WAITING");

    xTaskNotifyWait(0, ULONG_MAX, &ulNotifiedValue, portMAX_DELAY);

    ESP_LOGI(TAG, "\n NOTIFICATION \n");

    ESP_LOGI(TAG, "LED TASK RUNNING");
    vTaskDelay(pdMS_TO_TICKS(1000));
}
}
</code>```

When I run the code and sent Led ON command, I can see the logs

```<code>LED WAITING (from taskLED definition)
DATA COMES (from getDataOverMqtt definition)
Null Pointer (from getDataOverMqtt definition)
</code>```

After that I was hoping to see on the logs

```<code>NOTIFICATION (from taskLED defition)
</code>```

////////////////////////////////////// ORIGINAL POST BEFORE EDITS IS BELOW

I am trying to learn FreeRtos and C++.

I need to pass taskHandle to another class and want to use them for notify function. What is the best way to do that?

In taskControl.cpp file I created tasks as below.

```<code>void task1(void *param);
TaskHandle_t handleTask1;

void task2(void *param);
TaskHandle_t handleTask2;

status = xTaskCreate(task1, "task1", 4096, NULL, 2, &handleTask1);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "task1 CREATED");

status = xTaskCreate(task2, "task2", 4096, NULL, 2, &handleTask2);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "task2 CREATED");
</code>```

I thought I can pass handleTask2 into another class via constructor

```<code>M m(&handleTask2);
</code>```

In classM.h file, M is declared as below

```<code>class M
{
private:
    static TaskHandle_t *handlerTask;
public:
    M(TaskHandle_t *taskToNotify)
    {
        handlerTask = taskToNotify;
    }
};
</code>```

And I tried to use handlerTask as below in classM.cpp file.

```<code>xTaskNotify(&handlerTask, valueToSend, eSetValueWithoutOverwrite);
</code>```

What am I missing? What is the correct way to do this kind of thing?

Sorry for if my question is not clear.

Body:
OK it was not wise to ask question with some assumptions. Here is the detailed version.

I have 2 task, 1 for MQTT and 1 for LED. I want to read a data over MQTT and take an action to turn on an LED.

Here is my task declarations:

void taskMqtt(void *param);
xTaskHandle handleTaskMqtt;

void taskLed(void *param);
xTaskHandle handleTaskLed;

Here is the task creation part

status = xTaskCreate(taskMqtt, "taskMqtt", 4096, NULL, 2, handleTaskMqtt);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "taskMqtt CREATED");

status = xTaskCreate(taskLed, "taskLed", 4096, NULL, 2, &handleTaskLed);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "taskLed CREATED");

I created my Mqtt object like this and it works fine.

Mqtt mqtt("192.168.137.212", move(uptrWifi), handleTaskLed);

Here is the Mqtt.h file to observe class declaration

class Mqtt
{
private:
std::unique_ptr<Wifi> uptrWifi;
static xTaskHandle handlerTask;

static const char *subscribeTopic;
static const char *publishTopic;

static esp_mqtt_client_config_t _mqttCfg;
static esp_mqtt_client_handle_t _clientCfg;

static void mqttEventHandler(void *arg, esp_event_base_t eventBase, int32_t eventId, void *eventData);

public:
Mqtt(const char *brokerIp, std::unique_ptr<Wifi> uptrToWifi, xTaskHandle taskToNotify);
void init(void);
void sendDataOverMqtt(std::string title, int data);
void sendDataOverMqtt(std::string title, int data, std::string pubTopic);
static void getDataOverMqtt(char *data, int dataLen);

void setTopics(std::string subTopic, std::string pubTopic);
};

In Mqtt.cpp file I defined

xTaskHandle Mqtt::handlerTask;

and constructor

Mqtt::Mqtt(const char *brokerIp, std::unique_ptr<Wifi> uptrToWifi,
xTaskHandle taskToNotify)
{
_mqttCfg.host = brokerIp;
ESP_LOGI("MQTT_H", "MQTT BROKER IP SET\n");

uptrWifi = move(uptrToWifi);
handlerTask = taskToNotify;
}

and here is my function for read data and forward to the LED task.

void Mqtt::getDataOverMqtt(char *data, int dataLen)
{
static uint32_t valueToSend = 1;

if (strncmp(data, "Led ON", 6) == 0)
{
    ESP_LOGI(TAG, "\nDATA COMES \n");

    if (handlerTask != NULL)
    {
        xTaskNotify(handlerTask, valueToSend, eSetValueWithOverwrite);
    }
    else
    {
        printf("\nNULL pointer\n");
        fflush(stdout);
    }

    printf("\nCMD=%.*s\n\n", dataLen, data);
}
else if (strncmp(data, "Led OFF", 7) == 0)
{
    printf("\nCMD=%.*s\n\n", dataLen, data);
}
}

And here is the LED task

void taskLed(void *param)
{
uint32_t ulNotifiedValue = false;

while (1)
{
    ESP_LOGI(TAG, "LED WAITING");

    xTaskNotifyWait(0, ULONG_MAX, &ulNotifiedValue, portMAX_DELAY);

    ESP_LOGI(TAG, "\n NOTIFICATION \n");

    ESP_LOGI(TAG, "LED TASK RUNNING");
    vTaskDelay(pdMS_TO_TICKS(1000));
}
}

When I run the code and sent Led ON command, I can see the logs

LED WAITING (from taskLED definition)
DATA COMES (from getDataOverMqtt definition)
Null Pointer (from getDataOverMqtt definition)

After that I was hoping to see on the logs

NOTIFICATION (from taskLED defition)

////////////////////////////////////// ORIGINAL POST BEFORE EDITS IS BELOW

I am trying to learn FreeRtos and C++.

I need to pass taskHandle to another class and want to use them for notify function. What is the best way to do that?

In taskControl.cpp file I created tasks as below.

void task1(void *param);
TaskHandle_t handleTask1;

void task2(void *param);
TaskHandle_t handleTask2;

status = xTaskCreate(task1, "task1", 4096, NULL, 2, &handleTask1);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "task1 CREATED");

status = xTaskCreate(task2, "task2", 4096, NULL, 2, &handleTask2);
configASSERT(status == pdPASS);
ESP_LOGI(TAG, "task2 CREATED");

I thought I can pass handleTask2 into another class via constructor

M m(&handleTask2);

In classM.h file, M is declared as below

class M
{
private:
    static TaskHandle_t *handlerTask;
public:
    M(TaskHandle_t *taskToNotify)
    {
        handlerTask = taskToNotify;
    }
};

And I tried to use handlerTask as below in classM.cpp file.

xTaskNotify(&handlerTask, valueToSend, eSetValueWithoutOverwrite);

What am I missing? What is the correct way to do this kind of thing?

Sorry for if my question is not clear.


问:
How to get data for 11 months only in Excel (Cubevalue)?
I can not understand how to get data for 11 months only? I have this: =CUBEMEMBER("sql17 ASTV Indications";"[Date].[30.11.2021]"). I need to get data not only for this day (30.11) but for 11 months till 30.11 (01.01-30.11). I can not solve it. If I put this formula, I have data only for 30.11: =N(CUBEVALUE("sql17 KLIF Sales";$AO$2;$AH$11;R$2;$AH$12))

Please help!

enter image description here

=CUBEMEMBER("sql17 ASTV Indications";"[Date].[30.11.2021]")


问:
Why is VSCode Python debugger slowing down execution by a factor of 5
I run a Python 3.10 script that analyzes some 350 SQL files using the sqlparse module. When I run this via "Run Python File" in VSCode 1.73.1 it takes about 4 seconds. When I run it via "Debug Python File", it takes roughly 5 times as long.

The final analysis will run on a set of 1,500 SQL files, and debugging something that sits on top of the analysis result (a heavy dependencies network of objects) will probably take more than a minute in each iteration. This will slow down the development cycle considerably, somewhat like in the old times when we had a compile/bind-cycle before we can run our latest change.

I will probably survive, but I am curious: Where does this excessive runtime come from?


问:
To get the current date and month in full calendar as we click on change the month
full calendar
as you see in the image, this is the full calendar. I am trying to get the current month and date.

```<code><FullCalendar
                {...rest}
                plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
                events={calendarEvents}
                editable={hasFeatureAccess(
                  permissionName,
                  'updateEvent',
                  groupsReferenceData
                )}
                selectable={hasFeatureAccess(
                  permissionName,
                  'addEvent',
                  groupsReferenceData
                )}
                select={
                  hasFeatureAccess(
                    permissionName,
                    'addEvent',
                    groupsReferenceData
                  )
                    ? handleDateSelect
                    : undefined
                }
                eventClick={
                  hasFeatureAccess(
                    permissionName,
                    'updateEvent',
                    groupsReferenceData
                  )
                    ? handleEventClick
                    : undefined
                }
                initialView='dayGridMonth'
                height='100%'
              />
</code>```

As I change months in my full calendar, I want the current date and month that date and month I want to use in calling the API.

Body:
full calendar
as you see in the image, this is the full calendar. I am trying to get the current month and date.

<FullCalendar
                {...rest}
                plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
                events={calendarEvents}
                editable={hasFeatureAccess(
                  permissionName,
                  'updateEvent',
                  groupsReferenceData
                )}
                selectable={hasFeatureAccess(
                  permissionName,
                  'addEvent',
                  groupsReferenceData
                )}
                select={
                  hasFeatureAccess(
                    permissionName,
                    'addEvent',
                    groupsReferenceData
                  )
                    ? handleDateSelect
                    : undefined
                }
                eventClick={
                  hasFeatureAccess(
                    permissionName,
                    'updateEvent',
                    groupsReferenceData
                  )
                    ? handleEventClick
                    : undefined
                }
                initialView='dayGridMonth'
                height='100%'
              />

As I change months in my full calendar, I want the current date and month that date and month I want to use in calling the API.


问:
PyQt5 - Move button actions inside a separate thread using QThread()
I am new to building GUIs in Python and even more to multithreaded programming, hence, I apologise in advance if my vocabulary/terminology is not accurate enough.

I have the following code that builds a GUI using PyQt5.

```<code>    import PyQt5
    import automation_main
    from PyQt5.QtWdigets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *

    class Window(QMainWindow):
        def __init__(self):
        super().__init__()
            self.setWindowTite('Test')
            self.setGeometry(100, 100, 500)
            self.UiComponents() #calling the UI components method
            self.UiWidgets() #calling the UI widgets method
            self.show()

        def UiComponents(self):
            button1 = QPushButton('Hello', parent=self)
            button1.setGeometry(120, 670, 150, 50)
            button1.clicked.connect(self.clickme) #button1 calls the clickme() method

        def UiWidgets(self):

            # here I define a textbox where the user inputs a year
            self.textbox = QLineEdit(self)
            self.textbox.setGeometry(185, 140, 450, 40)
            self.textbox.returnPressed.connect(self.entered)

            # here I define a QlineEdit where the user chooses a month
            self.combobox = QComboBox(self)
            self.combobox.setGeometry(185, 255, 450, 40)
            options = ['Jan', 'Feb', 'Mar']
            self.combobox.setEditable(True)
            self.combobox.addItems(options)
            line_edit = self.combobox.lineEdit()
            line_edit.setAlignment(Qt.AlignCenter)
            line_edit.setReadOnly(True)
            self.combobox.activated[str].connect(self.selected)

        def entered(self):
            #defines self.entered_text that correponds to the user input in the QLineEdit()
            self.entered_text = int(self.textbox.text())

        def selected(self, text):
            #defines self.selected_text that correponds to the user selection in theQComboBox()
            self.selected_text = text

        #Finally

        def clickme(self):
            # uses functions self.entered_text and self.selected_text inside the function block
            year_loc = automation_main.main(self.selected_text, self.entered_text)

</code>```

What I have attempted:

I have created a Worker class and included the clickme() function in it with generic

```<code>    class Worker(QObject):

        finished = pyqtSignal()
        progress = pyqtSignal(int)
        def clickme(x, y):
            year_loc = automation_main.main(x, y)
</code>```

I created a method in class Window() that creates a thread

```<code>    def createWrokerThread(self):
        self.worker = Worker()
        self.worker_thread = QtCore.QThread()
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
</code>```

Then I called this method inside the class Window() constructor namely

```<code>    class Window(QMainWindow):
        def __init__(self):
            ...
            self.createWorkerThread()
            ...
</code>```

I changed the button action in UiComponents():

```<code>    def UiComponents(self):
        button1 = QPushButton('Hello', parent=self)
        button1.setGeometry(120, 670, 150, 50)
        button1.clicked.connect(self.worker.clickme(self.entered_text, self.selected_text)
</code>```

Problem: I get an error saying that 'Window' has no attribute 'entered_text'

Thank you very much in advance!

Body:
I am new to building GUIs in Python and even more to multithreaded programming, hence, I apologise in advance if my vocabulary/terminology is not accurate enough.

I have the following code that builds a GUI using PyQt5.

    import PyQt5
    import automation_main
    from PyQt5.QtWdigets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *

    class Window(QMainWindow):
        def __init__(self):
        super().__init__()
            self.setWindowTite('Test')
            self.setGeometry(100, 100, 500)
            self.UiComponents() #calling the UI components method
            self.UiWidgets() #calling the UI widgets method
            self.show()

        def UiComponents(self):
            button1 = QPushButton('Hello', parent=self)
            button1.setGeometry(120, 670, 150, 50)
            button1.clicked.connect(self.clickme) #button1 calls the clickme() method

        def UiWidgets(self):

            # here I define a textbox where the user inputs a year
            self.textbox = QLineEdit(self)
            self.textbox.setGeometry(185, 140, 450, 40)
            self.textbox.returnPressed.connect(self.entered)

            # here I define a QlineEdit where the user chooses a month
            self.combobox = QComboBox(self)
            self.combobox.setGeometry(185, 255, 450, 40)
            options = ['Jan', 'Feb', 'Mar']
            self.combobox.setEditable(True)
            self.combobox.addItems(options)
            line_edit = self.combobox.lineEdit()
            line_edit.setAlignment(Qt.AlignCenter)
            line_edit.setReadOnly(True)
            self.combobox.activated[str].connect(self.selected)

        def entered(self):
            #defines self.entered_text that correponds to the user input in the QLineEdit()
            self.entered_text = int(self.textbox.text())

        def selected(self, text):
            #defines self.selected_text that correponds to the user selection in theQComboBox()
            self.selected_text = text

        #Finally

        def clickme(self):
            # uses functions self.entered_text and self.selected_text inside the function block
            year_loc = automation_main.main(self.selected_text, self.entered_text)

What I have attempted:

I have created a Worker class and included the clickme() function in it with generic

    class Worker(QObject):

        finished = pyqtSignal()
        progress = pyqtSignal(int)
        def clickme(x, y):
            year_loc = automation_main.main(x, y)

I created a method in class Window() that creates a thread

    def createWrokerThread(self):
        self.worker = Worker()
        self.worker_thread = QtCore.QThread()
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()

Then I called this method inside the class Window() constructor namely

    class Window(QMainWindow):
        def __init__(self):
            ...
            self.createWorkerThread()
            ...

I changed the button action in UiComponents():

    def UiComponents(self):
        button1 = QPushButton('Hello', parent=self)
        button1.setGeometry(120, 670, 150, 50)
        button1.clicked.connect(self.worker.clickme(self.entered_text, self.selected_text)

Problem: I get an error saying that 'Window' has no attribute 'entered_text'

Thank you very much in advance!


问:
Create a png preview image from hex color palette files in java, batch process all those files in a directory
I am trying to create a simple class that will help me organize my hundred's of text files that represent distinct color palettes in hex format. No size restrictions but in most cases colors are less than 256 per file and support transparency also (6 or 8 hex digits).

the format is simply a text file like this (a value per line):

546A817F

A7AC827F

ACBFB97F

9DB3BA7F

...

The goal is to create a preview png image per every palette file in a direcory. (format is PNG in order to support transparency, and when viewed in image viewers easily see/get the actual color).
Preferably constructed in colored rectangles side by side, preferably with the option to set a title with the hex value.

I have tried with the following code, but there are problems in the constriction of the Graphics2D object.

The functions goes like this:
1.scan a directory for all the files,
2.for every file, we scan contents and create a list of the hex values that holds
3. we count those colors and create a png image with those colors as filled rectangles, side by side. (and maybe print the hex value also inside/top/bottom of every rectangle)
4. The best would be not to have a fixed size image, but a variable one, taking care the amount of colors per list/file.

a simple example of placing colors can be found here: http://www.java2s.com/Code/Java/2D-Graphics-GUI/ColorGradient.htm

I am not a java developer, just trying to develop simple tools to make my life easier for my personal projects. I do not care a about good code practices, I am interested only in the final result, so I'm sorry for the mixed up code or mistakes!

code till now, the alignment of rectangles is broken, loops for scanning I think work simply ok, but images I think overlay the previous graphics object on top of each other (best seen with transparency).
any contribution welcomed.  Thanks in advance.

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import static java.nio.charset.Charset.defaultCharset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.imageio.ImageIO;

/**
 *
 * @author
 */
public class ConvertFromHexColorListToImage {

     public      Color c = new Color (0,0,0,0);

public  List<String> list = new ArrayList<>();
   int count;
       private  BufferedImage buffer;

     // the size of our image
   private   int IMAGE_SIZE = 800;
   public ConvertFromHexColorListToImage() throws IOException {

   }

    protected BufferedImage getBuffer() throws IOException {
        if (buffer == null) {
            buffer = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE/2, BufferedImage.TYPE_INT_ARGB);

try (Stream<Path> filePathStream=Files.walk(Paths.get("data/multi_hex/hex_only/"))) {
    filePathStream.forEach(filePath -> {

        if (Files.isRegularFile(filePath)) {

              System.out.println(filePath);
              count++;
               System.out.println("count = " +count);
           try {
//list = new ArrayList<>();
             list = Files.readAllLines(filePath);
              System.out.println("list = "+list);

        // one image per list index

     for (int i = 0; i < count; i++) {

         for(int j = 0; j < list.size(); j++){

         Graphics2D   g = (Graphics2D) buffer.getGraphics();

//c = new Color(0,0,0,0);
c = HexToColor(list.get(j));
Random rand = new Random();

        // Show all the predefined colors.

                float size = 25;
        float x = -size * list.size() / 8;
        float y = -size * 3 / 2;

                Rectangle2D r = new Rectangle2D.Float(
              x + IMAGE_SIZE/12 * (float)j, y, IMAGE_SIZE/12, IMAGE_SIZE/12);

//          c = HexToColor(list.get(j));

          g.setPaint(c);
          g.fill(r);

g.dispose();

}

     }

                                     File f = new File("data/image_pal/MyFile"+""+count+".png"); // i=files, j=colors
    System.out.println("Created IMAGE = "+f);
   if (!ImageIO.write(buffer, "PNG", f)) {
  throw new RuntimeException("Unexpected error writing image");

         }

           }catch (IOException ex) {
              Logger.getLogger(ConvertFromHexColorListToImage.class.getName()).log(Level.SEVERE, null, ex);
           }

        }
    });

}

        }
        return buffer;
    }

    //https://stackoverflow.com/questions/4129666/how-to-convert-hex-to-rgb-using-java
   /**
    * Converts a hex string to a color. If it can't be converted null is
    * returned.
    *
    * @param hex (i.e. #CCCCCCFF or CCCCCC)
    * @return Color
    */
   public static Color HexToColor(String hex)
   {
      hex = hex.replace("#", "");
      switch (hex.length()) {
         case 6:
            return new Color(
                    Integer.valueOf(hex.substring(0, 2), 16),
                    Integer.valueOf(hex.substring(2, 4), 16),
                    Integer.valueOf(hex.substring(4, 6), 16));
         case 8:
            return new Color(
                    Integer.valueOf(hex.substring(0, 2), 16),
                    Integer.valueOf(hex.substring(2, 4), 16),
                    Integer.valueOf(hex.substring(4, 6), 16),
                    Integer.valueOf(hex.substring(6, 8), 16)); //alpha FF
      }
      //return null;
      return new Color(0, 0, 0, 0);
   }

    public static void main(String[] args) throws IOException {

        ConvertFromHexColorListToImage test0 = new ConvertFromHexColorListToImage();
        test0.getBuffer();

        System.out.println("bufferedimage = "+test0.buffer);

    }
   }
</code>```

Body:
I am trying to create a simple class that will help me organize my hundred's of text files that represent distinct color palettes in hex format. No size restrictions but in most cases colors are less than 256 per file and support transparency also (6 or 8 hex digits).

the format is simply a text file like this (a value per line):

546A817F

A7AC827F

ACBFB97F

9DB3BA7F

...

The goal is to create a preview png image per every palette file in a direcory. (format is PNG in order to support transparency, and when viewed in image viewers easily see/get the actual color).
Preferably constructed in colored rectangles side by side, preferably with the option to set a title with the hex value.

I have tried with the following code, but there are problems in the constriction of the Graphics2D object.

The functions goes like this:
1.scan a directory for all the files,
2.for every file, we scan contents and create a list of the hex values that holds
3. we count those colors and create a png image with those colors as filled rectangles, side by side. (and maybe print the hex value also inside/top/bottom of every rectangle)
4. The best would be not to have a fixed size image, but a variable one, taking care the amount of colors per list/file.

a simple example of placing colors can be found here: http://www.java2s.com/Code/Java/2D-Graphics-GUI/ColorGradient.htm

I am not a java developer, just trying to develop simple tools to make my life easier for my personal projects. I do not care a about good code practices, I am interested only in the final result, so I'm sorry for the mixed up code or mistakes!

code till now, the alignment of rectangles is broken, loops for scanning I think work simply ok, but images I think overlay the previous graphics object on top of each other (best seen with transparency).
any contribution welcomed.  Thanks in advance.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import static java.nio.charset.Charset.defaultCharset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.imageio.ImageIO;

/**
 *
 * @author
 */
public class ConvertFromHexColorListToImage {

     public      Color c = new Color (0,0,0,0);

public  List<String> list = new ArrayList<>();
   int count;
       private  BufferedImage buffer;

     // the size of our image
   private   int IMAGE_SIZE = 800;
   public ConvertFromHexColorListToImage() throws IOException {

   }

    protected BufferedImage getBuffer() throws IOException {
        if (buffer == null) {
            buffer = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE/2, BufferedImage.TYPE_INT_ARGB);

try (Stream<Path> filePathStream=Files.walk(Paths.get("data/multi_hex/hex_only/"))) {
    filePathStream.forEach(filePath -> {

        if (Files.isRegularFile(filePath)) {

              System.out.println(filePath);
              count++;
               System.out.println("count = " +count);
           try {
//list = new ArrayList<>();
             list = Files.readAllLines(filePath);
              System.out.println("list = "+list);

        // one image per list index

     for (int i = 0; i < count; i++) {

         for(int j = 0; j < list.size(); j++){

         Graphics2D   g = (Graphics2D) buffer.getGraphics();

//c = new Color(0,0,0,0);
c = HexToColor(list.get(j));
Random rand = new Random();

        // Show all the predefined colors.

                float size = 25;
        float x = -size * list.size() / 8;
        float y = -size * 3 / 2;

                Rectangle2D r = new Rectangle2D.Float(
              x + IMAGE_SIZE/12 * (float)j, y, IMAGE_SIZE/12, IMAGE_SIZE/12);

//          c = HexToColor(list.get(j));

          g.setPaint(c);
          g.fill(r);

g.dispose();

}

     }

                                     File f = new File("data/image_pal/MyFile"+""+count+".png"); // i=files, j=colors
    System.out.println("Created IMAGE = "+f);
   if (!ImageIO.write(buffer, "PNG", f)) {
  throw new RuntimeException("Unexpected error writing image");

         }

           }catch (IOException ex) {
              Logger.getLogger(ConvertFromHexColorListToImage.class.getName()).log(Level.SEVERE, null, ex);
           }

        }
    });

}

        }
        return buffer;
    }

    //https://stackoverflow.com/questions/4129666/how-to-convert-hex-to-rgb-using-java
   /**
    * Converts a hex string to a color. If it can't be converted null is
    * returned.
    *
    * @param hex (i.e. #CCCCCCFF or CCCCCC)
    * @return Color
    */
   public static Color HexToColor(String hex)
   {
      hex = hex.replace("#", "");
      switch (hex.length()) {
         case 6:
            return new Color(
                    Integer.valueOf(hex.substring(0, 2), 16),
                    Integer.valueOf(hex.substring(2, 4), 16),
                    Integer.valueOf(hex.substring(4, 6), 16));
         case 8:
            return new Color(
                    Integer.valueOf(hex.substring(0, 2), 16),
                    Integer.valueOf(hex.substring(2, 4), 16),
                    Integer.valueOf(hex.substring(4, 6), 16),
                    Integer.valueOf(hex.substring(6, 8), 16)); //alpha FF
      }
      //return null;
      return new Color(0, 0, 0, 0);
   }

    public static void main(String[] args) throws IOException {

        ConvertFromHexColorListToImage test0 = new ConvertFromHexColorListToImage();
        test0.getBuffer();

        System.out.println("bufferedimage = "+test0.buffer);

    }
   }


问:
How to configure T-ADS (Terminating-Access Domain Selection) for Android carrier/operator?
I am implementing a carrier application (https://source.android.com/docs/core/connect/uicc) that manages carrier configurations.

One part is to configure the T-ADS (Terminating-Access Domain Selection). This includes:

Whether it is supported

The T-ADS timer

Whether network remembers last domain

Whether it prefers PS or CS

Usually, the stuff like this can be found in CarrierConfigManager (https://developer.android.com/reference/android/telephony/CarrierConfigManager) configuration keys, but I could not find anything related to T-ADS. Also tried to check generally what is in docs related to it, but ended up without results.


问:
list of object is updating its values on updating another object in Blazor
When I am updating my Some properties of my MstService Class Object, on the same time it is updating SList of type List Too,Don't know why??

```<code>protected MstService Service { get; set; } = new MstService();
        public List<MstService> SList { get; set; } = new List<MstService>();

        public async Task ResetForm()
        {
            Service.Id = 0;
            Service.Name = "";
            Service.IsActive = false;
            values.Clear();
            btnSubmitDisabled = false;
            btnAddRangeDisabled = false;
            btnRemoveDisabled = false;
            SList = (await serviceMater.GetServices()).ToList();
        }
</code>```

Why the values are changing in SList

Body:
When I am updating my Some properties of my MstService Class Object, on the same time it is updating SList of type List Too,Don't know why??

protected MstService Service { get; set; } = new MstService();
        public List<MstService> SList { get; set; } = new List<MstService>();

        public async Task ResetForm()
        {
            Service.Id = 0;
            Service.Name = "";
            Service.IsActive = false;
            values.Clear();
            btnSubmitDisabled = false;
            btnAddRangeDisabled = false;
            btnRemoveDisabled = false;
            SList = (await serviceMater.GetServices()).ToList();
        }

Why the values are changing in SList


问:
Edit custom post type in front end
I'm trying to edit my posts through the front end, but I can't link the fields to the post that needs to be edited. I'm passing the post ID via url coming from another page, here I retrieve the ID to show the post information in the form fields. My goal is for the user to be able to enter some additional information (Two last fields of the form). But I am not able to save these fields in the post. Here is my code:

`

```<code><section id="editform">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <?php
          $post_id = ( ! empty( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) ? absint( $_GET['id'] ) : 0;
          $post_to_edit = $post_id ? get_post( $post_id ) : false;
          if ( current_user_can( 'edit_post', $post_id ) && $post_to_edit ) : ?>
            <form id="edit_form" method="post">
              <label>
                <span>Post title</span><br>
                <input type="text" name="post_title" value="<?php echo esc_attr( $post_to_edit->post_title ); ?>">
              </label>
              <!-- more form fields -->
              <input type="hidden" name="id" id="id" value="<?php echo esc_attr( $post_id ); ?>">
              <!-- nonce field -->
              <!-- submit -->
            </form>
            <form action="" method="post" id="uploadform">
              <div class="form-row">
                <div class="form-group col-sm-6 col-12">
                  <label for="inputnome">Nome</label>
                  <input readonly type="text" name="post_title" class="form-control" id="inputnome" placeholder="Nome" value="<?php echo esc_attr( $post_to_edit->post_title ); ?>">
                </div>
                <div class="form-group col-sm-6 col-12">
                  <label for="inputemail">Email</label>
                  <input readonly type="email" name="email" class="form-control" id="inputemail" aria-describedby="emailHelp" placeholder="Seu email" value="<?php echo esc_attr( $post_to_edit->_email ); ?>">
                </div>
                <div class="form-group col-sm-6 col-12">
                  <label for="inputdatanascimento">Data de nascimento</label>
                  <input readonly type="date" name="date" class="form-control" id="inputdatanascimento" placeholder="XX/XX/XXXX"  value="<?php echo esc_attr( $post_to_edit->_data_de_nascimento ); ?>">
                </div>
                <div class="form-group col-sm-6 col-12">
                  <label for="inputtel">Telefone de contato</label>
                  <input readonly type="tel" name="tel" class="form-control" id="inputtel" placeholder="(00) 00000-0000" value="<?php echo esc_attr( $post_to_edit->_telefone_de_contato ); ?>">
                </div>
                <div class="form-group col-sm-6 col-12">
                  <label for="inputcpf">CPF</label>
                  <input readonly type="text" name="cpf" class="form-control" id="inputcpf" placeholder="XXX.XXX.XXX-XX" value="<?php echo esc_attr( $post_to_edit->_cpf ); ?>">
                </div>
                <div class="form-group col-sm-6 col-12">
                  <label for="inputcidade">Cidade de locação</label>
                  <input readonly type="text" name="cidade" class="form-control" id="inputcidade" placeholder="Cidade de locação" value="<?php echo esc_attr( $post_to_edit->_cidade_de_locacao ); ?>">
                </div>

                <div class="form-group col-sm-6 col-12">
                  <label for="inputcidade">Nome do locador</label>
                  <input required type="text" name="nomelocador" class="form-control" id="nomelocador" placeholder="Nome do locador">
                  <div class="invalid-feedback" >
                    Por favor, insira uma cidade válida!
                  </div>
                </div>

                <div class="form-group col-sm-6 col-12">
                  <label for="inputcidade">CPF do locador</label>
                  <input required type="text" name="cpflocador" class="form-control" id="cpflocador" placeholder="CPF do locador">
                  <div class="invalid-feedback" >
                    Por favor, insira uma cidade válida!
                  </div>
                </div>

              </div>

              <button name="submit"  class="btn btn-primary " type="submit" id="submit" value="Publish">Enviar proposta</button>
            </form>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </section>
</code>```

`

`

```<code><?php
  $postTitle = $_POST['post_title'];
  $post = $_POST['post'];
  $submit = $_POST['submit'];
  $cpflocador = $_POST['cpflocador'];
  $nomelocador = $_POST['nomelocador'];

  if(isset($submit)){

    global $user_ID;

    $new_post = array(
      'post_title' => $postTitle,
      'post_content' => $post,
      'post_status'   => 'publish',
      'Nome_locador' => array( '_nomelocador' => $nomelocador ),
      'CPF_locador' => array( '_cpflocador' => $cpflocador ),
      'post_date' => date('Y-m-d H:i:s'),
      'post_author' => $user_ID,
      'post_type' => 'propostas',

    );

    $the_post_id = wp_update_post($new_post);
    add_post_meta( $the_post_id, '_nomelocador', $nomelocador );
    add_post_meta( $the_post_id, '_cpflocador', $cpflocador );

  }

  ?>
</code>```

`

I tried several times to send the information to the post through the id, but I couldn't

Title: Edit custom post type in front end

Body:
I'm trying to edit my posts through the front end, but I can't link the fields to the post that needs to be edited. I'm passing the post ID via url coming from another page, here I retrieve the ID to show the post information in the form fields. My goal is for the user to be able to enter some additional information (Two last fields of the form). But I am not able to save these fields in the post. Here is my code:

`

          <?php
          $post_id = ( ! empty( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) ? absint( $_GET['id'] ) : 0;
          $post_to_edit = $post_id ? get_post( $post_id ) : false;
          if ( current_user_can( 'edit_post', $post_id ) && $post_to_edit ) : ?>
            <form id="edit_form" method="post">

                Post title

                <input type="text" name="post_title" value="<?php echo esc_attr( $post_to_edit->post_title ); ?>">

              <input type="hidden" name="id" id="id" value="<?php echo esc_attr( $post_id ); ?>">

            </form>
            <form action="" method="post" id="uploadform">

                  Nome
                  <input readonly type="text" name="post_title" class="form-control" id="inputnome" placeholder="Nome" value="<?php echo esc_attr( $post_to_edit->post_title ); ?>">

                  Email
                  <input readonly type="email" name="email" class="form-control" id="inputemail" aria-describedby="emailHelp" placeholder="Seu email" value="<?php echo esc_attr( $post_to_edit->_email ); ?>">

                  Data de nascimento
                  <input readonly type="date" name="date" class="form-control" id="inputdatanascimento" placeholder="XX/XX/XXXX"  value="<?php echo esc_attr( $post_to_edit->_data_de_nascimento ); ?>">

                  Telefone de contato
                  <input readonly type="tel" name="tel" class="form-control" id="inputtel" placeholder="(00) 00000-0000" value="<?php echo esc_attr( $post_to_edit->_telefone_de_contato ); ?>">

                  CPF
                  <input readonly type="text" name="cpf" class="form-control" id="inputcpf" placeholder="XXX.XXX.XXX-XX" value="<?php echo esc_attr( $post_to_edit->_cpf ); ?>">

                  Cidade de locação
                  <input readonly type="text" name="cidade" class="form-control" id="inputcidade" placeholder="Cidade de locação" value="<?php echo esc_attr( $post_to_edit->_cidade_de_locacao ); ?>">

                  Nome do locador
                  <input required type="text" name="nomelocador" class="form-control" id="nomelocador" placeholder="Nome do locador">

                    Por favor, insira uma cidade válida!

                  CPF do locador
                  <input required type="text" name="cpflocador" class="form-control" id="cpflocador" placeholder="CPF do locador">

                    Por favor, insira uma cidade válida!

              <button name="submit"  class="btn btn-primary " type="submit" id="submit" value="Publish">Enviar proposta</button>
            </form>
            <?php endif; ?>

`

`

<?php
  $postTitle = $_POST['post_title'];
  $post = $_POST['post'];
  $submit = $_POST['submit'];
  $cpflocador = $_POST['cpflocador'];
  $nomelocador = $_POST['nomelocador'];

  if(isset($submit)){

    global $user_ID;

    $new_post = array(
      'post_title' => $postTitle,
      'post_content' => $post,
      'post_status'   => 'publish',
      'Nome_locador' => array( '_nomelocador' => $nomelocador ),
      'CPF_locador' => array( '_cpflocador' => $cpflocador ),
      'post_date' => date('Y-m-d H:i:s'),
      'post_author' => $user_ID,
      'post_type' => 'propostas',

    );

    $the_post_id = wp_update_post($new_post);
    add_post_meta( $the_post_id, '_nomelocador', $nomelocador );
    add_post_meta( $the_post_id, '_cpflocador', $cpflocador );

  }

  ?>

`

I tried several times to send the information to the post through the id, but I couldn't


问:
JavaScript file included in

    <form name="hi" action="https://www.google.com/search">
      <input type="text" name="q" size="20" id="search_query" />

      <input
        type="button"
        onclick="return omg2('thank you', 'goldenrod', 20);"
        value="OMG"
      />
      <input
        type="button"
        onclick="return omg2('thanks', 'aquamarine')"
        value="omg"
      />
      <input type="submit" value="google" />
    </form>

```
<p>Here is my JavaScript:</p>
```
      function omg2(value, bgcolor, size = 40) {
        //var textbox = document.hi.q;
        var textbox = document.getElementById('search_query');
        textbox.value = value + '; ' + 'size = ' + size ;
        textbox.style.backgroundColor = bgcolor;
        textbox.setAttribute('size', size);
      }
```

Title: JavaScript file included in <script> tag does not run when using CodeSandbox service

Body:
I'm using CodeSandbox.io

I wrote some JavaScript that runs fine when I include it in  tags in the file.

But when I put it in a separate file, it doesn't run

Here is my code:

https://codesandbox.io/s/brave-voice-6kqtq3?file=/index.html

My HTML:

    <form name="hi" action="https://www.google.com/search">
      <input type="text" name="q" size="20" id="search_query" />

      <input
        type="button"
        onclick="return omg2('thank you', 'goldenrod', 20);"
        value="OMG"
      />
      <input
        type="button"
        onclick="return omg2('thanks', 'aquamarine')"
        value="omg"
      />
      <input type="submit" value="google" />
    </form>

Here is my JavaScript:

      function omg2(value, bgcolor, size = 40) {
        //var textbox = document.hi.q;
        var textbox = document.getElementById('search_query');
        textbox.value = value + '; ' + 'size = ' + size ;
        textbox.style.backgroundColor = bgcolor;
        textbox.setAttribute('size', size);
      }


问:
Alphanumeric text returns as NA
I am pulling a file from excel into R and all seems to work reasonably well except for one of my columns that contains alphanumeric character eg 12345Name,when I pull this in I get NA for all these cells.

I done a little test and removed the letters for example 12345 this seems to pull in fine. what am I doing wrong.

what has also thrown me off is I have a column with postcode for example sw165NL and this seems to pull in fine without issues, any ideas

Title: Alphanumeric text returns as NA


问:
Problem with getting data in continuous loop
Im trying to get data from database continuously after clicking a button, but it does not work. The pin is supposed to appear at given coordinates from database but instead it just stands still at the neutral point. neutral location

I've used the same approach to save the data and it works perfectly fine in a loop.

Getting the data:

```<code>Device.StartTimer(TimeSpan.FromSeconds(10), () =>
        {
            Task.Run(async () =>
            {

                var response = await mapsRepo.GetPartnerLocation("tDwV0laF9ueBre8jHwxw6EsnCry1");

                double lattitude = Convert.ToDouble(response[0].lat);
                double longitude = Convert.ToDouble(response[0].lng);

                pin.Position = new Position(lattitude, longitude);

            });
            return true;
        });
</code>```

The problem seems to be with a loop itself, while i remove it and leave only firebase request, the data is taken correctly but not in the continuous loop of course
Expected pin behavior is to track the person, which it does perfectly fine without the loop expected pin behaviour expected pin behaviour

Maps package:

xamarin.forms.maps\5.0.0.2515\

Body:
Im trying to get data from database continuously after clicking a button, but it does not work. The pin is supposed to appear at given coordinates from database but instead it just stands still at the neutral point. neutral location

I've used the same approach to save the data and it works perfectly fine in a loop.

Getting the data:

Device.StartTimer(TimeSpan.FromSeconds(10), () =>
        {
            Task.Run(async () =>
            {

                var response = await mapsRepo.GetPartnerLocation("tDwV0laF9ueBre8jHwxw6EsnCry1");

                double lattitude = Convert.ToDouble(response[0].lat);
                double longitude = Convert.ToDouble(response[0].lng);

                pin.Position = new Position(lattitude, longitude);

            });
            return true;
        });

The problem seems to be with a loop itself, while i remove it and leave only firebase request, the data is taken correctly but not in the continuous loop of course
Expected pin behavior is to track the person, which it does perfectly fine without the loop expected pin behaviour expected pin behaviour

Maps package:

xamarin.forms.maps\5.0.0.2515\


问:
I have an HTML string which i am parsing using interweave. I want to add a span tag to the html string if there is a matching character/string
I am implementing a functionality where the searched string needs to be highlighted.
The functionality is working for the 'Job' response but not for the 'Description'

Data.Job='Diver' Data.Description="'
Diver

Deep Ocean Diver

'"

highlightSearchedString (text,highlight){
if(text && highlight) {
      const parts = text.split(new RegExp(`(${highlight})`, 'gi'));
      const  node =
        {
          parts.map((part, i) => {part})
        }

      return node;
    }
    return text;
}```
</div>
</div>

highlightSearchedString is working fine for Data.Job but not for Data.Description. How can I make it work for Data.Description as well?
This is how my React JS file is looking like
NOTE: I want the span tag to be appended to the Description by not disturbing the other HTML Tags and ignore them. So my Data.Description should look like <code>Data.Description="'<div><span={backgroundColor: "yellow"}>Diver</span></div><br><table><tr>Deep Ocean <span style={backgroundColor: "yellow"}>Div</span>er</tr></table>'"</code></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><div>{highlightSearchedString((Data.Job,'DIV')} </div> //working
<Interweave content={highlightSearchedString(Data.description,'DIV')}></Interweave> //not working </code>```

Body:
I am implementing a functionality where the searched string needs to be highlighted.
The functionality is working for the 'Job' response but not for the 'Description'

Data.Job='Diver' Data.Description="'
Diver

Deep Ocean Diver

'"

highlightSearchedString (text,highlight){
if(text && highlight) {
      const parts = text.split(new RegExp(`(${highlight})`, 'gi'));
      const  node =
        {
          parts.map((part, i) => {part})
        }

      return node;
    }
    return text;
}

highlightSearchedString is working fine for Data.Job but not for Data.Description. How can I make it work for Data.Description as well?
This is how my React JS file is looking like
NOTE: I want the span tag to be appended to the Description by not disturbing the other HTML Tags and ignore them. So my Data.Description should look like Data.Description="'
Diver

Deep Ocean Diver

'"

{highlightSearchedString((Data.Job,'DIV')}
 //working
<Interweave content={highlightSearchedString(Data.description,'DIV')}></Interweave> //not working


问:
How to define object from 3rd party library in .proto file?
How can I define an object from 3rd party library in .proto file ?

ex -

```<code>syntax = 'proto3';

package com.example;

service StorageController {
  rpc storePatient(Patient) returns (ResponseStatus) { };
}

message ResponseStatus {
  int64 code = 1;
  string message = 2;
}
</code>```

here, the Patient object should be coming from hl7 3rd party library as below

```<code>import org.hl7.fhir.r4.model.Patient;
</code>```

Patient is a very complex object and I can't define all its fields like below in .proto file. so this is not the answer I am looking for.

```<code>message Patient {
  string patientName = 2;
  int64 patientAge = 3;
  // Many Many fields and also has nested properties
}
</code>```

How can I use Patient object from 3rd party library in .proto file?

Body:
How can I define an object from 3rd party library in .proto file ?

ex -

syntax = 'proto3';

package com.example;

service StorageController {
  rpc storePatient(Patient) returns (ResponseStatus) { };
}

message ResponseStatus {
  int64 code = 1;
  string message = 2;
}

here, the Patient object should be coming from hl7 3rd party library as below

import org.hl7.fhir.r4.model.Patient;

Patient is a very complex object and I can't define all its fields like below in .proto file. so this is not the answer I am looking for.

message Patient {
  string patientName = 2;
  int64 patientAge = 3;
  // Many Many fields and also has nested properties
}

How can I use Patient object from 3rd party library in .proto file?


问:
React custom http-hook abortController() bug
I have this custom http hook with abort when you try to go to a different page (I saw it in a tutorial but I am not truly sure I need it). When I fetch data with it and useEffect(), I have this error on the backend but the request is executed and everything is as planned. My question is, how to improve my code so it does not throw this error and do I need this functionality with abortController() ?

http-hook.ts

```<code>import { useCallback, useRef, useEffect } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { selectError, showError } from "src/redux/error";
import { selectLoading, startLoading, stopLoading } from "src/redux/loading";

export const useHttpClient = () => {
  const dispatch = useDispatch();
  const error = useSelector(selectError);
  const loading = useSelector(selectLoading);

  const activeHttpRequests: any = useRef([]);

  const sendRequest = useCallback(
    async (url, method = "GET", body = null, headers = {}) => {
      dispatch(startLoading());
      const httpAbortCtrl = new AbortController();
      activeHttpRequests.current.push(httpAbortCtrl);

      try {
        const response = await fetch(url, {
          method,
          body,
          headers,
          signal: httpAbortCtrl.signal,
        });

        const responseData = await response.json();

        activeHttpRequests.current = activeHttpRequests.current.filter(
          (reqCtrl) => reqCtrl !== httpAbortCtrl
        );

        if (!response.ok) {
          throw new Error(responseData.message);
        }

        dispatch(stopLoading());
        return responseData;
      } catch (err) {
        dispatch(showError(err.message));
        dispatch(stopLoading());
        throw err;
      }
    },
    []
  );

  useEffect(() => {
    return () => {
      activeHttpRequests.current.forEach((abortCtrl: any) => abortCtrl.abort());
    };
  }, []);

  return { loading, error, sendRequest };
};

</code>```

UserInfo.tsx

```<code>import React, { Fragment, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useHttpClient } from "src/hooks/http-hook";
import classes from "./UserInfo.module.css";

const UserInfo = () => {
  const { sendRequest } = useHttpClient();
  const [currentUser, setCurrentUser] = useState<any>();

  const userId = useParams<any>().userId;

  useEffect(() => {
    const fetchCurrentUser = async () => {
      try {
        const responseData = await sendRequest(
          `http://localhost:5000/api/user/${userId}`
        );
        setCurrentUser(responseData.user);
        console.log("currentUser ", currentUser);
      } catch (err) {
        console.log(err);

      }
    };
    fetchCurrentUser();
  }, [sendRequest ,userId]);

  return currentUser ? (
    <Fragment>
      <div className={classes.cover} />
      <div className={classes.user_info}>
        <img
          alt="user_img"
          src={`http://localhost:5000/${currentUser.image}`}
          className={classes.user_img}
        />
        <div className={classes.text}>
          <p>
            Name: {currentUser.name} {currentUser.surname}
          </p>
          <p>Email: {currentUser.email}</p>
          <p>Age: {currentUser.age}</p>
        </div>
      </div>{" "}
    </Fragment>
  ) : (
    <p>No current user</p>
  );
};

export default UserInfo;

</code>```

Backend

getCurrentUser.ts controller

```<code>const getCurrentUser = async (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) => {
  const userId = req.params.userId;

  let user;
  try {
    user = await User.findById(userId);
  } catch (err) {
    const error = new HttpError("Could not fetch user", 500);
    return next(error);
  }
  res.json({ user: user.toObject({ getters: true }) });
};
</code>```

Body:
I have this custom http hook with abort when you try to go to a different page (I saw it in a tutorial but I am not truly sure I need it). When I fetch data with it and useEffect(), I have this error on the backend but the request is executed and everything is as planned. My question is, how to improve my code so it does not throw this error and do I need this functionality with abortController() ?

http-hook.ts

import { useCallback, useRef, useEffect } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { selectError, showError } from "src/redux/error";
import { selectLoading, startLoading, stopLoading } from "src/redux/loading";

export const useHttpClient = () => {
  const dispatch = useDispatch();
  const error = useSelector(selectError);
  const loading = useSelector(selectLoading);

  const activeHttpRequests: any = useRef([]);

  const sendRequest = useCallback(
    async (url, method = "GET", body = null, headers = {}) => {
      dispatch(startLoading());
      const httpAbortCtrl = new AbortController();
      activeHttpRequests.current.push(httpAbortCtrl);

      try {
        const response = await fetch(url, {
          method,
          body,
          headers,
          signal: httpAbortCtrl.signal,
        });

        const responseData = await response.json();

        activeHttpRequests.current = activeHttpRequests.current.filter(
          (reqCtrl) => reqCtrl !== httpAbortCtrl
        );

        if (!response.ok) {
          throw new Error(responseData.message);
        }

        dispatch(stopLoading());
        return responseData;
      } catch (err) {
        dispatch(showError(err.message));
        dispatch(stopLoading());
        throw err;
      }
    },
    []
  );

  useEffect(() => {
    return () => {
      activeHttpRequests.current.forEach((abortCtrl: any) => abortCtrl.abort());
    };
  }, []);

  return { loading, error, sendRequest };
};

UserInfo.tsx

import React, { Fragment, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useHttpClient } from "src/hooks/http-hook";
import classes from "./UserInfo.module.css";

const UserInfo = () => {
  const { sendRequest } = useHttpClient();
  const [currentUser, setCurrentUser] = useState<any>();

  const userId = useParams<any>().userId;

  useEffect(() => {
    const fetchCurrentUser = async () => {
      try {
        const responseData = await sendRequest(
          `http://localhost:5000/api/user/${userId}`
        );
        setCurrentUser(responseData.user);
        console.log("currentUser ", currentUser);
      } catch (err) {
        console.log(err);

      }
    };
    fetchCurrentUser();
  }, [sendRequest ,userId]);

  return currentUser ? (
    <Fragment>

        <img
          alt="user_img"
          src={`http://localhost:5000/${currentUser.image}`}
          className={classes.user_img}
        />

            Name: {currentUser.name} {currentUser.surname}

Email: {currentUser.email}

Age: {currentUser.age}

{" "}
    </Fragment>
  ) : (

No current user

  );
};

export default UserInfo;

Backend

getCurrentUser.ts controller

const getCurrentUser = async (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) => {
  const userId = req.params.userId;

  let user;
  try {
    user = await User.findById(userId);
  } catch (err) {
    const error = new HttpError("Could not fetch user", 500);
    return next(error);
  }
  res.json({ user: user.toObject({ getters: true }) });
};


问:
Postgres keep showing that password is not supplied
I'm unable to connect/authenticate to psql for some reason. From the command line, I can log in, query, etc without any issues with the user and password but when I try to do this through my laravel app, I keep getting:

production.ERROR: SQLSTATE[08006] [7] fe_sendauth: no password supplied

In .env I have added ( I have real MYDB, MYUSER, MYPASS added there)

```<code>DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=MYDB
DB_USERNAME=MYUSER
DB_PASSWORD=MYPASS
</code>```

In my config/database.php

```<code> 'default' => env('DB_CONNECTION', 'pgsql'),
 ....

 'connections' => [

 'pgsql' => [
            'driver' => 'pgsql',
            //'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'MYDB'),
            'username' => env('DB_USERNAME', 'MYUSER'),
            'password' => env('DB_PASSWORD', 'MYDB'),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
 ...
</code>```

In my controller

```<code>$results = DB::connection('pgsql')
            ->table('my_table')
            ->join('second_table', 'second_table.id', '=', 'my_table.second_table_id')
            ->whereRaw("'{$search}'::text[] <@ second_table.tags")
            ->select('second_table.*', 'second_table.*')
            ->get();
</code>```

This is what I have in pg_hba.conf

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
</code>```

And this is what I see when I type \du

```<code> Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 MYUSER    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

</code>```

I have tried to reload the postgres, nginx, and cleared cache, views, and config from the artisan.

I have no other ideas.

UPDATE:I have change config/database.php to

```<code>...

        'pgsql' => [
            ....
            'database' =>  'database',
            'username' => 'user',
            'password' => 'password',
            ...
        ],
...
</code>```

Body:
I'm unable to connect/authenticate to psql for some reason. From the command line, I can log in, query, etc without any issues with the user and password but when I try to do this through my laravel app, I keep getting:

production.ERROR: SQLSTATE[08006] [7] fe_sendauth: no password supplied

In .env I have added ( I have real MYDB, MYUSER, MYPASS added there)

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=MYDB
DB_USERNAME=MYUSER
DB_PASSWORD=MYPASS

In my config/database.php

 'default' => env('DB_CONNECTION', 'pgsql'),
 ....

 'connections' => [

 'pgsql' => [
            'driver' => 'pgsql',
            //'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'MYDB'),
            'username' => env('DB_USERNAME', 'MYUSER'),
            'password' => env('DB_PASSWORD', 'MYDB'),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
 ...

In my controller

$results = DB::connection('pgsql')
            ->table('my_table')
            ->join('second_table', 'second_table.id', '=', 'my_table.second_table_id')
            ->whereRaw("'{$search}'::text[] <@ second_table.tags")
            ->select('second_table.*', 'second_table.*')
            ->get();

This is what I have in pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

And this is what I see when I type \du

 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 MYUSER    | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

I have tried to reload the postgres, nginx, and cleared cache, views, and config from the artisan.

I have no other ideas.

UPDATE:I have change config/database.php to

...

        'pgsql' => [
            ....
            'database' =>  'database',
            'username' => 'user',
            'password' => 'password',
            ...
        ],
...


问:
Room Dao error: SQL error or missing database (no such table)
I have a requirement for two different Room tables with the same ShoppingListItem Entity. So, I recreated another Entity data class model with the same properties but with a different name, CustomSortShoppingListItemEntity. But, Room throws the error stating that there is no such table which is specified as custom_sort_shopping_list_items in the CustomSortShoppingListItemEntity data class. Do I have to create a separate Dao for the custom_sort_shopping_list_items table? How can I fix this?

Error message

```<code>error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such table: custom_sort_shopping_list_items)

public abstract java.lang.Object countCustomSortListItems(long listId, @org.jetbrains.annotations.NotNull()
</code>```

ShoppingListItemEntity

```<code>@Entity(
    tableName = "shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class ShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,
    @ColumnInfo(name = "name")
    val name: String,
    @ColumnInfo(name = "category")
    val category: String,
    @ColumnInfo(name = "quantity")
    val quantity: String,
    @ColumnInfo(name = "set_quantity")
    val setQuantity: String,
    @ColumnInfo(name = "set_total")
    val setTotal: String,
    @ColumnInfo(name = "unit")
    val unit: String,
    @ColumnInfo(name = "item_ppu")
    val itemPPU: String,
    @ColumnInfo(name = "item_set_ppu")
    val itemSetPPU: String,
    @ColumnInfo(name = "notes")
    val notes: String,
    @ColumnInfo(name = "coupon_amount")
    val couponAmount: String,
    @ColumnInfo(name = "set_coupon_amount")
    val setCouponAmount: String,
    @ColumnInfo(name = "item_total")
    val itemTotal: String,
    @ColumnInfo(name = "item_set_total")
    val itemSetTotal: String,
    @ColumnInfo(name = "image_uri")
    val itemImageUri: String?,
    @ColumnInfo(name = "thumbnail_uri")
    val itemThumbnailUri: String?,
    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)
</code>```

CustomSortShoppingListItemEntity

```<code>@Entity(
    tableName = "custom_sort_shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class CustomSortShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,
    @ColumnInfo(name = "name")
    val name: String,
    @ColumnInfo(name = "category")
    val category: String,
    @ColumnInfo(name = "quantity")
    val quantity: String,
    @ColumnInfo(name = "set_quantity")
    val setQuantity: String,
    @ColumnInfo(name = "set_total")
    val setTotal: String,
    @ColumnInfo(name = "unit")
    val unit: String,
    @ColumnInfo(name = "item_ppu")
    val itemPPU: String,
    @ColumnInfo(name = "item_set_ppu")
    val itemSetPPU: String,
    @ColumnInfo(name = "notes")
    val notes: String,
    @ColumnInfo(name = "coupon_amount")
    val couponAmount: String,
    @ColumnInfo(name = "set_coupon_amount")
    val setCouponAmount: String,
    @ColumnInfo(name = "item_total")
    val itemTotal: String,
    @ColumnInfo(name = "item_set_total")
    val itemSetTotal: String,
    @ColumnInfo(name = "image_uri")
    val itemImageUri: String?,
    @ColumnInfo(name = "thumbnail_uri")
    val itemThumbnailUri: String?,
    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)
</code>```

Shopping List Items Dao

```<code>@Dao
interface ShoppingListItemDao {
    //===== SHOPPING LIST TABLE =====//

    //Create
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertShoppingListItem(item: ShoppingListItemEntity)

    //Read
    @Query("SELECT (SELECT COUNT(*) FROM shopping_list_items WHERE shopping_list_id = :listId)")
    suspend fun countListItems(listId: Long): Int

    @Query("SELECT * FROM shopping_list_items WHERE shopping_list_id = :listId")
    fun getAllShoppingListItems(listId: Long): PagingSource<Int, ShoppingListItemEntity>

    @Query("SELECT * FROM shopping_list_items WHERE id = :id")
    suspend fun getShoppingListItemById(id: Long): ShoppingListItemEntity

    //Update
    @Update(entity = ShoppingListItemEntity::class)
    suspend fun updateShoppingListItem(item: ShoppingListItemEntity)

    //Delete
    @Delete
    suspend fun deleteShoppingListItem(item: ShoppingListItemEntity)

    //===== CUSTOM SORT TABLE =====//

    //Create
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Read --> Throws error here
    @Query("SELECT (SELECT COUNT(*) FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId)")
    suspend fun countCustomSortListItems(listId: Long): Int

    @Query("SELECT * FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId")
    fun getAllCustomSortShoppingListItems(listId: Long): PagingSource<Int, CustomSortShoppingListItemEntity>

    //Update
    @Update(entity = ShoppingListItemEntity::class)
    suspend fun updateCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Delete
    @Delete
    suspend fun deleteCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Update All
    @Query("DELETE FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId")
    suspend fun deleteAllCustomSortShoppingListItems(listId: Long)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAllCustomSortShoppingListItems(customItems: List<CustomSortShoppingListItemEntity>)
}
</code>```

Body:
I have a requirement for two different Room tables with the same ShoppingListItem Entity. So, I recreated another Entity data class model with the same properties but with a different name, CustomSortShoppingListItemEntity. But, Room throws the error stating that there is no such table which is specified as custom_sort_shopping_list_items in the CustomSortShoppingListItemEntity data class. Do I have to create a separate Dao for the custom_sort_shopping_list_items table? How can I fix this?

Error message

error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such table: custom_sort_shopping_list_items)

public abstract java.lang.Object countCustomSortListItems(long listId, @org.jetbrains.annotations.NotNull()

ShoppingListItemEntity

@Entity(
    tableName = "shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class ShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,
    @ColumnInfo(name = "name")
    val name: String,
    @ColumnInfo(name = "category")
    val category: String,
    @ColumnInfo(name = "quantity")
    val quantity: String,
    @ColumnInfo(name = "set_quantity")
    val setQuantity: String,
    @ColumnInfo(name = "set_total")
    val setTotal: String,
    @ColumnInfo(name = "unit")
    val unit: String,
    @ColumnInfo(name = "item_ppu")
    val itemPPU: String,
    @ColumnInfo(name = "item_set_ppu")
    val itemSetPPU: String,
    @ColumnInfo(name = "notes")
    val notes: String,
    @ColumnInfo(name = "coupon_amount")
    val couponAmount: String,
    @ColumnInfo(name = "set_coupon_amount")
    val setCouponAmount: String,
    @ColumnInfo(name = "item_total")
    val itemTotal: String,
    @ColumnInfo(name = "item_set_total")
    val itemSetTotal: String,
    @ColumnInfo(name = "image_uri")
    val itemImageUri: String?,
    @ColumnInfo(name = "thumbnail_uri")
    val itemThumbnailUri: String?,
    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)

CustomSortShoppingListItemEntity

@Entity(
    tableName = "custom_sort_shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class CustomSortShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,
    @ColumnInfo(name = "name")
    val name: String,
    @ColumnInfo(name = "category")
    val category: String,
    @ColumnInfo(name = "quantity")
    val quantity: String,
    @ColumnInfo(name = "set_quantity")
    val setQuantity: String,
    @ColumnInfo(name = "set_total")
    val setTotal: String,
    @ColumnInfo(name = "unit")
    val unit: String,
    @ColumnInfo(name = "item_ppu")
    val itemPPU: String,
    @ColumnInfo(name = "item_set_ppu")
    val itemSetPPU: String,
    @ColumnInfo(name = "notes")
    val notes: String,
    @ColumnInfo(name = "coupon_amount")
    val couponAmount: String,
    @ColumnInfo(name = "set_coupon_amount")
    val setCouponAmount: String,
    @ColumnInfo(name = "item_total")
    val itemTotal: String,
    @ColumnInfo(name = "item_set_total")
    val itemSetTotal: String,
    @ColumnInfo(name = "image_uri")
    val itemImageUri: String?,
    @ColumnInfo(name = "thumbnail_uri")
    val itemThumbnailUri: String?,
    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)

Shopping List Items Dao

@Dao
interface ShoppingListItemDao {
    //===== SHOPPING LIST TABLE =====//

    //Create
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertShoppingListItem(item: ShoppingListItemEntity)

    //Read
    @Query("SELECT (SELECT COUNT(*) FROM shopping_list_items WHERE shopping_list_id = :listId)")
    suspend fun countListItems(listId: Long): Int

    @Query("SELECT * FROM shopping_list_items WHERE shopping_list_id = :listId")
    fun getAllShoppingListItems(listId: Long): PagingSource<Int, ShoppingListItemEntity>

    @Query("SELECT * FROM shopping_list_items WHERE id = :id")
    suspend fun getShoppingListItemById(id: Long): ShoppingListItemEntity

    //Update
    @Update(entity = ShoppingListItemEntity::class)
    suspend fun updateShoppingListItem(item: ShoppingListItemEntity)

    //Delete
    @Delete
    suspend fun deleteShoppingListItem(item: ShoppingListItemEntity)

    //===== CUSTOM SORT TABLE =====//

    //Create
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Read --> Throws error here
    @Query("SELECT (SELECT COUNT(*) FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId)")
    suspend fun countCustomSortListItems(listId: Long): Int

    @Query("SELECT * FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId")
    fun getAllCustomSortShoppingListItems(listId: Long): PagingSource<Int, CustomSortShoppingListItemEntity>

    //Update
    @Update(entity = ShoppingListItemEntity::class)
    suspend fun updateCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Delete
    @Delete
    suspend fun deleteCustomSortShoppingListItem(item: CustomSortShoppingListItemEntity)

    //Update All
    @Query("DELETE FROM custom_sort_shopping_list_items WHERE shopping_list_id = :listId")
    suspend fun deleteAllCustomSortShoppingListItems(listId: Long)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAllCustomSortShoppingListItems(customItems: List<CustomSortShoppingListItemEntity>)
}


问:
Varying image size from batch to batch performance
I'm new to pytorch and I just saw that if I use a custom collate_fn for my dataloader, I can pad the input images (which are varying in size) to be the size of the largest image in the batch, and I don't need to pad according to max image size in the whole dataset. My question is, if the size of images changes in each batch, can pytorch still optimize the operations, or would it be faster to pad everything to the same size?

Thanks.

I remember something in tensorlflow, where if the size changed, it had to do a full retrace in the graph which was slow. Is there something similar here?


问:
Auto-complete List vanishes as I press enter in vscode
Until yesterday, autocomplete was working fine. Now when I press enter on my desired option from my auto-complete list, the list disappears and my cursor moves to the next line.


问:
How we can auto re-enroll android devices after the factory reset without Zero Touch Portal account
I want that if someone completes a hard reset on the Android device, then the device re-enrolled automatically by their serial number. The zero-touch portal provides this feature but we are trying without a portal

I already apply the zero touch portal but no response from google