问:
How to implement a database in Tkinter switching between frames?
I'm working based on Switch between two frames in tkinter, and it's still a project in process but I have a recurrent problem using databases.

Here's my code:

```<code>import tkinter as tk

import sqlite3

import threading

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        self.resizable(0,0)

        self.title("Findex")

        w, h = self.winfo_screenwidth(), self.winfo_screenheight()

        self.overrideredirect(1)

        self.geometry("%dx%d+0+0" % (w, h))

        container = tk.Frame(self)

        container.pack(side="top", fill = "both", expand = True)

        container.grid_rowconfigure(0, weight = 1)

        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}

        for F in (Inicio, Registro, RegistroError, Consulta):

            page_name = F.__name__

            frame=F(parent = container, controller = self)

            self.frames[page_name] = frame

            frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame("Inicio")

    def show_frame(self, page_name):

        frame = self.frames[page_name]

        frame.tkraise()

    def get_page(self, page_class):

        return self.frames[page_class]

class Inicio(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        labelInicio = tk.Label(self, text = "Bienvendido a Findex")

        labelInicio.pack()

        botonIncio = tk.Button(self, text = "Comenzar",
            command = lambda: controller.show_frame("Registro"))

        botonIncio.pack()

class Registro(tk.Frame):

     def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        def Usuario():

            if entryNombre.get() == "":

                labelError.config(text = "No introdujo ningún nombre")

            else:

                labelError.config(text = "")

                labelNombre = tk.Label(self,
                 text = "Ha escrito " + entryNombre.get() +
                  " ¿es correcto?")

                labelNombre.pack()

                def Paso():

                    controller.show_frame("Consulta")

                def Tiempo():

                    timer = threading.Timer(3.0, Paso)

                    timer.start()

                    labelAcceso = tk.Label(self,
                     text = "Adelante, " + entryNombre.get())

                    labelAcceso.pack()

                botonSi = tk.Button(self, text = "Sí",
                 command = Tiempo)

                botonSi.pack()

                botonNo = tk.Button(self, text = "No",
                    command = lambda: controller.show_frame("RegistroError"))

                botonNo.pack()

        labelInstruction = tk.Label(self,
         text = "Para continuar introduzca su nombre")

        labelInstruction.pack()

        entryNombre = tk.Entry(self)

        entryNombre.pack()

        botonConfirmar = tk.Button(self, text = "Confirmar",
         command = Usuario)

        botonConfirmar.pack()

        labelError = tk.Label(self)

        labelError.pack()

class RegistroError(tk.Frame):

     def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        def Usuario():

            if entryNombre.get() == "":

                labelError.config(text = "No introdujo ningún nombre")

            else:

                labelError.config(text = "")

                labelNombre = tk.Label(self,
                 text = "Ha escrito " + entryNombre.get() +
                  " ¿es correcto?")

                labelNombre.pack()

                def Paso():

                    controller.show_frame("Consulta")

                def Tiempo():

                    timer = threading.Timer(2.0, Paso)

                    timer.start()

                    labelAcceso = tk.Label(self,
                     text = "Adelante, " + entryNombre.get())

                    labelAcceso.pack()

                botonSi = tk.Button(self, text = "Sí",
                 command = Tiempo)

                botonSi.pack()

                def Error():

                    labelNombre.config(text = "")

                    labelInstruction.config(text = "")

                    botonSi.config(state = "disabled")

                    botonNo.config(state = "disabled")

                    entryNombre.config(state = "disabled")

                    botonConfirmar.config(state = "disabled")

                    labelFin = tk.Label(self,
                        text = "Se han agotado las oportunidades. Inténtelo de nuevo")

                    labelFin.pack()

                    def Salir():

                        quit()

                    botonSalir = tk.Button(self, text = "Aceptar y Salir",
                        command = Salir)

                    botonSalir.pack()

                botonNo = tk.Button(self, text = "No" , command = Error)

                botonNo.pack()

        labelInstruction = tk.Label(self,
         text = "Para continuar introduzca su nombre")

        labelInstruction.pack()

        entryNombre = tk.Entry(self)

        entryNombre.pack()

        botonConfirmar = tk.Button(self, text = "Confirmar",
         command = Usuario)

        botonConfirmar.pack()

        labelError = tk.Label(self)

        labelError.pack()

class Consulta(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        labelConsulta = tk.Label(self,
            text = "Ingrese el nombre de un producto, marca o tienda",
             padx = 30, pady = 15)

        labelConsulta.pack()

        entryConsulta = tk.Entry(self)

        entryConsulta.pack()

        def Call():

            miConexion = sqlite3.connect("Findex")

            miCursor = miConexion.cursor()

            query = entryConsulta.get()

            miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", query)

            table = miCursor.fetchall()

            textConsulta.insert(1.0, table)

            miConexion.commit()

        botonConsulta = tk.Button(self, text = "Buscar", command = Call)

        botonConsulta.pack()

        textConsulta = tk.Text(self, bd = 2)

        textConsulta.pack()

if __name__ == "__main__":

    app = SampleApp()

    app.mainloop()
</code>```

And here's where I create the database:

```<code>    import sqlite3

miConexion = sqlite3.connect("Findex")

miCursor = miConexion.cursor()

miCursor.execute("""

    CREATE TABLE IF NOT EXISTS 'PRODUCTOS' (

    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    NOMBRE VARCHAR(50),
    MARCA VARCHAR(50),
    PESO INTEGER,
    UNIDAD VARCHAR(20),
    PRECIO INTEGER,
    CATEGORIA VARCHAR(50),
    ESTABLECIMIENTO VARCHAR(50))

    """)

datos = [

    ("Sirope", "Suli", 700, "mililitros", 300, "Bebidas", "Palí"),
    ("Azúcar", "Doña María", 2, "kilogramos", 1225, "Granos",  "Palí"),
    ("Arroz", "Indiana", 1800, "gramos", 1495, "Granos", "Palí"),
    ("Café", "Rey", 500, "gramos", 1525, "Bebidas", "Palí"),
    ("Frijoles", "Indiana", 900, "gramos", 1175, "Granos", "Palí"),
    ("Sal", "Sal Sol", 500, "gramos", 225, "Granos", "Palí"),
    ("Aceite", "Clover", 1.5, "litros", 675, "Aceite/Margarina/Mantequilla", "Palí"),
    ("Huevos", "Don Cristóbal", 500, "gramos", 1975, "Huevos", "Palí"),
    ("Cereal", "Jack's", 250, "gramos", 2100, "Cereales", "Palí"),
    ("Mantequilla", "Dos Pinos", 500, "gramos", 675, "Aceite/Margarina/Mantequilla", "Palí"),
    ("Leche", "Dos Pinos", 1, "litros", 504, "Lácteos", "Palí"),
    ("Fideos", "Roma", 200, "gramos", 485, "Pastas", "Palí"),
    ("Jabón", "Fort 3", 1, "kilogramos", 550, "Limpieza", "Palí"),
    ("Desinfectante", "Floral", 750, "mililitros", 550, "Limpieza", "Palí"),
    ("Crema dental", "Oral B", 53, "mililitros", 900, "Cuidado personal", "Palí"),
    ("Jabón de baño", "Protex", 110, "gramos", 505, "Cuidado personal", "Palí"),
    ("Galletas", "Pozuelo", 31.5, "gramos", 1400, "Snacks", "Palí"),
    ("Papel higiénico", "Nevax", 1000, "hojas", 2450, "Cuidado personal", "Palí"),
    ("Toallas", "Nevax", 100, "hojas", 1300, "Limpieza", "Palí"),
    ("Refresco", "Lio-Té", 100, "gramos", 240, "Bebidas", "Palí"),
    ("Leche", "Delactomy", 1000, "mililitros", 2795, "Lácteos", "Perimercados"),
    ("Jamón cocido", "Cinta Azul", 250, "gramos", 2285, "Embutidos", "Perimercados"),
    ("Salsa inglesa", "Banquete", 700, "gramos", 1950, "Salsas", "Perimercados"),
    ("Aceite", "Capullo", 900, "mililitros", 925, "Aceite/Margarina/Mantequilla", "Perimercados"),
    ("Detergente", "Xedex", 5000, "gramos", 7750, "Limpieza", "Perimercados"),
    ("Lavaplatos", "Axion", 850, "gramos", 1610, "Limpieza", "Perimercados"),
    ("Arroz", "Imperio", 1, "kilogramos", 1180, "Granos", "Perimercados"),
    ("Pasta tipo cabello ángel", "Roma", 250, "gramos", 645, "Pastas", "Perimercados"),
    ("Pan blanco", "Bimbo", 450, "gramos", 1285, "Panes", "Perimercados"),
    ("Frijoles molidos", "Ducal", 400, "gramos", 910, "Enlatados", "Perimercados"),
    ("Crema dental", "Colgate", 75, "mililitros", 1390, "Cuidado personal", "Perimercados"),
    ("Protectores diarios", "Saba", 60, "unidades", 1495, "Cuidado personal", "Perimercados"),
    ("Café", "1820", 340, "gramos", 2810, "Bebidas", "Perimercados"),
    ("Avena", "Quaker", 300, "gramos", 805, "Cereales", "Perimercados"),
    ("Yogurt", "Yoplait", 750, "gramos", 1610, "Lácteos", "Perimercados"),
    ("Tomate", "-", 1, "kilogramos", 1050, "Frutas", "Perimercados"),
    ("Uvas mixtas", "-", 500, "gramos", 2600, "Frutas", "Perimercados"),
    ("Muslo de pollo", "-", 1, "kilogramos", 2300, "Carnes", "Perimercados"),
    ("Chorizo", "-", 1, "kilogramos", 3020, "Carnes", "Perimercados"),
    ("Queso", "Zarcero", 1, "kilogramos", 4200, "Lácteos", "Perimercados"),
    ("Aceite", "Capullo", 900, "mililitros", 880, "Aceite/Margarina/Mantequilla", "Megasuper"),
    ("Café", "Rey Selecto", 500, "gramos", 1995, "Bebidas", "Megasuper"),
    ("Margarina", "Numar", 452, "gramos", 1045, "Aceite/Margarina/Mantequilla", "Megasuper"),
    ("Yogurt", "Coronado", 1000, "mililitros", 1675, "Lácteos", "Megasuper"),
    ("Galleta soda", "Gama", 192, "gramos", 470, "Snacks", "Megasuper"),
    ("Molida premium de res", "-", 1, "kilogramos", 5540, "Carnes", "Megasuper"),
    ("Queso Turrialba", "Dos Pinos", 1, "kilogramos", 4270, "Lácteos", "Megasuper"),
    ("Chile dulce", "-", 1, "unidades", 325, "Verduras", "Megasuper"),
    ("Sandía", "-", 1, "kilogramos", 595, "Frutas", "Megasuper"),
    ("Huevos", "-", 1, "kilogramos", 1650, "Huevos", "Megasuper"),
    ("Hongos rebanados", "Del Monte", 184, "gramos", 530, "Enlatados", "Megasuper"),
    ("Frijoles rojos", "Luisiana", 900, "gramos", 1095, "Granos", "Megasuper"),
    ("Papel higiénico", "Higienol", 4, "unidades", 1550, "Limpieza", "Megasuper"),
    ("Detergente en polvo", "Rinso", 5000, "gramos", 1650, "Limpieza", "Megasuper"),
    ("Alimento para perro", "Dog Chow", 4000, "gramos", 10640, "Mascotas", "Megasuper"),
    ("Chuleta de cerdo", "-", 1, "kilogramos", 3690, "Carnes", "Megasuper"),
    ("Cerveza", "Imperial", 350, "mililitros", 780, "Bebidas alcohólicas", "Megasuper"),
    ("Vino", "Clos", 750, "mililitros", 3320, "Bebidas alcohólicas", "Megasuper"),
    ("Posta de cerdo", "-", 1, "kilogramos", 3490, "Carnes", "Megasuper"),
    ("Toallas sanitarias", "Kotex", 12, "unidades", 1645, "Ciudades personal", "Megasuper"),
    ("Crema dental", "Colgate", 75, "mililitros", 1510, "Cuidado personal", "Freshmarket"),
    ("Frito Lay", "Tostitos", 283, "gramos", 2620, "Snacks", "Freshmarket"),
    ("Vino", "San Telmo", 750, "mililitros", 7915, "Bebidas alcohólicas", "Freshmarket"),
    ("Helado Trirts", "Dos Pinos", 540, "gramos", 2950, "Lácteos", "Freshmarket"),
    ("Repollo verde", "-", 1, "unidades", 695, "Verduras", "Freshmarket"),
    ("Néctar mixto fruta", "Dos Pinos", 1, "litros", 960, "Bebidas", "Freshmarket"),
    ("Pan baguette", "AMMM", 300, "gramos", 1000, "Panadería", "Freshmarket"),
    ("Sandía", "-", 1, "kilogramos", 850, "Frutas", "Freshmarket"),
    ("Tomate", "-", 1, "kilogramos", 1250, "Frutas", "Freshmarket"),
    ("Plátono verde", "-", 1, "unidades", 395, "Frutas", "Freshmarket"),
    ("Papa", "-", 1, "kilogramos", 1295, "Verduras", "Freshmarket"),
    ("Manga", "-", 1, "kilogramos", 1650, "Frutas", "Freshmarket"),
    ("Ron", "Flor de Caña", 750, "mililiros", 7000, "Bebidas alcohólicas", "Freshmarket"),
    ("Papas tostadas", "Lays", 184, "gramos", 1800, "Snacks", "Freshmarket"),
    ("Jugo de naranja", "Dos Pinos", 1.8, "litros", 2930, "Bebidas", "Freshmarket"),
    ("Sundae", "Dos Pinos", 110, "gramos", 1620, "Lácteos", "Freshmarket"),
    ("Bebida energética", "Gatorade", 600, "mililitros", 1460, "Bebidas", "Freshmarket"),
    ("Deligurt", "Dos Pinos", 200, "mililitros", 850, "Lácteos", "Freshmarket"),
    ("Gaseosa", "Coca Cola", 2, "litros", 2285, "Bebidas", "Freshmarket"),
    ("Papas tostadas", "Pringles", 125, "gramos", 2300, "Snacks", "Freshmarket"),
    ("Toalla nocturna", "Saba", 40, "unidades", 5575, "Cuidado personal", "AutoMercado"),
    ("Acondicionador para cabello", "Alea", 500, "mililitros", 4215, "Cuidado personal", "AutoMercado"),
    ("Shampoo con keratina", "Suave", 373, "mililitros", 4000, "Cuidado personal", "AutoMercado"),
    ("Atún en trozos", "Pronto", 640, "gramos", 7320, "Enlatados", "AutoMercado"),
    ("Café", "Rey", 400, "gramos", 3500, "Bebidas", "AutoMercado"),
    ("Frijoles molidos", "Ducal", 400, "gramos", 865, "Enlatados", "AutoMercado"),
    ("Mayonesa con aceite de oliva", "Alolivo", 400, "gramos", 1595, "Salsas", "AutoMercado"),
    ("Cereal integral", "Nestle", 450, "gramos", 2700, "Cereales", "AutoMercado"),
    ("Vino tinto", "Broquel", 750, "mililitros", 10785, "Bebidas alcohólicas", "AutoMercado"),
    ("Queso mozzarella", "Crystal Farms", 227, "gramos", 3250, "Lácteos", "AutoMercado"),
    ("Jamón de pavo", "Cinta Azul", 1, "kilogramos", 9925, "Embutidos", "AutoMercado"),
    ("Bistec de lomo", "AutoMercado", 1, "kilogramos", 14170, "Carnes", "AutoMercado"),
    ("Chicharrones ahumados", "Jack's", 75, "gramos", 1400, "Carnes", "AutoMercado"),
    ("Maní con miel", "The Carolina Nut Co", 340, "gramos", 3100, "Snacks", "AutoMercado"),
    ("Limón ácido", "-", 15, "unidades", 3800, "Frutas", "AutoMercado"),
    ("Filet de pechuga", "AutoMercado", 1, "kilogramos", 7875, "Carnes", "AutoMercado"),
    ("Cerveza amarga", "Warsteiner", 500, "mililitros", 1395, "Bebidas alcohólicas", "AutoMercado"),
    ("Crema croporal", "Bilka", 180, "mililitros", 10265, "Cuidado Personal", "AutoMercado"),
    ("Tinte para cabello", "Koleston", 1, "unidades", 5915, "Cuidado Personal", "AutoMercado"),
    ("Toallitas desmaquillantes", "Asepxia", 25, "unidades", 5445, "Cuidado Personal", "AutoMercado")

    ]

miCursor.executemany("INSERT INTO PRODUCTOS VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)", datos)

miConexion.commit()

miConexion.close()
</code>```

