text:
Q: Python - Tkinter how to close window after button is pressed? So there is a first window for the user to log into. Once the user has logged in they can start the game by clicking the "continue" button. The command of this button is set to the function con which should close the window using the window.destroy() function however whenever I try to click it I always receive an error stating "window is not defined"
import sqlite3
from tkinter import ttk
import tkinter
from tkinter import messagebox

#SQL DATABASES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def SQLQuestion():
    with sqlite3.connect("games.db") as db:
        cursor = db.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS game (
                questionID integer PRIMARY KEY AUTOINCREMENT,
                question text,
                answer text
                )""")

def SQLUser():
    with sqlite3.connect("User.db") as db:
        cursor = db.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS user (
                userID INTEGER PRIMARY KEY,
                username VARCHAR(20) NOT NULL,
                password VARCHAR(20) NOT NULL,
                userscore INTEGER,
                usertime REAL
                )""")

#SQL USER LOG IN/CREATE/DELETE ACCOUNT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def login(usernameLogin, passwordLogin):
    while True:
        username = usernameLogin.get()#Asks for username
        password = passwordLogin.get()#Asks for password
        with sqlite3.connect("User.db") as db:#Creates a connection to database
            c = db.cursor()
        find_user = ("SELECT * FROM user WHERE username = ? AND password = ?")#Validates inputs for account
        c.execute(find_user,[(username),(password)])
        results = c.fetchall()#Fetches values from database

        if results:#Validates if the username/password is recognised
            for i in results:
                messagebox.showinfo("", "Welcome "+i[1]+"!")
                QuestionMenu()
            break

        else:
            messagebox.showinfo("", "Password and username is not recognised")
            break
        window.destroy()

def newUser(username1, password1):
    found = 0
    while found == 0:
        username = username1.get()
        with sqlite3.connect("User.db") as db:
            c = db.cursor()
        findUser = ("SELECT * FROM user WHERE username = ?")
        c.execute(findUser, [(username)])#Checks existence of username in database

        if c.fetchall():
            messagebox.showinfo("Username", "Username taken please try again.")
            break
        else:
            messagebox.showinfo("", "Account has been created!")
            found = 1

    password = password1.get()
    insertData = '''INSERT INTO user(username, password)
    VALUES(?,?)'''#Inserts new account into databse
    c.execute(insertData, [(username),(password)])
    db.commit()

def newUserTkinter():
    window = tkinter.Tk()
    window.title("Create new account")

    labelOne = ttk.Label(window, text = "Enter a username:")
    labelOne.grid(row = 0, column = 0)
    username1 = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = username1)
    usernameEntry.grid(row = 1, column = 0)

    labelTwo = ttk.Label(window, text = "Enter a password:")
    labelTwo.grid(row = 2, column = 0)
    password1 = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = password1)
    passwordEntry.grid(row = 3, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: newUser(username1, password1))
    btn.grid(row = 3, column = 1)

def removeUser(usernameD, passwordD):
    exists = 0
    while exists == 0:#Validates exsistence of account username
        username = usernameD.get()
        password = passwordD.get()
        with sqlite3.connect("User.db") as db:
            c = db.cursor()
        findUser = ("SELECT * FROM user WHERE username = ?")
        c.execute(findUser, [(username)])

        if c.fetchall():
            messagebox.showinfo("Delete account", "Account deleted!")
            exists = 1
        else:
            messagebox.showinfo("", "Account does not exist")
            break

    remove_user = ("DELETE from user WHERE username = ? AND password = ?")
    c.execute(remove_user,[(username),(password)])
    db.commit()

def removeUserTkinter():
    window = tkinter.Tk()
    window.title("Delete account")

    labelOne = ttk.Label(window, text = "Enter account username:")
    labelOne.grid(row = 0, column = 0)
    usernameD = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameD)
    usernameEntry.grid(row = 1, column = 0)

    labelTwo = ttk.Label(window, text = "Enter account password:")
    labelTwo.grid(row = 2, column = 0)
    passwordD = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordD)
    passwordEntry.grid(row = 3, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: removeUser(usernameD, passwordD))
    btn.grid(row = 3, column = 1)

def menu():
    with sqlite3.connect("User.db") as db:
        c = db.cursor()
    c.execute("SELECT * FROM user")
    print(c.fetchall())

    window = tkinter.Tk()
    window.title("Treasure Hunt Game!")

    labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ USER MENU ~~~~~~~~~~~~~
    """)#label displays instruction
    labelOne.grid(row = 0, column = 0)#places label in a grid

    btn = ttk.Button(window, text = "Create account", command = newUserTkinter)
    btn.grid(row = 1, column = 0)#places button in a grid

    btn = ttk.Button(window, text = "Delete account", command = removeUserTkinter)
    btn.grid(row = 2, column = 0)#places button in a grid

    labelTwo = ttk.Label(window, text = "Login to your account:")
    labelTwo.grid(row = 3, column = 0)

    usernameLogin = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameLogin)
    usernameEntry.grid(row = 5, column = 0)

    labelTwo = ttk.Label(window, text = "Username")
    labelTwo.grid(row = 4, column = 0)

    passwordLogin = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordLogin)
    passwordEntry.grid(row = 7, column = 0)

    labelTwo = ttk.Label(window, text = "Password")
    labelTwo.grid(row = 6, column = 0)

    btn = ttk.Button(window, text="Log in", command=lambda: login(usernameLogin, passwordLogin))
    btn.grid(row = 7, column = 1)

#SQL QUESTION ADD/REMOVE/GET~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def insert_question(emp):
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("INSERT INTO game VALUES (?, ?, ?)", (emp))
    conn.commit()

def get_question():
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT * FROM game")
    return c.fetchall()

def get_number_total_question(): #Get the total number of question
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT COUNT(*) FROM game")
    return c.fetchone()[0]

def get_single_question(question_number): #Get a question from the database
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT question FROM game WHERE questionID="+str(question_number))
    return c.fetchone()[0]

def get_answer(question_number): #Get the answer from the database
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT answer FROM game WHERE questionID="+str(question_number))
    return c.fetchone()[0]

def remove_question(emp):
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("DELETE from game WHERE question = ?", [emp])
    conn.commit()

#Tkinter~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def showInstructions():
    messagebox.showinfo("Instructions", """You are a treasure hunter, your goal is to collect atleast 100
gold by the end of the game from treasure chests randomly scattered across the grid.There are 10 chests within a grid and
each treasure chest is worth 10 gold but can only be reclaimed 3 times before it is replaced by a bandit.
Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then 100 gold this means you lose!

Press enter to continue...""")#messagebox used for more simple functions (showing messages)

def showLeaderboard():
    messagebox.showinfo("Leaderboard", "shows leaderboard")

def con():
    messagebox.showinfo("Game", "Time to play!")
    window.destroy()

def showQuestions():
    emps = get_question()
    messagebox.showinfo("List of questions/answers", emps)

def AddQuestion(mathquestion, mathanswer):
    mathquestion1 = mathquestion.get()
    mathanswer1 = mathanswer.get()
    emp_1 = (None, mathquestion1, mathanswer1)
    insert_question(emp_1)
    messagebox.showinfo("Question inputed!")

    emps = get_question()
    print(emps)

def removeQuestion(DeleteQuestion):
    exists = 0
    while exists == 0:#Validates exsistence of question
        DeleteQuestion1 = DeleteQuestion.get()
        conn = sqlite3.connect('games.db')
        c = conn.cursor()
        findQuestion = ("SELECT * FROM game WHERE question = ?")
        c.execute(findQuestion, [(DeleteQuestion1)])

        if c.fetchall():
            messagebox.showinfo("Delete qustion","Question deleted!")
            exists = 1
        else:
            messagebox.showinfo("","Question does not exist")
            break

    remove_question(DeleteQuestion1)

def removeQuestionTk():
    window = tkinter.Tk()
    window.title("Remove a question.")

    labelOne = ttk.Label(window, text = "Enter question to remove:")
    labelOne.grid(row = 0, column = 0)
    DeleteQuestion = tkinter.StringVar(window)#value type is classified as a string
    questionEntry = ttk.Entry(window, width = 30, textvariable = DeleteQuestion)
    questionEntry.grid(row = 1, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: removeQuestion(DeleteQuestion))
    btn.grid(row = 1, column = 1)

def QuestionMenu():
    with sqlite3.connect("games.db") as db:
        c = db.cursor()

    window = tkinter.Tk()
    window.title("Treasure Hunt Game!")

    labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ GAME MENU ~~~~~~~~~~~~~
    """)#label displays instruction
    labelOne.grid(row = 0, column = 0)#places label in a grid

    btn = ttk.Button(window, text = "View instructions", command = showInstructions)
    btn.grid(row = 1, column = 0)#places button in a grid

    btn = ttk.Button(window, text = "View leaderboard", command = showLeaderboard)
    btn.grid(row = 2, column = 0)

    btn = ttk.Button(window, text = "View all questions", command = showQuestions)
    btn.grid(row = 3, column = 0)

    btn = ttk.Button(window, text = "Continue", command = con)
    btn.grid(row = 4, column = 0)

    labelTwo = ttk.Label(window, text = "Enter a math question:")
    labelTwo.grid(row = 5, column = 0)
    mathquestion = tkinter.StringVar()#value type is classified as a string
    userEntryQ = ttk.Entry(window, width = 30, textvariable = mathquestion)
    userEntryQ.grid(row = 6, column = 0)

    labelTwo = ttk.Label(window, text = "Enter the answer to this question:")
    labelTwo.grid(row = 7, column = 0)
    mathanswer = tkinter.StringVar()
    userEntryQ = ttk.Entry(window, width = 30, textvariable = mathanswer)
    userEntryQ.grid(row = 8, column = 0)

    btn = ttk.Button(window, text = "Submit", command=lambda: AddQuestion(mathquestion, mathanswer))
    btn.grid(row = 8, column = 1)

    btn = ttk.Button(window, text = "Remove a question", command = removeQuestionTk)
    btn.grid(row = 9, column = 0)#places button in a grid

