问:
proper way to communicate between more than two processes in pyqt5 python
I currently have two processes, one is my pyqt5 MainWindow (parent process) and a child process. I mainly use Pipe to communicate between the two. As per my research, a Pipe can have only two end-points which in my case, it has already been given to the two end-points above. But I now am in need of a temporary third/brother process which is created when a user click on pyqt5 button any time. The brother process needs to send pyqtSignal to parent process for result output.

Why not use threads? 1. I don't want the child thread to access parent thread's memory. 2. there is no direct way to abruptly kill a thread unless using try & except method, which I cannot use. Hence, I need to use multiprocessing.

Can anyone tell me If I need a third pipe for my brother process, if so, how do I implement it to my pyqt5 application. Reproducible code is below.

Code main.py:

```<code>import os
import sys
import PyQt5
from PyQt5 import QtWidgets
from multiprocessing import Process, Queue, Pipe
from untitled import Ui_MainWindow
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtCore import pyqtSignal, QObject, Qt
from PyQt5.QtGui import QPixmap, QStandardItemModel, QStandardItem, QIcon
from multiprocessing import Process, Queue, Pipe
import time

sys.path.insert(0, os.path.abspath("."))

class Emitter(QThread):
    pcLBL = pyqtSignal(str)

    def __init__(self, from_process: Pipe):
        super().__init__()
        self.data_from_process = from_process

    def run(self):
        while True:
            try:
                sd = self.data_from_process.recv()
            except EOFError:
                break
            else:
                if(len(sd) > 1 and sd[0] == "pcLBL"):
                    self.pcLBL.emit(sd[1])

class childProc(Process):
    def __init__(self, to_emitter: Pipe, from_mother: Queue, daemon=True):
        super().__init__()
        self.daemon = daemon
        self.to_emitter = to_emitter
        self.data_from_mother = from_mother

    def run(self):
        i = 0
        while(True):
            print("talking to mommy")
            self.to_emitter.send(["pcLBL", "Yollo mommy, I am your first child "+str(i)])
            i += 1
            time.sleep(10)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, child_process_queue: Queue, emitter: Emitter):
        QMainWindow.__init__(self)

        self.process_queue = child_process_queue
        self.emitter = emitter
        self.emitter.daemon = True
        self.emitter.start()
        self.setupUi(self)
        self.mainCode()

    def mainCode(self):
        self.someBTN.clicked.connect(self.testFunc)
        self.emitter.pcLBL.connect(self.pcLBL.setText)

    def testFunc(self):
        files = ["c:\\windows\\system32\\cmd.exe"]
        mother_pipe, child_pipe = Pipe()
        queue = Queue()
        emitter = Emitter(mother_pipe)
        broProc = brotherProc(files[0], child_pipe, self.process_queue)
        broProc.start()

class brotherProc(Process):
    def __init__(self, files, to_emitter: Pipe, from_mother: Queue, daemon=True):
        super().__init__()
        self.daemon = daemon
        self.to_emitter = to_emitter
        self.data_from_mother = from_mother
        self.files = files

    def run(self):
        print("started")
        doStuff(self.to_emitter, self.files, 2)

def doStuff(signaller, file, num):
    signaller.send(["pcLBL", "Hello mother"])

def pickleChildProc(child_pipe, queue):
    cp = childProc(child_pipe, queue)
    cp.start()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    mother_pipe, child_pipe = Pipe()
    queue = Queue()
    emitter = Emitter(mother_pipe)
    childProc = pickleChildProc(child_pipe, queue)

    Dialog = MainWindow(queue, emitter)

    Dialog.show()
    sys.exit(app.exec_())
</code>```