I expect write the name, mark or shop of a product and insert all the information about the products that match with the entry in the text field, but it gives me 'OperationalError' or 'sqlite3.ProgrammingError'.

答:
I think the problem is here

```<code>query = entryConsulta.get()
miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", query)
</code>```

your statment accept 3 args but you pass only one

try so

```<code>query = entryConsulta.get()
args = (query,query,query)
miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", args)
</code>```

anyway I think that you have to decoupling your code between more modules, if you are interested on this type of program I would suggest you this my
didactic work on github

https://github.com/1966bc/Tkinterlite

Hasta luego;)

Body:
I'm working based on Switch between two frames in tkinter, and it's still a project in process but I have a recurrent problem using databases.

Here's my code:

import tkinter as tk

import sqlite3

import threading

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        self.resizable(0,0)

        self.title("Findex")

        w, h = self.winfo_screenwidth(), self.winfo_screenheight()

        self.overrideredirect(1)

        self.geometry("%dx%d+0+0" % (w, h))

        container = tk.Frame(self)

        container.pack(side="top", fill = "both", expand = True)

        container.grid_rowconfigure(0, weight = 1)

        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}

        for F in (Inicio, Registro, RegistroError, Consulta):

            page_name = F.__name__

            frame=F(parent = container, controller = self)

            self.frames[page_name] = frame

            frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame("Inicio")

    def show_frame(self, page_name):

        frame = self.frames[page_name]

        frame.tkraise()

    def get_page(self, page_class):

        return self.frames[page_class]