SQLUser()
SQLQuestion()
menu()

A: this will work with the login button,,,, i sent the window with the login function
here i added the window to the function
def login(usernameLogin, passwordLogin,btn):

.
here in the "btn.destroy()" i closed the window
if results:#Validates if the username/password is recognised
            for i in results:
                messagebox.showinfo("", "Welcome "+i[1]+"!")
                btn.destroy()
                QuestionMenu()

.
here i sent the window to the function.
btn = ttk.Button(window, text="Log in", command=lambda: login(usernameLogin, passwordLogin,window))

.
import sqlite3
from tkinter import ttk
import tkinter
from tkinter import messagebox

#SQL DATABASES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def SQLQuestion():
    with sqlite3.connect("games.db") as db:
        cursor = db.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS game (
                questionID integer PRIMARY KEY AUTOINCREMENT,
                question text,
                answer text
                )""")

def SQLUser():
    with sqlite3.connect("User.db") as db:
        cursor = db.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS user (
                userID INTEGER PRIMARY KEY,
                username VARCHAR(20) NOT NULL,
                password VARCHAR(20) NOT NULL,
                userscore INTEGER,
                usertime REAL
                )""")

#SQL USER LOG IN/CREATE/DELETE ACCOUNT~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def login(usernameLogin, passwordLogin,btn):
    while True:
        username = usernameLogin.get()#Asks for username
        password = passwordLogin.get()#Asks for password
        with sqlite3.connect("User.db") as db:#Creates a connection to database
            c = db.cursor()
        find_user = ("SELECT * FROM user WHERE username = ? AND password = ?")#Validates inputs for account
        c.execute(find_user,[(username),(password)])
        results = c.fetchall()#Fetches values from database

        if results:#Validates if the username/password is recognised
            for i in results:
                messagebox.showinfo("", "Welcome "+i[1]+"!")
                btn.destroy()
                QuestionMenu()
            break

        else:
            messagebox.showinfo("", "Password and username is not recognised")
            break
        window.destroy()

def newUser(username1, password1):
    found = 0
    while found == 0:
        username = username1.get()
        with sqlite3.connect("User.db") as db:
            c = db.cursor()
        findUser = ("SELECT * FROM user WHERE username = ?")
        c.execute(findUser, [(username)])#Checks existence of username in database

        if c.fetchall():
            messagebox.showinfo("Username", "Username taken please try again.")
            break
        else:
            messagebox.showinfo("", "Account has been created!")
            found = 1

    password = password1.get()
    insertData = '''INSERT INTO user(username, password)
    VALUES(?,?)'''#Inserts new account into databse
    c.execute(insertData, [(username),(password)])
    db.commit()

def newUserTkinter():
    window = tkinter.Tk()
    window.title("Create new account")

    labelOne = ttk.Label(window, text = "Enter a username:")
    labelOne.grid(row = 0, column = 0)
    username1 = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = username1)
    usernameEntry.grid(row = 1, column = 0)

    labelTwo = ttk.Label(window, text = "Enter a password:")
    labelTwo.grid(row = 2, column = 0)
    password1 = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = password1)
    passwordEntry.grid(row = 3, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: newUser(username1, password1))
    btn.grid(row = 3, column = 1)

def removeUser(usernameD, passwordD):
    exists = 0
    while exists == 0:#Validates exsistence of account username
        username = usernameD.get()
        password = passwordD.get()
        with sqlite3.connect("User.db") as db:
            c = db.cursor()
        findUser = ("SELECT * FROM user WHERE username = ?")
        c.execute(findUser, [(username)])

        if c.fetchall():
            messagebox.showinfo("Delete account", "Account deleted!")
            exists = 1
        else:
            messagebox.showinfo("", "Account does not exist")
            break

    remove_user = ("DELETE from user WHERE username = ? AND password = ?")
    c.execute(remove_user,[(username),(password)])
    db.commit()

def removeUserTkinter():
    window = tkinter.Tk()
    window.title("Delete account")

    labelOne = ttk.Label(window, text = "Enter account username:")
    labelOne.grid(row = 0, column = 0)
    usernameD = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameD)
    usernameEntry.grid(row = 1, column = 0)

    labelTwo = ttk.Label(window, text = "Enter account password:")
    labelTwo.grid(row = 2, column = 0)
    passwordD = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordD)
    passwordEntry.grid(row = 3, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: removeUser(usernameD, passwordD))
    btn.grid(row = 3, column = 1)

def menu():
    with sqlite3.connect("User.db") as db:
        c = db.cursor()
    c.execute("SELECT * FROM user")
    print(c.fetchall())

    window = tkinter.Tk()
    window.title("Treasure Hunt Game!")

    labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ USER MENU ~~~~~~~~~~~~~
    """)#label displays instruction
    labelOne.grid(row = 0, column = 0)#places label in a grid

    btn = ttk.Button(window, text = "Create account", command = newUserTkinter)
    btn.grid(row = 1, column = 0)#places button in a grid

    btn = ttk.Button(window, text = "Delete account", command = removeUserTkinter)
    btn.grid(row = 2, column = 0)#places button in a grid

    labelTwo = ttk.Label(window, text = "Login to your account:")
    labelTwo.grid(row = 3, column = 0)

    usernameLogin = tkinter.StringVar(window)#value type is classified as a string
    usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameLogin)
    usernameEntry.grid(row = 5, column = 0)

    labelTwo = ttk.Label(window, text = "Username")
    labelTwo.grid(row = 4, column = 0)

    passwordLogin = tkinter.StringVar(window)#value type is classified as a string
    passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordLogin)
    passwordEntry.grid(row = 7, column = 0)

    labelTwo = ttk.Label(window, text = "Password")
    labelTwo.grid(row = 6, column = 0)

    btn = ttk.Button(window, text="Log in", command=lambda: login(usernameLogin, passwordLogin,window))
    btn.grid(row = 7, column = 1)

#SQL QUESTION ADD/REMOVE/GET~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def insert_question(emp):
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("INSERT INTO game VALUES (?, ?, ?)", (emp))
    conn.commit()

def get_question():
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT * FROM game")
    return c.fetchall()

def get_number_total_question(): #Get the total number of question
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT COUNT(*) FROM game")
    return c.fetchone()[0]

def get_single_question(question_number): #Get a question from the database
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT question FROM game WHERE questionID="+str(question_number))
    return c.fetchone()[0]

def get_answer(question_number): #Get the answer from the database
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("SELECT answer FROM game WHERE questionID="+str(question_number))
    return c.fetchone()[0]

def remove_question(emp):
    conn = sqlite3.connect('games.db')
    c = conn.cursor()
    c.execute("DELETE from game WHERE question = ?", [emp])
    conn.commit()

#Tkinter~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def showInstructions():
    messagebox.showinfo("Instructions", """You are a treasure hunter, your goal is to collect atleast 100
gold by the end of the game from treasure chests randomly scattered across the grid.There are 10 chests within a grid and
each treasure chest is worth 10 gold but can only be reclaimed 3 times before it is replaced by a bandit.
Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then 100 gold this means you lose!

Press enter to continue...""")#messagebox used for more simple functions (showing messages)

def showLeaderboard():
    messagebox.showinfo("Leaderboard", "shows leaderboard")

def con():
    messagebox.showinfo("Game", "Time to play!")
    window.destroy()

def showQuestions():
    emps = get_question()
    messagebox.showinfo("List of questions/answers", emps)

def AddQuestion(mathquestion, mathanswer):
    mathquestion1 = mathquestion.get()
    mathanswer1 = mathanswer.get()
    emp_1 = (None, mathquestion1, mathanswer1)
    insert_question(emp_1)
    messagebox.showinfo("Question inputed!")

    emps = get_question()
    print(emps)

def removeQuestion(DeleteQuestion):
    exists = 0
    while exists == 0:#Validates exsistence of question
        DeleteQuestion1 = DeleteQuestion.get()
        conn = sqlite3.connect('games.db')
        c = conn.cursor()
        findQuestion = ("SELECT * FROM game WHERE question = ?")
        c.execute(findQuestion, [(DeleteQuestion1)])

        if c.fetchall():
            messagebox.showinfo("Delete qustion","Question deleted!")
            exists = 1
        else:
            messagebox.showinfo("","Question does not exist")
            break

    remove_question(DeleteQuestion1)

def removeQuestionTk():
    window = tkinter.Tk()
    window.title("Remove a question.")

    labelOne = ttk.Label(window, text = "Enter question to remove:")
    labelOne.grid(row = 0, column = 0)
    DeleteQuestion = tkinter.StringVar(window)#value type is classified as a string
    questionEntry = ttk.Entry(window, width = 30, textvariable = DeleteQuestion)
    questionEntry.grid(row = 1, column = 0)

    btn = ttk.Button(window, text="Submit", command=lambda: removeQuestion(DeleteQuestion))
    btn.grid(row = 1, column = 1)

def QuestionMenu():
    with sqlite3.connect("games.db") as db:
        c = db.cursor()

    window = tkinter.Tk()
    window.title("Treasure Hunt Game!")

    labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ GAME MENU ~~~~~~~~~~~~~
    """)#label displays instruction
    labelOne.grid(row = 0, column = 0)#places label in a grid

    btn = ttk.Button(window, text = "View instructions", command = showInstructions)
    btn.grid(row = 1, column = 0)#places button in a grid

    btn = ttk.Button(window, text = "View leaderboard", command = showLeaderboard)
    btn.grid(row = 2, column = 0)

    btn = ttk.Button(window, text = "View all questions", command = showQuestions)
    btn.grid(row = 3, column = 0)

    btn = ttk.Button(window, text = "Continue", command = con)
    btn.grid(row = 4, column = 0)

    labelTwo = ttk.Label(window, text = "Enter a math question:")
    labelTwo.grid(row = 5, column = 0)
    mathquestion = tkinter.StringVar()#value type is classified as a string
    userEntryQ = ttk.Entry(window, width = 30, textvariable = mathquestion)
    userEntryQ.grid(row = 6, column = 0)

    labelTwo = ttk.Label(window, text = "Enter the answer to this question:")
    labelTwo.grid(row = 7, column = 0)
    mathanswer = tkinter.StringVar()
    userEntryQ = ttk.Entry(window, width = 30, textvariable = mathanswer)
    userEntryQ.grid(row = 8, column = 0)

    btn = ttk.Button(window, text = "Submit", command=lambda: AddQuestion(mathquestion, mathanswer))
    btn.grid(row = 8, column = 1)

    btn = ttk.Button(window, text = "Remove a question", command = removeQuestionTk)
    btn.grid(row = 9, column = 0)#places button in a grid