pyqt5Main.py:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.someBTN = QtWidgets.QPushButton(self.centralwidget)
        self.someBTN.setGeometry(QtCore.QRect(260, 260, 251, 23))
        self.someBTN.setObjectName("someBTN")
        self.pcLBL = QtWidgets.QLabel(self.centralwidget)
        self.pcLBL.setGeometry(QtCore.QRect(30, 350, 731, 20))
        self.pcLBL.setObjectName("pcLBL")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.someBTN.setText(_translate("MainWindow", "Create Process"))
        self.pcLBL.setText(_translate("MainWindow", "Show results here"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

With above on line signaller.send(["pcLBL", "Hello mother process"]) in the brother process, I get BrokenPipeError: [WinError 232] The pipe is being closed.

Can anyone tell me what is wrong with my code?

Body:
I currently have two processes, one is my pyqt5 MainWindow (parent process) and a child process. I mainly use Pipe to communicate between the two. As per my research, a Pipe can have only two end-points which in my case, it has already been given to the two end-points above. But I now am in need of a temporary third/brother process which is created when a user click on pyqt5 button any time. The brother process needs to send pyqtSignal to parent process for result output.

Why not use threads? 1. I don't want the child thread to access parent thread's memory. 2. there is no direct way to abruptly kill a thread unless using try & except method, which I cannot use. Hence, I need to use multiprocessing.

Can anyone tell me If I need a third pipe for my brother process, if so, how do I implement it to my pyqt5 application. Reproducible code is below.

Code main.py:

import os
import sys
import PyQt5
from PyQt5 import QtWidgets
from multiprocessing import Process, Queue, Pipe
from untitled import Ui_MainWindow
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtCore import pyqtSignal, QObject, Qt
from PyQt5.QtGui import QPixmap, QStandardItemModel, QStandardItem, QIcon
from multiprocessing import Process, Queue, Pipe
import time

sys.path.insert(0, os.path.abspath("."))

class Emitter(QThread):
    pcLBL = pyqtSignal(str)

    def __init__(self, from_process: Pipe):
        super().__init__()
        self.data_from_process = from_process

    def run(self):
        while True:
            try:
                sd = self.data_from_process.recv()
            except EOFError:
                break
            else:
                if(len(sd) > 1 and sd[0] == "pcLBL"):
                    self.pcLBL.emit(sd[1])

class childProc(Process):
    def __init__(self, to_emitter: Pipe, from_mother: Queue, daemon=True):
        super().__init__()
        self.daemon = daemon
        self.to_emitter = to_emitter
        self.data_from_mother = from_mother

    def run(self):
        i = 0
        while(True):
            print("talking to mommy")
            self.to_emitter.send(["pcLBL", "Yollo mommy, I am your first child "+str(i)])
            i += 1
            time.sleep(10)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, child_process_queue: Queue, emitter: Emitter):
        QMainWindow.__init__(self)

        self.process_queue = child_process_queue
        self.emitter = emitter
        self.emitter.daemon = True
        self.emitter.start()
        self.setupUi(self)
        self.mainCode()

    def mainCode(self):
        self.someBTN.clicked.connect(self.testFunc)
        self.emitter.pcLBL.connect(self.pcLBL.setText)

    def testFunc(self):
        files = ["c:\\windows\\system32\\cmd.exe"]
        mother_pipe, child_pipe = Pipe()
        queue = Queue()
        emitter = Emitter(mother_pipe)
        broProc = brotherProc(files[0], child_pipe, self.process_queue)
        broProc.start()

class brotherProc(Process):
    def __init__(self, files, to_emitter: Pipe, from_mother: Queue, daemon=True):
        super().__init__()
        self.daemon = daemon
        self.to_emitter = to_emitter
        self.data_from_mother = from_mother
        self.files = files

    def run(self):
        print("started")
        doStuff(self.to_emitter, self.files, 2)

def doStuff(signaller, file, num):
    signaller.send(["pcLBL", "Hello mother"])

def pickleChildProc(child_pipe, queue):
    cp = childProc(child_pipe, queue)
    cp.start()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    mother_pipe, child_pipe = Pipe()
    queue = Queue()
    emitter = Emitter(mother_pipe)
    childProc = pickleChildProc(child_pipe, queue)

    Dialog = MainWindow(queue, emitter)

    Dialog.show()
    sys.exit(app.exec_())

pyqt5Main.py:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.someBTN = QtWidgets.QPushButton(self.centralwidget)
        self.someBTN.setGeometry(QtCore.QRect(260, 260, 251, 23))
        self.someBTN.setObjectName("someBTN")
        self.pcLBL = QtWidgets.QLabel(self.centralwidget)
        self.pcLBL.setGeometry(QtCore.QRect(30, 350, 731, 20))
        self.pcLBL.setObjectName("pcLBL")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.someBTN.setText(_translate("MainWindow", "Create Process"))
        self.pcLBL.setText(_translate("MainWindow", "Show results here"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

With above on line signaller.send(["pcLBL", "Hello mother process"]) in the brother process, I get BrokenPipeError: [WinError 232] The pipe is being closed.

Can anyone tell me what is wrong with my code?


来源: stackexchange

问:
Can't assemble a .S file using arm-none-eabi-gcc
I am following a tutorial on how to make an operating system for the raspberry pi. I want to follow this tutorial on a Raspberry Pi running Raspbian.

When I try to assemble some assembly using arm-none-eabi-gcc (arm-none-eabi-gcc -mcpu=cortex-a7 -fpic -ffreestanding -c boot/boot.S -o boot/boot.o), I get this:

```<code>/usr/lib/gcc/arm-none-eabi/8.3.1/cc1: error while loading shared libraries: /lib/aarch64-linux-gnu/libisl.so.23: unexpected PLT reloc type 0x00
make: *** [Makefile:2: all] Error 1
</code>```

I don't know why this happens, because I installed the arm-none-eabi-gcc package...

How can I fix this?

ContentLicense: CC BY-SA 4.0

Body:
I am following a tutorial on how to make an operating system for the raspberry pi. I want to follow this tutorial on a Raspberry Pi running Raspbian.

When I try to assemble some assembly using arm-none-eabi-gcc (arm-none-eabi-gcc -mcpu=cortex-a7 -fpic -ffreestanding -c boot/boot.S -o boot/boot.o), I get this:

/usr/lib/gcc/arm-none-eabi/8.3.1/cc1: error while loading shared libraries: /lib/aarch64-linux-gnu/libisl.so.23: unexpected PLT reloc type 0x00
make: *** [Makefile:2: all] Error 1

I don't know why this happens, because I installed the arm-none-eabi-gcc package...

How can I fix this?


问:
How to merge DataFrames, using multiple columns and additionally using conditions from DataFrames columns use operator AND?
I have the part of code that works well in MS SQL:

```<code>    select *  from table_1
    full outer join table_2 on
                                table_1.Name = table_2.Name_2 and
                                table_1.Qty = table_2.Qty_2 and
                                table_1.[Month] = table_2.Month_2 and
                                table_1.class = 'X' and
                                table_2.class_2 = 'Y'
</code>```

But i need to create the same code in python and i am trying to do this:

```<code>df_merge = pd.merge(table_1, table_2, how='outer', left_on=['Name', 'Qty', 'Month'], right_on=['Name_2', 'Qty_2', 'Month_2'])
</code>```

But how to add this condition and table_1.class = 'X' and table_2.class_2 = 'Y'for the merge without using where, it will give a different result:

```<code>& (table_1['class'] == 'X') & (table_2['class_2'] == 'Y')
</code>```

Body:
I have the part of code that works well in MS SQL:

    select *  from table_1
    full outer join table_2 on
                                table_1.Name = table_2.Name_2 and
                                table_1.Qty = table_2.Qty_2 and
                                table_1.[Month] = table_2.Month_2 and
                                table_1.class = 'X' and
                                table_2.class_2 = 'Y'

But i need to create the same code in python and i am trying to do this:

df_merge = pd.merge(table_1, table_2, how='outer', left_on=['Name', 'Qty', 'Month'], right_on=['Name_2', 'Qty_2', 'Month_2'])

But how to add this condition and table_1.class = 'X' and table_2.class_2 = 'Y'for the merge without using where, it will give a different result:

& (table_1['class'] == 'X') & (table_2['class_2'] == 'Y')


问:
Save an text from Google Speech-to-text to cloud storage
Is it possible to directly save the text from speech to text to cloud storage using python client library?

At the moment I was able to perform this save operation only by waiting for the end of the speech-to-text operation, saving the text stack as a file and only then uploading it to the storage bucket


问:
React mui template disappears in search bar partial color
I am implementing it using the mui template of React, but the color on the top of the search bar disappeared like in the picture.
I definitely haven't touched that part, but there was a problem, even if I gave the margin or padding, the color of that part disappeared. What's the problem?


问:
tailwind grid overflow scrolling not working
I have a grid in which I just want to show 4 elements and if elements exceed to limit I want to add scrolling here is the code using Next Js + tailwind

```<code>
<div className= {`grid grid-rows-1 grid-cols-4  gap-4  bg-slate-600 relative h-full p-5 overflow-x-scroll`}>
        <div className="h-full bg-blue-800 w-full"></div>
        <div className="h-full bg-blue-600 w-full"></div>
        <div className="h-full bg-blue-200 w-full"></div>
        <div className="h-full bg-blue-600 w-full"></div>
        <div className="h-full bg-blue-800 w-full"></div>
        <div className="h-full bg-blue-700 w-full"></div>
</div>

</code>```

Problem:

four elements are looking as they expect but the rest of them are not showing anywhere even though I added overflow-x-scroll.

Body:
I have a grid in which I just want to show 4 elements and if elements exceed to limit I want to add scrolling here is the code using Next Js + tailwind

<div className= {`grid grid-rows-1 grid-cols-4  gap-4  bg-slate-600 relative h-full p-5 overflow-x-scroll`}>

Problem:

four elements are looking as they expect but the rest of them are not showing anywhere even though I added overflow-x-scroll.


问:
How to validate a field's value based on another field's value in Mongoose
I want to check: If my schema.type ==='gas' then my schema.status should be good,

if schema.type = noGas then my schema.status should be bad.

Both fields are mandatory.

I was able to make a field mandatory or not based on another field value.

```<code>const bottle: Schema = new Schema({
  type: {
    type: String,
    required: true,
    enum: ['gas', 'noGas'],
  },
  status: {
    type: String,
    enum: ['good', 'bad']
    required(this: IBottle): boolean {
      // Check values here. But I could only ensure the field as required or not.
      return this.type === 'gas' || this.type === 'noGas';
    }

  }
});
</code>```

But what if besides that, I also want to validate the value of the field, not just if it is present.

How could I do that?

I saw this example, which is using Validate() to validate  the value, but i need a little more. I need to also SET the field's value, based on the value of the other field.

Body:
I want to check: If my schema.type ==='gas' then my schema.status should be good,

if schema.type = noGas then my schema.status should be bad.

Both fields are mandatory.

I was able to make a field mandatory or not based on another field value.

const bottle: Schema = new Schema({
  type: {
    type: String,
    required: true,
    enum: ['gas', 'noGas'],
  },
  status: {
    type: String,
    enum: ['good', 'bad']
    required(this: IBottle): boolean {
      // Check values here. But I could only ensure the field as required or not.
      return this.type === 'gas' || this.type === 'noGas';
    }

  }
});

But what if besides that, I also want to validate the value of the field, not just if it is present.

How could I do that?

I saw this example, which is using Validate() to validate  the value, but i need a little more. I need to also SET the field's value, based on the value of the other field.


问:
f.seek(0) ValueError: I/O operation on closed file
```<code>    with open("mailler.txt", "r+") as f:
   satirlar = f.readlines()
   secilen_satir = random.choice(satirlar)
   mail= secilen_satir.split(":")[0]
   sifre = secilen_satir.split(":")[1]
   sleep(1)
f.seek(0)
for i in satirlar:
        if i != secilen_satir:
                f.write(i)
f.truncate()
While True:
with open("mailler.txt", "r+") as f:
   satirlar = f.readlines()
   secilen_satir = random.choice(satirlar)
   mail= secilen_satir.split(":")[0]
   sifre = secilen_satir.split(":")[1]
   sleep(1)
f.seek(0)
for i in satirlar:
        if i != secilen_satir:
                f.write(i)
f.truncate()
</code>```

how can i loop this code? i just want to open mailler.txt print mail + sifre and then delete line

Body:
    with open("mailler.txt", "r+") as f:
   satirlar = f.readlines()
   secilen_satir = random.choice(satirlar)
   mail= secilen_satir.split(":")[0]
   sifre = secilen_satir.split(":")[1]
   sleep(1)
f.seek(0)
for i in satirlar:
        if i != secilen_satir:
                f.write(i)
f.truncate()
While True:
with open("mailler.txt", "r+") as f:
   satirlar = f.readlines()
   secilen_satir = random.choice(satirlar)
   mail= secilen_satir.split(":")[0]
   sifre = secilen_satir.split(":")[1]
   sleep(1)
f.seek(0)
for i in satirlar:
        if i != secilen_satir:
                f.write(i)
f.truncate()

how can i loop this code? i just want to open mailler.txt print mail + sifre and then delete line


问:
discord.ext.commands.errors.MissingRequiredArgument: extension is a required argument that is missing
Main.py

```<code>[enter image description here](https://i.stack.imgur.com/nHlGf.png)
</code>```

Bot.py

```<code>import discord
from discord.ext import commands
import os

intents = discord.Intents.all()
client = commands.Bot(command_prefix = "!", intents=intents)
client.remove_command("help")

@client.command()
async def load(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.load_extension(f"cogs.{extension}")
        await ctx.send("Коги загружени...")
    else:
        await ctx.send("Иди нахуй!")

@client.command()
async def unload(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.unload_extension(f"cogs.{extension}")
        await ctx.send("Коги вигружени...")
    else:
        await ctx.send("Иди нахуй!")

@client.command()
async def reload(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.unload_extension(f"cogs.{extension}")
        client.load_extension(f"cogs.{extension}")
        await ctx.send("Коги перезагружени...")
    else:
        await ctx.send("Иди нахуй!")

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run("*")
</code>```

Error:

```<code>[enter image description here](https://i.stack.imgur.com/5pxqB.png)
</code>```

Can you help me? I already tried to reinstall discord.
And also it does not accept commands. Is it because I can't load the logs?
Can please anyone help me?
If you need more details from me, just say it.
The bot starts and works stably.

Body:
Main.py

[enter image description here](https://i.stack.imgur.com/nHlGf.png)

Bot.py

import discord
from discord.ext import commands
import os

intents = discord.Intents.all()
client = commands.Bot(command_prefix = "!", intents=intents)
client.remove_command("help")

@client.command()
async def load(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.load_extension(f"cogs.{extension}")
        await ctx.send("Коги загружени...")
    else:
        await ctx.send("Иди нахуй!")

@client.command()
async def unload(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.unload_extension(f"cogs.{extension}")
        await ctx.send("Коги вигружени...")
    else:
        await ctx.send("Иди нахуй!")

@client.command()
async def reload(ctx, extension):
    if ctx.author.id == 569942050145828864:
        client.unload_extension(f"cogs.{extension}")
        client.load_extension(f"cogs.{extension}")
        await ctx.send("Коги перезагружени...")
    else:
        await ctx.send("Иди нахуй!")

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run("*")

Error:

[enter image description here](https://i.stack.imgur.com/5pxqB.png)

Can you help me? I already tried to reinstall discord.
And also it does not accept commands. Is it because I can't load the logs?
Can please anyone help me?
If you need more details from me, just say it.
The bot starts and works stably.


问:
Check constraint noninfringement in PuLP
I have just created a model in PuLP, though its result seems to have violated its constraints. Is there a quick way to check the value of each constraint?</p>


问:
FLTK Fl_Button doesn't work when adding a handle(event) override
I try to implement a "clickable grid" in FLTK. I have two Fl_Input to give the dimensions of the grid and a Fl_Button to draw the grid. So far, no problem, everything is working.

But when I added the fact that the cell of the grid change of color when clicking it, the button and the inputs don't work anymore...

I tried to implement the handle override like so:

```<code>int handle(int event) {
    switch(event) {
        case FL_MOVE:
            canvas.mouseMove(Point{Fl::event_x(), Fl::event_y()});
            return 1;
        case FL_PUSH:
            canvas.mouseClick(Point{Fl::event_x(), Fl::event_y()});
            return 1;
    }
    return 0;
}
</code>```

The FL_MOVE is used to change the frame color of the cell when going over it and the FL_PUSH is used to change the color of the cell.

Maybe the fltk handle overriding is incomptabile with buttons and other widgets ?

I'm struggling to understand what's happening...

Thank you very much for your help.

Body:
I try to implement a "clickable grid" in FLTK. I have two Fl_Input to give the dimensions of the grid and a Fl_Button to draw the grid. So far, no problem, everything is working.

But when I added the fact that the cell of the grid change of color when clicking it, the button and the inputs don't work anymore...

I tried to implement the handle override like so:

int handle(int event) {
    switch(event) {
        case FL_MOVE:
            canvas.mouseMove(Point{Fl::event_x(), Fl::event_y()});
            return 1;
        case FL_PUSH:
            canvas.mouseClick(Point{Fl::event_x(), Fl::event_y()});
            return 1;
    }
    return 0;
}

The FL_MOVE is used to change the frame color of the cell when going over it and the FL_PUSH is used to change the color of the cell.

Maybe the fltk handle overriding is incomptabile with buttons and other widgets ?

I'm struggling to understand what's happening...

Thank you very much for your help.


问:
Why can't I open the CSS Theme in Codenameone
I was working on some changes to my CSS file and at the time of execution it sent me the error shown. I tried generating another CSS file and even put a minimum of code, but the problem persists.


问:
How can I extract zip files on google colab?
```<code>import zipfile
from google.colab import drive

drive.mount('/content/drive')

zip_ref = zipfile.ZipFile("/content/drive/MyDrive/datasets/dogs-vs-cats.zip", 'r')
zip_ref.extractall("/content/drive/MyDrive/datasets")
zip_ref.close()
</code>```

When I tried to extract zip on google colab I cant do. I send my zip file into drive folder and tried it like the above but I get an error:

```<code>---------------------------------------------------------------------------
BadZipFile                                Traceback (most recent call last)
<ipython-input-1-95a942b124d0> in <module>
      4 drive.mount('/content/drive')
      5
----> 6 zip_ref = zipfile.ZipFile("/content/drive/MyDrive/datasets/dogs-vs-cats.zip", 'r')
      7 zip_ref.extractall("/content/drive/MyDrive/datasets")
      8 zip_ref.close()

1 frames
/usr/lib/python3.8/zipfile.py in _RealGetContents(self)
   1334             raise BadZipFile("File is not a zip file")
   1335         if not endrec:
-> 1336             raise BadZipFile("File is not a zip file")
   1337         if self.debug > 1:
   1338             print(endrec)

BadZipFile: File is not a zip file
</code>```

After this error I tried to extract from google colab itself but I get the same error all the time. I tried on another datasets but it doesn't work.

I tried to solve with unzip method but it doesn't work.

Body:
import zipfile
from google.colab import drive

drive.mount('/content/drive')

zip_ref = zipfile.ZipFile("/content/drive/MyDrive/datasets/dogs-vs-cats.zip", 'r')
zip_ref.extractall("/content/drive/MyDrive/datasets")
zip_ref.close()

When I tried to extract zip on google colab I cant do. I send my zip file into drive folder and tried it like the above but I get an error:

---------------------------------------------------------------------------
BadZipFile                                Traceback (most recent call last)
<ipython-input-1-95a942b124d0> in <module>
      4 drive.mount('/content/drive')
      5
----> 6 zip_ref = zipfile.ZipFile("/content/drive/MyDrive/datasets/dogs-vs-cats.zip", 'r')
      7 zip_ref.extractall("/content/drive/MyDrive/datasets")
      8 zip_ref.close()

1 frames
/usr/lib/python3.8/zipfile.py in _RealGetContents(self)
   1334             raise BadZipFile("File is not a zip file")
   1335         if not endrec:
-> 1336             raise BadZipFile("File is not a zip file")
   1337         if self.debug > 1:
   1338             print(endrec)

BadZipFile: File is not a zip file

After this error I tried to extract from google colab itself but I get the same error all the time. I tried on another datasets but it doesn't work.

I tried to solve with unzip method but it doesn't work.


问:
Elasticsearch additional 'should' clause enforcing empty results
I have an Elasticsearch index for the Wikipedia corpus with documents of four types (paragraph, infobox, list, and table). Each document has the following fields: page_title, section_path, and document_text.

I'm querying this corpus with a question, "what country is Narora located in?" scoped within a single page ("List of nuclear power stations") and document type ("table") as the following, which should return the table documents found in this Wikipedia page.

{
    "size": 100,
    "_source": [
        "id",
        "document_text",
        "section_path",
        "page_title",
    ],
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "document_text": "what country is Narora located in?"
                    }
                },
                {
                    "match": {
                        "section_path": "what country is Narora located in?"
                    }
                },
                {
                    "match": {
                        "page_title": "what country is Narora located in?"
                    }
                }
            ],
            "must": [
                {
                    "match": {
                        "page_title": "List of nuclear power stations"
                    }
                },
                {
                    "match": {
                        "paragraph_type": "table"
                    }
                }
            ]
        }
    }
}
```

This query returns empty results. When I remove one of the two should clauses, either section_path or page_title, I get multiple table documents as a result, including the "In service" one here, which has a mention of Narora in its document_text field.

Now, granted that the page_title ("List of nuclear power stations") and section_path ("In service", "Under construction" ...) don't overlap with the question. But I'm surprised by this behavior as the should clause is only supposed to affect the scoring, and not what matches (source). So adding a should clause shouldn't cause Elasticsearch to return an empty result.

Any thoughts on what could be going on here? Is there any way to force Elasticsearch to ignore the should clause/s if there's no match and still return ALL the documents that match the rest of the must criteria?

Body:
I have an Elasticsearch index for the Wikipedia corpus with documents of four types (paragraph, infobox, list, and table). Each document has the following fields: page_title, section_path, and document_text.

I'm querying this corpus with a question, "what country is Narora located in?" scoped within a single page ("List of nuclear power stations") and document type ("table") as the following, which should return the table documents found in this Wikipedia page.

{
    "size": 100,
    "_source": [
        "id",
        "document_text",
        "section_path",
        "page_title",
    ],
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "document_text": "what country is Narora located in?"
                    }
                },
                {
                    "match": {
                        "section_path": "what country is Narora located in?"
                    }
                },
                {
                    "match": {
                        "page_title": "what country is Narora located in?"
                    }
                }
            ],
            "must": [
                {
                    "match": {
                        "page_title": "List of nuclear power stations"
                    }
                },
                {
                    "match": {
                        "paragraph_type": "table"
                    }
                }
            ]
        }
    }
}

This query returns empty results. When I remove one of the two should clauses, either section_path or page_title, I get multiple table documents as a result, including the "In service" one here, which has a mention of Narora in its document_text field.

Now, granted that the page_title ("List of nuclear power stations") and section_path ("In service", "Under construction" ...) don't overlap with the question. But I'm surprised by this behavior as the should clause is only supposed to affect the scoring, and not what matches (source). So adding a should clause shouldn't cause Elasticsearch to return an empty result.

Any thoughts on what could be going on here? Is there any way to force Elasticsearch to ignore the should clause/s if there's no match and still return ALL the documents that match the rest of the must criteria?


问:
want to send data from all the collections in mongodb to my frontend but i am not able to access the access my dataToSend array outside the loop
i want to store all the collections data stored in mongodb inside an array and then send it as a response to my frontend
`

```<code>collectionsNames=[];
const dataToSend = [];
const arr=[];
router.get("/showCollections",(req,res,next)=>{
  console.log("in showCollections");
  mongoose.connection.db.listCollections().toArray(function(err, names){

    for(let i=0;i<names.length;i++){
      collectionName=names[i].name;
      if(collectionName.localeCompare("users")!=0){
        collectionsNames.push(collectionName)
      }
    }
    // console.log(collectionsNames);

    for (let i=0;i<collectionsNames.length;i++) {
      mongoose.connection.db.collection(collectionsNames[i], function (err, collection) {
        collection.find({}).toArray( function(err,data){
          dataToSend.push(data);//want to access this array outside the loop to send it as a response to the frontend
          // console.log(dataToSend);
          // console.log(data);
        })
      })

    }
    // console.log(2);
  })

  // var resultArray = [];

})
</code>```

`

i tried making an array and adding all the data to it and then sending it to the frontend but the array data is not accessible outside the loop this is maybe because of asynchronous behaviour of nodejs but i dont know how to implement async await in my code

Body:
i want to store all the collections data stored in mongodb inside an array and then send it as a response to my frontend
`

collectionsNames=[];
const dataToSend = [];
const arr=[];
router.get("/showCollections",(req,res,next)=>{
  console.log("in showCollections");
  mongoose.connection.db.listCollections().toArray(function(err, names){

    for(let i=0;i<names.length;i++){
      collectionName=names[i].name;
      if(collectionName.localeCompare("users")!=0){
        collectionsNames.push(collectionName)
      }
    }
    // console.log(collectionsNames);

    for (let i=0;i<collectionsNames.length;i++) {
      mongoose.connection.db.collection(collectionsNames[i], function (err, collection) {
        collection.find({}).toArray( function(err,data){
          dataToSend.push(data);//want to access this array outside the loop to send it as a response to the frontend
          // console.log(dataToSend);
          // console.log(data);
        })
      })

    }
    // console.log(2);
  })

  // var resultArray = [];

})

`

i tried making an array and adding all the data to it and then sending it to the frontend but the array data is not accessible outside the loop this is maybe because of asynchronous behaviour of nodejs but i dont know how to implement async await in my code


问:
(Flutter) ListView.builder with a TextField and TextEditingController desync behavior
I'm getting a desync behavior with ListView.builder, TextField, and TextEditingController.
When I'm adding/removing an "issue" object the text that I see once I tap the issue is "shifted" one down or just way wrong, but the controller still affects the same object.
I'm adding pictures for clarification:

So here you can see all the objects

Once i tap say the first top one "5"

Now i add an new "issue" object

Then i click again on the object i clicked before "5" which is the second top one now:

I cant seem to understand why this behavoir happens and how to fix it.
finally im posting my code for more refrense:

// ignore_for_file: non_constant_identifier_names, sized_box_for_whitespace
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dronebag/app.dart';
import 'package:dronebag/config/font_size.dart';
import 'package:dronebag/domain/battery_issue_repository/battery_issue_repository.dart';
import 'package:dronebag/domain/battery_repository/battery_repository.dart';
import 'package:dronebag/domain/battery_station_issue_repository/battery_station_issue_repository.dart';
import 'package:dronebag/domain/battery_station_repository/src/models/models.dart';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import '../widgets/widgest.dart';

class BatteryStationDetails extends StatefulWidget {
  final String groupID;
  final BatteryStation batteryStation;
  const BatteryStationDetails({
    Key? key,
    required this.groupID,
    required this.batteryStation,
  }) : super(key: key);

  @override
  State<BatteryStationDetails> createState() => _BatteryStationDetailsState();
}

class _BatteryStationDetailsState extends State<BatteryStationDetails> {
  final formKey = GlobalKey<FormState>();
  final TextEditingController serial_numberController = TextEditingController();
  final TextEditingController batteryIssueDetailController =
      TextEditingController();
  final TextEditingController batteryCycleController = TextEditingController();
  final TextEditingController date_boughtController = TextEditingController();
  final double sizedBoxHight = 16;
  final TextEditingController battery_pairsController = TextEditingController();

  @override
  void initState() {
    // ignore: todo
    // TODO: implement initState

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final fetch = FirestoreFetch(
        groupID: widget.groupID, batteryStation: widget.batteryStation);
    final create = FirestoreCreate(
        groupID: widget.groupID, batteryStation: widget.batteryStation);
    return Scaffold(
        appBar: AppBar(
          backgroundColor: ThemeColors.scaffoldBgColor,
          title: Text(
            "Battery Station ${widget.batteryStation.serial_number}",
            style: GoogleFonts.poppins(
              color: ThemeColors.whiteTextColor,
              fontSize: FontSize.xxLarge,
              fontWeight: FontWeight.w600,
            ),
          ),
          actions: [
            TextButton(
              child: Text(
                'Edit Station \nDetails',
                textAlign: TextAlign.center,
                style: GoogleFonts.poppins(
                  color: Colors.blue,
                  fontSize: FontSize.medium,
                  fontWeight: FontWeight.w600,
                ),
              ),
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (context) => EditBatteryStationDialog(
                          batteryStation: widget.batteryStation,
                          groupID: widget.groupID,
                        ));
              },
            ),
          ],
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(38),
            child: Column(children: [
              Text(
                'Batteries',
                style: GoogleFonts.poppins(
                  color: ThemeColors.textFieldHintColor,
                  fontSize: FontSize.large,
                  fontWeight: FontWeight.w600,
                ),
              ),
              StreamBuilder<List<Battery>>(
                  stream: fetch.fetchBatteries(),
                  builder: ((context, snapshot) {
                    if (snapshot.hasData) {
                      final batteries = snapshot.data!;
                      batteries.sort(
                        (a, b) {
                          return a.serial_number.compareTo(b.serial_number);
                        },
                      );
                      return GridView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          childAspectRatio: 1.8,
                        ),
                        itemCount: batteries.length,
                        shrinkWrap: true,
                        itemBuilder: (context, index) {
                          return BatteryTile(
                              battery: batteries[index],
                              batteryStation: widget.batteryStation,
                              groupID: widget.groupID);
                        },
                      );
                    } else if (snapshot.hasError) {
                      return SingleChildScrollView(
                        child: Text('Something went wrong! \n\n$snapshot',
                            style: const TextStyle(color: Colors.white)),
                      );
                    } else {
                      return const Center(child: CircularProgressIndicator());
                    }
                  })),
              const SizedBox(height: 20),
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      style: GoogleFonts.poppins(
                        color: ThemeColors.textFieldHintColor,
                        fontSize: FontSize.large,
                        fontWeight: FontWeight.w600,
                      ),
                      text: "Station\'s Issue list ",
                    ),
                    const WidgetSpan(
                        child: Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 20, 0),
                    )),
                    TextSpan(
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          create.createBatteryStationIssue();
                        },
                      text: 'Add Issue',
                      style: GoogleFonts.poppins(
                        color: ThemeColors.primaryColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w600,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 12),
//vvvvvvvvvvvvvvvvvvRELEVENTvvvvvvvvvvvvvvvvvvvv//
              StreamBuilder<List<BatteryStationIssue>>(
                stream: fetch.fetchBatteryStationIssue(),
                builder: ((context, snapshot) {
                  if (snapshot.hasData) {
                    final batteryStationIssues = snapshot.data!;
                    //print(issues.length);
                    return Container(
                      child: ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: batteryStationIssues.length,
                        itemBuilder: (context, index) {
                          print("==========");
                          return BatteryStationIssueTile(
                              groupID: widget.groupID,
                              batteryStation: widget.batteryStation,
                              batteryStationIssue: batteryStationIssues[index]);
                        },
                      ),
                    );
                  } else if (snapshot.hasError) {
                    return SingleChildScrollView(
                      child: Text('Something went wrong! \n\n$snapshot',
                          style: const TextStyle(color: Colors.white)),
                    );
                  } else {
                    return const Center(child: CircularProgressIndicator());
                  }
                }),
              ),
            ]),
          ),
        ));
  }
}

```
<pre class="lang-dart prettyprint-override"><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dronebag/config/font_size.dart';
import 'package:dronebag/config/theme_colors.dart';
import 'package:dronebag/domain/battery_station_issue_repository/battery_station_issue_repository.dart';
import 'package:dronebag/domain/battery_station_repository/battery_station_repository.dart';
import 'package:dronebag/widgets/utils.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class BatteryStationIssueTile extends StatefulWidget {
  final String groupID;
  final BatteryStation batteryStation;
  final BatteryStationIssue batteryStationIssue;
  const BatteryStationIssueTile({
    Key? key,
    required this.groupID,
    required this.batteryStation,
    required this.batteryStationIssue,
  }) : super(key: key);

  @override
  State<BatteryStationIssueTile> createState() =>
      _BatteryStationIssueTileState();
}

class _BatteryStationIssueTileState extends State<BatteryStationIssueTile> {
  TextEditingController batteryStationIssueDetailController =
      TextEditingController();

  @override
  void initState() {

    batteryStationIssueDetailController =
        TextEditingController(text: widget.batteryStationIssue.detail);
    super.initState();

  }

  @override
  void dispose() {
    batteryStationIssueDetailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String issueDescription = widget.batteryStationIssue.detail;
    Color textDescriptionColor = ThemeColors.whiteTextColor;
    if (widget.batteryStationIssue.detail == "") {
      issueDescription = "Click me to add description";
      textDescriptionColor = ThemeColors.greyTextColor;
    }
    print("Issue:");
    print(widget.batteryStationIssue.detail);
    return ListTile(
      onTap: (() {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            backgroundColor: ThemeColors.scaffoldBgColor,
            scrollable: true,
            title: Center(
              child: Text(
                "Edit issue description",
                style: GoogleFonts.poppins(
                  color: ThemeColors.whiteTextColor,
                  fontSize: FontSize.large,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            content: TextFormField(
              controller: batteryStationIssueDetailController,
              keyboardType: TextInputType.multiline,
              maxLines: null,
              style: GoogleFonts.poppins(
                color: ThemeColors.whiteTextColor,
                fontSize: FontSize.medium,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                fillColor: ThemeColors.textFieldBgColor,
                filled: true,
                hintText: "Issue description",
                hintStyle: GoogleFonts.poppins(
                  color: ThemeColors.textFieldHintColor,
                  fontSize: FontSize.small,
                  fontWeight: FontWeight.w400,
                ),
                border: const OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.all(Radius.circular(18)),
                ),
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('Cancel')),
              TextButton(
                  onPressed: () {
                    final docBatteryStationIssue = FirebaseFirestore.instance
                        .collection('groups')
                        .doc(widget.groupID)
                        .collection('battery_stations')
                        .doc(widget.batteryStation.id)
                        .collection('issues')
                        .doc(widget.batteryStationIssue.id);
                    docBatteryStationIssue.update(
                        {'detail': batteryStationIssueDetailController.text});
                    Navigator.pop(context);
                    Utils.showSnackBarWithColor(
                        'Issue has been updated', Colors.blue);
                  },
                  child: const Text(
                    'Update issue',
                    style: TextStyle(color: Colors.blue),
                  )),
            ],
          ),
        );
      }),
      title: Padding(
        padding: const EdgeInsets.all(0),
        child: Container(
          decoration: const BoxDecoration(
              color: Color.fromARGB(255, 32, 32, 32),
              borderRadius: BorderRadius.all(Radius.circular(5))),
          child: Center(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(8, 5, 8, 5),
              child: Column(
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '${widget.batteryStationIssue.date.day}-${widget.batteryStationIssue.date.month}-${widget.batteryStationIssue.date.year}',
                      style: GoogleFonts.poppins(
                        color: ThemeColors.whiteTextColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      issueDescription,
                      style: GoogleFonts.poppins(
                        color: textDescriptionColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          'Status:  ${widget.batteryStationIssue.status}',
                          style: GoogleFonts.poppins(
                            color: ThemeColors.whiteTextColor,
                            fontSize: FontSize.medium,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          iconSize: 24,
                          splashColor: Colors.transparent,
                          color: Colors.red,
                          icon: const Icon(Icons.delete),
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                  backgroundColor: ThemeColors.scaffoldBgColor,
                                  title: Center(
                                    child: Text(
                                      "Delete this issue?",
                                      style: GoogleFonts.poppins(
                                        color: ThemeColors.whiteTextColor,
                                        fontSize: FontSize.large,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                  actions: [
                                    TextButton(
                                        onPressed: () {
                                          Navigator.pop(context);
                                        },
                                        child: const Text(
                                          'Cancle',
                                          style: TextStyle(color: Colors.blue),
                                        )),
                                    TextButton(
                                        onPressed: () {
                                          FirebaseFirestore.instance
                                              .collection('groups')
                                              .doc(widget.groupID)
                                              .collection('battery_stations')
                                              .doc(widget.batteryStation.id)
                                              .collection("issues")
                                              .doc(
                                                  widget.batteryStationIssue.id)
                                              .delete();
                                          Navigator.pop(context);
                                        },
                                        child: const Text(
                                          'Yes Delete',
                                          style: TextStyle(color: Colors.red),
                                        )),
                                  ]),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Body:
I'm getting a desync behavior with ListView.builder, TextField, and TextEditingController.
When I'm adding/removing an "issue" object the text that I see once I tap the issue is "shifted" one down or just way wrong, but the controller still affects the same object.
I'm adding pictures for clarification:

So here you can see all the objects

Once i tap say the first top one "5"

Now i add an new "issue" object

Then i click again on the object i clicked before "5" which is the second top one now:

I cant seem to understand why this behavoir happens and how to fix it.
finally im posting my code for more refrense:

// ignore_for_file: non_constant_identifier_names, sized_box_for_whitespace
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dronebag/app.dart';
import 'package:dronebag/config/font_size.dart';
import 'package:dronebag/domain/battery_issue_repository/battery_issue_repository.dart';
import 'package:dronebag/domain/battery_repository/battery_repository.dart';
import 'package:dronebag/domain/battery_station_issue_repository/battery_station_issue_repository.dart';
import 'package:dronebag/domain/battery_station_repository/src/models/models.dart';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import '../widgets/widgest.dart';

class BatteryStationDetails extends StatefulWidget {
  final String groupID;
  final BatteryStation batteryStation;
  const BatteryStationDetails({
    Key? key,
    required this.groupID,
    required this.batteryStation,
  }) : super(key: key);

  @override
  State<BatteryStationDetails> createState() => _BatteryStationDetailsState();
}

class _BatteryStationDetailsState extends State<BatteryStationDetails> {
  final formKey = GlobalKey<FormState>();
  final TextEditingController serial_numberController = TextEditingController();
  final TextEditingController batteryIssueDetailController =
      TextEditingController();
  final TextEditingController batteryCycleController = TextEditingController();
  final TextEditingController date_boughtController = TextEditingController();
  final double sizedBoxHight = 16;
  final TextEditingController battery_pairsController = TextEditingController();

  @override
  void initState() {
    // ignore: todo
    // TODO: implement initState

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final fetch = FirestoreFetch(
        groupID: widget.groupID, batteryStation: widget.batteryStation);
    final create = FirestoreCreate(
        groupID: widget.groupID, batteryStation: widget.batteryStation);
    return Scaffold(
        appBar: AppBar(
          backgroundColor: ThemeColors.scaffoldBgColor,
          title: Text(
            "Battery Station ${widget.batteryStation.serial_number}",
            style: GoogleFonts.poppins(
              color: ThemeColors.whiteTextColor,
              fontSize: FontSize.xxLarge,
              fontWeight: FontWeight.w600,
            ),
          ),
          actions: [
            TextButton(
              child: Text(
                'Edit Station \nDetails',
                textAlign: TextAlign.center,
                style: GoogleFonts.poppins(
                  color: Colors.blue,
                  fontSize: FontSize.medium,
                  fontWeight: FontWeight.w600,
                ),
              ),
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (context) => EditBatteryStationDialog(
                          batteryStation: widget.batteryStation,
                          groupID: widget.groupID,
                        ));
              },
            ),
          ],
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(38),
            child: Column(children: [
              Text(
                'Batteries',
                style: GoogleFonts.poppins(
                  color: ThemeColors.textFieldHintColor,
                  fontSize: FontSize.large,
                  fontWeight: FontWeight.w600,
                ),
              ),
              StreamBuilder<List<Battery>>(
                  stream: fetch.fetchBatteries(),
                  builder: ((context, snapshot) {
                    if (snapshot.hasData) {
                      final batteries = snapshot.data!;
                      batteries.sort(
                        (a, b) {
                          return a.serial_number.compareTo(b.serial_number);
                        },
                      );
                      return GridView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          childAspectRatio: 1.8,
                        ),
                        itemCount: batteries.length,
                        shrinkWrap: true,
                        itemBuilder: (context, index) {
                          return BatteryTile(
                              battery: batteries[index],
                              batteryStation: widget.batteryStation,
                              groupID: widget.groupID);
                        },
                      );
                    } else if (snapshot.hasError) {
                      return SingleChildScrollView(
                        child: Text('Something went wrong! \n\n$snapshot',
                            style: const TextStyle(color: Colors.white)),
                      );
                    } else {
                      return const Center(child: CircularProgressIndicator());
                    }
                  })),
              const SizedBox(height: 20),
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      style: GoogleFonts.poppins(
                        color: ThemeColors.textFieldHintColor,
                        fontSize: FontSize.large,
                        fontWeight: FontWeight.w600,
                      ),
                      text: "Station\'s Issue list ",
                    ),
                    const WidgetSpan(
                        child: Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 20, 0),
                    )),
                    TextSpan(
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          create.createBatteryStationIssue();
                        },
                      text: 'Add Issue',
                      style: GoogleFonts.poppins(
                        color: ThemeColors.primaryColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w600,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 12),
//vvvvvvvvvvvvvvvvvvRELEVENTvvvvvvvvvvvvvvvvvvvv//
              StreamBuilder<List<BatteryStationIssue>>(
                stream: fetch.fetchBatteryStationIssue(),
                builder: ((context, snapshot) {
                  if (snapshot.hasData) {
                    final batteryStationIssues = snapshot.data!;
                    //print(issues.length);
                    return Container(
                      child: ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: batteryStationIssues.length,
                        itemBuilder: (context, index) {
                          print("==========");
                          return BatteryStationIssueTile(
                              groupID: widget.groupID,
                              batteryStation: widget.batteryStation,
                              batteryStationIssue: batteryStationIssues[index]);
                        },
                      ),
                    );
                  } else if (snapshot.hasError) {
                    return SingleChildScrollView(
                      child: Text('Something went wrong! \n\n$snapshot',
                          style: const TextStyle(color: Colors.white)),
                    );
                  } else {
                    return const Center(child: CircularProgressIndicator());
                  }
                }),
              ),
            ]),
          ),
        ));
  }
}

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dronebag/config/font_size.dart';
import 'package:dronebag/config/theme_colors.dart';
import 'package:dronebag/domain/battery_station_issue_repository/battery_station_issue_repository.dart';
import 'package:dronebag/domain/battery_station_repository/battery_station_repository.dart';
import 'package:dronebag/widgets/utils.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class BatteryStationIssueTile extends StatefulWidget {
  final String groupID;
  final BatteryStation batteryStation;
  final BatteryStationIssue batteryStationIssue;
  const BatteryStationIssueTile({
    Key? key,
    required this.groupID,
    required this.batteryStation,
    required this.batteryStationIssue,
  }) : super(key: key);

  @override
  State<BatteryStationIssueTile> createState() =>
      _BatteryStationIssueTileState();
}

class _BatteryStationIssueTileState extends State<BatteryStationIssueTile> {
  TextEditingController batteryStationIssueDetailController =
      TextEditingController();

  @override
  void initState() {

    batteryStationIssueDetailController =
        TextEditingController(text: widget.batteryStationIssue.detail);
    super.initState();

  }

  @override
  void dispose() {
    batteryStationIssueDetailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String issueDescription = widget.batteryStationIssue.detail;
    Color textDescriptionColor = ThemeColors.whiteTextColor;
    if (widget.batteryStationIssue.detail == "") {
      issueDescription = "Click me to add description";
      textDescriptionColor = ThemeColors.greyTextColor;
    }
    print("Issue:");
    print(widget.batteryStationIssue.detail);
    return ListTile(
      onTap: (() {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            backgroundColor: ThemeColors.scaffoldBgColor,
            scrollable: true,
            title: Center(
              child: Text(
                "Edit issue description",
                style: GoogleFonts.poppins(
                  color: ThemeColors.whiteTextColor,
                  fontSize: FontSize.large,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            content: TextFormField(
              controller: batteryStationIssueDetailController,
              keyboardType: TextInputType.multiline,
              maxLines: null,
              style: GoogleFonts.poppins(
                color: ThemeColors.whiteTextColor,
                fontSize: FontSize.medium,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                fillColor: ThemeColors.textFieldBgColor,
                filled: true,
                hintText: "Issue description",
                hintStyle: GoogleFonts.poppins(
                  color: ThemeColors.textFieldHintColor,
                  fontSize: FontSize.small,
                  fontWeight: FontWeight.w400,
                ),
                border: const OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.all(Radius.circular(18)),
                ),
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('Cancel')),
              TextButton(
                  onPressed: () {
                    final docBatteryStationIssue = FirebaseFirestore.instance
                        .collection('groups')
                        .doc(widget.groupID)
                        .collection('battery_stations')
                        .doc(widget.batteryStation.id)
                        .collection('issues')
                        .doc(widget.batteryStationIssue.id);
                    docBatteryStationIssue.update(
                        {'detail': batteryStationIssueDetailController.text});
                    Navigator.pop(context);
                    Utils.showSnackBarWithColor(
                        'Issue has been updated', Colors.blue);
                  },
                  child: const Text(
                    'Update issue',
                    style: TextStyle(color: Colors.blue),
                  )),
            ],
          ),
        );
      }),
      title: Padding(
        padding: const EdgeInsets.all(0),
        child: Container(
          decoration: const BoxDecoration(
              color: Color.fromARGB(255, 32, 32, 32),
              borderRadius: BorderRadius.all(Radius.circular(5))),
          child: Center(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(8, 5, 8, 5),
              child: Column(
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '${widget.batteryStationIssue.date.day}-${widget.batteryStationIssue.date.month}-${widget.batteryStationIssue.date.year}',
                      style: GoogleFonts.poppins(
                        color: ThemeColors.whiteTextColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      issueDescription,
                      style: GoogleFonts.poppins(
                        color: textDescriptionColor,
                        fontSize: FontSize.medium,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          'Status:  ${widget.batteryStationIssue.status}',
                          style: GoogleFonts.poppins(
                            color: ThemeColors.whiteTextColor,
                            fontSize: FontSize.medium,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          iconSize: 24,
                          splashColor: Colors.transparent,
                          color: Colors.red,
                          icon: const Icon(Icons.delete),
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                  backgroundColor: ThemeColors.scaffoldBgColor,
                                  title: Center(
                                    child: Text(
                                      "Delete this issue?",
                                      style: GoogleFonts.poppins(
                                        color: ThemeColors.whiteTextColor,
                                        fontSize: FontSize.large,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                  actions: [
                                    TextButton(
                                        onPressed: () {
                                          Navigator.pop(context);
                                        },
                                        child: const Text(
                                          'Cancle',
                                          style: TextStyle(color: Colors.blue),
                                        )),
                                    TextButton(
                                        onPressed: () {
                                          FirebaseFirestore.instance
                                              .collection('groups')
                                              .doc(widget.groupID)
                                              .collection('battery_stations')
                                              .doc(widget.batteryStation.id)
                                              .collection("issues")
                                              .doc(
                                                  widget.batteryStationIssue.id)
                                              .delete();
                                          Navigator.pop(context);
                                        },
                                        child: const Text(
                                          'Yes Delete',
                                          style: TextStyle(color: Colors.red),
                                        )),
                                  ]),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}


问:
Bouncerate based on ProductSKU Google Analytics UA via python
I want to prepare a report to show bounceRate based on productSku but below code return only users doesnt represent any information about bounceRate. Do you have any idea?</p>
```<code>high_bounce_rate = {'reportRequests': [{'viewId': your_view_id,
                            'pageSize': 200000,
                            'dateRanges': [{'startDate': '2022-12-01', 'endDate': '2022-12-01'}],
                            'metrics': [{'expression': 'ga:users'},
                                        {"expression": "ga:bounceRate"}],
                            'dimensions': [{'name': 'ga:date'},
                                          {"name": "ga:productSku"}],
                            "pivots": [{"dimensions": [{"name": "ga:channelGrouping"}],
                                        "metrics": [{"expression": "ga:users"},
                                                    {"expression": "ga:bounceRate"}]
                                       }]
                          }]}
</code>```

Body:
I want to prepare a report to show bounceRate based on productSku but below code return only users doesnt represent any information about bounceRate. Do you have any idea?

high_bounce_rate = {'reportRequests': [{'viewId': your_view_id,
                            'pageSize': 200000,
                            'dateRanges': [{'startDate': '2022-12-01', 'endDate': '2022-12-01'}],
                            'metrics': [{'expression': 'ga:users'},
                                        {"expression": "ga:bounceRate"}],
                            'dimensions': [{'name': 'ga:date'},
                                          {"name": "ga:productSku"}],
                            "pivots": [{"dimensions": [{"name": "ga:channelGrouping"}],
                                        "metrics": [{"expression": "ga:users"},
                                                    {"expression": "ga:bounceRate"}]
                                       }]
                          }]}


问:
Flutter - Build Failed With An Exception. How to upgrade dependencies?
This is the what I am getting in Android Studio

FAILURE: Build failed with an exception.

Where:
Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I tried using flutter pub upgrade --major-versions but the issue has not been resolved.
This is what it showed after using flutter pub upgrade --major-versions

```<code>Resolving dependencies...
  async 2.9.0 (2.10.0 available)
  boolean_selector 2.1.0 (2.1.1 available)
  characters 1.2.1
  clock 1.1.1
  collection 1.16.0 (1.17.0 available)
  cupertino_icons 1.0.5
  fake_async 1.3.1
  flutter 0.0.0 from sdk flutter
  flutter_test 0.0.0 from sdk flutter
  matcher 0.12.12 (0.12.14 available)
  material_color_utilities 0.1.5 (0.2.0 available)
  meta 1.8.0
  path 1.8.2 (1.8.3 available)
  sky_engine 0.0.99 from sdk flutter
  source_span 1.9.0 (1.9.1 available)
  stack_trace 1.10.0 (1.11.0 available)
  stream_channel 2.1.0 (2.1.1 available)
  string_scanner 1.1.1 (1.2.0 available)
  term_glyph 1.2.1
  test_api 0.4.12 (0.4.17 available)
  vector_math 2.1.2 (2.1.4 available)
No dependencies changed.
12 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.
</code>```

Upon using flutter pub outdated this is what I got

[*] indicates versions that are not the latest available.

Package Name              Current   Upgradable  Resolvable  Latest

direct dependencies: all up-to-date.

transitive dependencies:
collection                *1.16.0   *1.16.0     *1.16.0     1.17.0
material_color_utilities  *0.1.5    *0.1.5      *0.1.5      0.2.0
vector_math               *2.1.2    *2.1.2      *2.1.2      2.1.4

transitive dev_dependencies:
async                     *2.9.0    *2.9.0      *2.9.0      2.10.0
boolean_selector          *2.1.0    *2.1.0      *2.1.0      2.1.1
matcher                   *0.12.12  *0.12.12    *0.12.12    0.12.14
path                      *1.8.2    *1.8.2      *1.8.2      1.8.3
source_span               *1.9.0    *1.9.0      *1.9.0      1.9.1
stack_trace               *1.10.0   *1.10.0     *1.10.0     1.11.0
stream_channel            *2.1.0    *2.1.0      *2.1.0      2.1.1
string_scanner            *1.1.1    *1.1.1      *1.1.1      1.2.0
test_api                  *0.4.12   *0.4.12     *0.4.12     0.4.17
all dependencies are up-to-date.

Can someone please tell me how to solve this issue? I cannot figure out what needs to be done here.
I keep getting the same error code.
How to update these dependencies to the newer version? I don't know how to do it.

Body:
This is the what I am getting in Android Studio

FAILURE: Build failed with an exception.

Where:
Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I tried using flutter pub upgrade --major-versions but the issue has not been resolved.
This is what it showed after using flutter pub upgrade --major-versions

Resolving dependencies...
  async 2.9.0 (2.10.0 available)
  boolean_selector 2.1.0 (2.1.1 available)
  characters 1.2.1
  clock 1.1.1
  collection 1.16.0 (1.17.0 available)
  cupertino_icons 1.0.5
  fake_async 1.3.1
  flutter 0.0.0 from sdk flutter
  flutter_test 0.0.0 from sdk flutter
  matcher 0.12.12 (0.12.14 available)
  material_color_utilities 0.1.5 (0.2.0 available)
  meta 1.8.0
  path 1.8.2 (1.8.3 available)
  sky_engine 0.0.99 from sdk flutter
  source_span 1.9.0 (1.9.1 available)
  stack_trace 1.10.0 (1.11.0 available)
  stream_channel 2.1.0 (2.1.1 available)
  string_scanner 1.1.1 (1.2.0 available)
  term_glyph 1.2.1
  test_api 0.4.12 (0.4.17 available)
  vector_math 2.1.2 (2.1.4 available)
No dependencies changed.
12 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.

Upon using flutter pub outdated this is what I got

[*] indicates versions that are not the latest available.

Package Name              Current   Upgradable  Resolvable  Latest

direct dependencies: all up-to-date.

transitive dependencies:
collection                *1.16.0   *1.16.0     *1.16.0     1.17.0
material_color_utilities  *0.1.5    *0.1.5      *0.1.5      0.2.0
vector_math               *2.1.2    *2.1.2      *2.1.2      2.1.4

transitive dev_dependencies:
async                     *2.9.0    *2.9.0      *2.9.0      2.10.0
boolean_selector          *2.1.0    *2.1.0      *2.1.0      2.1.1
matcher                   *0.12.12  *0.12.12    *0.12.12    0.12.14
path                      *1.8.2    *1.8.2      *1.8.2      1.8.3
source_span               *1.9.0    *1.9.0      *1.9.0      1.9.1
stack_trace               *1.10.0   *1.10.0     *1.10.0     1.11.0
stream_channel            *2.1.0    *2.1.0      *2.1.0      2.1.1
string_scanner            *1.1.1    *1.1.1      *1.1.1      1.2.0
test_api                  *0.4.12   *0.4.12     *0.4.12     0.4.17
all dependencies are up-to-date.

Can someone please tell me how to solve this issue? I cannot figure out what needs to be done here.
I keep getting the same error code.
How to update these dependencies to the newer version? I don't know how to do it.


问:
Thrift client type cannot be resolved c++
I'm hoping to reuse an opened thrift connection to send/recieve multiple messages/responses over the duration of a session.

The client is created in the file

Client.h

```<code>#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "User.h"
#include <future>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client connect(const std::string &host, int port);

string run_command(Client client, const int32_t op_code, const std::string addr);
</code>```

Client.cpp

```<code>#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "Client.h"
#include <future>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client connect(const std::string &host, int port) {

  std::shared_ptr<TTransport> socket(new TSocket(host, port));
  std::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
  std::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
  Client client(protocol);
  cout << "CONNECTING";
  transport->open();
  return client;
}

string run_command(Client client, const int32_t op_code, const std::string addr){
  printf("CLIENT\n");
  client.send_run_command(op_code, addr);
  printf("CLIENT SEND_RUN_COMMAND COMPLETE\n");
  string resp;
  client.recv_run_command(resp);
  printf("CLIENT RECV_RUN_COMMAND COMPLETE: %s\n", resp.c_str());
  return resp;
}
</code>```

However, I want to reuse the same client in a different file.

Shell.cpp

```<code>#include "Client.h"
#include <future>

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client client;

int32_t
taskset_fn(int32_t argc, char** argv) {
    // stuff omitted
    // auto client = connect("127.0.0.1", 9095); -> don't want to recreate client every time
    string output = run_command(client, 6, string(cmd_buf));
    return 0;
}

int lwshell_connect(const std::string &host, int port){
    client = connect("127.0.0.1", 9095);
}
</code>```

Building yields the following error:

```<code>no matching function for call to ‘ClientT<apache::thrift::protocol::TProtocol>::ClientT()’
 Client client;
        ^~~~~~
In file included from [full path omitted]/programs/libuser/librpc/src/Client.h:7:0,
                 from [full path omitted]/programs/libuser
[full path omitted]/programs/libuser/librpc/src/User.h:183:3: note: candidate: ClientT<Protocol_>::ClientT(std::shared_ptr<_Tp>, std::shared_ptr<_Tp>) [with Protocol_ = apache::thrift::protocol::TProtocol]
   ClientT(std::shared_ptr< Protocol_> iprot, std::shared_ptr< Protocol_> oprot) {
   ^~~~~~~
[full path omitted]/programs/libuser/librpc/src/User.h:183:3: note:   candidate expects 2 arguments, 0 provided
[full path omitted]/programs/libuser/librpc/src/User.h:180:3: note: candidate: ClientT<Protocol_>::ClientT(std::shared_ptr<_Tp>) [with Protocol_ = apache::thrift::protocol::TProtocol]
   ClientT(std::shared_ptr< Protocol_> prot) {
   ^~~~~~~
[full path omitted]/programs/libuser/librpc/src/User.h:180:3: note:   candidate expects 1 argument, 0 provided
</code>```

In short, the compiler thinks that Client client; is a function call, but I just want a static instance of the client. How can I make a reusable thrift client?

Things I've tried

1.

I have tried doing Client client(std::shared_ptr<TProtocol>);, which results in

```<code>: could not convert ‘client’ from ‘Client (*)(std::shared_ptr<apache::thrift::protocol::TProtocol>) {aka ClientT<apache::thrift::protocol::TProtocol>
(*)(std::shared_ptr<apache::thrift::protocol::TProtocol>)}’ to ‘Client {aka ClientT<apache::thrift::protocol::TProtocol>}’
</code>```

2.

Making the global client a Client*:

Shell.cpp

```<code>Client* client;
...

    Client client_temp = connect("127.0.0.1", 9095);
    client = &client_temp;
    printf("addr: %p\n", (void*) client);
...
    printf("taskset ptr: %p\n", (void*) client);
    string output = run_command(*client, 6, string(cmd_buf));```
```
<p>causes segfault</p>
```▶ ./ShellUser
CONNECTINGaddr: 0x7fffbfdf2430
$ taskset 1
RECV:taskset 1
, 10
parsing
ARG: taskset
TASKSET
taskset ptr: 0x7fffbfdf2430
[1]    27587 segmentation fault (core dumped)  ./ShellUser
```

Body:
I'm hoping to reuse an opened thrift connection to send/recieve multiple messages/responses over the duration of a session.

The client is created in the file

Client.h

#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "User.h"
#include <future>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client connect(const std::string &host, int port);

string run_command(Client client, const int32_t op_code, const std::string addr);

Client.cpp

#include <iostream>

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "Client.h"
#include <future>

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client connect(const std::string &host, int port) {

  std::shared_ptr<TTransport> socket(new TSocket(host, port));
  std::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
  std::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
  Client client(protocol);
  cout << "CONNECTING";
  transport->open();
  return client;
}

string run_command(Client client, const int32_t op_code, const std::string addr){
  printf("CLIENT\n");
  client.send_run_command(op_code, addr);
  printf("CLIENT SEND_RUN_COMMAND COMPLETE\n");
  string resp;
  client.recv_run_command(resp);
  printf("CLIENT RECV_RUN_COMMAND COMPLETE: %s\n", resp.c_str());
  return resp;
}

However, I want to reuse the same client in a different file.

Shell.cpp

#include "Client.h"
#include <future>

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

Client client;

int32_t
taskset_fn(int32_t argc, char** argv) {
    // stuff omitted
    // auto client = connect("127.0.0.1", 9095); -> don't want to recreate client every time
    string output = run_command(client, 6, string(cmd_buf));
    return 0;
}

int lwshell_connect(const std::string &host, int port){
    client = connect("127.0.0.1", 9095);
}

Building yields the following error:

no matching function for call to ‘ClientT<apache::thrift::protocol::TProtocol>::ClientT()’
 Client client;
        ^~~~~~
In file included from [full path omitted]/programs/libuser/librpc/src/Client.h:7:0,
                 from [full path omitted]/programs/libuser
[full path omitted]/programs/libuser/librpc/src/User.h:183:3: note: candidate: ClientT<Protocol_>::ClientT(std::shared_ptr<_Tp>, std::shared_ptr<_Tp>) [with Protocol_ = apache::thrift::protocol::TProtocol]
   ClientT(std::shared_ptr< Protocol_> iprot, std::shared_ptr< Protocol_> oprot) {
   ^~~~~~~
[full path omitted]/programs/libuser/librpc/src/User.h:183:3: note:   candidate expects 2 arguments, 0 provided
[full path omitted]/programs/libuser/librpc/src/User.h:180:3: note: candidate: ClientT<Protocol_>::ClientT(std::shared_ptr<_Tp>) [with Protocol_ = apache::thrift::protocol::TProtocol]
   ClientT(std::shared_ptr< Protocol_> prot) {
   ^~~~~~~
[full path omitted]/programs/libuser/librpc/src/User.h:180:3: note:   candidate expects 1 argument, 0 provided

In short, the compiler thinks that Client client; is a function call, but I just want a static instance of the client. How can I make a reusable thrift client?

Things I've tried

1.

I have tried doing Client client(std::shared_ptr<TProtocol>);, which results in

: could not convert ‘client’ from ‘Client (*)(std::shared_ptr<apache::thrift::protocol::TProtocol>) {aka ClientT<apache::thrift::protocol::TProtocol>
(*)(std::shared_ptr<apache::thrift::protocol::TProtocol>)}’ to ‘Client {aka ClientT<apache::thrift::protocol::TProtocol>}’

2.

Making the global client a Client*:

Shell.cpp

Client* client;
...

    Client client_temp = connect("127.0.0.1", 9095);
    client = &client_temp;
    printf("addr: %p\n", (void*) client);
...
    printf("taskset ptr: %p\n", (void*) client);
    string output = run_command(*client, 6, string(cmd_buf));```

causes segfault

▶ ./ShellUser
CONNECTINGaddr: 0x7fffbfdf2430
$ taskset 1
RECV:taskset 1
, 10
parsing
ARG: taskset
TASKSET
taskset ptr: 0x7fffbfdf2430
[1]    27587 segmentation fault (core dumped)  ./ShellUser


问:
nuxt errors build and development for library
I'm trying to connect the library to nuxt, but when building or developing, a webpack error falls. This happens when I include the library by name or by direct path from node_modules, but if I include it from the project root, then there will be no errors. How can I solve this problem?

Error:

ERROR in ./node_modules/air-datepicker/air-datepicker.js 1:7295
Module parse failed: Unexpected token (1:7295)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

webpack complains about .?, but only in node_modules, again, if I move the source to the root of the project, then there will be no errors. This can be viewed at the link, the first included file is a module, and the second is the source of the module in the root of the project

Example


问:
Google OAuth consent screen - Contacts API access
Google cloud console OAuth consent screen, I got the below email from Google. No part of my app access to contacts.

my guess is may be I am using flutter share_plus package to share the app with other users, is this why I am getting the below email from Google. Do I need to enable the scope in OAuth Consent screen and send justifications?

Your project has recently accessed these scopes, which were not
included in your verification request:

https://www.googleapis.com/auth/contacts.readonly

If you need access to these additional scopes:

Add the scopes listed above to your project in your Google Cloud
Console.

Click 'Submit for verification'. Provide justification for additional
scope(s) and create a new demo video showing login and use of the new
scope(s)

Please help me with this.


问:
JBDC: ResultSet not positioned properly, perhaps you need to call next in java
just trying some JBDC for the first time and I am wondering about an error that I don't seem to be able to fix: "ResultSet not positioned properly, perhaps you need to call next in java." I only works if I put rs1 before the first IF but that skips the first row in my table so that doesn't make any sense. (Don't worry about exception handling etc. this is the rawest of rawest states of my program)

```<code>    public void rechnungslauf() {
        try {
            LocalDate date = LocalDate.now();

            ResultSet rs = getPositionen.executeQuery();
            ResultSet rs1 = printRechnung.executeQuery();
            ResultSet rs2 = getTotalCost.executeQuery();

            rs1.next();
        if (rs.next()) {

            System.out.println("-----------------------------------------------\n" + "Name: " + rs1.getString("nachname") + "\nVorname: " + rs1.getString("vorname") + "\nDatum: " + date + "\nAuftragsNr.: " + rs.getString("AuftragsNr.") + "\n");

            while (rs.next()) {

                String beschreibung = rs.getString("Beschreibung");
                String menge = rs.getString("Menge");
                String preis = rs.getString("Preis pro Mengeneinheit");
                String netto = rs.getString("Nettopreis");

                double a = Double.parseDouble(preis);
                double b = Double.parseDouble(netto);

                double d = (double) Math.round(a * 100) / 100;
                double e = (double) Math.round(b * 100) / 100;

                System.out.printf(menge + "x " + "%-20s € %-5s € %-5s\n", beschreibung, d, e);

                }

            while (rs2.next()) {
                String totalNetto = rs2.getString("Total Netto");
                String totalBrutto = rs2.getString("Total Brutto");
                String totalMwSt = rs2.getString("Total MwSt");

                double a = Double.parseDouble(totalNetto);
                double b = Double.parseDouble(totalBrutto);
                double c = Double.parseDouble(totalMwSt);

                double d = (double) Math.round(a * 100) / 100;
                double e = (double) Math.round(b * 100) / 100;
                double f = (double) Math.round(c * 100) / 100;

                System.out.println("\nNetto: "+ "€ " + d + "\nMehrwertsteuer: " + "€ " + f + "\nBrutto " + "€ " + e);
            }

            System.out.println("-----------------------------------------------\n");

        }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

I don't understand it good enough to understand why its not working.

Body:
just trying some JBDC for the first time and I am wondering about an error that I don't seem to be able to fix: "ResultSet not positioned properly, perhaps you need to call next in java." I only works if I put rs1 before the first IF but that skips the first row in my table so that doesn't make any sense. (Don't worry about exception handling etc. this is the rawest of rawest states of my program)

    public void rechnungslauf() {
        try {
            LocalDate date = LocalDate.now();

            ResultSet rs = getPositionen.executeQuery();
            ResultSet rs1 = printRechnung.executeQuery();
            ResultSet rs2 = getTotalCost.executeQuery();

            rs1.next();
        if (rs.next()) {

            System.out.println("-----------------------------------------------\n" + "Name: " + rs1.getString("nachname") + "\nVorname: " + rs1.getString("vorname") + "\nDatum: " + date + "\nAuftragsNr.: " + rs.getString("AuftragsNr.") + "\n");

            while (rs.next()) {

                String beschreibung = rs.getString("Beschreibung");
                String menge = rs.getString("Menge");
                String preis = rs.getString("Preis pro Mengeneinheit");
                String netto = rs.getString("Nettopreis");

                double a = Double.parseDouble(preis);
                double b = Double.parseDouble(netto);

                double d = (double) Math.round(a * 100) / 100;
                double e = (double) Math.round(b * 100) / 100;

                System.out.printf(menge + "x " + "%-20s € %-5s € %-5s\n", beschreibung, d, e);

                }

            while (rs2.next()) {
                String totalNetto = rs2.getString("Total Netto");
                String totalBrutto = rs2.getString("Total Brutto");
                String totalMwSt = rs2.getString("Total MwSt");

                double a = Double.parseDouble(totalNetto);
                double b = Double.parseDouble(totalBrutto);
                double c = Double.parseDouble(totalMwSt);

                double d = (double) Math.round(a * 100) / 100;
                double e = (double) Math.round(b * 100) / 100;
                double f = (double) Math.round(c * 100) / 100;

                System.out.println("\nNetto: "+ "€ " + d + "\nMehrwertsteuer: " + "€ " + f + "\nBrutto " + "€ " + e);
            }

            System.out.println("-----------------------------------------------\n");

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

I don't understand it good enough to understand why its not working.


问:
Spotify /authorize endpoint
I would like to know which is the /authorize endpoint, after some search I see that it's https://accounts.spotify.com/authorize?client_ID, but why? where is the documentation about it? I don't see any endpoints list and the guide only tell me to "send a GET request to the /authorize endpoint" without tell me which is the endpoint.
Sorry, I only want to know the logic behind the endpoint address

Thank you

Title: Spotify /authorize endpoint


问:
Business logic in Model MVC
I've seen some definitions of Model in MVC pattern and I noticed that some people say that it corresponds to data and data structure and some people says that it handles business logic.

There is any consent about this?

Title: Business logic in Model MVC


问:
Failed to launch debug adapter locally when changing ASPNETCORE_ENVIRONMENT
I have a solution with a pretty standard config structure

```<code>appsettings.json
   appsettings.Development.json
   appsettings.Testing.json
   appsettings.Production.json
</code>```

Testing and Production servers have an ASPNETCORE_ENVIRONMENT set to Testing and Production respectively and the everything works, proper config get's chosen, etc.

I wanted to load appsettings.Testing.json in my local Visual Studio so I went to my launchSettings.json and changed ASPNETCORE_ENVIRONMENT to Testing and Studio throws the error on launch.

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28725",
      "sslPort": 44342
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Testing"  <- was "Development"
      },
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}"
    }
  }
}
</code>```

Just to summarize all I did was changed that one setting from Testing to Development and Studio throws the Failed to launch debug adapter error upon launching.

And that's kinda it, nothing in the output windows, nothing in the windows eventviewer that I could find.

Body:
I have a solution with a pretty standard config structure

appsettings.json
   appsettings.Development.json
   appsettings.Testing.json
   appsettings.Production.json

Testing and Production servers have an ASPNETCORE_ENVIRONMENT set to Testing and Production respectively and the everything works, proper config get's chosen, etc.

I wanted to load appsettings.Testing.json in my local Visual Studio so I went to my launchSettings.json and changed ASPNETCORE_ENVIRONMENT to Testing and Studio throws the error on launch.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28725",
      "sslPort": 44342
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Testing"  <- was "Development"
      },
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}"
    }
  }
}

Just to summarize all I did was changed that one setting from Testing to Development and Studio throws the Failed to launch debug adapter error upon launching.

And that's kinda it, nothing in the output windows, nothing in the windows eventviewer that I could find.