class Inicio(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        labelInicio = tk.Label(self, text = "Bienvendido a Findex")

        labelInicio.pack()

        botonIncio = tk.Button(self, text = "Comenzar",
            command = lambda: controller.show_frame("Registro"))

        botonIncio.pack()

class Registro(tk.Frame):

     def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        def Usuario():

            if entryNombre.get() == "":

                labelError.config(text = "No introdujo ningún nombre")

            else:

                labelError.config(text = "")

                labelNombre = tk.Label(self,
                 text = "Ha escrito " + entryNombre.get() +
                  " ¿es correcto?")

                labelNombre.pack()

                def Paso():

                    controller.show_frame("Consulta")

                def Tiempo():

                    timer = threading.Timer(3.0, Paso)

                    timer.start()

                    labelAcceso = tk.Label(self,
                     text = "Adelante, " + entryNombre.get())

                    labelAcceso.pack()

                botonSi = tk.Button(self, text = "Sí",
                 command = Tiempo)

                botonSi.pack()

                botonNo = tk.Button(self, text = "No",
                    command = lambda: controller.show_frame("RegistroError"))

                botonNo.pack()

        labelInstruction = tk.Label(self,
         text = "Para continuar introduzca su nombre")

        labelInstruction.pack()

        entryNombre = tk.Entry(self)

        entryNombre.pack()

        botonConfirmar = tk.Button(self, text = "Confirmar",
         command = Usuario)

        botonConfirmar.pack()

        labelError = tk.Label(self)

        labelError.pack()

class RegistroError(tk.Frame):

     def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        def Usuario():

            if entryNombre.get() == "":

                labelError.config(text = "No introdujo ningún nombre")

            else:

                labelError.config(text = "")

                labelNombre = tk.Label(self,
                 text = "Ha escrito " + entryNombre.get() +
                  " ¿es correcto?")

                labelNombre.pack()

                def Paso():

                    controller.show_frame("Consulta")

                def Tiempo():

                    timer = threading.Timer(2.0, Paso)

                    timer.start()

                    labelAcceso = tk.Label(self,
                     text = "Adelante, " + entryNombre.get())

                    labelAcceso.pack()

                botonSi = tk.Button(self, text = "Sí",
                 command = Tiempo)

                botonSi.pack()

                def Error():

                    labelNombre.config(text = "")

                    labelInstruction.config(text = "")

                    botonSi.config(state = "disabled")

                    botonNo.config(state = "disabled")

                    entryNombre.config(state = "disabled")

                    botonConfirmar.config(state = "disabled")

                    labelFin = tk.Label(self,
                        text = "Se han agotado las oportunidades. Inténtelo de nuevo")

                    labelFin.pack()

                    def Salir():

                        quit()

                    botonSalir = tk.Button(self, text = "Aceptar y Salir",
                        command = Salir)

                    botonSalir.pack()

                botonNo = tk.Button(self, text = "No" , command = Error)

                botonNo.pack()

        labelInstruction = tk.Label(self,
         text = "Para continuar introduzca su nombre")

        labelInstruction.pack()

        entryNombre = tk.Entry(self)

        entryNombre.pack()

        botonConfirmar = tk.Button(self, text = "Confirmar",
         command = Usuario)

        botonConfirmar.pack()

        labelError = tk.Label(self)

        labelError.pack()

class Consulta(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        self.controller = controller

        labelConsulta = tk.Label(self,
            text = "Ingrese el nombre de un producto, marca o tienda",
             padx = 30, pady = 15)

        labelConsulta.pack()

        entryConsulta = tk.Entry(self)

        entryConsulta.pack()

        def Call():

            miConexion = sqlite3.connect("Findex")

            miCursor = miConexion.cursor()

            query = entryConsulta.get()

            miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", query)

            table = miCursor.fetchall()

            textConsulta.insert(1.0, table)

            miConexion.commit()

        botonConsulta = tk.Button(self, text = "Buscar", command = Call)

        botonConsulta.pack()

        textConsulta = tk.Text(self, bd = 2)

        textConsulta.pack()

if __name__ == "__main__":

    app = SampleApp()

    app.mainloop()

And here's where I create the database:

    import sqlite3

miConexion = sqlite3.connect("Findex")

miCursor = miConexion.cursor()

miCursor.execute("""

    CREATE TABLE IF NOT EXISTS 'PRODUCTOS' (

    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    NOMBRE VARCHAR(50),
    MARCA VARCHAR(50),
    PESO INTEGER,
    UNIDAD VARCHAR(20),
    PRECIO INTEGER,
    CATEGORIA VARCHAR(50),
    ESTABLECIMIENTO VARCHAR(50))

    """)

datos = [

    ("Sirope", "Suli", 700, "mililitros", 300, "Bebidas", "Palí"),
    ("Azúcar", "Doña María", 2, "kilogramos", 1225, "Granos",  "Palí"),
    ("Arroz", "Indiana", 1800, "gramos", 1495, "Granos", "Palí"),
    ("Café", "Rey", 500, "gramos", 1525, "Bebidas", "Palí"),
    ("Frijoles", "Indiana", 900, "gramos", 1175, "Granos", "Palí"),
    ("Sal", "Sal Sol", 500, "gramos", 225, "Granos", "Palí"),
    ("Aceite", "Clover", 1.5, "litros", 675, "Aceite/Margarina/Mantequilla", "Palí"),
    ("Huevos", "Don Cristóbal", 500, "gramos", 1975, "Huevos", "Palí"),
    ("Cereal", "Jack's", 250, "gramos", 2100, "Cereales", "Palí"),
    ("Mantequilla", "Dos Pinos", 500, "gramos", 675, "Aceite/Margarina/Mantequilla", "Palí"),
    ("Leche", "Dos Pinos", 1, "litros", 504, "Lácteos", "Palí"),
    ("Fideos", "Roma", 200, "gramos", 485, "Pastas", "Palí"),
    ("Jabón", "Fort 3", 1, "kilogramos", 550, "Limpieza", "Palí"),
    ("Desinfectante", "Floral", 750, "mililitros", 550, "Limpieza", "Palí"),
    ("Crema dental", "Oral B", 53, "mililitros", 900, "Cuidado personal", "Palí"),
    ("Jabón de baño", "Protex", 110, "gramos", 505, "Cuidado personal", "Palí"),
    ("Galletas", "Pozuelo", 31.5, "gramos", 1400, "Snacks", "Palí"),
    ("Papel higiénico", "Nevax", 1000, "hojas", 2450, "Cuidado personal", "Palí"),
    ("Toallas", "Nevax", 100, "hojas", 1300, "Limpieza", "Palí"),
    ("Refresco", "Lio-Té", 100, "gramos", 240, "Bebidas", "Palí"),
    ("Leche", "Delactomy", 1000, "mililitros", 2795, "Lácteos", "Perimercados"),
    ("Jamón cocido", "Cinta Azul", 250, "gramos", 2285, "Embutidos", "Perimercados"),
    ("Salsa inglesa", "Banquete", 700, "gramos", 1950, "Salsas", "Perimercados"),
    ("Aceite", "Capullo", 900, "mililitros", 925, "Aceite/Margarina/Mantequilla", "Perimercados"),
    ("Detergente", "Xedex", 5000, "gramos", 7750, "Limpieza", "Perimercados"),
    ("Lavaplatos", "Axion", 850, "gramos", 1610, "Limpieza", "Perimercados"),
    ("Arroz", "Imperio", 1, "kilogramos", 1180, "Granos", "Perimercados"),
    ("Pasta tipo cabello ángel", "Roma", 250, "gramos", 645, "Pastas", "Perimercados"),
    ("Pan blanco", "Bimbo", 450, "gramos", 1285, "Panes", "Perimercados"),
    ("Frijoles molidos", "Ducal", 400, "gramos", 910, "Enlatados", "Perimercados"),
    ("Crema dental", "Colgate", 75, "mililitros", 1390, "Cuidado personal", "Perimercados"),
    ("Protectores diarios", "Saba", 60, "unidades", 1495, "Cuidado personal", "Perimercados"),
    ("Café", "1820", 340, "gramos", 2810, "Bebidas", "Perimercados"),
    ("Avena", "Quaker", 300, "gramos", 805, "Cereales", "Perimercados"),
    ("Yogurt", "Yoplait", 750, "gramos", 1610, "Lácteos", "Perimercados"),
    ("Tomate", "-", 1, "kilogramos", 1050, "Frutas", "Perimercados"),
    ("Uvas mixtas", "-", 500, "gramos", 2600, "Frutas", "Perimercados"),
    ("Muslo de pollo", "-", 1, "kilogramos", 2300, "Carnes", "Perimercados"),
    ("Chorizo", "-", 1, "kilogramos", 3020, "Carnes", "Perimercados"),
    ("Queso", "Zarcero", 1, "kilogramos", 4200, "Lácteos", "Perimercados"),
    ("Aceite", "Capullo", 900, "mililitros", 880, "Aceite/Margarina/Mantequilla", "Megasuper"),
    ("Café", "Rey Selecto", 500, "gramos", 1995, "Bebidas", "Megasuper"),
    ("Margarina", "Numar", 452, "gramos", 1045, "Aceite/Margarina/Mantequilla", "Megasuper"),
    ("Yogurt", "Coronado", 1000, "mililitros", 1675, "Lácteos", "Megasuper"),
    ("Galleta soda", "Gama", 192, "gramos", 470, "Snacks", "Megasuper"),
    ("Molida premium de res", "-", 1, "kilogramos", 5540, "Carnes", "Megasuper"),
    ("Queso Turrialba", "Dos Pinos", 1, "kilogramos", 4270, "Lácteos", "Megasuper"),
    ("Chile dulce", "-", 1, "unidades", 325, "Verduras", "Megasuper"),
    ("Sandía", "-", 1, "kilogramos", 595, "Frutas", "Megasuper"),
    ("Huevos", "-", 1, "kilogramos", 1650, "Huevos", "Megasuper"),
    ("Hongos rebanados", "Del Monte", 184, "gramos", 530, "Enlatados", "Megasuper"),
    ("Frijoles rojos", "Luisiana", 900, "gramos", 1095, "Granos", "Megasuper"),
    ("Papel higiénico", "Higienol", 4, "unidades", 1550, "Limpieza", "Megasuper"),
    ("Detergente en polvo", "Rinso", 5000, "gramos", 1650, "Limpieza", "Megasuper"),
    ("Alimento para perro", "Dog Chow", 4000, "gramos", 10640, "Mascotas", "Megasuper"),
    ("Chuleta de cerdo", "-", 1, "kilogramos", 3690, "Carnes", "Megasuper"),
    ("Cerveza", "Imperial", 350, "mililitros", 780, "Bebidas alcohólicas", "Megasuper"),
    ("Vino", "Clos", 750, "mililitros", 3320, "Bebidas alcohólicas", "Megasuper"),
    ("Posta de cerdo", "-", 1, "kilogramos", 3490, "Carnes", "Megasuper"),
    ("Toallas sanitarias", "Kotex", 12, "unidades", 1645, "Ciudades personal", "Megasuper"),
    ("Crema dental", "Colgate", 75, "mililitros", 1510, "Cuidado personal", "Freshmarket"),
    ("Frito Lay", "Tostitos", 283, "gramos", 2620, "Snacks", "Freshmarket"),
    ("Vino", "San Telmo", 750, "mililitros", 7915, "Bebidas alcohólicas", "Freshmarket"),
    ("Helado Trirts", "Dos Pinos", 540, "gramos", 2950, "Lácteos", "Freshmarket"),
    ("Repollo verde", "-", 1, "unidades", 695, "Verduras", "Freshmarket"),
    ("Néctar mixto fruta", "Dos Pinos", 1, "litros", 960, "Bebidas", "Freshmarket"),
    ("Pan baguette", "AMMM", 300, "gramos", 1000, "Panadería", "Freshmarket"),
    ("Sandía", "-", 1, "kilogramos", 850, "Frutas", "Freshmarket"),
    ("Tomate", "-", 1, "kilogramos", 1250, "Frutas", "Freshmarket"),
    ("Plátono verde", "-", 1, "unidades", 395, "Frutas", "Freshmarket"),
    ("Papa", "-", 1, "kilogramos", 1295, "Verduras", "Freshmarket"),
    ("Manga", "-", 1, "kilogramos", 1650, "Frutas", "Freshmarket"),
    ("Ron", "Flor de Caña", 750, "mililiros", 7000, "Bebidas alcohólicas", "Freshmarket"),
    ("Papas tostadas", "Lays", 184, "gramos", 1800, "Snacks", "Freshmarket"),
    ("Jugo de naranja", "Dos Pinos", 1.8, "litros", 2930, "Bebidas", "Freshmarket"),
    ("Sundae", "Dos Pinos", 110, "gramos", 1620, "Lácteos", "Freshmarket"),
    ("Bebida energética", "Gatorade", 600, "mililitros", 1460, "Bebidas", "Freshmarket"),
    ("Deligurt", "Dos Pinos", 200, "mililitros", 850, "Lácteos", "Freshmarket"),
    ("Gaseosa", "Coca Cola", 2, "litros", 2285, "Bebidas", "Freshmarket"),
    ("Papas tostadas", "Pringles", 125, "gramos", 2300, "Snacks", "Freshmarket"),
    ("Toalla nocturna", "Saba", 40, "unidades", 5575, "Cuidado personal", "AutoMercado"),
    ("Acondicionador para cabello", "Alea", 500, "mililitros", 4215, "Cuidado personal", "AutoMercado"),
    ("Shampoo con keratina", "Suave", 373, "mililitros", 4000, "Cuidado personal", "AutoMercado"),
    ("Atún en trozos", "Pronto", 640, "gramos", 7320, "Enlatados", "AutoMercado"),
    ("Café", "Rey", 400, "gramos", 3500, "Bebidas", "AutoMercado"),
    ("Frijoles molidos", "Ducal", 400, "gramos", 865, "Enlatados", "AutoMercado"),
    ("Mayonesa con aceite de oliva", "Alolivo", 400, "gramos", 1595, "Salsas", "AutoMercado"),
    ("Cereal integral", "Nestle", 450, "gramos", 2700, "Cereales", "AutoMercado"),
    ("Vino tinto", "Broquel", 750, "mililitros", 10785, "Bebidas alcohólicas", "AutoMercado"),
    ("Queso mozzarella", "Crystal Farms", 227, "gramos", 3250, "Lácteos", "AutoMercado"),
    ("Jamón de pavo", "Cinta Azul", 1, "kilogramos", 9925, "Embutidos", "AutoMercado"),
    ("Bistec de lomo", "AutoMercado", 1, "kilogramos", 14170, "Carnes", "AutoMercado"),
    ("Chicharrones ahumados", "Jack's", 75, "gramos", 1400, "Carnes", "AutoMercado"),
    ("Maní con miel", "The Carolina Nut Co", 340, "gramos", 3100, "Snacks", "AutoMercado"),
    ("Limón ácido", "-", 15, "unidades", 3800, "Frutas", "AutoMercado"),
    ("Filet de pechuga", "AutoMercado", 1, "kilogramos", 7875, "Carnes", "AutoMercado"),
    ("Cerveza amarga", "Warsteiner", 500, "mililitros", 1395, "Bebidas alcohólicas", "AutoMercado"),
    ("Crema croporal", "Bilka", 180, "mililitros", 10265, "Cuidado Personal", "AutoMercado"),
    ("Tinte para cabello", "Koleston", 1, "unidades", 5915, "Cuidado Personal", "AutoMercado"),
    ("Toallitas desmaquillantes", "Asepxia", 25, "unidades", 5445, "Cuidado Personal", "AutoMercado")

    ]

miCursor.executemany("INSERT INTO PRODUCTOS VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)", datos)

miConexion.commit()

miConexion.close()

I expect write the name, mark or shop of a product and insert all the information about the products that match with the entry in the text field, but it gives me 'OperationalError' or 'sqlite3.ProgrammingError'.

Body:
I think the problem is here

query = entryConsulta.get()
miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", query)

your statment accept 3 args but you pass only one

try so

query = entryConsulta.get()
args = (query,query,query)
miCursor.execute("SELECT * FROM PRODUCTOS WHERE NOMBRE = ? OR MARCA = ? OR ESTABLECIMIENTO = ?", args)

anyway I think that you have to decoupling your code between more modules, if you are interested on this type of program I would suggest you this my
didactic work on github

https://github.com/1966bc/Tkinterlite

Hasta luego;)


来源: stackexchange

问:
Test out parameters with Nunit in a single statement
Is it possible to test the return value and out parametes with the same assert?
Im looking for something like this:

```<code>Assert.That(int.TryParse("1", out var number), Is.True.And(// check for number == 1));
</code>```

答:
You can try

```<code>Assert.IsTrue(int.TryParse("1", out var number) && number == 1);
</code>```

POC: .net fiddle

** without Assert, just to check condition

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to test the return value and out parametes with the same assert?
Im looking for something like this:

Assert.That(int.TryParse("1", out var number), Is.True.And(// check for number == 1));

Body:
You can try

Assert.IsTrue(int.TryParse("1", out var number) && number == 1);

POC: .net fiddle

** without Assert, just to check condition


问:
Dynamically add html on click on a amp webpage
Is it possible to dynamically add HTML to a webpage on click when using AMP?

Something along the lines of the

```<code><button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp-
bind"</button>

<div [text]="foo">This is the placeholder to append the new
content</div>
</code>```

But rather than text HTML?

答:
What you need can be achieved using amp-script.

https://github.com/ampproject/amphtml/blob/master/extensions/amp-script/amp-script.md

From github:

```<code><!-- hello-world.html -->
<amp-script layout="container" src="https://example.com/hello-world.js">
  <button id="hello">Insert Hello World!</button>
</amp-script>

// hello-world.js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
  const el = document.createElement('h1');
  el.textContent = 'Hello World!';
  // `document.body` is effectively the <amp-script> element.
  document.body.appendChild(el);
});
</code>```

Body:
Is it possible to dynamically add HTML to a webpage on click when using AMP?

Something along the lines of the

<button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp-
bind"</button>

This is the placeholder to append the new
content

But rather than text HTML?

Body:
What you need can be achieved using amp-script.

https://github.com/ampproject/amphtml/blob/master/extensions/amp-script/amp-script.md

From github:

<!-- hello-world.html -->
<amp-script layout="container" src="https://example.com/hello-world.js">
  <button id="hello">Insert Hello World!</button>
</amp-script>

// hello-world.js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
  const el = document.createElement('h1');
  el.textContent = 'Hello World!';
  // `document.body` is effectively the <amp-script> element.
  document.body.appendChild(el);
});


问:
ProjectName.iOS Could not register the assembly 'OpenTK-1.0'
I am pretty new in the Xamarin world and I need some help starting the iOS simulator on iPhone X (12.2) or whatever iPhone version.
For example, when I try to start iPhone X (12.2) simulator and start debugging, I get the following error:

ProjectName.iOS[7769:94324] Could not register the assembly 'OpenTK-1.0': System.TypeLoadException: Could not resolve type with token 01000010 from typeref (expected class 'ObjCRuntime.DeprecatedAttribute' in assembly 'Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065')

...

Unhandled Exception:

System.ArgumentOutOfRangeException: Token 0x2001513 is not valid in the scope of module Xamarin.iOS.dll
Parameter name: metadataToken

I only started to get this error after I have updated my Mac Mini to 10.14.5 Mojave and updated Xcode to 10.2.1 I have updated Mono on both windows and mac. I have made this update in order to be able to debug on my iPhone which updated to 12.3
The thing is that I can debug on my iPhone 6S with no problem, but when I try to debug on the iPhone simulator, that error pops out.

Currently I am using Visual Studio Professional 15.9.12 (latest version at this time).

Any thoughts?
Thanks!

答: I have updated my Xamarin Forms, I used version 3.6, I have updated it to version 4.0 and ran a clean and rebuild, the problem solved by itself. I am not sure what exactly caused the problem, but this update seems to have fixed the problem for me.</p>


问:
Trying to fill an array when a submit button is clicked
I've created a timer which has a submit button. This submit button only populates one slot of an array, it doesn't sequentially populate each slot on each click.

Currently I have it set up using a .push within the submit button function. This is where I think I'm going wrong.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

const ms = require('pretty-ms');

class Timer extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      time: 0,
      start: 0,
      isOn: false,

    }
    this.onItemMouseDown = this.onItemMouseDown.bind(this);
    this.onItemMouseUp = this.onItemMouseUp.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onItemMouseDown() {
    this.setState({
      time: this.state.time,
      start: Date.now() - this.state.time,
      isOn: true
    })

    //the below uses a predefined function setInterval with a nested arrow function setting the state again
    // which is time. More detail: It compares the time to the current date and time for accuracy. The interval is 1.
    this.timer = setInterval(() => this.setState({
      time: Date.now() - this.state.start
    }), 1);

  }

  onItemMouseUp() {
    this.setState({isOn: false});
    clearInterval(this.timer);
  }

  resetTimer() {
    this.setState({time: 0})
  }

  onSubmit() {
    const scoreArray = [];

    scoreArray.push(ms(this.state.time))

    console.log(scoreArray)

  }

  render() {

    if((this.state.isOn) === true){
    return(
      <React.Fragment>
      <div>
        <h3>timer: {ms(this.state.time)} </h3>

      </div>
    <div>
      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp} >start</button>

      <button onClick={this.resetTimer}>reset</button>

      </div>

      </React.Fragment>
    )
    } else {

      return(
        <React.Fragment>
      <div>
        <h3>Your time is: {ms(this.state.time)}</h3>
      </div>
      <div>
      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp}>Start</button>  <span></span>

      <button onClick={this.resetTimer}>Reset</button> <span></span>

      <button onClick={this.onSubmit}>Done!</button>
      </div>
      </React.Fragment>
      )
    }
  }

}