SQLUser()
SQLQuestion()
menu()


text:
Q: header('Location:') not redirecting I have a login page which checks the username and the password and if the credentials provided by the user matches it sets the session and redirects the user, it works on my godadd hosting account but now i have shifted my hosting and suddenly it has stopped working, following is the code
if (count($result) > 0)
            {
                $row= mysql_fetch_array($result);
                $userID = $row['userID'];
                $firstName = $row['FirstName'];

                $isActive = $row['IsActive'];

                if ($isActive == '1')
                {

                    $_SESSION['user'] = $firstName;
                    //var_dump($firstName); //it gives me the right username
                    //echo" - here";  //this also gets echoed
                    header("Location: http://google.com/"); //it just dies silently
                    exit;
                }

please help me find out where i went wrong

A: Are you outputting anything before calling header()?
If so, put ob_start() at the beginning of your script or make sure you're not echoing anything before header() is called

A: You need to make sure you don't output anything before the header tag. Since it was working before, I assume it's not an error where you are echo'n stuff before the call to header, and since you see no output, I assume it is outputting white-space. There are a few places where some whitespace and/or invisible characters can sneak into a file:
Put the cursor before your opening PHP tag (<? or <?php) and hit backspace a few times, then hit delete to delete the < and then retype the <. That will make sure there are no invisible characters being output to the browser before your headers.
Then go through any files that are included by that file, and do the same thing, as well as delete any ?> that you have at the end of the file. If those files include any othe files repeat this on them.

A: If you want to use header(), you must not echo anything prior to it.

A: add ob_start(); to the beginning of your script and add ob_end_flush(); to the end of your script to avoid this issue.
ob_start(); will turn output buffering on and ob_end_flush(); will send the contents of the topmost output buffer and turn this output buffer off.

redpajama_set_name: RedPajamaStackExchange


text:
Q: f:ajax not rendering h:selectManyListbox Using f:ajax component with h:selectManyListbox, it is firing the listener method but not refreshing the rendering list.
I have Market. When I select market it needs to display Sub-Markets. Initial page load will have all the Markets and Sub-Markets, but it needs to filter when user selects "Market".
Using below code:
   <ui:fragment id="uda2" rendered="#{udaList.index eq 1}">

   Market:

          <h:selectManyListbox style="width:360px;"   multiple="" pt:aria-required="true" required="required" pt:data-toggle="chosen"
             disabled="#  {licenseSelectionBean.isFieldEnabled(FormFieldsEnum.ITEM_UDA2)}"
          id="#{FormFieldsEnum.ITEM_UDA2.getFieldCode()}" size="1"
          name="#{FormFieldsEnum.ITEM_UDA2.getFieldCode()}"
        value="#{licenseSelectionBean.selectedItemUda2}"
        styleClass="sel-chosen">

        <f:selectItems var="uda2"
            value="#{licenseSelectionBean.selectUda2}" />
        <f:ajax event="change" execute="@this" render="@this udalist3"
                listener="#{licenseSelectionBean.onChangeFilter()}" />
    </h:selectManyListbox>

  </ui:fragment>
<ui:fragment rendered="#{udaList.index eq 2}">

Sub-Market:

      <h:selectManyListbox style="width:360px;"   multiple="" pt:aria-required="true" required="required" pt:data-toggle="chosen"
          disabled="#{licenseSelectionBean.isFieldEnabled(FormFieldsEnum.ITEM_UDA3)}"
        size="1"
        pt:name="udalist3"
        value="#{licenseSelectionBean.selectedItemUda3}"
        pt:id="udalist3"
        styleClass="sel-chosen">

        <f:selectItems var="uda3"
            value="#{licenseSelectionBean.selectUda3}" />

    </h:selectManyListbox>

  </ui:fragment>

Used "pt" for pass-through because JSF prefixing dynamic id.
How to resolve this problem?

A: Simple solution. Replace
<f:ajax event="change" execute="@this" render="@this udalist3"
listener="#{licenseSelectionBean.onChangeFilter()}" />

with
<f:ajax event="change" execute="@this" render="@form"
listener="#{licenseSelectionBean.onChangeFilter()}" />

This might cause some unnecesarry traffic. You can also encapsulate the second ui:fragment in a panelgroup, e.g.
<h:panelGroup id="wrapper">
  <ui:fragment rendered="#{udaList.index eq 2}">
   ....
</h:panelgroup>

and add replace "udalist3" with "wrapper" in the f:ajax render attribute.


text:
Q: animate height of a dropdown with 60fps I realized that animating height is an expensive operation. Even on high end computers (MacBook Pro), animating height often causes jagged animation.
Sample code:

document.querySelector("#title").addEventListener("click", () => {
  if (document.querySelector("#wrapper").style.height != "60px") {
    document.querySelector("#wrapper").style.height = "60px";
  } else {
    document.querySelector("#wrapper").style.height = "20px";
  }
});
#wrapper {
  height: 20px;
  transition-duration: 0.2s;
  overflow: hidden;
}

.item {
  height: 20px;
}

Title

Dropdown Label 1

Dropdown Label 2

Other stuff

https://jsfiddle.net/dy1o4a3c/1/
What is the alternative? I use css transform property to achieve 60fps animations, but I do not know how to use it to animate height of a dropdown.
Edit: Apparently if dev tools are open, the effect is magnified.


text:
Q: API openTab is not currently supported in this application I have below aura component added on the account record page from the app builder
HTML:
<aura:component implements="flexipage:availableForAllPageTypes">
    <lightning:workspaceAPI aura:id="workspace" />
    <lightning:button label="Open Tab" onclick="{! c.openTab }" />
</aura:component>

JS:
openTab: function (component, event, helper) {
    const workspaceAPI = component.find("workspace");
    workspaceAPI.openTab({
        url: '/apex/my_vf_page',
        focus: true
    }).then(function (response) {
        workspaceAPI.getTabInfo({
            tabId: response
        }).then(function (tabInfo) {
            console.log("The recordId for this tab is: " + tabInfo.recordId);
        });
    }).catch(function (error) {
        console.log(error);
    });
}

but it logs below error on the console log

Error: API openTab is not currently supported in this application.

Could someone please help me what am I doing wrong?


text:
Q: Getting pull access denied when trying to pull emr-6.3.0-latest base image from ECR I am following How to customize Docker images and trying to pull base image for emr-6.3.0-latest and try to modify it before I push to ECR. However when I execute below command
docker pull 755674844232.dkr.ecr.us-east-1.amazonaws.com/spark/emr-6.3.0-latest

I get error like
Error response from daemon: pull access denied for 755674844232.dkr.ecr.us-east-1.amazonaws.com/spark/emr-6.3.0-latest, repository does not exist or may require 'docker login': denied: User: arn:aws:iam::********:user/username is not authorized to perform: ecr:BatchGetImage on resource: arn:aws:ecr:us-east-1:755674844232:repository/spark/emr-6.3.0-latest

I have also ecr:BatchGetImage policy attached to my user. Not sure what I am missing?

A: Looks like the base image URI is incorrect on that documentation page that you linked, just as you suspected. I ran into the same problem, as you described, until I found this YouTube video, which had a working command:
$ aws ecr get-login-password --region us-east-2 | docker login --username AWS --password-stdin 711395599931.dkr.ecr.us-east-2.amazonaws.com
Login Succeeded
$ docker pull 711395599931.dkr.ecr.us-east-2.amazonaws.com/notebook-spark/emr-6.3.0:latest
latest: Pulling from notebook-spark/emr-6.3.0
321892dd332d: Pull complete
af6acd606054: Pull complete
aed277952843: Pull complete
ba95d0bc7985: Pull complete
7ef8149b3bb3: Pull complete
43d41e957447: Pull complete
b149cafdd5e8: Pull complete
Digest: sha256:4fafa37e98762663b55a53fa7c10ede6c58080ecda5e6749dcb2bcb4b15caa9b
Status: Downloaded newer image for 711395599931.dkr.ecr.us-east-2.amazonaws.com/notebook-spark/emr-6.3.0:latest
711395599931.dkr.ecr.us-east-2.amazonaws.com/notebook-spark/emr-6.3.0:latest

Maybe they forgot to update the documentation, when the URI was changed. Wouldn't be the first time in the history of IT...


text:
Q: Is it possible to write a C++ .dll library to export methods which is written within namespace and class? I am newbie to C++ dll concept, just want to know, is it possible to write a C++ .dll library to export method which is written inside a namespace and a class?
What I have tried...
/*JNLib.h Header File*/
#ifndef __JNLIB_H__
#define __JNLIB_H__
#include <string>
#include <vector>
using namespace std;

    namespace JNLib
    {
        class __declspec(dllexport) JNLibClass
        {
        public:
                void split_string();
        };
    }

#endif

and inside .cpp file
/*JNLib.cpp File*/
#include "stdafx.h"
#include "JNLib.h"

    namespace JNLib
    {
        void JNLibClass::split_string()
        {
            cout<<"Library called"<<std::endl;
        }
    }

Now I am able to compile this project and getting .dll file successfully. In another project, I am able to load library (.dll) file successfully by using LoadLibrary() method but GetProcAddress method returns null each time. The code I have written is
typedef void (CALLBACK  *f_funci)();
HINSTANCE dllinstance = LoadLibrary(L"..\\myLIB\\JNLib.dll");
f_funci funci = (f_funci)GetProcAddress(dllinstance, "split_string");

Please let me know what I am doing wrong.

A: There is no symbol called split_string in the library - the name has been mangled.
You can use the dumpbin tool on the DLL to see what symbols are exported. Alternatively, you can move what you want to export out the namespace/class and into an extern "C" block (which stops the name mangling).

A: It is possible to export a method within its namespace from a DLL.
First, define your method with your namespace, and as @OMGtechy wrote above - add the extern "C" decoration:
namespace MyNameSpace{
    extern "C" void foo();
}

Second, edit your project def file to specify your namespace mapping:
LIBRARY MyDllName
EXPORTS
    MyNameSpace::foo=foo

Now, when loading your method specify your namespace:
typedef void(*PFN_MYFUNC)();

HINSTANCE  hLib = ::LoadLibrary("MyDllName");
PFN_MYFUNC pfn  = (PFN_MYFUNC)::GetProcAddress( hLib, "MyNameSpace::foo");


text:
Q: Testing expectations on doubles in Sinatra app using spec I want to verify that a method was called on a service I want to inject into a Sinatra application using rspec but I can't find an example of how this is done. Here is my spec...
RSpec.configure do |config|
  config.include Rack::Test::Methods
end

def app
  App
end

describe 'Login' do
  context 'when the user is logged out' do
    describe 'POST on /signup' do
      it 'invokes signup on the user service with the correct parameters' do
        service = double('user_service').as_null_object
        service.should_receive(:signup).with(:username => 'RobA2345')
        post '/signup'
      end
    end
  end
end

Here the App is a modular Sinatra app. I come from a .NET background and I'd use constructor injection here to solve this problem but I know this isn't the ruby way to do it.
Help, as always, is appreciated.

A: Assuming that you're expecting to receive the message on a new instance of  UserService, there are a couple of ways to do this.  If you are using a recent version of rspec, this should work:
it 'invokes signup on the user service with the correct parameters' do
  UserService.any_instance.should_receive(:signup).with(:username => 'RobA2345')
  post '/signup'
end

Alternatively, this should work in just about any version of rspec:
it 'invokes signup on the user service with the correct parameters' do
  service = double('user_service').as_null_object
  UserService.stub(:new).and_return(service)
  service.should_receive(:signup).with(:username => 'RobA2345')
  post '/signup'
end


text:
Q: Docker complains "Address already in use" after docker restart command I am having a weird issue with my docker container. Everything works fine when dockers daemon starts up for the first time, but when docker is asked to restart a container, it will complain about address already used, despite the container was just running a second ago. This container will not start.
root@server:~# docker restart pihole
Error response from daemon: Cannot restart container pihole: Address already in use

Container is created from a following docker-compose. I do want to host DNS there, so I hardcode the IP addresses the network interface should receive.
version: "2"

services:
  pihole:
    container_name: pihole
    image: pihole/pihole:latest
    environment:
      TZ: 'Europe/Berlin'
      WEBPASSWORD: '**********'
      ServerIP: '192.168.178.16'
    volumes:
      - 'config:/etc/pihole'
      - 'dnsmasq:/etc/dnsmasq.d'
    networks:
      macvlan:
        ipv4_address: 192.168.178.16
        ipv6_address: fe80::10
    cap_add:
      - NET_ADMIN
    restart: unless-stopped

networks:
  macvlan:
    external:
      name: macvlan-bond0

volumes:
  config:
  dnsmasq:

Network macvlan-bond0 is a bulk standard macvlan network, with IPv4 subnet and gateway matching what DHCP would hand out, but with distint IPRange to avoid IP conflicts between containers and full blown hosts on that network.
root@server:~# docker network inspect macvlan-bond0
[
    {
        "Name": "macvlan-bond0",
        "Id": "322a33ac3db4dcaa286f1ca0369b1a50aac36c09a13ed7768d580daadb07db2b",
        "Created": "2022-08-30T11:16:30.144206169+01:00",
        "Scope": "local",
        "Driver": "macvlan",
        "EnableIPv6": true,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.178.0/24",
                    "IPRange": "192.168.178.32/28",
                    "Gateway": "192.168.178.1"
                },
                {
                    "Subnet": "fe80::/64",
                    "Gateway": "fe80::1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "7f71c160e8bd6d163f8fdc888c6a1355bbdd3bfab5e97d69b945c652b0d9c0e3": {
                "Name": "hass",
                "EndpointID": "8e2e911902caa928dfd5be8d476ca22bd65a3c92e2c1583893b7c9259c2224d1",
                "MacAddress": "02:42:c0:a8:b2:11",
                "IPv4Address": "192.168.178.17/24",
                "IPv6Address": "fe80::2/64"
            }
        },
        "Options": {
            "parent": "bond0"
        },
        "Labels": {}
    }
]

The only way to start it up again is to remove the network, recreate it and attach the containers to it again. Or completely restart docker daemon. Both are not ideal as you can imagine.
Am I doing something wrong here?
Running following docker build, on Ubuntu 18.04.6 LTS:
root@server:~# docker --version
Docker version 20.10.17, build 100c701

A: Check who is using same address/port
netstat -anlop|grep <address/port>

Remove container/process
docker rm docker_name
or
kill -9 <pid>

One you ensure address/port is free to use retry.


text:
Q: Explicit zero density estimate for Dirichlet $L$-functions Let's define $N(\alpha,T,\chi)=\sharp\lbrace \rho=\sigma+i\gamma: L(\rho,\chi)=0, \alpha\leq \sigma<1, |\gamma|\leq T\rbrace$ , where $\chi$ is a primitive Dirichlet character. We know, from Gallagher's paper, that
$$\sum_{q\leq T}\sum_{\chi\pmod{q}}N(\alpha,T,\chi)\ll T^{c(1-\alpha)}$$
for every $0\leq \alpha<1$ with $c>0$ an absolute costant.
But what about an explicit value of such costant $c$? I need some good and explicit estimate of the sum above. Can anyone help me?