export default Timer

  const rootElement = document.getElementById("root");
ReactDOM.render(<Timer />, rootElement);

</code>```

The submit button should then populate each array slot with a time value on each click.
I tend to overthink things. Is there a better alternative?
My ultimate goal is to populate the array and then (for educational purposes) display that array in JSX as a score/time list.

答:
The scoreArray data does not persist in your component. As currently constructed you are just reinitializing the array every time you call onSubmit. You can store it as a state-value instead.

In your state-definition

```<code>this.state = {
  time: 0,
  start: 0,
  isOn: false,
  scoreArray: []
}
</code>```

In onSubmit()

```<code>  onSubmit() {
    const { scoreArray } = this.state;

    this.setState({
       ...this.state,
       scoreArray: [...scoreArray, (ms(this.state.time))]
    } () => console.log(this.state.scoreArray))
  }
</code>```

Body:
I've created a timer which has a submit button. This submit button only populates one slot of an array, it doesn't sequentially populate each slot on each click.

Currently I have it set up using a .push within the submit button function. This is where I think I'm going wrong.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

const ms = require('pretty-ms');

class Timer extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      time: 0,
      start: 0,
      isOn: false,

    }
    this.onItemMouseDown = this.onItemMouseDown.bind(this);
    this.onItemMouseUp = this.onItemMouseUp.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onItemMouseDown() {
    this.setState({
      time: this.state.time,
      start: Date.now() - this.state.time,
      isOn: true
    })

    //the below uses a predefined function setInterval with a nested arrow function setting the state again
    // which is time. More detail: It compares the time to the current date and time for accuracy. The interval is 1.
    this.timer = setInterval(() => this.setState({
      time: Date.now() - this.state.start
    }), 1);

  }

  onItemMouseUp() {
    this.setState({isOn: false});
    clearInterval(this.timer);
  }

  resetTimer() {
    this.setState({time: 0})
  }

  onSubmit() {
    const scoreArray = [];

    scoreArray.push(ms(this.state.time))

    console.log(scoreArray)

  }

  render() {

    if((this.state.isOn) === true){
    return(
      <React.Fragment>

timer: {ms(this.state.time)}

      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp} >start</button>

      <button onClick={this.resetTimer}>reset</button>

      </React.Fragment>
    )
    } else {

      return(
        <React.Fragment>

Your time is: {ms(this.state.time)}

      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp}>Start</button>

      <button onClick={this.resetTimer}>Reset</button>

      <button onClick={this.onSubmit}>Done!</button>

      </React.Fragment>
      )
    }
  }

}

export default Timer

  const rootElement = document.getElementById("root");
ReactDOM.render(<Timer />, rootElement);

The submit button should then populate each array slot with a time value on each click.
I tend to overthink things. Is there a better alternative?
My ultimate goal is to populate the array and then (for educational purposes) display that array in JSX as a score/time list.

Body:
The scoreArray data does not persist in your component. As currently constructed you are just reinitializing the array every time you call onSubmit. You can store it as a state-value instead.

In your state-definition

this.state = {
  time: 0,
  start: 0,
  isOn: false,
  scoreArray: []
}

In onSubmit()

  onSubmit() {
    const { scoreArray } = this.state;

    this.setState({
       ...this.state,
       scoreArray: [...scoreArray, (ms(this.state.time))]
    } () => console.log(this.state.scoreArray))
  }


问:
Dependency injection @ Runtime
I have a controller that looks simplyfied as below.
I want to use Dependency injection for all my DataServices.

In the database I have several datawarehouses for each Client.
Is it possible to inject my DatawareHouseService without creating a new instance @runtime?
I first need to call the MainService to get the correct connectionstring.

```<code>    protected internal IMainService mainService;
    public EventController(ITeamleaderMainService MainService)
   {
        this.mainService = MainService;
   }
    public async Task<HttpResponseMessage> Post([FromBody]JObject Value)
   {
    var companySettings = await mainService .GetCompanySettingsByGroup(Value["Account_Id"].ToObject<int>());

    using (DataWareHouseService dwSService = new DataWareHouseService(companySettings.EntityConnectionstring()))
    {
       //Do some stuff

    }
   }
</code>```

答:
You can register and inject factory delegate Func<string, DataWareHouseService>. Here you can see an example.

```<code>using (var dwSService = _dwhClientFactory.Invoke(companySettings.EntityConnectionstring()))
{
   //Do some stuff
}
</code>```

If you want to have single instance per client you can create DwhClientResolver class which could be like this:

```<code>public class DwhClientResolver : IDwhClientResolver
{
    private readonly ConcurrentDictionary<string, Lazy<DataWareHouseService>> _instances =
        new ConcurrentDictionary<string, Lazy<DataWareHouseService>>();

    public DataWareHouseService GetClient(string connStr) =>
        _instances.GetOrAdd(connStr, x => new Lazy<DataWareHouseService>(() => new DataWareHouseService(x))).Value;
}