A: Matti Jutila (On Linnik's Constant, Math. Scand. 41 (1977), 45-62) proved that if $Q\geq 2$, $T\geq 1$, and $4/5\leq\alpha\leq 1$, and $\epsilon>0$, then
$\sum_{q\leq Q}\sideset{}{'}\sum_{\chi\bmod{q}}N(\alpha,\chi,T)\ll_{\epsilon}(Q^2 T)^{(2+\epsilon)(1-\alpha)},$
where the decoration ' indicates a sum over primitive characters.  (The restriction to primitive characters is necessary.)  The density hypothesis (which follows from the generalized Riemann hypothesis for Dirichlet $L$-functions) predicts that the above estimate holds for $1/2\leq\alpha\leq 1$, and so we have the density hypothesis in a limited range of $\alpha$.  Montgomery's bound
$\sum_{q\leq Q}\sideset{}{'}\sum_{\chi\bmod q}N(\alpha,T,\chi)\ll(Q^2 T)^{\frac{3(1-\alpha)}{2-\alpha}}(\log QT)^{13},\qquad 1/2\leq\alpha\leq 4/5$
should suffice for most applications when $\alpha$ is far from 1.


text:
Q: Convergence of $\sum_{n=1}^{\infty}\frac{a^{-n+1}+1}{n^a}$ How do I study the convergence of the series $$\sum_{n=1}^{\infty}\frac{a^{-n+1}+1}{n^a}$$ for $a>0$?
I have tried all the tests I know without succeeding: ratio test, comparison test, root test...

A: Hint:
Write
$$\frac{a^{-n+1}+1}{n^a}=\frac{a^n+a}{a^nn^a}$$
and now apply the (limit or not) comparison test with $\;\frac1{n^a}\;$ . Distinguish cases.

A: The series converges iff $a>1$: if it converges then so does $\sum \frac 1 {n^{a}}$ so we must have $a>1$. Conversely, if $a>1$ then split the series into two parts and show that  each of them converges.

A: We have that
$$\frac{a^{-n+1}+1}{n^a}=\frac{a+a^n}{a^nn^a}$$
then we can distinguish two cases

*

*$0<a\le 1$
$$\frac{a^{-n+1}+1}{n^a}\sim \frac{1}{a^{n-1}n^a}>\frac{1}{n^a}$$

*

*$a>1$
$$\frac{a^{-n+1}+1}{n^a}\sim \frac{1}{n^a}$$


text:
Q: Convert Wordpress shortcodes into plain html I am building a static landing page on WordPress root folder, and I need to import some shortcodes from an existing page located in wp-content directory.
What I do is import with $post = get_post($post_id) the post containing my shortcode, then I extract it ->

$output = apply_filters( 'the_content', $post->post_content );

Finally I do ->

echo do_shortcode($output);

The issue here is that on the page I got displayed only the raw format of the shortcode, like [shortcode];
There is a way to convert shortcodes into plain html so my page can display it correctly or I am missing some require/include somewhere?
I already added define( 'WP_USE_THEMES', false ); require "wp-load.php";

A: First of all, you have a syntax error. If your shortcode is stored in the $output variable, you would need to call echo do_schortcode($output);.
But, wouldn't simply the_content(); do the trick? I believe the shortcodes would be processed if you do this.
You can make a new query with WP_Query, and then use the_content() in the loop.
$args = array(
  'post_type' => 'post', // This selects only posts
  'post_status' => 'publish' // Only published posts
);
// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '
';
    while ( $the_query->have_posts() ) {
        $the_query->the_post(); ?>

<?php the_content(); ?>

    <?php }
    echo '
';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

A: For other who wonders about it: I resolved adding  WPBMap::addAllMappedShortcodes(); to my function, which renders all shortcodes!

define( 'WP_USE_THEMES', false );
require_once "wp-load.php";
require_once "wp-content/themes/salient/functions.php";

/*
Function that gets an object containing post data
and returns in output the post_content value.

Return string.
*/
function get_post_content(){

    //renderize shortcode
    WPBMap::addAllMappedShortcodes();

    $post = get_post(INSERT_POST_NUMBER);
    $output = apply_filters( 'the_content', $post->post_content );
    $value = do_shortcode($output);
    return $value;
}


text:
Q: Execute method when user leaves and then starts application I have a question about the android lifecycle. This is my onCreate method of my main application:
@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    decode = new Decode(this);

    adjustToDimensions();
    setLoadingScreen("Zorgdossier wordt geladen...");
    initReceiver();
    startCommunicationWithServer();
}

I set the screen to a loading screen, initialize a broadcastReceiver and send a message to the server.
Now, when I press the home button and start my application again I always want to start this activity so I've added
android:clearTaskOnLaunch="true"

To the manifest.
But now I want the startCommunicationWithServer() to be executed when the user starts the application again. This method sends a message to the server, and the server on the other hand sends a message that I receive in the receiver.
With this message I decide which screen to show.
I've tried to put it in the onRestart method:
    @Override
protected void onRestart() {
    Log.d("MainActivity", "activity restarted");
    startCommunicationWithServer();
    super.onRestart();
}

But this activity is shown multiple times troughout the application, so the onRestart method is executed each time. But I only need the startCommunicationWithServer() to be executed at the start of the application.
So long story short, how can I call the startCommunicationWithServer() method when the user exits and subsequently starts my application?


text:
Q: Mob limit per chunk Some sources say that there is no mob-limit-per-chunk, other say, that there is one. I found this formula on the Minecraft-Wiki: cap = constant * chunks / 256
Is this true for minecraft vanilla (PC)? If so:

*

*What it the value of "constant"?

*Will mobs despawn if a chunks reaches this limit but more mobs are delivered from other chunks?

Why am I asking this:
I want to build a mob farm without using a mob spawner (see this video). I thought that it would be clever to create a bigger spawn-area by making it 4x the size from the farm in the video. If this limit exists, I would place the farm in a way that it reaches a bigger amount of chunks.

A: This limit is for all existing mobs in the loaded chunks. Generally mobs stop spawning when active mob count reaches this number, but a code quirk allows squids to exceed the limit.
Mobs will not despawn automatically when the limit is reached, only spawning is suppressed. If existing mobs despawn (using their independent criteria), spawning can continue.
Again, limit is per all loaded chunks, not per chunk.
Practically, for mob farms, you usually don't need to consider this limit. The true limiting factor is that mobs immediately despawn when further that 128 meters from the player, so your whole farm must fit a 128 m sphere around where you will stand.
As for the value of constant, try reading the next sentence in the wiki you quoted:
Hostile = 70
Passive = 10
Ambient (Bats) = 15
Water = 5

A: from what i have seen and heard there is no spawn limit per chunk but a spawn limit overall. so the more poeple on a server the less mobs per unlit loaded area.


text:
Q: Kafka-Zookeeper Authentication without SASL I am trying to enable SASL_PLAINTEXT authentication between Kafka broker and client, while not requiring it between Kafka and Zookeeper. Currently I am using confluent offering of Kafka, with CDH Zookeeper. Is there a way to pass in a flag to disable SASL for Kafka <-> Zookeeper?

A: You need to set the environment variable ZOOKEEPER_SASL_ENABLED=false. This is configured for Kafka broker


text:
Q: Solve $(A^TA)^{−1}(X+B^T)(C^{−1}B^{−1})^T =I$ Let $A, B, C \in M_n(\Bbb R)$ be invertible. Find $X \in M_n(\Bbb R)$ such that
$(A^TA)^{−1}(X+B^T)(C^{−1}B^{−1})^T =I$.
Express $X$ using no inverses and at most two transposes and show your choice of $X$
works.
I have no idea where to start. Can somebody give me a hint?

A: Hint: let's take two matrices $P,\,Q$. Then $(PQ)^T=Q^TP^T$ and $(PQ)^{-1}= Q ^{-1} P ^{-1}$. Expand parantheses and express $X$ directly.

A: Hint: $\forall A, B \in M_n(\Bbb R), (AB)^{-1}=B^{-1}A^{-1}$ and $(AB)^T=B^TA^T$

A: Note that
$$(C^{-1}B^{-1})^T=((BC)^{-1})^T=((BC)^T)^{-1}$$
so multiplying on the left and on right of the equality
$$(A^TA)^{−1}(X+B^T)(C^{−1}B^{−1})^T =I$$
by $A^TA$ and $(BC)^T$ respectively we find
$$X+B^T=A^TA(BC)^T=A^TAC^TB^T$$
and finally we have
$$X=A^TAC^TB^T-B^T=(BCA^TA-B)^T$$


text:
Q: Optimizing a Select with Subquery that is loading VERY slow I have a SELECT that is a little bit tricky, as I try to display data that has to be calculated on the fly.
The data is logged from a SmartHome system and displayed in the visualization solution Grafana.
So I have to handle all of this in MySQL and can't really edit the data or the frontend to do some of this work.
The diagram should show the average temperature per day for a time range that can be selected in the UI.
The data in MySQL is a table like that:
   DEVICE    |       READING       |       VALUE       |       TIMESTAMP
-----------------------------------------------------------------------------
 Thermometer |     temperature     |        20.0       |  2107.10.12 00:12:59
 Thermometer |     temperature     |        20.2       |  2107.10.12 00:24:12
                                  ...

The Request first creates a virtual table (that is not in the database) with timestamps for every full hours for about 10 years.
This is running very quick and doesn't seem to be a reason for my slow fetches
After that I strip down the virtual table to values only within the visible time range in my diagram.
On all of these full-hour-timestamps I have to run a sub-select to get the last temperature value that was logged before the full hour.
This values are then grouped by day and the average is calculated.
That way I get the average over 24 values for each full hour from 00:00 to 23:00.
Based on different wether sites, this is how the official average temperature is normally calculated.
Here is the Select Statement:
SELECT
    filtered.hour as time,
    AVG((SELECT VALUE
        FROM history
        WHERE READING="temperature" AND DEVICE="Thermometer" AND TIMESTAMP <= filtered.hour
        ORDER BY TIMESTAMP DESC
        LIMIT 1
    )) as value
FROM (
    SELECT calculated.hour as hour FROM (
            SELECT DATE_ADD(DATE_SUB(DATE($__timeTo()), INTERVAL 10 YEAR), INTERVAL t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i HOUR) as hour
            FROM (SELECT 0 as i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0,
                     (SELECT 0 as i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1,
                     (SELECT 0 as i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2,
                     (SELECT 0 as i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t3,
                     (SELECT 0 as i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t4
    ) calculated
    WHERE calculated.hour >=  $__timeFrom() AND calculated.hour <= $__timeTo()
) filtered
GROUP BY DATE(filtered.hour)

For a timespan of a week it already takes about 5-10 seconds for the diagram to show up. For a month you're close to half a minute.
All my other (simple fetches without calculations) diagrams are loading in about or less than a second.
As I'm a completely MySQL noob and just started to build some SELECTs for my smart home, I don't really know how this can be improved.
Any ideas from the pros? :)

A: Unless I'm overseeing something really obvious and it doesn't really matter on how many results the average per day is calculated you could really simplify your query and get rid of the subquery's. This should also give you a boost in speed.
SELECT DATE(`TIMESTAMP`) AS `date`, AVG(`VALUE`) AS `value` FROM `history` WHERE `READING`='temperature' AND `DEVICE`='Thermometer' AND DATE(`TIMESTAMP`) BETWEEN 'date1' AND 'date2'

Just replace date1 & date2 with the values you want, for example 2017-10-15.


text:
Q: Can there be a "handwritten paper"?
Yesterday, someone slipped this sloppily handwritten scrap of paper under my door.

which (without the adverbs and fancy adjectives) essentially conveys this idea:

Someone gave me a handwritten paper.

But you don't have (see below), do you?

[...] a written paper.

A safe alternative:

Someone gave me a piece of paper on which there was handwriting.

which is too long and bland for my purpose.
Can there be a "handwritten paper"? If not, how should I rephrase my sentence?

A: This question manufactures a problem where none exists.
The only issue one might have with "a handwritten paper" is with  a paper,  which, in the sense of "a sheet of paper, a document", is something of an archaism nowadays, appearing only in legal contexts, which tend to be linguistically formulaic and conservative:

The prosecutor asked the witness if he knew that to be true from
  something he had been told, or from a written paper he had seen.

These days, we say "a piece of paper" or "a note" when our meaning is "sheet or piece of paper" (as distinct from "an essay").

She gave me a handwritten piece of paper.
She gave me a handwritten note.

The adjective handwritten means "having handwriting on it; produced by the act of writing with a handheld implement such as a pen or pencil."

A: Actually "handwritten paper" is fine, although in this case "paper" does not mean the physical material but rather a school essay or other written assignment.  See definition 4 or 7 here.  Example:

She handed in her paper late, but her teacher still gave her an A.

However it's not a phrase you hear much these days.  See this Ngram as an example -- note the sharp decline since 2000.  Students are more often required to submit electronic or printed documents (though I'm sure there are good reasons why a teacher might require a handwritten paper now and then.)
Of course, that's not your question.  The reason I mention the other definition is because when you say:

Someone put a handwritten paper under my door"

The listener will assume you mean a school paper, written by hand.  If you want to be clear that you're talking about a note, then that's what you should say:

Someone put this handwritten note under my door.

The listener will assume the note is written on paper unless otherwise specified:

Someone put this note, written in magic marker on the back of a cardboard pizza box, under my door.

Although a "note" implies there was a message on the paper intended for someone.  If instead there was just some random writing that happened to be on a piece of paper:

Someone put this paper under my door, on which they'd handwritten something, but I have no idea what it says or who it's for.

A: In the first sentence, both "handwritten" and "of paper" apply to the word "scrap," not to each other.
If you were to say, "someone gave me a scrap of paper," I would have no trouble at all comprehending it.
If you were to say, "someone gave me a handwritten scrap," I would think it sounded a touch strange, since scrap is ambiguous.  Does scrap here refer to the quality of what was written on (crumpled paper, perhaps), or does it mean you were only given part of a document?


text:
Q: Elegant applications of advanced techniques to "olympiad" problems I am interested in applications of somewhat "advanced machinery" (with respect to the usual machinery involved in these cases, which is usually elementary) to olympiad or (high school-level) contest problems in mathematics which yield simple, insight-provoking solutions.
This may be something as simple as basic group theory or linear algebra, for instance. I shall post an example of what I'm looking for as an answer.
Please don't post joke-ish things like the "Fermat's Last Theorem is too weak to prove that $\sqrt 2$ is irrational" thing, please.

Perhaps we could make this CW and have separate answers, each on applications of a specific area of mathematics?

A: An example would be Tim Gowers' beautiful proof of the following problem:

Let $n$ be an even integer. How many subsets of the set $\{1,2,\dots,n\}$ can you pick if they all have to have odd size but the intersection of any two of them has to have even size?

using basic linear algebra over finite fields.
Concisely, he considers the characteristic vectors of these subsets and shows that they must be linearly independent over $\Bbb F_2$ for the condition to hold, so the maximum number of such subsets is just $n$.
Takeaway idea: the dot product of the characteristic vectors (over $\Bbb Z$, of course) is equal to the size of the intersection.


text:
Q: How to upload templates and static files to a django app? I am trying to upload webpages to my django server.
They are all project of mine, and I want to be able to add more projects in the future through the admin panel:
I am working in an app called projects
This is the model I am using:
from django.db import models
from django.utils.timezone import now
from django.core.files.storage import FileSystemStorage

# Create your models here.
class Project(models.Model):
    class ProjectType(models.TextChoices):
        PYTHON = 'Python'
        JAVASCRIPT = 'Javascript'
        REACTJS = 'React.js'
        REACTNATIVE = 'React Native'
        JAVA = 'Java'
        C = 'C'
        CPP = 'C++'

    def upload_location_photo(instance, filename):
        return f'photos/projects/{instance.slug}/{filename}'

    def upload_location_template(instance, filename):
        #I want to get into, app: projects, folder: templates/projects
        return f'projects/templates/projects/{instance.slug}/{filename}'

    def upload_location_static(instance, filename):
        #I want to get into, app: projects, folder: static/projects
        return f'projects/static/projects/{instance.slug}/{filename}'

    slug = models.CharField(max_length=200, unique=True)
    project_type = models.CharField(max_length=50, choices=ProjectType.choices, default=ProjectType.JAVASCRIPT)
    title = models.CharField(max_length=150)
    description = models.TextField(blank=True)
    date_completed = models.DateTimeField(default=now, blank=True)
    photo_main = models.ImageField(upload_to=upload_location_photo)
    photo_1 = models.ImageField(upload_to=upload_location_photo, blank=True)
    photo_2 = models.ImageField(upload_to=upload_location_photo, blank=True)
    photo_3 = models.ImageField(upload_to=upload_location_photo, blank=True)
    #FILE UPLOAD OF JS APPS
    file_html = models.FileField(upload_to=upload_location_template, max_length=100, blank=True)
    file_css = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)
    file_js = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)

This is in a django app called projects.
This issue is, that the html, css, and js files are being uploaded into: media/projects/static/projects and media/projects/templates/projects
instead of going into my app, they are being saved in the global media folder, how can I stop this, and direct them into my app's template and static folder?

A: Sorry, I asked that question too soon, however now I can help someone else hopefully!
I needed to add a few lines of code:
new imports:
import os
from django.core.files.storage import FileSystemStorage
from django.conf import settings

Adjust my upload location functions:
    def upload_location_template(instance, filename):
        return f'{instance.slug}/{filename}'

    def upload_location_static(instance, filename):
        return f'{instance.slug}/{filename}'

Create new storage locations, and add them as arguments to my FileFields:
    template_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/templates/projects/'))
    static_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/static/projects/'))
    file_html = models.FileField(upload_to=upload_location_template, storage=template_storage, max_length=100, blank=True)
    file_css = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)
    file_js = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)

It is now working perfectly, used this answer here: https://helperbyte.com/questions/177113/django-multiple-media-root


text:
Q: Spacing and Page Break Issues for long equations. The aligned and align* dilemma Basically, for one long string of equations, I need to be able to have it continue over multiple pages.  I also need there to be a regular new paragraph space between the Title of the page and the string of equations.  I only need this for this particular equation, and need everything else to remain the same.
The aligned environment allows for the spacing to be exactly as I desire, but doesn't allow the page break.
The align* environment allows for the page break, but puts additional white space under the title, which I cannot have.
Is there a way for me to have both the things I desire simultaneously?

A: Insert the instruction \allowdisplaybreaks in the preamble, after loading the amsmath package. And, instead of using the \title and \maketitle machinery, just type \begin{center} \Huge <Title String> \end{center}.


text:
Q: many to many form, mongoid & rails 3 I have 2 models in my app. A Shopping_list and a Product
The shopping list can contain many products, a product can be a part of many shopping lists.
The shopping list -
class Shopping_list
  include Mongoid::Document
  field :name, :type => String
  has_and_belongs_to_many :products
end

And the product
class Product
  include Mongoid::Document
  field :name, :type => String
  has_and_belongs_to_many :shopping_lists
end

If a user visits /shopping_list/some_id/edit I want them to see  -
a) The name of the product in a text box
b) A series of checkboxes listing all of the products that they can check to add to that list.
c) A submit button.

My controller looks like this
def edit
  @shopping_list = Shopping_list.find(params[:id])
  render :action => 'edit'
end

My view looks like this
<%= simple_form_for(@shopping_list) do |f| %>
    <%= f.input :name %>
    <%= f.input :articles, :as => :check_boxes %> #I know this is completely wrong. What do I do to fix?
    <%= f.button :submit %>
<% end %>

This does not work at all and I'm a bit stumped. Not sure how to proceed while using Mongoid.
Advice appreciated.

A: try this
<%= simple_form_for(@shopping_list) do |f| %>
   <%= f.input :name %>
   <%= f.association :products,:collection => @shopping_list.products.collect{ |p| [p.name, p.id] }, :as => :check_boxes %>
   <%= f.button :submit %>
<% end %>


text:
Q: How to add 1 day to the checkout date I want to add 1 more day to the checkout, that is, end date must be greater than start date.
Here are my codes for the bootstrap datepicker:

$(function() {

  $('#datetimepicker1').datetimepicker({
    format: 'YYYY-MM-DD',
    minDate: new Date()
  });

  $('#datetimepicker2').datetimepicker({
    format: 'YYYY-MM-DD',
    minDate: new Date($('#from_date').val())
  });

  $('#from_date').on("blur", function() {
    $('#datetimepicker2').data("DateTimePicker").destroy();
    $('#datetimepicker2').datetimepicker({
      format: 'YYYY-MM-DD',
      minDate: new Date($('#from_date').val())
    });
  });
});

  Check-in

    <input type="text" class="form-control" id="from_date" name="checkin" />

  Check-out

    <input type="text" class="form-control" id="to_date" name="checkout" />

A: You can do something like this:
var date = new Date();
date.setDate(date.getDate() + 1);

A: One solution among many would be to get fromDate in milliseconds via getTime and add 1 day equivalent milliseconds to it:
var fromDate = $('#from_date').val();
// To date = fromDate + 1 day
// milliseconds = 24 hours * 60 minutes * 60 seconds * 1000
var toDateMillisecs = new Date(fromDate).getTime() + (24 * 3600 * 1000);
var toDate = new Date(toDateMillisecs);

A: Just use moment add method for this in combination with linked pickers, after all you need to include the moment library to use the picker.
We set the minDate of the first picker to today using moment() and the maxDate too for the date we choose one the other picker
The minDate of the check-out will be the day selected on the first +1
We listen to the changes using the events provided by the picker in this case dp.change
This way you don't have to be looking for the value of the textbox with blur all the time and it's pretty much easier to understand.