public interface IDwhClientResolver
{
    DataWareHouseService GetClient(string connStr);
}
</code>```

, register it as a singleton and inject IDwhClientResolver in all places where you need DataWareHouseService.

Also you can check keyed-services approach but usage of DwhClientResolver is simpler.

Title: Dependency injection @ Runtime

Body:
I have a controller that looks simplyfied as below.
I want to use Dependency injection for all my DataServices.

In the database I have several datawarehouses for each Client.
Is it possible to inject my DatawareHouseService without creating a new instance @runtime?
I first need to call the MainService to get the correct connectionstring.

    protected internal IMainService mainService;
    public EventController(ITeamleaderMainService MainService)
   {
        this.mainService = MainService;
   }
    public async Task<HttpResponseMessage> Post([FromBody]JObject Value)
   {
    var companySettings = await mainService .GetCompanySettingsByGroup(Value["Account_Id"].ToObject<int>());

    using (DataWareHouseService dwSService = new DataWareHouseService(companySettings.EntityConnectionstring()))
    {
       //Do some stuff

    }
   }

Body:
You can register and inject factory delegate Func<string, DataWareHouseService>. Here you can see an example.

using (var dwSService = _dwhClientFactory.Invoke(companySettings.EntityConnectionstring()))
{
   //Do some stuff
}

If you want to have single instance per client you can create DwhClientResolver class which could be like this:

public class DwhClientResolver : IDwhClientResolver
{
    private readonly ConcurrentDictionary<string, Lazy<DataWareHouseService>> _instances =
        new ConcurrentDictionary<string, Lazy<DataWareHouseService>>();

    public DataWareHouseService GetClient(string connStr) =>
        _instances.GetOrAdd(connStr, x => new Lazy<DataWareHouseService>(() => new DataWareHouseService(x))).Value;
}

public interface IDwhClientResolver
{
    DataWareHouseService GetClient(string connStr);
}

, register it as a singleton and inject IDwhClientResolver in all places where you need DataWareHouseService.

Also you can check keyed-services approach but usage of DwhClientResolver is simpler.


问:
Write a function that returns the square of a number without using *,+ or pow
The task is to write a function that takes n as an input where n is a number (from -32768 to 32768) and returns the square of that number. Simple task except for the fact that we cannot use any operators such as *,+ or even use any Math. functions such as pow. eval is not allowed as well.
Even more challenging is that we must keep the character code count less than 39 characters.

I absolutely cannot think of a way to get the square of a number without using the + or *. And even worse, to keep the character count less, it's impossible for me.

Codes like this won't work because: I used the plus sign and the character count is more than 60.

```<code>function sq(n){
   var res=n;
   for(i=1;i<n;i++)
   res+=n;
return res;
}
</code>```

If n is a decimal, we are expected to return the nearest whole number as the result.
Thank you for reading all of this!

Edit: My problem has been solved. Thank you to everyone who has tried to help me with their codes as it helped me gain a new aspect of solving each problems.
Thank you very much again!

答:
** is not in your list, so you might be able to use it:

sq = n => n ** 2

console.log(sq(5));```
</div>
</div>
</p>

<p>You could also use <code>-</code> twice, instead of <code>+</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>sq=n=>{s=0;for(let i=n;i>0;i--)s=s-(-n);return s}

console.log(sq(5));</code>```

(function definition is 49 characters)

Body:
The task is to write a function that takes n as an input where n is a number (from -32768 to 32768) and returns the square of that number. Simple task except for the fact that we cannot use any operators such as *,+ or even use any Math. functions such as pow. eval is not allowed as well.
Even more challenging is that we must keep the character code count less than 39 characters.

I absolutely cannot think of a way to get the square of a number without using the + or *. And even worse, to keep the character count less, it's impossible for me.

Codes like this won't work because: I used the plus sign and the character count is more than 60.

function sq(n){
   var res=n;
   for(i=1;i<n;i++)
   res+=n;
return res;
}

If n is a decimal, we are expected to return the nearest whole number as the result.
Thank you for reading all of this!

Edit: My problem has been solved. Thank you to everyone who has tried to help me with their codes as it helped me gain a new aspect of solving each problems.
Thank you very much again!

Body:
** is not in your list, so you might be able to use it:

sq = n => n ** 2

console.log(sq(5));

You could also use - twice, instead of +:

sq=n=>{s=0;for(let i=n;i>0;i--)s=s-(-n);return s}

console.log(sq(5));

(function definition is 49 characters)


问:
sending commands from excel file to a c# program
I have a program that reads Data from Excel and write data to Excel file. I need to send commands from the Excel file to the c# program (e.g. capture the F9 from the excel and get it on the c# program)

I am using Microsoft.Office.Interop.Excel framework.

How can i do it?>

答:
oferyo,

Hello. You don't mention what sorts of volume of data you need to deal with? Or the type, either (questions like: does the stuff 'sent' to the destination Excel file includes graphs or just data?).

You don't mention which version of C# you are using but you could consider calling a web service from the VBA script embedded in or added to the originating Excel spreadsheet?

MSDN article on calling WebServices from within VBA

I can't recall how to plumb VBA code into specific events on the Excel spreadsheet (like the recalculate/press of F9) but I think that should be trivial.

If you are using C# 3.5 or later you can host a WCF service within the application ... but I would suggest describing the question better because it may be the VBA->WCF/WebService->Application solution might be seriously over-engineered?

Hope this helps you think about the options you have within VBA ...

regards,

Aidanapword

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Finding the sum of minimum distance from the points in one list to points in other list?
I have two lists containing x and y number of n-dimensional points respectively. I had to calculate the sum of minimum distances of each point in list one (containing x points) from each point in second list (containing y points). The distance I am calculating is Euclidean distance. The optimized solution is needed.

I have already implemented its naive solution in Python. But its time complexity is too much to be used anywhere. There will be optimization possible. Can this problems time complexity be reduced than what I have implemented?

I was reading thispaper which I was trying to implement. In this they were having the similar problem to which they stated that it's special condition of Earth Mover Distance. As there was no code given, hence unable to know how it got implemented. Thus my naive implementation, the above code was too slow to work on data set of 11k documents. I used Google Colab for executing my code.

# Calculating Euclidean distance between two points
def euclidean_dist(x,y):
  dd = 0.0
  #len(x) is number of dimensions. Basically x and y is a
  #list which contains coordinates of a point
  for i in range(len(x)):
    dd = dd+(x[i]-y[i])**2
  return dd**(1/2)

# Calculating the desired solution to our problem
def dist(l1,l2):
  min_dd = 0.0
  dd = euclidean_dist(l1[0],l2[0])
  for j in range(len(l1)):
    for k in range(len(l2)):
      temp = euclidean_dist(l1[j],l2[k])
      if dd > temp:
        dd = temp
    min_dd = min_dd+dd
    dd = euclidean_dist(l1[j],l2[0])
  return min_dd
```

答:
To reduce runtime, I would suggest finding manhattan distances (delta x + delta y), sorting the resulting array for each point and then creating a buffer of +20% of lowest manhattan distance, if values in the sorted list are in that range of +20%, you can  compute euclidean distances and find the correct/minimum euclidean answer.

This will reduce some time, but the 20% figure might not reduce time if the points are all close together as most of them will fit in the buffer region, try fine-tuning the 20% parameter to see what works best for your dataset. Keep in mind reducing it too much might lead to inaccurate answers due to the nature of euclidean vs. manhattan distances.


问:
Trying to build server side datatable from pdo query
I have to build a data table from server side because I have more than 200k rows, and I don't have the choice I need to make it from an execute statement like:

```<code>$result['draw']=1;
$temp = BD::query('SELECT * FROM `ersmessages` WHERE 1 LIMIT 10');
$result['recordsTotal'] = sizeof($temp);
$result['recordsFiltered'] = sizeof($temp);
$result['data'] = $temp;
</code>```

But when I'm doing this that does not page my results and for 200k rows it's giving an error. If I limit the query that works but on one page.

My JS looks like:

```<code> $('#tableAllMessages').DataTable( {
        "processing": true,
        "serverSide": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": "req/getAllMessages.php"
    } );
</code>```

How should I proceed to have a paged data table with 200k rows? I can't obviously use the ssp.

答:
ok the problem has been solved, i needed to put the recordsTotal to my maximum(200k rows)  size and i needed to add an offset to the query, that way i am able to paginate my table. </p>

```<code>$offset = $_REQUEST['start'];
$result['recordsTotal'] = 200000;
$query = BD::query('SELECT * FROM `ersmessages` WHERE 1 ORDER BY `idERSMessage` ASC LIMIT 10 OFFSET '.intval($offset))
$result['data'] = $query;
$result['draw']=$_REQUEST['draw'];
</code>```

Body:
I have to build a data table from server side because I have more than 200k rows, and I don't have the choice I need to make it from an execute statement like:

$result['draw']=1;
$temp = BD::query('SELECT * FROM `ersmessages` WHERE 1 LIMIT 10');
$result['recordsTotal'] = sizeof($temp);
$result['recordsFiltered'] = sizeof($temp);
$result['data'] = $temp;

But when I'm doing this that does not page my results and for 200k rows it's giving an error. If I limit the query that works but on one page.

My JS looks like:

 $('#tableAllMessages').DataTable( {
        "processing": true,
        "serverSide": true,
        "paging": true,
        "searching": { "regex": true },
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
        "pageLength": 10,
        "ajax": "req/getAllMessages.php"
    } );

How should I proceed to have a paged data table with 200k rows? I can't obviously use the ssp.

Body:
ok the problem has been solved, i needed to put the recordsTotal to my maximum(200k rows)  size and i needed to add an offset to the query, that way i am able to paginate my table.

$offset = $_REQUEST['start'];
$result['recordsTotal'] = 200000;
$query = BD::query('SELECT * FROM `ersmessages` WHERE 1 ORDER BY `idERSMessage` ASC LIMIT 10 OFFSET '.intval($offset))
$result['data'] = $query;
$result['draw']=$_REQUEST['draw'];


问:
what is shortest way to export what's in a tree view to an excel file
I have a treeView witch has a lot of data I want to export this data to excel file.
I want the simplest way to do this.

I have an idea witch is to convert whats in tree view to data frame then save the data frame as excel file.
but I don't know if it's good idea or not ?!

```<code>from tkinter import filedialog
import pandas as pd
from collections import defaultdict

file = filedialog.asksaveasfilename(title="Select file","nameOfFile.xlsx",filetypes=[("Excel file", "*.xlsx")])
if file:
    ids=tree.get_children()
    dict = defaultdict(list)
    for id in ids:
        date=dt.datetime.strptime(tree.set(id, "#13"), '%Y-%m-%d %H:%M:%S')
        dateChosed=dt.datetime.strptime(monthToExport.get(), "%B-%Y")
        if (date.year == dateChosed.year) and (date.month == dateChosed.month):
            dict["1"].append(tree.item(id)["text"])
            dict["2"].append(tree.item(id)["values"][0])

    dict = pd.DataFrame.from_dict(dict)
    try:
        dict.to_excel(file, engine='xlsxwriter',index= False)
    except:
        print("Close the file than retry")
else:
    print("You did not save the file")
</code>```