$(function() {
  let $checkIn = $('#datetimepicker1');
  let $checkOut = $('#datetimepicker2');

  $checkIn.datetimepicker({
    useCurrent: false,
    format: 'YYYY-MM-DD',
    minDate: moment()
  });

  $checkOut.datetimepicker({
    useCurrent: false,
    format: 'YYYY-MM-DD',
  });

  $checkIn.on("dp.change", function(e) {
    //Here we add a day more to the Check-out
    $checkOut.data("DateTimePicker").minDate(e.date.add(1, 'day'));
  });

  $checkOut.on("dp.change", function(e) {
    $checkIn.data("DateTimePicker").maxDate(e.date);
  });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet" />

  Check-in

    <input type="text" class="form-control" id="from_date" name="checkin" />

  Check-out

    <input type="text" class="form-control" id="to_date" name="checkout" />


text:
Q: Set new object equal to otherObject.method()? I'm learning java and come across something which confuses me quite a bit. I'm watching a video on an explanation of how http requests work...
URL theURL = new URL("http://www.google.com");
**URLConnection theConn = theURL.openConnection();**

I understand the first line in that it is just creating a URL object with an actual url as an argument. But I don't understand how in the second line, a URLConnection object is being created and being set equal to a method of the other object, or is that method returning something?

A: The method is returning a URLConnection as documented by the URL.openConnection() Javadoc which says (in part)

Returns a URLConnection instance that represents a connection to the remote object referred to by the URL.


text:
Q: NHibernate error accessing Informix database - System error occurred in network function I'm having a problem communicating with the Informix database using NHibernate, for a limited time works, but pass that particular time the error happens.
Follow the evidence below:
NHibernate.TransactionException: Begin failed with SQL exception ---> IBM.Data.Informix.IfxException: ERROR [08S01] [Informix .NET provider]Communication link failure.
   em IBM.Data.Informix.IfxConnection.BeginTransactionObject(IsolationLevel isolevel)
   em IBM.Data.Informix.IfxConnection.BeginTransaction(IsolationLevel isolevel)
   em IBM.Data.Informix.IfxConnection.System.Data.IDbConnection.BeginTransaction(IsolationLevel isolevel)
   em NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   --- Fim do rastreamento de pilha de exceções internas ---
   em NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   em NHibernate.Transaction.AdoTransaction.Begin()
   em NHibernate.Impl.SessionImpl.BeginTransaction()

NHibernate.TransactionException: Begin failed with SQL exception ---> IBM.Data.Informix.IfxException: ERROR [HY000] [Informix .NET provider][Informix]System error occurred in network function.
   em IBM.Data.Informix.DBCWrapper..ctor(IfxConnection connection)
   em IBM.Data.Informix.IfxConnectionPool.IfxConnPoolNode..ctor(IfxConnection connection)
   em IBM.Data.Informix.IfxConnectionPool.OpenNewConnection(IfxConnection connection, ConnectionPoolType ConnPoolType)
   em IBM.Data.Informix.IfxConnectionPool.Open(IfxConnection connection)
   em IBM.Data.Informix.IfxConnPoolManager.Open(IfxConnection connection)
   em IBM.Data.Informix.IfxConnection.Open()
   em NHibernate.Connection.DriverConnectionProvider.GetConnection()
   em NHibernate.AdoNet.ConnectionManager.GetConnection()
   em NHibernate.Impl.SessionImpl.get_Connection()
   em NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   --- Fim do rastreamento de pilha de exceções internas ---
   em NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
   em NHibernate.Transaction.AdoTransaction.Begin()
   em NHibernate.Impl.SessionImpl.BeginTransaction()
   em nddConnect.Client.EntryDocumentsComponent.NHibernate.Context.NHibernateSessionManager.Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
   em Microsoft.Practices.Unity.InterceptionExtension.InterceptionBehaviorPipeline.Invoke(IMethodInvocation input, InvokeInterceptionBehaviorDelegate target)
   em DynamicModule.ns.Wrapped_IComponentFacade_b83011052f234f2b9e18ae4d34bd90cc.CaptureJobConfig(IDictionary`2 dicEntryConfigJob)
   em Connect.Client.EntryDocumentsComponent.Controller.EntryJobController.GetJob(Guid transportActionGuid);

I tried various methods to simulate the error, but all to no avail.
I'm thinking it's a possible latency in the database after that getting something "stuck" in the section.
Could someone help me?

A: You may use DB2 Entity Framework driver to connect Informix server.
(No Entity Framework support by using Informix native .NET driver)
(At IDS server you may need to configure DRDA port to use DB2 EF driver)
By using this driver you will be able to use LINQ commands .
LINQ is one of the alternate for NHibernate.

A: After studies in the customer environment and logs it was found that the error occurred due to completion of a backup in a certain schedule that caused instability in the bank resulting in connection error and after that the the application did not work properly need to be restarted (the service), grateful for the help


text:
Q: Build gradle dependency tree without downloading jars A jar has been removed from organization's repository for being unsafe, but we can download its pom. We are trying to figure which dependencies of a project are dependent on it. Tried running gradle dependencies but that doesn't complete due to the same missing jar.
Is there any gradle command or something similar to create dependency tree for the project without trying to download jars? As far as I understand, creating dependency tree should only require POMs. Please correct me if I am wrong. I am somewhat new with gradle.


text:
Q: What commands exist just for fun? There's lot of stuff we can do at a terminal, many of them very useful.
But, what commands are there that exist only to amuse the user?

A: *

*sl
Very often we mistype ls as sl.
what if you get something like this:

install sl:
sudo apt-get install sl

*Fortune
Fortune ----> prints random stuff

install fortune:
sudo apt-get install fortune

*Cowsay(part 1)
want cow on terminal?

install cowsay
sudo apt-get install cowsay

cowsay + fortune

*cowsay(part 2)
you will see something like this:

install xcowsay
sudo apt-get install xcowsay

*cmatrix

install cmatrix
sudo apt-get install cmatrix

*bb(one of mine favourite)

press 8. turn up volume to max(wear headphone)
it will show you something like this:

And then it will play music!
install bb
sudo apt-get install bb


text:
Q: Any Way to Maintain Data Consistency among Modules? Usually if we have many resources which owned by single module and modified by many threads and we want to keep data consistency among these threads, one way to do that is using locks.
But this seems impossible when resources are distributed into several modules. For example, suppose we have three modules, they are SocketsLayer, SessionLayer, FileTransferLayer. And some other asumptions:

*

*SocketsLayer
Maintain all (non-blocking) sockets;
Use one thread to listen and read from sockets;
Use same thread to delete sockets when closed and notify SessionLayer asynchronously.

*SessionLayer
Create a session for each user;
Each user has one socket called CmdChannel for send/recv commands;
Each user has several sockets called DataChannel for send/recv file data;
Each (username, cmd socket, data sockets) is called a session.
Once socket is registered as CmdChannel for USER, session for this user is created.
Once CmdChannel is closed or broken, Session which owns it became invalid (BE DELETED).
Once Session became invalid, all data sockets became invalid.
Use one thread to create session and delete session.

*FileTransferLayer
Each user has several file transfer tasks;
Each file transfer task has its own data socket;
All tasks belong to one user share one command socket;
Once the user's session became invalid, tasks belong to this user must be deleted.
Use one thread to create tasks and delete tasks.
Suppose one cmd channel is being registered for SomeUser (handled by SessionLayer), now SessionLayer is going to create a session for this user. But what if this cmd socket is closed by peer during the period the session is being created?
UPDATE
Sockets in SocketsLayer and session in SessionLayer and tasks in FileTransferLayer, all these three types of data belong to the same user must keep consistent. But they are owned by different modules, so how to maintain data consistency among these three modules?


text:
Q: Selecting more graphics at once I'm making a map on ArcMap and I converted the legend to graphics in order to manually manage my symbols and texts. For instance I want to increase the size of all the points in the legend to the same value. If I ungroup all elements I can then select all points one by one keeping control key pressed and then change the size for all of them in one move. Then I would need to regroup all the elements together in order to be able to move the legend around as a single piece. The problem is I couldn't find a way to select more graphics at once, for example with a rectangular selection. That would save me much time especially when regrouping.
Alternatively, is there a faster method to do this whole operation (changing legend items size)?

A: Just hold the SHIFT Button down while you draw a  rectangular over the elements.
Fore more details see the ArcGIS help, Using mouse shortcuts in the table of contents.

Shift+click selects all layers or data frames between two layers or data frames within the same table of contents level.


text:
Q: Expression resolves to an unused function So I have been messing around with saving and calling from NSUserDefaults and I have made progress but I keep on getting this error.
"Expression resolves to an unused function"
The program is supposed to save a string from a textfield so that if you close the program and open it the string will still be their. Unless, you press save again and then the string (Label) will change.
The problem prevents me from running the program so I have not been able to test the new code that I wrote.
Here is the source code feel free to try it.  All of this is written in swift.
//
//  ViewController.swift
//  Help
//
//  Created by Lucas on 9/30/15.
//  Copyright (c) 2015 Lucas. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet var Savedlbl: UILabel!
    @IBOutlet var Textfield: UITextField!
    @IBOutlet var Label: UILabel!

    var current = ""
    var Saved = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        let currentDefault = NSUserDefaults.standardUserDefaults()

        Savedlbl.text = currentDefault.valueForKey("saved") as? String

        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func Set(sender: AnyObject) {

        setall()

    }
func setall()
    {
        current = Textfield.text!
        Label.text = Textfield.text!
        Savedlbl.text = Textfield.text!

        let currentDefault = NSUserDefaults.standardUserDefaults()

        Savedlbl.text = currentDefault.valueForKey("saved") as? String
         currentDefault.setValue(Saved, forKey: "saved")
            currentDefault.synchronize
            }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

A: The line:
currentDefault.synchronize

should be:
currentDefault.synchronize()


text:
Q: Outlook 2010 still automatically downloading pictures even though its turned off One of my users at work has received an email with what looks like a webbug image in; however the URL is a UNC network path "\\af12.mail.ru\cgi-bin\" and Outlook pops up a "Connecting to: \\af12.mail.ru\cgi-bin\" message as it tries to connect, so I checked the automatic download settings and made sure they were set to not allow automatic download:

After restarting Outlook and opening the email the connecting message came up again, I've checked the settings and they are still as I've set them.

A: You may create a Registry Key to block this:
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common
Dword: BlockHTTPImages
Value: 1
If issue continues, we can run outlook in safe mode as suggested in this TechNet thread to see the result.
To do this, please exit Outlook. Press Win +R to open Run. Type outlook /safe and then click Enter.


text:
Q: Apt-get installers: how does it works I need to learn new aspect of development: making apt-get installers. Because of it, I need to find out, how it works. I tried to search information about it, but 90% of it is apt-get man's.
For example: user prints sudo apt-get install package_name, and what? Is there installation script on server from sources.list file? If yes, how does it execute on client's computer?
I'll be glad to learn it with your help. May be it's stupid question, but I really can't find necessary information about this topic. Thank you!

A: Short answer is apt-get download package from server which sources.list includes and execute install script. Long answer is you can study the debian developer document from http://www.debian.org/doc/manuals/developers-reference/best-pkging-practices.html.


text:
Q: Violation of Fatou's theorem? I have an assignment where the answer I have come up with violates Fatou's lemma. Clearly, I have either reached the wrong answer or misunderstood Fatou's lemma. Please help me find out which one it is!
We have a measure space (X, A, u) and a sequence of pair-wise disjoint subsets $(A_{n} )_{n \in \mathbb{N}}$. u($A_{n})=1$ for all $n \in \mathbb{N}$.
We also have a sequence of (indicator)functions $f_{n}=1_{A_{n}}$.
We are now asked to calculate $\underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}$ and determine which of the values $\int \underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}\: du$ and $\underset{n\rightarrow \infty}{\text{limsup}} \int f_{n} \: du$ are largest.
Fatou's lemma is that $\underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}\leq \int \underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}\: du$, as long as $f_{n}$ are all bounded.
The answer I've come up with is $\underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}=1_{\emptyset}$, $\int \underset{n\rightarrow \infty}{\text{limsup}}\:f_{n}\: du=0$ and $\underset{n\rightarrow \infty}{\text{limsup}} \int f_{n} \: du=1$. Where am I going wrong?

A: The hypothesis for this version of Fatou's lemma is that there exists a non-negative, integrable function $g$ such that $f_n \leq g$ for all $n$; i.e., $\int \sup_n f_n <+\infty$. This fails for your sequence, since $\sup_n f_n$ is the indicator function of a set of infinite measure.
Also, it looks like just a typo, but the conclusion should be $\limsup \int f_n \leq \int \limsup f_n$.


text:
Q: trying to create a switch with logical operators #include <iostream>
#include <string>
using namespace std;

int main()
{
    int Hours;
    cout << "please enter number of hours worked";
    cin >> Hours;
    switch (Hours)
    {
    case 1: Hours == 40;
        cout << "worked full time this week";
        break;
    case 2:   Hours <= 30;
        cout << "You worked less than 40 this week available shifts on board";
        break;
    case 3: Hours > 30 && Hours < 40;
        cout << "You almost have 40 hrs check the board to see if shifts are available please do not go over 40 hrs";
        break;
    default:
        cout << " invalid entry see you manager or try again";
    }

    {

    return 0;

}

I've done something wrong honestly do not really understand switch statements so just doing something pretty basic. I am getting a build error every time I try to run it. I want the user to input how many hrs worked and based on that display the message. I think an if/else statement would honestly be better but wanted to use a switch statement to get some practice.

A: That's not the way you use switch
switch will take the value and compare it with all case. You can't do larger and less using switch.
You should use if-else instead:
if(Hours == 40)
{
    std::cout << "worked full time this week";
}
else if(Hours <= 30)
{
    std::cout << "You worked less than 40 this week available shifts on board";
}
else if(Hours > 30 && Hours < 40)
{
    std::cout << "You almost have 40 hrs check the board to see if shifts are available please do not go over 40 hrs";
}
else
{
    std::cout << " invalid entry see you manager or try again";
}


text:
Q: Не работает скрипт по стрельбе в canvas

var game = {
  sprites: {
    battleship: undefined,
    enemyShip: undefined,
    //Пуля
    bullet: undefined
  },

  init: function() {
    var canvas = document.getElementById('myCanvas');
    this.ctx = canvas.getContext("2d");

    this.width = canvas.width;
    this.height = canvas.height;

    window.addEventListener('keydown', (event) => {
      if (event.keyCode == 37 && game.battleship.x > 0) {
        game.battleship.x -= 8
      } else if (event.keyCode == 39 && game.battleship.x < 710) {
        game.battleship.x += 8
      }
    });
  },

  load: function() {
    for (var key in this.sprites) {
      this.sprites[key] = new Image();
      this.sprites[key].src = "sprites/" + key + ".png";
    }
  },

  start: function() {
    this.init();
    this.load();
    this.run();
  },

  render: function() {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.ctx.drawImage(this.sprites.battleship, battleship.x, battleship.y, 68, 68);

    for (var i = 0; i < this.enemyShipes.length; i++) {
      let enemyShip = this.enemyShipes[i];
      this.ctx.drawImage(this.sprites.enemyShip, enemyShip.x, enemyShip.y, 60, 60);

      if (enemyShip.y !== battleship.y - 61) {
        enemyShip.y += enemyShip.grav;
      }

      if (enemyShip.y == 60) {
        this.enemyShipes.push({
          x: Math.floor(Math.random() * 710),
          y: 0,
          grav: 0
        });
      };
    }

    //Вот я повесил событие в котором условие которое проверяет, если нажата кнопка пробел то этот
    //элемент должен появляться на холсте, но пуля не появляется
    window.addEventListener('keydown', (event) => {
      if (event.keyCode == 32) {
        this.ctx.drawImage(this.sprites.bullet, this.bullet.x, this.bullet.y, 18, 32);
      }
    })
  },

  run: function() {
    this.render();

    window.requestAnimationFrame(() => {
      game.run();
    });
  }
};

game.battleship = {
  x: 355,
  y: 520
}

let battleship = game.battleship;

game.enemyShipes = [];
game.enemyShipes[0] = {
  x: Math.floor(Math.random() * 710),
  y: 0,
  grav: 1
}

//Параметры пули
game.bullet = {
  x: battleship.x + 25,
  y: battleship.y
}

window.addEventListener('load', () => {
  game.start()
});
* {
  padding: 0;
  margin: 0;
}

@font-face {
  font-family: cosmoFont;
  src: url(fonts/CosmoShrift.otf);
}

body {
  background-image: url(sprites/background.jpg);
  background-repeat: no-repeat;
  font-family: cosmoFont;
}

canvas {
  background-color: #686868;
  opacity: 0.5;
  display: block;
  margin: 0 auto;
  margin-top: 40px;
}

.game-name {
  color: #ffffff;
  text-align: center;
  font-size: 40px;
  margin-top: 20px;
}

Cosmo War

<canvas id="myCanvas" width="780" height="620"></canvas>

A: Проблема заключается в том, что не сохраняется и не отрисовывается в новом кадре уже созданный снаряд, как это делается с кораблями. Т.е. если мы отключим очистку экрана, то увидим отрисованый снаряд:

var game = {
  sprites: {
    battleship: undefined,
    enemyShip: undefined,
    //Пуля
    bullet: undefined
  },

  init: function () {
    var canvas = document.getElementById("myCanvas");
    this.ctx = canvas.getContext("2d");

    this.width = canvas.width;
    this.height = canvas.height;

    window.addEventListener("keydown", (event) => {
      if (event.keyCode == 37 && game.battleship.x > 0) {
        game.battleship.x -= 8;
      } else if (event.keyCode == 39 && game.battleship.x < 710) {
        game.battleship.x += 8;
      }
    });
  },

  load: function () {
    for (var key in this.sprites) {
      this.sprites[key] = new Image();
      this.sprites[
        key
      ].src = `https://via.placeholder.com/50x50.png?text=${key}`; //"sprites/" + key + ".png";
    }
  },

  start: function () {
    this.init();
    this.load();
    this.run();
  },

  render: function () {
    //this.ctx.clearRect(0, 0, this.width, this.height);
    this.ctx.drawImage(
      this.sprites.battleship,
      battleship.x,
      battleship.y,
      68,
      68
    );

    for (var i = 0; i < this.enemyShipes.length; i++) {
      let enemyShip = this.enemyShipes[i];
      this.ctx.drawImage(
        this.sprites.enemyShip,
        enemyShip.x,
        enemyShip.y,
        60,
        60
      );

      if (enemyShip.y !== battleship.y - 61) {
        enemyShip.y += enemyShip.grav;
      }

      if (enemyShip.y == 60) {
        this.enemyShipes.push({
          x: Math.floor(Math.random() * 710),
          y: 0,
          grav: 0
        });
      }
    }

    //Вот я повесил событие в котором условие которое проверяет, если нажата кнопка пробел то этот
    //элемент должен появляться на холсте, но пуля не появляется
    window.addEventListener("keydown", (event) => {
      if (event.keyCode == 32) {
        this.ctx.drawImage(
          this.sprites.bullet,
          this.bullet.x,
          this.bullet.y,
          50,
          50
        );
      }
    });
  },

  run: function () {
    this.render();

    window.requestAnimationFrame(() => {
      game.run();
    });
  }
};

game.battleship = {
  x: 100,
  y: 100
};

let battleship = game.battleship;

game.enemyShipes = [];
game.enemyShipes[0] = {
  x: Math.floor(Math.random() * 200),
  y: 0,
  grav: 1
};

//Параметры пули
game.bullet = {
  x: battleship.x + 100,
  y: battleship.y
};

window.addEventListener("load", () => {
  game.start();
});
canvas {
  width: 300px;
  height: 300px;
}
<canvas id="myCanvas"></canvas>


text:
Q: How do I add a submit button, and specify that the form should go to "/action_page.php"? Add a submit button, and specify that the form should go to "/action_page.php".
<form ____________="/action_page.php">

Name: <input type="text" name="name">

<_________________________>

A: Try this:
<form action="/action_page.php">
    Name: <input type="text" name="name">
    <input type="submit" value="Send Request">
</form>

A: You must use:
<form method="get" action="/action_page.php">
  <input type="submit" value="Submit"/>
</form>

And learn this https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form


text:
Q: syntax error, unexpected '}' - weird I'm using the code down below to delete old files, but it keeps saying: syntax error, unexpected '}', but I can't spot where, please help me to fix it..
function destroy($dir) {
$mydir = opendir($dir);
while($file = readdir($dir)) {
    if($file != "." && $file != "..") {
        chmod($dir.$file, 0777);
        if(is_dir($dir.$file)) {
            chdir('.');
            while($dir.$file) {
                if(date("U",filectime($file) >= time() - 3600)
                {
                    unlink($dir.$file)
                }
            }

        }
        else
            unlink($dir.$file) or DIE("couldn't delete $dir$file
");
    }
}
closedir($dir);
}

A: function destroy($dir) {
$mydir = opendir($dir);
while($file = readdir($dir)) {
    if($file != "." && $file != "..") {
        chmod($dir.$file, 0777);
        if(is_dir($dir.$file)) {
            chdir('.');
            while($dir.$file) {
                if(date("U",filectime($file) >= time() - 3600)) // missing )
                {
                    unlink($dir.$file); // missing ;
                }
            }

        }
        else
            unlink($dir.$file) or DIE("couldn't delete $dir$file
");
    }
}
closedir($dir);
}