答:
```<code>from tkinter import filedialog
import pandas as pd
from collections import defaultdict

file = filedialog.asksaveasfilename(title="Select file","nameOfFile.xlsx",filetypes[("Excel file", "*.xlsx")])
if file:
    ids=tree.get_children()
    dict = defaultdict(list)
    for id in ids:
        date=dt.datetime.strptime(tree.set(id, "#13"), '%Y-%m-%d %H:%M:%S')
        dateChosed=dt.datetime.strptime(monthToExport.get(), "%B-%Y")
        if (date.year == dateChosed.year) and (date.month == dateChosed.month):
            dict["1"].append(tree.item(id)["text"])
            dict["2"].append(tree.item(id)["values"][0])

    dict = pd.DataFrame.from_dict(dict)
    try:
       dict.to_excel(file, engine='xlsxwriter',index= False)
    except:
       print("Close the file than retry")
else:
print("You did not save the file")
</code>```

Body:
I have a treeView witch has a lot of data I want to export this data to excel file.
I want the simplest way to do this.

I have an idea witch is to convert whats in tree view to data frame then save the data frame as excel file.
but I don't know if it's good idea or not ?!

from tkinter import filedialog
import pandas as pd
from collections import defaultdict

file = filedialog.asksaveasfilename(title="Select file","nameOfFile.xlsx",filetypes=[("Excel file", "*.xlsx")])
if file:
    ids=tree.get_children()
    dict = defaultdict(list)
    for id in ids:
        date=dt.datetime.strptime(tree.set(id, "#13"), '%Y-%m-%d %H:%M:%S')
        dateChosed=dt.datetime.strptime(monthToExport.get(), "%B-%Y")
        if (date.year == dateChosed.year) and (date.month == dateChosed.month):
            dict["1"].append(tree.item(id)["text"])
            dict["2"].append(tree.item(id)["values"][0])

    dict = pd.DataFrame.from_dict(dict)
    try:
        dict.to_excel(file, engine='xlsxwriter',index= False)
    except:
        print("Close the file than retry")
else:
    print("You did not save the file")


问:
PHP String Manipulation: Extract hrefs
I have a string of HTML that I would like to check to see if there are any links inside of it and, if so, extract them and put them in an array. I can do this in jQuery with the simplicity of its selectors but I cannot find the right methods to use in PHP.

For example, the string may look like this:

```<code><h1>Doctors</h1>
<a title="C - G" href="linkl.html">C - G</a>
<a title="G - K" href="link2.html">G - K</a>
<a title="K - M" href="link3.html">K - M</a>
</code>```

How (in PHP) can i turn it into an array that looks something like:

```<code>[1]=>"link1.html"
[2]=>"link2.html"
[3]=>"link3.html"
</code>```

Thanks,
Ian

答:
One line solution </p>

```<code>$href = (string)( new SimpleXMLElement($your_html_tag))['href'];
</code>```

Title: PHP String Manipulation: Extract hrefs

Body:
I have a string of HTML that I would like to check to see if there are any links inside of it and, if so, extract them and put them in an array. I can do this in jQuery with the simplicity of its selectors but I cannot find the right methods to use in PHP.

For example, the string may look like this:

Doctors

C - G
G - K
K - M

How (in PHP) can i turn it into an array that looks something like:

[1]=>"link1.html"
[2]=>"link2.html"
[3]=>"link3.html"

Thanks,
Ian

Body:
One line solution

$href = (string)( new SimpleXMLElement($your_html_tag))['href'];


问:
Objective-C retain question
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

```<code>scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];
</code>```

and:

```<code>- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}
</code>```

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom

答:
Previous answers are correct: don't use -retainCount, and make sure that you call [super dealloc] last in your own -dealloc implementation.

I want to add that you'll probably never see a case (not that you should be looking) where -retainCount returns 0. If an object's retainCount drops to zero, the object is deallocated. In fact, it seems that Cocoa never even bothers to set the retainCount to zero... -release appears to deallocate the object if the previous retainCount was 1. Just one more reason to consider -retainCount to be a private implementation detail.

Title: Objective-C retain question

Body:
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];

and:

- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom


问:
Display r Shiny actionButton Title in mouseover popup
I have done research on how to display actionButton title when mouseover. I understand javascript, but not sure how to fix this issue.

On mouseover, I want the Title of Button to be displayed not the html code itself.  I will appreciate any help or ideas to solve this. Below is POC code:

```<code>library(shiny)
library(DT)
library(dplyr)

shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("table")
  ),
  server = function(input, output) {

  # create a summary table
    summary_iris <- group_by(iris, Species) %>%
      summarise(Count = n())

    summary_iris$Species <- levels(summary_iris$Species)

    shinyInput <- function(FUN, len, id, label, ...) {
      inputs <- character(len)

      for (i in seq_len(len)) {
        label <- summary_iris$Species[i]
        inputs[i] <- as.character(FUN(paste0(id, i),label=label, ...))
      }
      inputs
    }

    output$table <- DT::renderDataTable({
      DT <- summary_iris %>%
        mutate(Species = shinyInput(actionButton,
                                    nrow(summary_iris), 'button_', label = Species, class="bttn-unite",
                                    onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'))
      DT::datatable(DT, rownames = FALSE, escape = FALSE,
                    options = list(rowCallback = JS(
                      "function(row, data) {",
                      "var full_text = data[0]",
                      "$('td:eq(0)', row).attr('title', full_text);",
                      "}")))
    })
  }
)
</code>```

Again, thank you in advance for your help, pointers, or examples I missed during my research.

How do I make the button look like Unite Button on this site? This is not important, but I was struggling with that too.

答:
You can use a regular expression to extract the text:

```<code>rowCallback = JS(
  "function(row, data) {",
  "  var r = />(.*)</;",
  "  var full_text = r.exec(data[0])[1]",
  "  $('td:eq(0)', row).attr('title', full_text);",
  "}")
</code>```

Or you can turn the string into a HTML object with jQuery, and then extract the text:

```<code>rowCallback = JS(
  "function(row, data) {",
  "  var full_text = $(data[0]).text();",
  "  $('td:eq(0)', row).attr('title', full_text);",
  "}")
</code>```

Body:
I have done research on how to display actionButton title when mouseover. I understand javascript, but not sure how to fix this issue.

On mouseover, I want the Title of Button to be displayed not the html code itself.  I will appreciate any help or ideas to solve this. Below is POC code:

library(shiny)
library(DT)
library(dplyr)

shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("table")
  ),
  server = function(input, output) {

  # create a summary table
    summary_iris <- group_by(iris, Species) %>%
      summarise(Count = n())

    summary_iris$Species <- levels(summary_iris$Species)

    shinyInput <- function(FUN, len, id, label, ...) {
      inputs <- character(len)

      for (i in seq_len(len)) {
        label <- summary_iris$Species[i]
        inputs[i] <- as.character(FUN(paste0(id, i),label=label, ...))
      }
      inputs
    }

    output$table <- DT::renderDataTable({
      DT <- summary_iris %>%
        mutate(Species = shinyInput(actionButton,
                                    nrow(summary_iris), 'button_', label = Species, class="bttn-unite",
                                    onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'))
      DT::datatable(DT, rownames = FALSE, escape = FALSE,
                    options = list(rowCallback = JS(
                      "function(row, data) {",
                      "var full_text = data[0]",
                      "$('td:eq(0)', row).attr('title', full_text);",
                      "}")))
    })
  }
)

Again, thank you in advance for your help, pointers, or examples I missed during my research.

How do I make the button look like Unite Button on this site? This is not important, but I was struggling with that too.

Body:
You can use a regular expression to extract the text:

rowCallback = JS(
  "function(row, data) {",
  "  var r = />(.*)</;",
  "  var full_text = r.exec(data[0])[1]",
  "  $('td:eq(0)', row).attr('title', full_text);",
  "}")

Or you can turn the string into a HTML object with jQuery, and then extract the text:

rowCallback = JS(
  "function(row, data) {",
  "  var full_text = $(data[0]).text();",
  "  $('td:eq(0)', row).attr('title', full_text);",
  "}")


问:
How to send WebSocketSubject messages only from client to server?
I created an observable for my websocket connection using WebSocketSubject from rxjs. So far so good the server-client communication is working. Now the thing is: I can't distinguish between the origins of the message in my client. I send messages by calling next() on the subject. All subscriptions on the client get those messages too. How can I send messages only to the server instead?

The implementation mainly stems from this article: https://medium.com/factory-mind/angular-websocket-node-31f421c753ff

My code:

```<code>socket$: WebSocketSubject<any>;

constructor() {
  this.socket$ = WebSocketSubject.create(SOCKET_URL);

  this.socket$.subscribe(
    (message) => console.log('<-- ' + message),
    (err) => console.error('Error on WebSocket:', err),
    () => console.warn('Completed!')
   );
}

send(message: SocketMessage) {
  const tmp: any = {};
  tmp.type = message.type;
  tmp.payload = message.payload;
  // This will be received by the server but also by client subscriptions = bad
  this.socket$.next(JSON.stringify(tmp));
}
</code>```

答:
I found a solution trying to have your described behavior :

RxJS6's WebSocket's documentation states that

Calling next does not affect subscribers of WebSocketSubject - they have no information that something was sent to the server (unless of course the server responds somehow to a message).

Thus, by using RxJS 6 instead of RxJS 5 you should not have the described behavior.

Body:
I created an observable for my websocket connection using WebSocketSubject from rxjs. So far so good the server-client communication is working. Now the thing is: I can't distinguish between the origins of the message in my client. I send messages by calling next() on the subject. All subscriptions on the client get those messages too. How can I send messages only to the server instead?

The implementation mainly stems from this article: https://medium.com/factory-mind/angular-websocket-node-31f421c753ff

My code:

socket$: WebSocketSubject<any>;

constructor() {
  this.socket$ = WebSocketSubject.create(SOCKET_URL);

  this.socket$.subscribe(
    (message) => console.log('<-- ' + message),
    (err) => console.error('Error on WebSocket:', err),
    () => console.warn('Completed!')
   );
}

send(message: SocketMessage) {
  const tmp: any = {};
  tmp.type = message.type;
  tmp.payload = message.payload;
  // This will be received by the server but also by client subscriptions = bad
  this.socket$.next(JSON.stringify(tmp));
}


问:
Azure DevOps - Change Reason
With an inherited process with - we cannot modify Reason or Root Cause picklist values?  How can this actually be used by a professional organization if we cannot customize it to fit our process?

https://learn.microsoft.com/en-us/azure/devops/organizations/settings/work/customize-process-workflow?view=azure-devops

答: The picklist values of Reason for the default states are not able to be modified. You could try to add a custom State or a custom work item type, the Reason can be modified when you use custom States or custom work item types.

Title: Azure DevOps - Change Reason


问:
Search by a parameter on a database using spring
I have this two id's, ID_A and ID_B.

What I want to do is to do a search based on this two id but the user doesnt need two input the two of them.

For example, I have two input boxes for the user to input ID_A and ID_B.

When searching the object with the ID_A, i want my query to ignore my ID_B (make it default-NOT NULL). On a database is possible to do that with the wild card '%' but I dont know how to do that in spring. Both of the ID's are BigDecimals.

I tried to do

```<code>if(ID_A==null)
substituteParmeter(ID_A)
</code>```

The substitute parameter method changes the current value of a certain parameter to a wildcard '%'.However when doing this query:

```<code>Select t from Table t where t.ID_A like :id_a and t.ID_B like :id_b
</code>```

If the id_a or id_b is '%', the program caught the error that found a '%' and its supposed to be a bigDecimal.

How can I go arround the error?

Thanks.

答:
You can use the query like:

```<code>Select t from Table t where :id_a  is null or t.ID_A  like :id_a and  :id_b is null or t.ID_B like :id_b
</code>```

Hope this is useful for you.

Body:
I have this two id's, ID_A and ID_B.

What I want to do is to do a search based on this two id but the user doesnt need two input the two of them.

For example, I have two input boxes for the user to input ID_A and ID_B.

When searching the object with the ID_A, i want my query to ignore my ID_B (make it default-NOT NULL). On a database is possible to do that with the wild card '%' but I dont know how to do that in spring. Both of the ID's are BigDecimals.

I tried to do

if(ID_A==null)
substituteParmeter(ID_A)

The substitute parameter method changes the current value of a certain parameter to a wildcard '%'.However when doing this query:

Select t from Table t where t.ID_A like :id_a and t.ID_B like :id_b

If the id_a or id_b is '%', the program caught the error that found a '%' and its supposed to be a bigDecimal.

How can I go arround the error?

Thanks.

Body:
You can use the query like:

Select t from Table t where :id_a  is null or t.ID_A  like :id_a and  :id_b is null or t.ID_B like :id_b

Hope this is useful for you.


问:
VirtualKey detect when is held down
I am trying to get when you press the key that it continuous movement when a key is held down. But when press it move once and wait a second before it continues. I am using:

```<code>Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDownAsync;
</code>```

and to get check in the method:

```<code>args.VirtualKey == Windows.System.VirtualKey.S;
</code>```

Is there a way that it does not pause for that second, I just want to continues as long that key is held down.

答:
You cannot influence the speed by which the system reports the KeyDown event here, but you can subscribe to the KeyUp even too, and assume that key is pressed between the first time it is reported by KeyDown until a corresponding KeyUp occurs -

```<code>Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
</code>```

And the methods:

```<code>private void CoreWindow_KeyDown(
   Windows.UI.Core.CoreWindow sender,
   Windows.UI.Core.KeyEventArgs args)
{
    if (args.VirtualKey == Windows.System.VirtualKey.S)
    {
        //StartMoving(); (or keep moving if already started previously)
    }
}

private void CoreWindow_KeyUp(
   Windows.UI.Core.CoreWindow sender,
   Windows.UI.Core.KeyEventArgs args)
{
    if (args.VirtualKey == Windows.System.VirtualKey.S)
    {
        //StopMoving();
    }
}
</code>```

Title: VirtualKey detect when is held down

Body:
I am trying to get when you press the key that it continuous movement when a key is held down. But when press it move once and wait a second before it continues. I am using:

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDownAsync;

and to get check in the method:

args.VirtualKey == Windows.System.VirtualKey.S;

Is there a way that it does not pause for that second, I just want to continues as long that key is held down.

Body:
You cannot influence the speed by which the system reports the KeyDown event here, but you can subscribe to the KeyUp even too, and assume that key is pressed between the first time it is reported by KeyDown until a corresponding KeyUp occurs -

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;

And the methods:

private void CoreWindow_KeyDown(
   Windows.UI.Core.CoreWindow sender,
   Windows.UI.Core.KeyEventArgs args)
{
    if (args.VirtualKey == Windows.System.VirtualKey.S)
    {
        //StartMoving(); (or keep moving if already started previously)
    }
}

private void CoreWindow_KeyUp(
   Windows.UI.Core.CoreWindow sender,
   Windows.UI.Core.KeyEventArgs args)
{
    if (args.VirtualKey == Windows.System.VirtualKey.S)
    {
        //StopMoving();
    }
}


问:
htaccess redirect subpages from old category to same pages in different category
I want to redirect all my pages from categery old to category new.

http://mywebsite.com/old/page1 to http://mywebsite.com/new/page1
http://mywebsite.com/old/page2 to http://mywebsite.com/new/page2

This is not work

```<code>RewriteRule ^old/(.*) http://mywebsite.com/new/$1 [R=301,L]
</code>```

答:
found a solution

RedirectMatch 301 /old/(.*) /new/$1

Body:
I want to redirect all my pages from categery old to category new.

http://mywebsite.com/old/page1 to http://mywebsite.com/new/page1
http://mywebsite.com/old/page2 to http://mywebsite.com/new/page2

This is not work

RewriteRule ^old/(.*) http://mywebsite.com/new/$1 [R=301,L]


答:
It is similar to a k-nearest-neighbor problem so finding each closest point to a given point cost O(N) and for your problem should be O(N^2).

Sometimes Using kd-tree MAY improve some performance if your data is low-dimensional.

Title: Finding the sum of minimum distance from the points in one list to points in other list?

Body:
I have two lists containing x and y number of n-dimensional points respectively. I had to calculate the sum of minimum distances of each point in list one (containing x points) from each point in second list (containing y points). The distance I am calculating is Euclidean distance. The optimized solution is needed.

I have already implemented its naive solution in Python. But its time complexity is too much to be used anywhere. There will be optimization possible. Can this problems time complexity be reduced than what I have implemented?

I was reading thispaper which I was trying to implement. In this they were having the similar problem to which they stated that it's special condition of Earth Mover Distance. As there was no code given, hence unable to know how it got implemented. Thus my naive implementation, the above code was too slow to work on data set of 11k documents. I used Google Colab for executing my code.

# Calculating Euclidean distance between two points
def euclidean_dist(x,y):
  dd = 0.0
  #len(x) is number of dimensions. Basically x and y is a
  #list which contains coordinates of a point
  for i in range(len(x)):
    dd = dd+(x[i]-y[i])**2
  return dd**(1/2)

# Calculating the desired solution to our problem
def dist(l1,l2):
  min_dd = 0.0
  dd = euclidean_dist(l1[0],l2[0])
  for j in range(len(l1)):
    for k in range(len(l2)):
      temp = euclidean_dist(l1[j],l2[k])
      if dd > temp:
        dd = temp
    min_dd = min_dd+dd
    dd = euclidean_dist(l1[j],l2[0])
  return min_dd


答:
You could divide n by 1 / n

For rounding off without using Math.round, I have used this:

s=n=>(r=>(r-~~r<.5?0:1)- -~~r)(n/(1/n))

console.log(s(5));
console.log(s(4.4));
console.log(s(-4.44));```

This has 39 characters.

Title: Write a function that returns the square of a number without using *,+ or pow

Body:
The task is to write a function that takes n as an input where n is a number (from -32768 to 32768) and returns the square of that number. Simple task except for the fact that we cannot use any operators such as *,+ or even use any Math. functions such as pow. eval is not allowed as well.
Even more challenging is that we must keep the character code count less than 39 characters.

I absolutely cannot think of a way to get the square of a number without using the + or *. And even worse, to keep the character count less, it's impossible for me.

Codes like this won't work because: I used the plus sign and the character count is more than 60.

function sq(n){
   var res=n;
   for(i=1;i<n;i++)
   res+=n;
return res;
}

If n is a decimal, we are expected to return the nearest whole number as the result.
Thank you for reading all of this!

Edit: My problem has been solved. Thank you to everyone who has tried to help me with their codes as it helped me gain a new aspect of solving each problems.
Thank you very much again!

Body:
You could divide n by 1 / n

For rounding off without using Math.round, I have used this:

s=n=>(r=>(r-~~r<.5?0:1)- -~~r)(n/(1/n))

console.log(s(5));
console.log(s(4.4));
console.log(s(-4.44));

This has 39 characters.


问:
I want to make a query based on the current logged in user id in Angular using firebase as my back-end
I've created a bookmarking feature which if the users clicks at the bookmark button the user's id will be save to that documents bookmark array in firebase which is working fine.

But i want to show all bookmarks by a user in the bookmark page/tab (it's a news site btw the documents have title, picture, article, bookmarks and so on kind of data).

I've got it to work manually

bookmarks$: Observable<lajmiId[]>;
bookmarksBehaviorSubject : BehaviorSubject<string|null>;

constructor(
    private afs: AngularFirestore,
    public authService: AuthService,
    private ls: LoginService) {

this.bookmarksBehaviorSubject = new BehaviorSubject(null);
    this.bookmarks$ = this.bookmarksBehaviorSubject.pipe(
      switchMap(string => this.afs.collection<lajmiId>('lajmet', ref =>
        ref.where('bookmarks', 'array-contains', 'manually_written_uid')).valueChanges())
    );
}

```

<p>Which works however when i try to pas in the uid dynamically based on the current logged in user it's not working,</p>

<pre class="lang-js prettyprint-override"><code>var uid = this.authService.userData.uid;

this.bookmarksBehaviorSubject = new BehaviorSubject(null);
    this.bookmarks$ = this.bookmarksBehaviorSubject.pipe(
      switchMap(string => this.afs.collection<lajmiId>('lajmet', ref =>
        ref.where('bookmarks', 'array-contains', uid)).valueChanges())
    );
</code>```

This gives me an error of undefined since it's trying to read the uid before the data is ready to be used since the data is asynchronous.

I've tried putting the code in the ngOnInit() block same result.
I've tried creating an observable with the uid data still same result.
i just can't seem to figure this out.

My authServise looks something like this:

import { User } from '../core/user';

export class AuthService {
    userData: Observable<any>;

    constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public ngZone: NgZone, //ngZone service to move outside scope warning
    private dialogRef: MatDialog
    ) {
       this.afAuth.authState.subscribe(user => {
            if (user) {
                this.userData = user;
                localStorage.setItem('user', JSON.stringify(this.userData));
                JSON.parse(localStorage.getItem('user'));
            }
        })
    }
}
```

My User.ts contains the User interfase.

Any help is much appreciated.

答:
In your auth service you need to make the user as an Observable and then you can easily subsribe it on ngOnInit.

Suppose your auth.service.ts

```<code>export class AuthService{
   user$:Observable<any>;
 constructor(private router: Router,
          private afAuth: AngularFireAuth,
          private db:AngularFirestore,
          ) {
            this.user$ = this.afAuth.authState.pipe(
              switchMap(user => {
                if (user) {
//here you get the logged in user cred like uid
//you can use uid to refer in your collection
                  return this.afs.collection<lajmiId>(`lajmet/${user.uid}`).valueChanges()
                } else {
                  return of(null)
                }
              })
            )
          }
}
</code>```

This will always give you the current logged in user and then you can easily subscribe after importing your authservice in the component you are trying to fetch.

```<code>this.authService.user$.take(1).subscribe(data=>{
//data of the user logged in
})
</code>```

Body:
I've created a bookmarking feature which if the users clicks at the bookmark button the user's id will be save to that documents bookmark array in firebase which is working fine.

But i want to show all bookmarks by a user in the bookmark page/tab (it's a news site btw the documents have title, picture, article, bookmarks and so on kind of data).

I've got it to work manually

bookmarks$: Observable<lajmiId[]>;
bookmarksBehaviorSubject : BehaviorSubject<string|null>;

constructor(
    private afs: AngularFirestore,
    public authService: AuthService,
    private ls: LoginService) {

this.bookmarksBehaviorSubject = new BehaviorSubject(null);
    this.bookmarks$ = this.bookmarksBehaviorSubject.pipe(
      switchMap(string => this.afs.collection<lajmiId>('lajmet', ref =>
        ref.where('bookmarks', 'array-contains', 'manually_written_uid')).valueChanges())
    );
}

Which works however when i try to pas in the uid dynamically based on the current logged in user it's not working,

var uid = this.authService.userData.uid;

this.bookmarksBehaviorSubject = new BehaviorSubject(null);
    this.bookmarks$ = this.bookmarksBehaviorSubject.pipe(
      switchMap(string => this.afs.collection<lajmiId>('lajmet', ref =>
        ref.where('bookmarks', 'array-contains', uid)).valueChanges())
    );

This gives me an error of undefined since it's trying to read the uid before the data is ready to be used since the data is asynchronous.

I've tried putting the code in the ngOnInit() block same result.
I've tried creating an observable with the uid data still same result.
i just can't seem to figure this out.

My authServise looks something like this:

import { User } from '../core/user';

export class AuthService {
    userData: Observable<any>;

    constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public ngZone: NgZone, //ngZone service to move outside scope warning
    private dialogRef: MatDialog
    ) {
       this.afAuth.authState.subscribe(user => {
            if (user) {
                this.userData = user;
                localStorage.setItem('user', JSON.stringify(this.userData));
                JSON.parse(localStorage.getItem('user'));
            }
        })
    }
}

My User.ts contains the User interfase.

Any help is much appreciated.

Body:
In your auth service you need to make the user as an Observable and then you can easily subsribe it on ngOnInit.

Suppose your auth.service.ts

export class AuthService{
   user$:Observable<any>;
 constructor(private router: Router,
          private afAuth: AngularFireAuth,
          private db:AngularFirestore,
          ) {
            this.user$ = this.afAuth.authState.pipe(
              switchMap(user => {
                if (user) {
//here you get the logged in user cred like uid
//you can use uid to refer in your collection
                  return this.afs.collection<lajmiId>(`lajmet/${user.uid}`).valueChanges()
                } else {
                  return of(null)
                }
              })
            )
          }
}

This will always give you the current logged in user and then you can easily subscribe after importing your authservice in the component you are trying to fetch.

this.authService.user$.take(1).subscribe(data=>{
//data of the user logged in
})


问:
how to select an option from a dropdown list in a webpage using the inner text
How to select an option from a dropdown list in a webpage using the inner text

below is vba code

```<code>Sub navigation_site_with_part_number()
    Dim eRow As Long
    Dim ele As Object
    Set sht = Sheets("Sheet1")
    RowCount = 1`enter code here
    eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Set objIE = CreateObject("InternetExplorer.Application")
    requestnumber = InputBox("Enter the request number.")
    With objIE
    .Visible = True
    .navigate "*http://www.auto.com*"
    Do While .Busy Or _
    .readyState <> 4
    DoEvents
    Loop
    .document.getElementsByid("inspNumber").selectedinnertext = 2
   .document.getElementById("InspQuery_Search").Click
    Do While .Busy Or _
   .readyState <> 4
    DoEvents
    Loop
    End With
</code>```

Below is Html code:

div id="RequestNumberGroup" class="form-group">
Request Number:
<select class="form-control" id="inspNumber" name="inspNumber">
  <option value=""></option>
  <option value="813">20190205</option>
  <option value="1034">20190426</option>
  <option value="1059">20190451</option>
  <option value="1061">20190453</option>
  <option value="1064">20190456</option>
  <option value="1065">20190457</option>```

I expected to select the option in dropdownlist with requestnumber not option value

答:
There isn't a select by text option in IE implementation.

1) Either gather collection/nodelist of options and loop comparing innerText against desired text string then select if found and Exit For

```<code>Dim options As Object, i As Long, found As Boolean

Set options = ie.document.querySelectorAll("#inspNumber options")

For i = 0 To options.length - 1
    If options.item(i).innerText = "target string" Then
        options.item(i).Selected = True
        found = True
        Exit For
    End If
Next
If Not found Then
    'do something if not found
End If
</code>```

2) Use selenium vba wrapper which does implement this functionality

```<code>Dim ele As Select
Set ele = driver.FindElementById("inspNumber").AsSelect
ele.SelectByText "Option Text"
</code>```

N.B. Of course there are using attributes values and selectedIndex methods but you didn't want those.

Body:
How to select an option from a dropdown list in a webpage using the inner text

below is vba code

Sub navigation_site_with_part_number()
    Dim eRow As Long
    Dim ele As Object
    Set sht = Sheets("Sheet1")
    RowCount = 1`enter code here
    eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Set objIE = CreateObject("InternetExplorer.Application")
    requestnumber = InputBox("Enter the request number.")
    With objIE
    .Visible = True
    .navigate "*http://www.auto.com*"
    Do While .Busy Or _
    .readyState <> 4
    DoEvents
    Loop
    .document.getElementsByid("inspNumber").selectedinnertext = 2
   .document.getElementById("InspQuery_Search").Click
    Do While .Busy Or _
   .readyState <> 4
    DoEvents
    Loop
    End With

Below is Html code:

div id="RequestNumberGroup" class="form-group">
Request Number:
<select class="form-control" id="inspNumber" name="inspNumber">
  <option value=""></option>
  <option value="813">20190205</option>
  <option value="1034">20190426</option>
  <option value="1059">20190451</option>
  <option value="1061">20190453</option>
  <option value="1064">20190456</option>
  <option value="1065">20190457</option>

I expected to select the option in dropdownlist with requestnumber not option value

Body:
There isn't a select by text option in IE implementation.

1) Either gather collection/nodelist of options and loop comparing innerText against desired text string then select if found and Exit For

Dim options As Object, i As Long, found As Boolean

Set options = ie.document.querySelectorAll("#inspNumber options")

For i = 0 To options.length - 1
    If options.item(i).innerText = "target string" Then
        options.item(i).Selected = True
        found = True
        Exit For
    End If
Next
If Not found Then
    'do something if not found
End If

2) Use selenium vba wrapper which does implement this functionality

Dim ele As Select
Set ele = driver.FindElementById("inspNumber").AsSelect
ele.SelectByText "Option Text"

N.B. Of course there are using attributes values and selectedIndex methods but you didn't want those.


问:
Doctrine 2, decimal can only contain 14 digits
EDIT: This was just confirmed as a bug in Doctrine 2
http://www.doctrine-project.org/jira/browse/DDC-1112?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15724#action_15724

I have a Doctrine 2 entity and the value is mapped like this (with regular getter/setter):

```<code>/**
 * @Column(type="decimal", precision=40, scale=30)
 */
protected $someValue;

/**
 * @return decimal
 */
public function getSomeValue()
{
    return $this->someValue;
}

/**
 * @param decimal $someValue
 */
public function setSomeValue($someValue)
{
    $this->someValue = $someValue;
}
</code>```

When I set that value from my code, the value gets written into the database correctly. But, and that is my problem, when I get the value (via getter or \Doctrine\Common\Util\Debug::dump()), it always gives me a number with maximum 14 digits, and it rounds the value. I read the record with the default findById().

```<code>eg: with value 1234567890.012345678901234567890123456789 I have 1234567890.0123
eg: with value 890.0123456789012345678901234567890123456 I have 890.01234567890
</code>```

I of course want all digits, not just 14. The field in MySQL is declared like this:

someValue decimal(40,30) NOT NULL,

When I get the value with raw PHP and mysql_query(), it returns correctly.

Edit: seems like the problem is that Doctrine returns a float:

```<code>["someValue":protected]=> float(234567890.01235)
</code>```

What's wrong, what should I check next, how to fix, any clues?

答: It sounds like Doctrine2 is returning the float value and is running into floating point precision while mysql_query() is returning the value as a string. You can do a var_dump() on each returned variable and see the scalar type.

Body:
EDIT: This was just confirmed as a bug in Doctrine 2
http://www.doctrine-project.org/jira/browse/DDC-1112?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15724#action_15724

I have a Doctrine 2 entity and the value is mapped like this (with regular getter/setter):

/**
 * @Column(type="decimal", precision=40, scale=30)
 */
protected $someValue;

/**
 * @return decimal
 */
public function getSomeValue()
{
    return $this->someValue;
}

/**
 * @param decimal $someValue
 */
public function setSomeValue($someValue)
{
    $this->someValue = $someValue;
}

When I set that value from my code, the value gets written into the database correctly. But, and that is my problem, when I get the value (via getter or \Doctrine\Common\Util\Debug::dump()), it always gives me a number with maximum 14 digits, and it rounds the value. I read the record with the default findById().

eg: with value 1234567890.012345678901234567890123456789 I have 1234567890.0123
eg: with value 890.0123456789012345678901234567890123456 I have 890.01234567890

I of course want all digits, not just 14. The field in MySQL is declared like this:

someValue decimal(40,30) NOT NULL,

When I get the value with raw PHP and mysql_query(), it returns correctly.

Edit: seems like the problem is that Doctrine returns a float:

["someValue":protected]=> float(234567890.01235)

What's wrong, what should I check next, how to fix, any clues?


问:
Why my loading gif makes my page to load slower?
I used some code to display a gif before my page load but it is
increasing  my page's loading speed...

Here is where I use that code - http://sarkarinaukrihome.com/

JS

```<code>$(window).load(function() {
  // Animate loader off screen
  $(".se-pre-con").fadeOut("fast");;
});
</code>```

HTML

```<code><div class="se-pre-con"></div>
</code>```

CSS

```<code>.no-js #loader {
  display: none;
}

.js #loader {
  display: block;
  position: absolute;
  left: 100px;
  top: 0;
}

.se-pre-con {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url(Preloader_2.gif) center no-repeat #fff;
}
</code>```

答:
You must resize to the exact desired dimensions of your HTML container and compress all images.

If you look closely at your network flow, you lose a lot of time to load all the images.

If you analyze the performance of your website, Google Chrome gives you recommendations and you have precisely this point mentioned with the possible gain if you perform the suggested actions.

To use the LightHouse Viewer of Google Chrome, read this

For the theoretical concept of image compressing, you can read this

To compress different images, you can use services like this

Body:
I used some code to display a gif before my page load but it is
increasing  my page's loading speed...

Here is where I use that code - http://sarkarinaukrihome.com/

JS

$(window).load(function() {
  // Animate loader off screen
  $(".se-pre-con").fadeOut("fast");;
});

HTML

CSS

.no-js #loader {
  display: none;
}

.js #loader {
  display: block;
  position: absolute;
  left: 100px;
  top: 0;
}

.se-pre-con {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: url(Preloader_2.gif) center no-repeat #fff;
}