text:
Q: Виджет на пустые данные авторизации У меня есть три окна, главное окно, окно с авторизацией и тест.
В окне авторизации данные заполняются пользователем отправляются в БД.
После нажатия кнопки  и в случае пустых полей необходимо чтобы появлялось окно  предупреждающее о том, что данные не заполнены и в БД ничего не отправлялось.
main.py:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox)
from titul import Ui_mainWindow
from login import Ui_Login
from test import Ui_Test
from Leksia import Ui_Leksia
import pymysql
from config import host, user, password, db_name

class MainWindow(QtWidgets.QMainWindow, Ui_mainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.connection = pymysql.connect(
            host=host,
            port=3306,
            user=user,
            password=password,
            database=db_name,
            cursorclass=pymysql.cursors.DictCursor
        )
        self.cursor = self.connection.cursor()

        self.Button_startTest.clicked.connect(self.openLogin)
        self.Button_runLR.clicked.connect(self.openLeksia)

    def openLeksia(self):
        self.leksia = LeksiaWindow()
        self.close()
        self.leksia.show()

    def openLogin(self):
        self.login = LoginWindow(self.connection)
        self.close()
        self.login.show()

class LeksiaWindow(QtWidgets.QMainWindow, Ui_Leksia):
    def __init__(self):
        super(LeksiaWindow, self).__init__()
        self.setupUi(self)

        self.pushButton_2.clicked.connect(self.returnToMain)

    def returnToMain(self):
        self.close()
        w.show()

class TestWindow(QtWidgets.QMainWindow, Ui_Test):
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setupUi(self)

class LoginWindow(QtWidgets.QMainWindow, Ui_Login):
    def __init__(self, connection):
        super(LoginWindow, self).__init__()
        self.setupUi(self)
        self.connection = connection
        self.cursor = self.connection.cursor()

        self.pushButton.clicked.connect(self.check_password)
        self.pushButton.clicked.connect(self.opentest)

    def opentest(self):
        self.fio = self.lineEdit_2.text()
        self.grupp = self.lineEdit_3.text()
        self.cursor.execute(f"INSERT INTO students (ФИО, Номер_группы) VALUES ('{self.fio}', '{self.grupp}')")
        self.connection.commit()

        self.test = TestWindow()
        self.close()
        self.test.show()

    def check_password(self):
        msg = QMessageBox()

        if self.lineEdit_2.text() == 'Username' and self.lineEdit_3.text() == '000':
            msg.setText('Данные отправлены')
            msg.exec_()
            app.quit()
        else:
            msg.setText('Введите данные')
            msg.exec_()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

tityl.py:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_mainWindow(object):
    def setupUi(self, mainWindow):
        mainWindow.setObjectName("mainWindow")
        mainWindow.resize(1100, 800)
        mainWindow.setStyleSheet("background-color: rgb(255, 255, 255);")
        mainWindow.setAnimated(True)
        self.centralwidget = QtWidgets.QWidget(mainWindow)
        self.centralwidget.setAutoFillBackground(False)
        self.centralwidget.setObjectName("centralwidget")
        self.Button_runLR = QtWidgets.QPushButton(self.centralwidget)
        self.Button_runLR.setGeometry(QtCore.QRect(400, 310, 271, 81))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.Button_runLR.setFont(font)
        self.Button_runLR.setStyleSheet("background-color: rgb(227, 210, 255);")
        self.Button_runLR.setObjectName("Button_runLR")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1101, 801))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("images.jpg"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        self.Button_startTest = QtWidgets.QPushButton(self.centralwidget)
        self.Button_startTest.setGeometry(QtCore.QRect(400, 530, 271, 81))
        font = QtGui.QFont()
        font.setFamily("Tahoma")
        font.setPointSize(14)
        self.Button_startTest.setFont(font)
        self.Button_startTest.setStyleSheet("background-color: rgb(227, 210, 255);")
        self.Button_startTest.setObjectName("Button_startTest")
        self.Button_Rezylt = QtWidgets.QPushButton(self.centralwidget)
        self.Button_Rezylt.setGeometry(QtCore.QRect(400, 420, 271, 81))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.Button_Rezylt.setFont(font)
        self.Button_Rezylt.setStyleSheet("background-color: rgb(227, 210, 255);")
        self.Button_Rezylt.setObjectName("Button_Rezylt")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(350, 100, 381, 51))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(227, 210, 255);")
        self.label_2.setObjectName("label_2")
        self.label.raise_()
        self.Button_runLR.raise_()
        self.Button_startTest.raise_()
        self.Button_Rezylt.raise_()
        self.label_2.raise_()
        mainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, mainWindow):
        _translate = QtCore.QCoreApplication.translate
        mainWindow.setWindowTitle(_translate("mainWindow", "Главная"))
        self.Button_runLR.setText(_translate("mainWindow", "Начать лабораторную \n"
"работу"))
        self.Button_startTest.setText(_translate("mainWindow", "Начать тест"))
        self.Button_Rezylt.setText(_translate("mainWindow", "Посмотреть результаты"))
        self.label_2.setText(_translate("mainWindow", "Изучение этапов преобразования биосигналов"))

login.py:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Login(object):
    def setupUi(self, Login):
        Login.setObjectName("Login")
        Login.resize(1100, 800)
        Login.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Login)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(280, 120, 581, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(490, 440, 141, 71))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.pushButton.setObjectName("pushButton")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(480, 310, 141, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_3.setObjectName("label_3")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(520, 190, 61, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(380, 260, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(380, 360, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth())
        self.lineEdit_3.setSizePolicy(sizePolicy)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(-4, -8, 1111, 811))
        self.label_4.setAutoFillBackground(False)
        self.label_4.setText("")
        self.label_4.setPixmap(QtGui.QPixmap("images2.jpg"))
        self.label_4.setScaledContents(True)
        self.label_4.setObjectName("label_4")
        self.label_4.raise_()
        self.label.raise_()
        self.pushButton.raise_()
        self.label_3.raise_()
        self.label_2.raise_()
        self.lineEdit_2.raise_()
        self.lineEdit_3.raise_()
        Login.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, Login):
        _translate = QtCore.QCoreApplication.translate
        Login.setWindowTitle(_translate("Login", "Авторизация"))
        self.label.setText(_translate("Login", "
Для прохождения теста необходимо заполнить ФИО и номер группы
"))
        self.pushButton.setText(_translate("Login", "Продолжить"))
        self.label_3.setText(_translate("Login", "
Номер группы
"))
        self.label_2.setText(_translate("Login", "
ФИО
"))

test.py:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Test(object):
    def setupUi(self, Test):
        Test.setObjectName("Test")
        Test.resize(1100, 800)
        Test.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Test)
        self.centralwidget.setObjectName("centralwidget")
        Test.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(Test)
        self.statusbar.setObjectName("statusbar")
        Test.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(Test)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1100, 21))
        self.menubar.setObjectName("menubar")
        Test.setMenuBar(self.menubar)

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

    def retranslateUi(self, Test):
        _translate = QtCore.QCoreApplication.translate
        Test.setWindowTitle(_translate("Test", "Тест"))

A: Я не уверен что правильно понял, то что вы хотите сделать.
Но предложу попробовать заменить класс LoginWindow:
class LoginWindow(QtWidgets.QMainWindow, Ui_Login):
    def __init__(self, connection):
        super(LoginWindow, self).__init__()
        self.setupUi(self)
        self.connection = connection
        self.cursor = self.connection.cursor()

        self.pushButton.clicked.connect(self.check_password)
        self.pushButton.clicked.connect(self.opentest)

    def opentest(self):
        self.fio = self.lineEdit_2.text()
        self.grupp = self.lineEdit_3.text()
        self.cursor.execute(f"INSERT INTO students (ФИО, Номер_группы) VALUES ('{self.fio}', '{self.grupp}')")
        self.connection.commit()

        self.test = TestWindow()
        self.close()
        self.test.show()

    def check_password(self):
        msg = QMessageBox()

        if self.lineEdit_2.text() == 'Username' and self.lineEdit_3.text() == '000':
            msg.setText('Данные отправлены')
            msg.exec_()
            app.quit()
        else:
            msg.setText('Введите данные')
            msg.exec_()

на
class LoginWindow(QtWidgets.QMainWindow, Ui_Login):
    def __init__(self, connection):
        super(LoginWindow, self).__init__()
        self.setupUi(self)

        self.connection = connection
        self.cursor = self.connection.cursor()

#        self.pushButton.clicked.connect(self.check_password)
#        self.pushButton.clicked.connect(self.opentest)
        self.pushButton.clicked.connect(self.check_password)              # +++

    def opentest(self):
#        self.fio = self.lineEdit_2.text()
#        self.grupp = self.lineEdit_3.text()

        self.cursor.execute(
            f"INSERT INTO students (ФИО, Номер_группы) VALUES ('{self.fio}', '{self.grupp}')"
        )
        self.connection.commit()

        self.test = TestWindow()
        self.test.show()
        self.close()

    def check_password(self):
        self.fio = self.lineEdit_2.text()
        self.grupp = self.lineEdit_3.text()
        if not self.fio or not self.grupp:
            msg = QMessageBox.information(
                self,
                'Внимание',
                'Введите данные для авторизации.'
            )
            return
        elif self.fio != 'Username' or self.grupp != '000':
            msg = QMessageBox.information(
                self,
                'Внимание',
                'Не правильно ввели данные для авторизации.'
            )
            return

        self.opentest()


text:
Q: Plotly-Dash displays the wrong graph (line plot instead of funnel) I am trying to display a simple funnel graph using dash and plotly. The problem is that it displays a line graph instead.
I followed the instructions from this answer, that is, used the code:
app = dash.Dash()

app.layout = html.Div([dcc.Graph(id='FunnelDashboard',
                figure = {'data':[
                        go.Funnel(
                        y = ["Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"],
                        x = [39, 27.4, 26.6, 11, 2])]
                        }
                        )])
if __name__ == '__main__':
    app.run_server()

but am getting this line plot instead.
What I expect to get is something like this.

A: Update dash:
pip install -U dash

With version 1.9.1, using this code:
import dash
import dash_html_components as html
import dash_core_components as dcc
from plotly import graph_objects as go

fig = go.Figure(go.Funnel(
    y = ["Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"],
    x = [39, 27.4, 20.6, 11, 2]))

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([dcc.Graph(id='FunnelDashboard',
                    figure=fig)])

if __name__ == '__main__':
    app.run_server()

you get:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sum values of a row of a pandas dataframe efficiently I have a python dataframe with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here
import pandas as pd
import numpy as np
df=pd.Dataframe(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])

Now here is what I want to achieve
df['D']=0.5*df['A']+0.3*df['B']+0.2*df['C']

The other alternative is to use the apply functionality of pandas
df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'])

I wanted to know which method takes less time when we have 1.5 millon rows and have to combine 8 columns

A: First method is faster, because is vectorized:
df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
print (df)

#[30000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)

df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
#similar timings with mul function
#df['D1']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)

df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)

print (df)

In [54]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
The slowest run took 10.84 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 950 µs per loop

In [55]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
The slowest run took 4.76 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.2 ms per loop

In [56]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 928 ms per loop

Another testing in 1.5M size DataFrame, apply method is very slow:
#[1500000 rows x 6 columns]
df = pd.concat([df]*500000).reset_index(drop=True)

In [62]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
10 loops, best of 3: 34.8 ms per loop

In [63]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
10 loops, best of 3: 31.5 ms per loop

In [64]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 47.3 s per loop

A: Using @jezrael's setup
df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
df = pd.concat([df]*30000).reset_index(drop=True)

Far more efficient to use a dot product.
np.array([[.5, .3, .2]]).dot(df.values.T).T

Timing


text:
Q: res.send() not returning anything I am using the Vimeo library to display a specific video.
My Node.js code:
app.get("/video/:id", (req, res) => {
    client.request(
    {
        method: "GET",
        path: `/videos/${req.params.id}`,
    },
    (error, body) => {
        if (error) {
            console.log(error);
        }

        res.send(body.data);
    });
});

console.log() before res.send() displays the object perfectly but does not send it, even though I get 200 response, the body is completely empty.


text:
Q: _.each will not loop through localStorage? When I try and run
_.each(localStorage, function(val){console.log(val)});

I get undefined for each value.

A: You can't directly iterate through LocalStorage because it's a Storage object.
If you want all the items in LocalStorage as an array, you can use _.values:
var values = _.values(localStorage);

Then you can iterate through the values:
_.each(values, function (val) { console.log(val); });

A: You don't need underscore.js
for(var key in localStorage) {
    console.log(localStorage.getItem(key))
}

or encapsulated
Object.keys(localStorage).map(function(key) {
    console.log(localStorage.getItem(key))
})


text:
Q: How to create internationalized blog with Strapi using Next.js getStaticPaths & getStaticProps I have a problem figuring out how to localize my content with Next.js and Strapi.
my current file structure looks like so:
pages/
   blog/
    - [post].tsx
    - portfolio.tsx

Inside portfolio I am fetching data for all posts created on Strapi, depending on which locale is currently set, like so:
  export const getStaticProps = async ({ locale }) => {
  const res = await fetch(
    `https://strapi.com/api/articles?locale=${locale}&populate=*`
  );
  const data = await res.json();

  return {
    props: {
      articles: data.data,
    },
  };
};

In [post] it looks like that:
  export const getStaticPaths = async ({ locales, locale }) => {
  const res = await fetch(
    `https://strapi.com/api/articles?locale=${locale}&populate=*`
  );

  const data = await res.json()

  const ids = data.data.map((post: any) => post.id);
  const paths = ids
    .map((id: any) =>
      locales.map((locale: any) => ({
        params: { post: id.toString() },
        locale,
      }))
    )
    .flat();

  return {
    paths,
    fallback: false,
  };
};

export const getStaticProps = async (context: any) => {
  const id = context.params.post;

  const res = await fetch(
    `https://strapi.tincors.com/api/articles/${id}?populate=*`
  );

  const res_blocks = await fetch(
    `https://strapi.tincors.com/api/articles/${id}?populate[blocks][populate]=*`
  );

  const data = await res.json();
  const blocks_data = await res_blocks.json();
  const block_data_slider = blocks_data.data.attributes.blocks[0].files.data;
  return {
    props: { article: data.data, slider: block_data_slider },
  };
};

Note that each article on Strapi has different id for it's localized version - so as an example:
article_1_pl has id of 10
but it's english variant has id of 12.
fun fact - on portfolio.tsx data is fetched successfully, and post miniature cards are properly displaying based on the current domain (on dev I am using two different hosts for i18n - localhost:3000 for PL & example.com:3000 for EN).
However once I try to redirect myself to the full article, by clicking on the post miniature card, I get the 404 page not found error in the browser, with these errors poping each second in the console logs Error.
It doesn't matter which local host I am currently at.
cards are wrapped in a <Link href="/blog/${id}" locale={route.locale} />
However the moment I change my code in [post].tsx by removing the "locale" from the endpoint:
   const res = await fetch(
    `https://strapi.com/api/articles?locale=${locale}&populate=*`
  );

to:
  const res = await fetch(
    `https://strapi.com/api/articles?populate=*`
  );

suddenly each of my PL articles on localhost:3000 are displayed properly, and only the english variants aren't working (404 page not found).
I assume that it is due to the fact, that by removing the "locale" from the API endpoint it only fetches the polish articles, not the english ones, but it baffles me why it's not working at all, when I use the localized endpoint source.
How I want my app to work:
I want article description (which is generated as a dynamic route) to display in active language, by fetching localized data by the post id.
My question is:
How do I fetch the proper localized data from Strapi in [post].tsx
when using getStaticPaths & getStaticProps. What is wrong with above code and how do I fix it?
I apologize if the above description is too chaotic to understand - feel free to ask for more explanations if necessary :)


text:
Q: How many cube roots does 1 have modulo 162? How many cube roots does $1$ have modulo $162$
this is equivalent to saying how many solutions to $x^3 \equiv 1 $ mod$162$
all my attempts are leading a dead end any help appreciated
the fact that 162 is Non-Carmichael doesn't seem to be an use
also this is at elementary number theory level so no group theory please
thanks

A: You have $162 = 2 \times 3^4$, so
$$(\mathbb Z/162 \mathbb Z)^\times = (\mathbb Z/2 \mathbb Z)^\times \times (\mathbb Z/3^4 \mathbb Z)^\times = (\mathbb Z/3^4 \mathbb Z)^\times.$$
Now, $(\mathbb Z/3^4 \mathbb Z)^\times = (\mathbb Z/3 \mathbb Z)^\times \times \mathbb Z/3^3 \mathbb Z$ is cyclic of order $\varphi(3^4)=54$, being a product of two cyclic groups of relatively prime orders $2$ and $3^3$. Since $3 \mid 54$, there are exactly $3$ elements in $(\mathbb Z/3^4 \mathbb Z)^\times$ of order $3$.

A: $162=3^4*2$
So you want
$x^3\equiv 1 \bmod 3^4$ and $x^3\equiv1 \bmod 2$, by the Chinese remainder theorem.
So $x^3\equiv1 \bmod 2.$
For the other part, $3^4$ has a cyclic multiplicative subgroup since $\lambda(3^4)=\varphi(3^4)$; by Carmichael's theorem, we have $\varphi(3^4)=54$. Find a primitive root $p$ (we know one exists); your solutions will be $1,p^{18},p^{36}.$
$2$ is a primitive root: So we want $1,2^{18}$ and $2^{36}$. We can calculate both of these via exponentiation by squaring.
We get $2^{18}\equiv28$ and $2^{36}\equiv 55$.
So the solutions are $1,55$ and $109$.

A: As $162$ is of the form $2p^m$ where prime $p=3,m=4$
it has at least one primitive root $g$(say).
Applying Discrete Logarithm on $x^3\equiv1\pmod{162}\ \ \ \ (1)$,
$3$indx$_gx\equiv0\pmod{54}\ \ \ \ (2)$
as $\phi(162)=\phi(2)\phi(81)=1\cdot3^{4-1}(3-1)=54$
Now using  Linear Congruence Theorem, as $(3,54)=3$ divides $0,$ equation$(2),$ has consequently $(1)$ will have exactly three solutions.

A: I believe the question is equivalent to asking what $x$ satisfies $x^3 \equiv 1 \mod 162$
I wrote the simple script:
for x = 1 to 161
    if ((x*x*x) mod 162 == 1) print x

This gave me 1, 55, and 109.


text:
Q: Multiple conditions in Twig I'm building a template with Twig. I was wondering what the fastest/best way is to deal with an if statement with multiple conditions.
Let's say I have 3 Images with 3 possible positions. Normally I would do this:
{% if image1 == 'centerleft' or 'topleft' or 'bottomleft' %}
{% set model_position = 'right' %}{% else %}{% set model_position = 'left' %}
{% endif %}

{% if image2 == 'centerleft' or 'topleft' or 'bottomleft' %}
{% set model_position = 'right' %}{% else %}{% set model_position = 'left' %}
{% endif %}

etc....
Is there a faster/cleaner way to do this? I can't figure out how to do that.

A: Try with this:
{% set model_position = image1 in ['centerleft', 'topleft', 'bottomleft'] ? 'right': 'left' %}

And so on...
edit - explanation:
I'm using ternary operator to get either left or right depending on the condition. in is Twig's containment operator and works like in_array function in PHP
So, if image1 is one of centerleft, topleft or bottomleft then right, else left


text:
Q: Why shouldn't I use apt-get install --qq without a no-action modifier? From man apt-get:

Note that quiet level 2 implies -y; you should never use -qq without a no-action modifier such as -d, --print-uris or -s as APT may decide to do something you did not expect.

Those options all, as suggested, don't actually install anything. What's wrong with using -qq as a quieter alternative to -y ?

A: When you use apt-get  without a no-action modifier, it means you are going to perform some actual operation with packages like install, remove, upgrade etc.
Single -q means quiet. It produces output suitable for logging, omitting progress indicators. But when you use -qq which is quiet level 2, it  implies quit with -y (--assume-yes). In this case no output will be produces except error.
Now why it is considered as dangerous?
Sometime apt-get removes some packages to satisfy the dependency. Using -qq in such condition may remove some package which is important for you or for the system without informing you.
So it is not considered as safe because  such operation can make your system unstable.


text:
Q: Environment variables not loading I just set up a server on ec2 and installed all that was needed.
Trying to start my rails app from the app's root dir in the ec2 instance using
RAILS_ENV=production rails s

gives me an error which suggests that my environment variables aren't loading
`validate_options': Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)
I have this in my ~/.bashrc
export S3_KEY="XXXXXXXXXXX"
export S3_SECRET="XXXXXXXXX"
export S3_REGION="XXXXX"
export S3_BUCKET="XXXXX"

Doing source ~/.bashrc
makes the RAILS_ENV=production rails s command work
and I can curl localhost:3000 to see my homepage html
all the commands have been run on the server after ssh-ing into it.
Shouldn't these environment variables be loaded automatically when I connect to the server using ssh?
Am I correct in assuming that since they don't seem to be loaded unless I manually source ~/.bashrc, my web server will not have access to them either?

A: If you don't find a way to make it work, I'd recommend you to use dotenv. It's very easy to configure.
In your gemfile:
gem 'dotenv-rails', :groups => [:development, :test]

In database.yml:
username: <%= ENV['DB_USER'] %>
password: <%= ENV['DB_PASS'] %>
etc ...

Then you just create in the main folder a file named .env with your configuration:
DB_USER = XXXX
DB_PASS = XXXX
etc ...

There is also something optional to add in application.rb.
Full documentation:
https://github.com/bkeepers/dotenv
An useful article:
http://blog.honeybadger.io/ruby-guide-environment-variables/

A: Figured it out.
# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

This bit was missing in ~/.profile on this newly setup server for some reason. Usually this is there by default.
This was causing my ~/.bashrc to not load up at all.


text:
Q: LINQ Except not working as expected I have some methods which return me a list of contacts that have not been queried on the last 360 days, 180 days and 90 days.
One person that has not been queried on the last 361 days, will also be returned by the query of 180 days and 90 days.
I thought I could do that with an Except, but thats certainly not working,
public class Contacto
{
    public int IdContacto { get; set; }
    public string PrimerApellido { get; set; }
    public string PrimerNombre { get; set; }
    public string SegundoApellido { get; set; }
    public string SegundoNombre { get; set; }
    public object Telefonos { get; set; }
    public int TipoTelefono { get; set; }
    public int IdEstado { get; set; }
    public DateTime? FechaArchivado { get; set; }
    public DateTime? FechaConsulta { get; set; }

GetOldContacts method
private static List<Contacto> GetOldContacts(int numberOfDays)
{
    try
    {
        DateTime filter = DateTime.Now.AddDays(-numberOfDays);
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(ConfigurationSettings.Apiurl);
        HttpResponseMessage response = client.GetAsync("api/ContactosDepurar?FechaInicial="+filter.ToShortDateString()).Result;
        if (response.IsSuccessStatusCode)
        {
            return response.Content.ReadAsAsync<List<Contacto>>().Result;
        }
        else
        {
            System.Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return null;
        }
    }
    catch (Exception ex)
    {
        System.Console.WriteLine(ex.Message);
        return null;
    }

}

And my Except logic
IEnumerable<Contacto> contactosDoceMeses = GetOldContacts(ConfigurationSettings.Ciclo3Dias);
IEnumerable<Contacto> contactosSeisMeses = GetOldContacts(ConfigurationSettings.Ciclo2Dias).Except<Contacto>(contactosDoceMeses);
IEnumerable<Contacto> contactosTresMeses = GetOldContacts(ConfigurationSettings.Ciclo1Dias).Except<Contacto>(contactosSeisMeses);

The problem is the second query is returning me the items on the first and it shouldnt

A: Linq's Except compares objects by their Equals(). You need to override Contacto's Equals and GetHashCode.
Many previous questions explain how:

*

*What's the best strategy for Equals and GetHashCode?

*What is the best algorithm for an overridden System.Object.GetHashCode?

Except also has an overload that recieves an IEqualityComparer if you prefer to implement one instead of overriding the functions
For specifying a comparer inline look at:

*

*Can I specify my explicit type comparator inline?


text:
Q: Forward and backward pagination with relay js Relay cursor connection specification says:

hasNextPage will be false if the client is not paginating with first,
  or if the client is paginating with first, and the server has
  determined that the client has reached the end of the set of edges
  defined by their cursors.

What I understand from that spec is that Relay can only paginate in one
direction; forwards or backwards. That seems reasonable for an infinite
scroll pagination implementation.
But how would one implement a sequential pages navigation similar to the stackoverflow questions page which
can navigate both ways?
Is Relay.js suitable for this kind pagination? I can't rely on hasNextPage and hasPreviousPage field which never has true value unless I paginate with first and last which is also very discouraged.

A:
What I understand from that spec is that relay can only paginate with single direction, forwards or backwards.

Correct. The original design was exactly that, an infinite scroll pagination. It was never intended to be used for bi-directional pagination.

But how about sequential pages like stackoverflow questions page?

This is quite tricky do to with the default implementation of Relay as it stands today because, as stated above, it was't designed for bi-directional navigation.
That said, you can still achieve this, though not through optimal means.

Method 1 - Passing page info through Relay
This is probably the easiest method to implement, though the less optimal one. It involves passing the page info to Relay as a GraphQL argument. This requires a new Relay query each time you navigate to a new page.
Example
Assume you have a view displaying a list of members. You fetch a list of member nodes with memberList. If you only want to display 10 members per "page" and we're on page 3, you could do:
app: () => Relay.QL`
  fragment on App {
    memberList(page: 3, limit: 10) {
      ...
    }
  }`
}

In your backend your SQL query would now look something like:
SELECT id, username, email FROM members LIMIT 20, 10;

Where 20 is the starting record: (page-1)*10 and 10 is the limit (how many items after the start). So the above will fetch the records 21-30.
Note that you would need initial values for page and limit. So your final query would be:
prepareVariables() {
  return {
    page: 1,
    limit: 10,
  };
},
fragments: {
  app: () => Relay.QL`
    fragment on App {
      memberList(page: $page, limit: $limit) {
        ...
      }
    }`
  }
}

And when navigating to a new page we need to update the values:
_goToPage = (pg) => {
  this.props.relay.setVariables({
    page: pg,
  });
}

Method 2 - Manually managing cursors
This is a slightly hacky implementation in that it essentially gives you a bi-directional navigation, even though is not natively supported. This approach is slightly more optimal to the first one, but sacrifices the ability to jump to a page directly.
Note that we cannot use both first and last:

Including a value for both first and last is strongly discouraged, as it is likely to lead to confusing queries and results.

Hence we would construct our query normally. Something like:
app: () => Relay.QL`
  fragment on App {
    memberList(first: 10, after: $cursor) {
      ...
    }
  }`
}

where the initial value for $cursor is null.
As you navigate to the next page and set the value for $cursor to be the cursor of the last member node, you also save the value in a local stack variable.
This way, whenever you navigate back you would simply pop the last cursor from the stack and use that for your after argument. It requires some extra logic in your application, but this is definitely doable.

A: Based on Method 2 given by @Chris,
This is my solution in VueJS, it's roughly the same for ReactJS as well.
    loadPage(type) {
      const { endCursor } = this.pageInfo
      let cursor = null
      if(type === 'previous') {
        this.cursorStack = this.cursorStack.slice(0, this.cursorStack.length - 1)
        cursor = this.cursorStack[this.cursorStack.length - 1]
      }
      else {
        cursor = endCursor
        this.cursorStack = [...this.cursorStack, cursor]
      }
      this.fetchMore({
        variables: { cursor: cursor },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) return previousResult
          return fetchMoreResult
        }
      })
    },

In template:
<button :disabled="!cursorStack.length" @click="loadPage('previous')" />
<button :disabled="!pageInfo.hasNextPage" @click="loadPage('next')" />


text:
Q: Enemy Boss movement AI Good day to all, I am trying to get an enemy boss ship to appear on screen and attack my ship and also dodge my attacks sometimes. So far I have gotten him to attack my ship but hes stays on the edge of the screen. Here is my code :
#pragma strict

// here are public variables for the enemy ship that can be accessed in the inspector
var health:int = 2;
var explosion:GameObject;
var expOrb:GameObject;
var enemyBullet:GameObject;
var expDrop:int = 3;
var hitSound:AudioClip;
var fireRate:float = 2.0;

//heres the private variable counter to keep track of time for fire rate.
private var counter:float = 0.0;

function Update () {
   //here we make counter count based on time for the fire rate
   counter += Time.deltaTime;

   //if the ship goes too far left, we destroy it.
   if(transform.position.x < -12){
      Destroy(gameObject);
   }

   //here we shoot 4 bullets if the counter counts higher than the fire rate.
   if(counter > fireRate){
      var custom1 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
      var custom2 = Instantiate(enemyBullet, transform.position - Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
      var custom3 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
      var custom4 = Instantiate(enemyBullet, transform.position- Vector3(0.5,0.1,0), Quaternion.Euler(-90,0,0));
      //to make the bullets spread, we add extra z velocity to each one to they all move on their own path.
      custom1.rigidbody.velocity.z = 3;
      custom2.rigidbody.velocity.z = 1;
      custom3.rigidbody.velocity.z = -1;
      custom4.rigidbody.velocity.z = -3;
      counter = 0.0;
   }

   //end of function update
}

//if a bullet hits the ship, the bullets sends us the hit message to trigger this function to bring down the ships health
function hit () {
   health -= 1;
   if(health != 0){
      if(audio.enabled == true){
         audio.PlayOneShot(hitSound);
      }
   }
   if(health <= 0){
      onDeath();
   }
}

//if health is 0, then this function is triggered to spawn some orbs, spawn the explosion animation object, and destroy itself
function onDeath () {
   Instantiate(expOrb,transform.position,Quaternion.Euler(-90,0,0));
   expDrop -= 1;
   if(expDrop <= 0){

       Instantiate(explosion,transform.position,Quaternion.Euler(-90,Random.Range(-180,180),0));
       Destroy(gameObject);
    }
    if(expDrop > 0){
       onDeath();
    }
 }

How do i add the movement aspect to it?

A: There are many ways to move an object, you can try:

*

*Transform.translate (http://docs.unity3d.com/ScriptReference/Transform.Translate.html)

*Modifying transform.position (http://answers.unity3d.com/questions/188998/transformposition.html)

*Adding force to it (http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html)

*And many other ways that I may have not known yet.
For a boss in this kind of game, the movement you may want is either random movement or following the player. Both are not hard to achieve.

*

*Random movement: just do a Random.Range(-1, 1) * bossSpeed *
time.deltaTime and apply it to the boss' x position.

*Following the player: get the player's x position then make the boss adjust to the position.

Then how to make the boss dodge the player's bullet sometimes? You can make the boss detect if a player's bullet is incoming by adding a collider thats stands in front of it. If a player's bullet collide with it, then random another number (eg. from 0 to 1). Afterwards, you just need to move the boss away if the random number is 1 and don't move the boss when the random number is 0.


text:
Q: Python Calculate New Date Based on Date Range I have a Python Pandas DataFrame containing birth dates of hockey players that looks like this:
Player         Birth Year    Birth Date
Player A         1990        1990-05-12
Player B         1991        1991-10-30
Player C         1992        1992-09-10
Player D         1990        1990-11-15

I want to create a new column labeled 'Draft Year' that is calculated based on this rule:
If MM-DD is before 09-15, Draft Year = Birth Year + 18
Else if MM-DD is after 09-15 Draft Year = Birth Year + 19

This would make the output from the example:
Player         Birth Year    Birth Date     Draft Year
Player A         1990        1990-05-12      2008
Player B         1991        1991-10-30      2010
Player C         1992        1992-09-10      2010
Player D         1990        1990-11-15      2009

I've tried separating the MM-DD from the date format by using
Data['Birth Date'] = Data['Birth Date'].str.split('-').str[1:]

But that returns me a list of [mm, dd] which is tricky to work with. Any suggestions on how to do this concisely would be greatly appreciated!

A: Use numpy.where:
data['Birth Date']=pd.to_datetime(data['Birth Date']) #to convert to datetime
cond=(df['Birth Date'].dt.month>=9)&(df['Birth Date'].dt.day>=15)
cond2=(df['Birth Date'].dt.month>=10)
data['Draft Year']=np.where(cond|cond2,data['Birth Year']+19,data['Birth Year']+18)

print(data)

Output
    Player  Birth Year Birth Date  Draft Year
0  PlayerA        1990 1990-05-12        2008
1  PlayerB        1991 1991-10-30        2010
2  PlayerC        1992 1992-09-10        2010
3  PlayerD        1990 1990-11-15        2009

A: Quick and Dirty
Make a column that is 100 * the month and add it to the day
cutoff = df['Birth Date'].pipe(lambda d: d.dt.month * 100 + d.dt.day)
df['Draft Year'] = df['Birth Year'] + 18 + (cutoff > 915)

df

     Player  Birth Year Birth Date  Draft Year
0  Player A        1990 1990-05-12        2008
1  Player B        1991 1991-10-30        2010
2  Player C        1992 1992-09-10        2010
3  Player D        1990 1990-11-15        2009

A: Datetime in the form yyyy-mm-dd are sortable as strings. This solution takes advantage of that fact:
df['Draft Year'] = df['Birth Year'] + np.where(df['Birth Date'].dt.strftime('%m-%d') < '09-15', 18, 19)


text:
Q: Facebook Graph API - running into field query/search How do I return Facebook IDs of my friends that use a certain application?
If you go to https://www.facebook.com/browse/?type=friends_using_app&app_id=2439131959 you'll see a list of your friends who have this application (on the far right)
I'm trying to either read the connections or search for the connections based on the social graph using the graph api.
https://graph.facebook.com/search?type=friends_using_app&app_id=6628568379 doesn't work
https://graph.facebook.com/?ids=?type=friends_using_app&app_id=6628568379 doesn't work either

A: Right now you have to use FQL: it can not be done with the graph API in its present state. Try this FQL:
SELECT uid FROM user WHERE is_app_user = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {userid})


text:
Q: Scala default TypeTag I'm using typetags in Scala to match options
def foo[T: TypeTag](bar: Any) = {
  bar match {
    case option: Option[T] => option match {
      case x if typeOf[T] <:< typeOf[List[Any]] => println("List Option")
      case x if typeOf[T] <:< typeOf[Map[Any, Any]] => println("Map Option")
      case x if typeOf[T] <:< typeOf[Boolean] => println("Boolean Option")
      case _ => println("String")
    }
    case _ => println("no Option")
  }
}

So when I use the function this way
foo[List[Any]](val)

all will be fine and the output is "List Option" in this case.
But when I try to use it without the TypeTag
foo(val)

the outputs is "List Option", regardless of whether it's a Option[List[Any]] or Option[String].
So now my question:
Is it possible to define a default value for my TypeTag T?
I want to use my function without the TypeTag if it is not needed and then the output should be "String" and not "List Option".
It is possible to define a default value for parameters, so maybe it is for TypeTag too.

A: Your problem is that the type T is not related to the type of the parameter bar.
This means, if you don't add the the type explicitly, the compiler will infer Nothing because it has no further information.
Nothing is a subtype of everything, so your subtype checks succeeds in the first branch already (in fact all your cases are true for Nothing).
Your code could be "improved" like this:
import scala.reflect.runtime.universe._
def foo[T: TypeTag](bar: Any) = {
  bar match {
    case option: Option[T] => option match {
      case x if typeOf[T] =:= typeOf[Nothing]       => println("Nothing")
      case x if typeOf[T] <:< typeOf[List[Any]]     => println("List Option")
      case x if typeOf[T] <:< typeOf[Map[Any, Any]] => println("Map Option")
      case x if typeOf[T] <:< typeOf[Boolean]       => println("Boolean Option")
      case _ => println("String")
    }
    case _ => println("no Option")
  }
}

I say "improved" because one should never ever write code like this. It feels like it tries to shoehorn some idiom from untyped languages into Scala.

A: def foo[T: TypeTag](bar: Any)

is just
def foo[T](bar: Any)(implicit tt: TypeTag[T])

So you can provide a default value:
def foo[T](bar: Any)(implicit tt: TypeTag[T]=...)

A: The easiest way was the solution.
I wrote another function.
Now if I need TypeTags I can use fooType else I can use foo.
def foo(bar: Any) = {
  fooType[String](bar)
}

def fooType[T: TypeTag](bar: Any) = {
  bar match {
    case option: Option[T] => option match {
      case x if typeOf[T] <:< typeOf[List[Any]] => println("List Option")
      case x if typeOf[T] <:< typeOf[Map[Any, Any]] => println("Map Option")
      case x if typeOf[T] <:< typeOf[Boolean] => println("Boolean Option")
      case _ => println("String")
    }
    case _ => println("no Option")
  }
}


text:
Q: To check login session Id after login in codeigniter I m going to check current user id and get info is male or female but condn false
public function profile() {
    $this->load->view('header');
    $uname = $this->session->userdata('uname');
    $row = $this->brid_groom_fetch->get_program_specific_gender();
    if ($row['uname']->uname == $uname) {
        $session_id = $this->session->userdata('session_id');
        var_dump($session_id);
    } else {
        echo 'fail';
    }
}

A: Do Not use any array object stdClass containing  variable simply check both var
public function profile() {
    $this->load->view('header');
    //     print_r($uname);
    if ($this->session->userdata('logged_in')) {
        //get Data from db
        $row = $this->brid_groom_fetch->get_program_specific_gender();
     //get session Id
        $uname = $this->session->userdata();
        //compare both variable directly don't use array format to compare
        if ($row = $uname) {
            $session_id = $this->session->userdata();
            var_dump($session_id);
        }
    }
}


text:
Q: minimize the runtime or the performance time of a code I was wondering how i can minimize the runtime of the following code
int j = 0;
while (j < n) {
    int i = 0;
    while (i < m) {
        cout << i*j;
        i++;
    }
    j++;
}

A: There's not much to do, these are just mere loops. However, it is usually more efficient to accumulate the strings and print at the end than printing tiny strings several times.


text:
Q: VueJS pass props to children in render function call I have a parent component that wraps multiple children 'child'. I want the parent to essentially have the same template as the vanilla markup which is why I am using the render function.
I want the parent to manage the state of which child is active. But the props don't appear to be passing down to the children.
I have tried applying what the documentation says, but props are undefined on the children. However if I do item.data.staticClass = 'testing-class'; that class applies to each child.
Vue.component('parent', {
  data: function() {
    return {
      activeIndex: 0
    }
  },
  render: function(createElement) {
    this.$options._renderChildren.forEach(function(item, index) {
      if (item.data === undefined) //whitespace?
      return;

      item.data.props = {
        activeindex: this.activeIndex,
        index: index
      }
    }.bind(this));

    return createElement('div', {}, this.$options._renderChildren);
  }
});

Vue.component('child', {
  template: '
Im a child
',
  props: ['activeindex', 'index'],
  mounted: function() {
    console.log(this.$props); //undefined
  }
});

new Vue({
  el: '#app'
});

JSFIDDLE DEMO

A: First of all, I think that this.$props will always be undefined. The $props property is accessible in a template like {{ $props }}, but those inline properties (frustratingly) don't always map up directly to the this variable available in the component's script. You can see the component's prop values using this.$options.propsData.
Secondly, you can use item.componentOptions.propsData to set the property values of the child component. (I think item.data.props is a misnomer referencing something else). Here's a fiddle with the change.


text:
Q: Is this the best way to store this data? I have a tree-like structure of data stored for a game recorded hourly. I have a tree of folders in the format: Username/Year/Month/date/time.csv
My aim is to replace that by :

*

*server gives the server the user was logged into.

*UserExperience will record all skills experience was gained in over the hour (and how much). So an aggregate for the hour.

*This is one I'm really unsure on : UserActivites. This could be variable text of some events that happened over the hour ("I levelled X skill to level Y", "I killed Z many of boss A", "I completed quest B") and many more that are added and removed overtime, so not something I can exactly make a primary-key. I'm not sure what can be done here.

Also not sure how to query statistics of some set of users between 2 dates but that is a separate problem.

A: So the activity (in UserActivites) is always one that relates to a (over the time maybe growing) Activities lookup table. The text representation of the activity is in the Activities table and you are just linking to it from your UserActivities table - seems ok so far. You have already a foreign key pointing from UserActivities.ActivityID to Activities.ActivityID (and the same for Username to UserStatus)?
The datetime is just a point in time - no need to put it into some sort of combined index (as the primary key is). You might index the datetime in the future for a better query performance though.
What I would do is:

*

*throw away the combined primary key on UserActivities

*create a non-meaningful, auto-incrementing integer primary key in the UserActivities table (ID INTEGER PRIMARY KEY)

Things you should consider:

*

*create an index on Username and another one on ActivityID in UserActivities; it's not necessary, but recommended that child key columns of foreign keys have an index (https://sqlite.org/foreignkeys.html#fk_indexes)

Your data design looks good that way. You mentioned "and removed overtime" concerning the user activities (if I understood correctly). If so I would create a boolean column in UserActivities for deleted records. That way you can analyze activities that have been removed. I would never delete records once they have been created in the database.


text:
Q: How can I use a filesize in order to read a file in WinAPI? I've opened a file with CreateFile and passed that handle into both GetFileSizeEx and SetFilePointerEx which can both be used to get the file size. I then need to use ReadFile or ReadFileEx to read in the data from the whole file into a buffer.
The problem I'm having is that GetFileSizeEx and SetFilePointerEx both provide the file size as a LARGE_INTEGER type but ReadFile takes a DWORD for the number of bytes to read. Is there some workaround for this?

A: Yes. Both ReadFile and ReadFileEx take a DWORD as parameter. I guess that's because Microsoft considered it to be unlikely to read more than 4GB at once.
The common approach is using the LowPart of the LARGE_INTEGER union which is of type DWORD.
Of course you have to check manually that the size of the file is less than 4GB that means that HighPart is zero. If it's not then you have to perform multiple calls to ReadFile.
For example:
LARGE_INTEGER li;
DWORD actuallyRead;
LPVOID lpBuf;
... (fills li and lpBuf) ...
result = ReadFileEx(
           hFile,
           lpBuf,
           li.LowPart,
           &actuallyRead,
           NULL
         );


text:
Q: Set values back to start If I click the button CHECKOUT a pop up shows up. In this pop up, you have the chance to abort the transaction. So if you abort the transaction all the values for the Items (French fires, Water, Burger) should be 0 again as seen in the picture below. Right now when i abort the transaction the values stay the way i configured them before. Can you help me with that?

OrderActivity.java
package com.nfc.netvision;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import static android.widget.Toast.*;

public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {

    RecyclerView recyclerView;
    ArrayList<ModelOrder> orderArrayList;
    TextView textView_order_price;
    TextView textView_order_count;
    Dialog epicDialog;
    Button btnCheckout;
    Button btnAbort;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        recyclerView = findViewById(R.id.recyclerview_order_scroll);
        textView_order_price = findViewById(R.id.textView_order_price);
        textView_order_count = findViewById(R.id.textView_order_count);
        btnCheckout = (Button) findViewById(R.id.btnCheckout);

        orderArrayList = new ArrayList<>();
        orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
        orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        RecyclerView.LayoutManager recLiLayoutManager = layoutManager;

        recyclerView.setLayoutManager(recLiLayoutManager);

        OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);

        recyclerView.setAdapter(adapter);

        epicDialog = new Dialog(this);

        btnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaitingPopUp();

            }
        });

    }

    private void showWaitingPopUp() {
        epicDialog.setContentView(R.layout.order_popup_waiting);
        epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        btnAbort = (Button) epicDialog.findViewById(R.id.btnAbort);
        btnAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               epicDialog.dismiss();
            }
        });
        epicDialog.show();
    }

    @Override
    public void onTotalChanged(String result) {
        NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        textView_order_price.setText( n.format(Integer.parseInt(result)));
    }

    @Override
    public void onCountChanged(String result) {
        textView_order_count.setText(result);

    }
}

OrderAdapter.java
package com.nfc.netvision;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.w3c.dom.Text;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {

    private int totalAmount;
    private int totalItems;
    private Context mContext;
    private ArrayList<ModelOrder> nList;

    private TotalListener listener;

    interface TotalListener{
        void onTotalChanged(String result);
        void onCountChanged(String result);

    }
    OrderAdapter(Context context, ArrayList<ModelOrder> list, TotalListener listener) {
        mContext = context;
        nList = list;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        final ModelOrder orderItem = nList.get(position);
        ImageView image = holder.item_image;
        final TextView name, place, price;
        name = holder.item_name;
        place = holder.item_place;
        price = holder.item_price;

        image.setImageResource(orderItem.getImage());

        name.setText(orderItem.getName());
        place.setText(orderItem.getPlace());
        price.setText(orderItem.getPrice());

        holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(orderItem.getCounter() > 0) {
                    orderItem.setCounter(orderItem.getCounter()-1);
                    holder.order_item_count.setText("" + orderItem.getCounter());
                    calculatePrice(Integer.parseInt((String) price.getText()), false);
                    countItems(orderItem.getCounter(), false);

                }

            }
        });

        holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(orderItem.getCounter() < 9) {
                    orderItem.setCounter(orderItem.getCounter() + 1);
                    holder.order_item_count.setText("" + orderItem.getCounter());
                    calculatePrice(Integer.parseInt((String) price.getText()), true);
                    countItems(orderItem.getCounter(), true);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return nList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView item_image;
        TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;

        public ViewHolder(@NonNull View itemView) {

            super(itemView);
            item_image = itemView.findViewById(R.id.order_item_image);
            item_name = itemView.findViewById(R.id.order_item_name);
            item_place = itemView.findViewById(R.id.order_item_place);
            item_price = itemView.findViewById(R.id.order_item_price);
            order_item_minus = itemView.findViewById(R.id.order_item_minus);
            order_item_plus = itemView.findViewById(R.id.order_item_plus);
            order_item_count = itemView.findViewById(R.id.order_item_count);
        }
    }

    private void calculatePrice(int pPrice, boolean pUpDown) {
        if(pUpDown) {
            totalAmount = totalAmount + pPrice;
        }
        else {
            totalAmount = totalAmount - pPrice;
        }

        listener.onTotalChanged(totalAmount+ "");
    }

    private void countItems(int pCounter, boolean pUpDown){
        if (pUpDown){
            totalItems = totalItems + 1;
        }
        else{
            totalItems = totalItems - 1;
        }
        listener.onCountChanged(totalItems+ "");

    }

}

A: They stay the way there were because inside your abort button's onClick you just dismiss the dialog and do not change the list values.
I suggest iterating through the list and setting all counters to 0.
Also, don't forget to notify your RecyclerView that you modified something, in this case you reset all counters to 0. Otherwise, you won't see the changes in your app.
private void showWaitingPopUp() {
    epicDialog.setContentView(R.layout.order_popup_waiting);
    epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    btnAbort = epicDialog.findViewById(R.id.btnAbort);
    btnAbort.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Set all orders count to 0
            for (ModelOrder modelOrder: orderArrayList) {
                modelOrder.setCounter(0);
            }
            // Notify RecyclerView about the changes
            adapter.notifyDataSetChanged();

            epicDialog.dismiss();
        }
    });
    epicDialog.show();
}

I noticed you didn't have the adapter as a global variable so declare it as such:
public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {

    // other variables

    // Change adapter variable to global
    OrderAdapter adapter;

    // ...

Side notes: I also noticed that you passed your activity twice inside your OrderAdapter constructor.
OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);

You can simply just do:
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);

Then inside your constructor:
OrderAdapter(Context context, ArrayList<ModelOrder> list) {
    mContext = context;
    nList = list;

    // You can simply cast the context to the listener
    listener = (TotalListener) context;
}

Hope my answer helps, happy coding!

Edit: I moved my answers to OP's other questions in the chat.


text:
Q: Using Futures in flutter old versions Android studio is giving me this error
info: The class 'Future' wasn't exported from 'dart:core' until version 2.1, but this code is required to be able to run on earlier versions.

If I put this
import 'dart:async';

the problem seems to go away. Could someone explain why this is happening and if this is the correct way to fix this.
Thanks a lot.
---- edit
Can I update dart core to something > 2.1
I am guess it is this line in my pubspec yaml
environment:
  sdk: ">=2.0.0-dev.68.0 <3.0.0"

Is there any downsides to doing thins i.e. running on older android/ios versions.

A: Open the terminal and execute the following:
flutter upgrade

This will upgrade both flutter and dart


text:
Q: jQuery: Setting cloned select boxes values problem In jQuery, I'm creating select boxes on the fly based on the number of items in a PHP array, and attempting to change the value of each select box option to the value of the array item.
First, here's the HTML:

    <select name="artistSelect[]" class="cat_list">
        <option value="">- none -</option>
    </select>

Here's the array conversion:
var arrayFromPHP = <?php echo json_encode($exhibArray) ?>; // There's our array from php->jquery

I then start by populating the options in the first select and then create the subsequent boxes within an 'each' loop in the 'success' callback:
$.ajax({
    url: 'artistpop.php',
    success: function(data){
        $('.cat_list').append(data); //Sets options for first select box
        $.each(arrayFromPHP, function (i, elem) { //loop through our array values
            $("#artistArea > .category_block:last .cat_list").val(elem); //set the select box value
            $('#artistArea > .category_block:last').after($('#artistArea > .category_block:last').clone()); //clone the previous select box
        });
    }
});

So... The problem is:
The initial box creation and population is working fine, as is the creation of the subsequent boxes.  However, only the first select box is set with the appropriate value from the array; the others remain on the 'none' option.
Could this be something wrong in the each loop?
I hope this is clear enough to understand - I'm confused!

A: Have you tried setting a "selected" attribute on the actual option you want as your default, rather than setting the value of the select? In other words, something like...
$('#artistArea > .category_block:last .cat_list option[value=' + elem + ']').attr('selected','selected');


text:
Q: Empty item at end of .each loop because of rails cycle method I have this list that should show all activities inside a category, and it sort of works but the last element that is displayed is strange. There are 4 activities in the DB for this particular category and at the end of the list I'm getting an item /categories/1/activities
%table.catlist
  - @category.activities.each do |activity|
    %tr{:class => cycle('one','two')}
      %td= link_to activity.name, [@category, activity]
      %td

I also tried:
link_to activity.name, category_activity_path(:category_id => @category.id, :id => activity.id)

But that's not working at all, and giving me this error:
No route matches {:category_id=>1, :action=>"show", :controller=>"activities", :id=>nil}

The routes are nested like this:
  resources :categories do
    resources :activities do
      resources :records
    end
  end

It's actually showing everything right, but it closes the list with this strange element which is basically the activity path, but without an id.
EDIT
I think this is happening because of the cycle method that is supposed to switch between CSS classes. Any ideas how the empty row can be avoided?

A: You are most probably building a new activity in your controller which is included in the list of activities for @category.  If you have the following code in your controller,
@activity = @category.activities.build

try changing it to
@activity = Activity.new category_id: @category.id

or add a check in the view to only show persisted activities.
- @category.activities.each do |activity|
  - next if activity.new_record?
  %tr{:class => cycle('one','two')}
    %td= link_to activity.name, [@category, activity]
    %td


text:
Q: Why onmouseover() function works with attribute onmouseover="javascript code" but doesn't work with addEventListener() function? My point is to trigger the onmouseover event in javascript code. I used the function
onmouseover() on an element. But it doesn't works in some situations.
This is a demo code:
HTML file:

Text Text

External Javascript file:
var myP = document.getElementById("p-id");
myP.addEventListener("mouseover", function() {
    this.style.backgroundColor = "red";
});
// trigger the mouseover:
myP.onmouseover(); // console error: onmouseover is not a function.

But onmouseover() function works well when I use the attribute onmouseover="javascript code" on the element:
HTML file:

Text Text

External Javascript file:
var myP = document.getElementById("p-id");
// trigger the mouseover:
myP.onmouseover(); // works well

I have been searching the reason for ages but I have no clues.

A: The onmouseover property is a setter/getter on HTMLElement.prototype:

var myP = document.getElementById("p-id");
const descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onmouseover');
console.log(descriptor);
console.log(descriptor.get.call(myP));

Text Text

When the getter is invoked, it will return either the handler that was previously attached using the setter, eg elm.onmouseover = someFn, or it will return the inline handler function.
In your upper code, the handler is neither inline nor is it attached via invoking the setter, so accessing the onmouseover property of the element returns null, which can't be called.
In your lower code, the handler is inline, so it's returned by accessing the onmouseover property, which invokes the getter.

It's good practice to never use inline handlers they have too many problems to be worth using, and to also not attach handlers via .on properties (because then, if another script tries to attach a handler to the same element, it'll overwrite the earlier handler).
If you want to trigger a listener function you just attached, you can either save the function in a variable first, then call it:

var myP = document.getElementById("p-id");
const fn = () => myP.style.backgroundColor = "red";
myP.addEventListener("mouseover", fn);
fn();

Text Text

Or dispatch an event to the element through the DOM:

var myP = document.getElementById("p-id");
myP.addEventListener("mouseover", () => myP.style.backgroundColor = "red");
myP.dispatchEvent(new Event('mouseover'));

Text Text


text:
Q: Google Chrome's status bar complete I'm Google Chrome user, but I don't like the format Chrome's status bar. Exactly, I want to see the full URL, not shorten.
How I can change that boundary imposed by GC Web browser?

A: You can't, short of editing the browsers code. Submit the suggestion to the Chromium team and maybe they'll add the option. However, no extension can do this (at least, not yet) and you can't change it in a setting.


text:
Q: Problem In Dual Booting I tried to install Ubuntu by dual booting it with windows 10 technical preview.
but when I started to install it I found that there was no option in Ubuntu 14.10 to dual boot it with windows 10.
so plz can anyone help to dualboot ubnutu 14.10 with windows 10 technical preview.

A: When dual booting windows, I like to partition my hard drive in windows before I attempt to install Ubuntu. Google "How to partition my hard drive on windows 10". This way when the Ubuntu install starts, it knows that your hard drive has free space to be able to install it "on the side". This might help that option show up in the Ubuntu installer window. When this happened to me, it was because it just wanted to install over windows because it didn't know it had free space and when I tried partitioning through Ubuntu it also just wanted to format everything first.

A: What I did was take an already installed Ubuntu 14 environment and zero out a spare drive with dc3dd as sudo dc3dd wipe=/dev/sdX (where sdX= the drive I wanted to blank, in my case it was sdc). I disconnected the drives I didn't want Windows to see (call me paranoid). Then I booted up the Windows 10 Technical preview and installed it onto the spare drive. After insuring that Win10 was functioning to the best of it's ability, I shut down, reconnected my Ubuntu 14 drive and my home drive (I keep home on a separate drive, not necessary but a preference). Booted up Ubuntu, opened a terminal with CTRL-ALT-T and issued the command sudo update-grub Upon reboot the Windows environment was available for booting on the grub menu and worked fine.


text:
Q: Convert spark dataframe to DeltaLake in Databricks I have a Spark dataframe which is actually a huge parquet file read from the container instance in Azure. And I want to make delta lake format out of it. By every time I try to do that it throws an error without any message attached.
I want to save it to the Databricks itself or to the container instance (if possible).
I tried already df.write.format("delta").save("f"abfss://{container}@{storage_account_name}.dfs.core.windows.net/my_data)
and
df.write.format("delta").saveAsTable("f"abfss://{container}@{storage_account_name}.dfs.core.windows.net/my_data)
and

CREATE DELTA TABLE lifetime_delta
USING parquet
OPTIONS (f"abfss://{container}@{storage_account_name}.dfs.core.windows.net/")

I do think I need to create a table somehow and I heard that since parquet is native for Delta Lake it's already existing in Delta Lake context but for some reason it's not quite true.
None of it worked for me. Thank you in advance.

A: There are two main ways to convert Parquet files to a Delta Lake:

*

*Read the Parquet files into a Spark DataFrame and write out the data as Delta files.  Looks like this is what you're trying to do.  Here's your code:

df.write.format("delta").save("f"abfss://{container}@{storage_account_name}.dfs.core.windows.net/my_data)

You may need to change it as follows in accordance with the Python f-string syntax:
df.write.format("delta").save(f"abfss://{container}@{storage_account_name}.dfs.core.windows.net/my_data")

*

*You can also convert from Parquet to Delta Lake in place using the following code:

from delta import *

deltaTable = DeltaTable.convertToDelta(spark, "parquet.`tmp/lake2`")

Here's an example notebook with code snippets to perform this operation that you may find useful.


text:
Q: Can someone explain to me the logic behind this recursion public int bunnyEars(int n) {
    if (n < 0) {
        throw new IllegalArgumentException();
    }
    if (n == 0) {
        return n;
    }
    if (n % 2 == 1)
       return 2 + bunnyEars(n - 1);

   return 3 + bunnyEars(n - 1);
}

can someone explain how bunnyEars(2) = 5
and also how it works?

A: From your comments, I understand that you already know the meaning of a recursive call. In order to make it clear how it works, you can trace the calls in some way. Given below is an example of one of the ways:
public class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(bunnyEars(2));
    }

    static int bunnyEars(int n) {
        if (n < 0) {
            throw new IllegalArgumentException();
        }
        if (n == 0) {
            System.out.println(n);
            return n;
        }
        if (n % 2 == 1) {
            System.out.print("2 + bunnyEars(" + n + "-1) -> ");
            return 2 + bunnyEars(n - 1);
        }
        System.out.print("3 + bunnyEars(" + n + "-1) -> ");
        return 3 + bunnyEars(n - 1);
    }
}

Output:
3 + bunnyEars(2-1) -> 2 + bunnyEars(1-1) -> 0
5

As you can see, 3 + 2 + 0 = 5 is what you get as the answer.
I hope, it helps. Feel free to comment in case of any doubt.

A: If the number n is less than 0, then an IllegalArgumentException is thrown, as evidenced by:
if (n < 0) {
   throw new IllegalArgumentException();
}

So, we know n is always supposed to be 0 or greater. We also know that the method is supposed to return when n is equal to 0, as evidenced by:
if (n == 0) {
    return n;
 }

So, presumably, the method public int bunnyEars(int n) will take a number equal to or greater than zero, and will start adding integers until the n is zero.
We see two different possible scenarios to take n's greater than zero and do something with them:
if (n % 2 ==1)
   return 2 + bunnyEars(n-1);
return 3 + bunnyEars(n -1); //else

What is happening here is if the n % 2 is equal to one (meaning that the number is odd, since every odd integer divided by two has a remainder of one), then the method is recursively called with the current n minus 1, and the final integer to return is incremented by two.
If the number is not odd (and is thus even), then the same thing is happening, but with the final integer to return incremented by 3.
So in your example of bunnyEars(2), we see that the n of 2 is both positive and greater than zero, so no error is thrown and the method does not return without recursion. Since 2 is an even number (2 % 2 is 0), the second return is used. This means that 3 + bunnyEars(1) is called.
Since 1 is also greater than 0, we go to the recursive methods again. Since 1 is an odd number (1 % 2 is 1), the first recursive return is called. This means we call 2 + bunnyEars(0).
Now, since n is 0, the return n from the if-statement is used:
if (n == 0) {
    return n;
 }

On the first round we had the final integer to return incremented by 3, and on the second time it was incremented by 2, for a total of 5. So the result is five.


text:
Q: Problem with procedure for solving an epsilon delta problem if $|x-2|<\delta$ then $|(1/x)-0.5|<0.2$
my procedure I've come up with by seeing it work 3 times on hw:
1. change the expression from looking like |…|<a to -a<…<a.
2. get x alone in the middle.
3. set left sides of both expressions equal to each other and same for right sides.
4. solve for delta.
5. take the smaller of the 2 delta values.

This doesn't work for problem above I get -4/3 and -4/7 for delta values and I put -4/3 into answer and it came out as wrong. I need a modification for the above procedure.
Edit
How i got the values -4/3 and -4/7:

*

*$-\delta<x-2<\delta$ and $-1/5<(1/x)-(1/2)<1/5$

*$2-\delta<x<\delta+2$ and   $10/3<x<10/7$

*$2-\delta=10/3$ and $\delta+2=10/7$

*$\delta=-4/3$ and $\delta=-4/7$

*$-4/3<-4/7$ -> $-4/3$

A: $\delta$ has to be positive!  You don't say how you got those negative values so it is impossible to say what you might have done wrong.
You want to find $\delta$ such that if $|x- 2|< \delta$ then $|(1/x)- 0.5|< 0.2$.  As your "procedure" says, write that second inequality as $-0.2< (1/x)- 0.5< .2$.  Now "solve for x".  Add 0.5 to both sides to get $0.3< 1/x< 0.7$.  Since $0.3< 1/x$, x is clearly positive so we can invert each part but also remember that this will reverse the inequality: $(1/0.7)< x< 1/0.3$.
(A little more rigorously: if $0.3< 1/x$ then $0.3x< 1$ so $x< (1/0.3)$.  If $1/x< 0.7$ and x is positive, then $1< 0.7x$ so $(1/0.7)< x$.)
For the other inequality, $|x- 2|< \delta$, we have $-\delta< x- 2< \delta$ so $2-\delta< x< 2+ \delta$.
Now, setting "left sides of both expressions equal to each other and same for right side" we have $1/0.7= 1.428= 2-\delta$ so $\delta= 2+ 1.428= 3.428$ and $1/0.3= 3.333= 2+ \delta$ so $\delta= 3.333- 2= 1.333$.  The smaller of those is 1.333 or 4/3.


text:
Q: json array to php I have array in json, but I want to print it in php.  I get in post this :
[{"cartData":{"id":"dragged_567737","left":"255px","top":"71px"}},{"cartData":{"id":"dragged_757836","left":"43px","top":"73px"}}]

but when I use print_r($_POST) in my php file, it print me the empty array.
there is my js code:
jQuery('#save_project_data').click( function() {
            var array=[];
            var numItems = $('.icart').length;

            $(".icart").each(function(index) {
                var cart_id = $(this).attr("id");
                var cart_left = $(this).css("left");
                var cart_top = $(this).css("top");

                var cartData = {
                   "id" : cart_id,
                   "left" : cart_left,
                   "top" : cart_top
                };
                queryStr = { "cartData" : cartData };
                array.push(queryStr);
            });

            var postData = JSON.stringify(array);
           $.ajax({
                   url  : "modules/cart_projects/saveData.php",
                   type : "POST",
                   dataType: 'json',
                   contentType: 'application/json; charset=utf-8',

                   data : postData,//{ 'data': '{"name":"chris"}' }
                   traditional: true,
                   success: function(){
                        alert("OK");
                    }
               });
            return false;
        });

A: PHP has native support for decoding JSON with json_decode();
$data = json_decode($_POST['myJson']);
print_r($data);

The PHP $_POST array is interpreted from key value pairs, so you need to change your ajax call like below, because your code is sending the post data with no key.
data : { myJson : postData },//{ 'data': '{"name":"chris"}' }

If you change the data structure like above, you need to also remove your application/json; charset=utf-8 content type.
From the Manual:

Takes a JSON encoded string and converts it into a PHP variable.

A: If you're sending raw JSON-strings to PHP, $_POST will not be populated (as it needs a standard urlencoded string as submitted by POST requests to decode). You can solve this by either using postData as an object: {'json': json}, so that you get the value in $_POST['json'], or by reading the raw response:
$json_string = file_get_contents('php://input');
$struct = json_decode($json_string, true);

A: Try to use json_decode() function.

A: According to jQuery.ajax() documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
To be safe, you might be better off using the jQuery.post() method.
Finally, I suggest to give the data property an object. That way you can set an identifier for your post data.
Javascript
{
    url: 'modules/cart_projects/saveData.php',
    data: {
        mydata: postData
    }
}

PHP
$_POST['mydata'];

If you need to decode the JSON:
json_decode($_POST['mydata']);


text:
Q: Tightly integrated private helper class in ASP.NET Semi-unimportant background:
I'm working on a page with two sets of collapsable panels.  (using nHibernate) I get category objects with a list of items in them, and for each category generate a left panel and right panel.  In both panels, there is a ListBox.  Items are pre-populated to the left list box and the user can select and move items into the right list box (under the corresponding category.)
As I've built and worked on it, I ended up with a lot of generic methods like buildPanel(side,categoryID) and then ended up with a lot of repeated if statements inside them to differentiate between the two sides
if type=PanelType.Left then
    set these 5 id strings to access components
else
    ...

The code got messy, so I moved a lot of the logic and static builder strings for the component ids into a private helper class in order to make other parts of the main class easier to read and follow.  The problem I see is that the private class is extremely dependant on specific structures in the parent class.  There's a very minimal amount of encapsulation going on and I'm possibly making the logic harder to follow even if the individual components in the code are easier to read.
My question is: When you're using a private class like this, is it acceptable to have it tightly integrated with the parent class (since it's private and implemented in the same file), am I better to refactor again and find a way of either simplifying my original code to be as short as possible without the helper class (stick all category/panel functions in one spot and hide them in their own region when I'm not using them), or should I move towards putting more of the logic in the helper class and simply mapping my events directly to the subclass.
After typing all this out, I'm leaning towards the last option, but I'm still torn/confused about the whole thing...

A: If you never use this panel mechanism on another page, then you don't need to refactor.
Furthermore, until you need to use it on another page, you don't know how to refactor the private class to make it reusable.

A: Pages are classes and as any class they can grow unwieldy. When you come to the stage where code is heavily coupled, it kind-of depends on how this coupling shows whether or not you should refactor. If the code is clear, concise and easy to follow, it's ok to leave it as it is. But if its hard to follow, if you cannot explain it to a co-worker in a few minutes or you think you won't understand it yourself in half a year than it's eligible for refactoring.
The Law of Demeter (light coupling) shouldn't only be applied in inter-class relationships, but also in inter-method relationships. This is often overlooked or underestimated. But sometimes too much refactoring leads to another extreme: too little coupling can become unreadable, too (just as having too many small methods or too many big ones).
I usually ask myself the question: does the code read like a book with clear chapters and storyline, or do I have to read each paragraph twice, or worse, turn back pages to understand it?


text:
Q: Como posso verificar se é um robô do facebook? Existe alguma forma de, com PHP, verificar se o acesso ao servidor está sendo feito por um robô/bot do facebook?

A: Segundo essa resposta do SO gringo:
if (
    strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit/") !== false ||
    strpos($_SERVER["HTTP_USER_AGENT"], "Facebot") !== false
) {
    // é provavelmente um bot do facebook
}
else {
    // nao eh um bot Facebook
}

A lista completa esta aqui mas esses dois sao os mais usados.


text:
Q: $S \times T$ is mixing iff $S$ and $T$ are mixing Could you please help me with the (iv) and (v) statements below, I don't have any idea how to prove them. These statements are from Grosse-Erdmann & Peris Manguillot's book Linear Chaos, p.17:

Thanks in advance.

A: I prove (v).
Assume that $S$ et $T$ are mixing. We have to prove that for every non-empty open sets $U$ and $V$ in $X \times Y$, $(S \times T)^{-n}(U) \cap V$ is non-empty for all $n$ large enough.
One need only to check the result when $U = U_1 \times U_2$ and $V = V_1 \times V_2$ with $U_1,V_1$ non empty open sets in $X$ and $U_2,V_2$ non empty open sets in $Y$. Indeed these cartesian products for a basis of open sets in $X \times Y$.
In this case, $(S \times T)^{-n}(U) \cap V = (S^{-n}(U_1) \cap V_1) \times (T^{-n}(U_2) \cap V_2)$. By assumption, one can find two non-negative integers $n_1$ and $n_2$ such that $S^{-n}(U_1) \cap V_1 \ne \emptyset$ whenever $n \ge n_1$ and $T^{-n}(U_2) \cap V_2 \ne \emptyset$ whenever $n \ge n_2$. Hence $(S \times T)^{-n}(U) \cap V \ne \emptyset$ whenever $n \ge \max(n_1,n_2)$.

A: Let us first set up some notation and give definitions. Let $X$ be a topological space, $T:X\to X$ be a continuous self-map of $X$. For two subsets $A,B\subseteq X$ call the set
$$N^T(A\to B)=\{n\in\mathbb{Z}_{\geq0}\,|\, T^n(A)\cap B\neq\emptyset\}$$
the set of return times from $A$ to $B$. Denote by $\mathcal{T}(X)^\ast$ the collection of all nonempty open subsets of $X$. $T$ is called

*

*topologically transitive (TT) if $\forall U,V\in\mathcal{T}(X)^\ast: N^T(U\to V)\neq\emptyset$.

*topologically strong mixing (TSM) if $\forall U,V\in\mathcal{T}(X)^\ast, \exists N\in\mathbb{Z}_{\geq0}: \mathbb{Z}_{\geq N}\subseteq N^T(U\to V)$.

Note that, when $X$ is Hausdorff, these definitions are equivalent to the definitions I used in my answer to your previous question (Topological weakly mixing implies totally transitive ), in light of another answer of mine (Isolated Points and Topological Transitivity ).
It is clear that TSM $\implies$ TT.

By an argument I provided in the second link above, we have that if $X$ is Hausdorff, then
$$T \text{ is TT } \iff \forall U,V\in\mathcal{T}(X)^\ast: N^T(U\to V) \text{ is infinite}.$$
Thus from this point of view the relation of TT to TSM is analogous to the common relation of "for infinitely many" to "for all but finitely many". Admittedly, once this is verified the parts of the proposition become exercises in syntactic manipulation.

Let $X,Y$ be Hausdorff topological spaces, $S:X\to X$ and $T:Y\to Y$ be continuous. We endow $X\times Y$ with product topology, thus $\forall U\in\mathcal{T}(X\times Y)^\ast, \exists U_1\in\mathcal{T}(X)^\ast,\exists U_2\in\mathcal{T}(Y)^\ast: U_1\times U_2\subseteq U$. We also have:
\begin{align*}
&\forall U_1, V_1\in\mathcal{T}(X)^\ast,\forall U_2,V_2\in\mathcal{T}(Y)^\ast:\\
&N^{S}(U_1\to V_1)\cap N^{T}(U_2\to V_2)= N^{S\times T}(\,(U_1\times U_2)\,\to\, (V_1\times V_2)\,),
\end{align*}
and
\begin{align*}
\forall U, V\in\mathcal{T}(X\times Y)^\ast,&\exists  U_1,V_1\in\mathcal{T}(X)^\ast, \exists U_2,V_2\in\mathcal{T}(Y)^\ast:\\
&U_1\times U_2\subseteq U, V_1\times V_2\subseteq V, \text{ and }\\
&N^{S}(U_1\to V_1)\cap N^{T}(U_2\to V_2)\subseteq N^{S\times T}(U\to V).
\end{align*}

For part (iv), the intersection of an infinite set and a cofinite set (i.e. a set whose complement is finite) is infinite. For the $(\impliedby)$ part of part (v), the intersection of two cofinite sets is cofinite, and for the $(\implies)$ part of part (v), note that if $U,V\in\mathcal{T}(X)^\ast$, then $U\times Y, V\times Y\in\mathcal{T}(X\times Y)^\ast$.

A: I prove (v), but with the definition of mixing for measure-preserving maps.
Call $\mu$ and $\nu$ the invariant measures considered ($\mu$ is invariant by $S$ and $\nu$ is invariant by $T$). The mixing property of $S \times T$ is equivalent to the property for $f$ and $g$ in $L^2(\mu \otimes \nu)$,
$$\langle f \circ (S \times T)^n, g \rangle \to \langle f,1 \rangle \times \langle 1, g \rangle \text{ as } n \to +\infty.$$
In particular, this condition must hold when $f$ and $g$ depend only on the first (second) variable, so the mixing property of $S$ (of $T$) is necessary.
Assume now that $S$ and $T$ are mixing. We have to prove the convergence above for every $f$ and $g$ in $L^2(\mu \otimes \nu)$. This is done by a density argument.
The functions $f_1 \otimes f_2$ where $f_1 \in L^2(\mu)$ and $f_2 \in L^2(\nu)$ form a total family in $L^2(\mu \otimes \nu)$. Using that the family bilinear forms $(f,g) \mapsto \langle f \circ (S \times T)^n, g \rangle$ is equicontinuous because of the inequality
$$|\langle f \circ (S \times T)^n, g \rangle| \le ||f||_{L^2(\mu)}||g||_{L^2(\nu)},$$
one needs only to consider the case where the functions $f$ and $g$ are tensor products $f_1 \otimes f_2$ and $g_1 \otimes g_2$. In this case, the scalar products splits in two parts by Fubini theorem and the convergence follows.


text:
Q: Can't get AlertDialog to dismiss when an item is selected Hey guys, I am having trouble getting my alert dialog to dismiss when an item is selected.  I used an AlertDialog builder to display it and I believe that this is my problem.  I cannot call dismiss because their is not builder.dismiss() method.  Is there a simple way to fix this problem? Here is my code. Thanks.
  AlertDialog.Builder builder = new AlertDialog.Builder(this);

 Context mContext = this;

 LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.numplayersdialog,
                                (ViewGroup) findViewById(R.id.layout_root));

 final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner);
 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
         this, R.array.num_players_array, android.R.layout.simple_spinner_item);
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spinner.setAdapter(adapter);

 builder.setTitle("Select Number of Players");

 spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
            int item = spinner.getSelectedItemPosition();
            commandWriter(item);
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

 builder.setView(layout);
 builder.show();

A: builder.show() returns an AlertDialog object. You can use this to close the dialog.


text:
Q: Нет кода для маркированного списка Код html страницы сайта:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>ResponsiveSlides.js · Responsive jQuery slideshow</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="../responsiveslides.css">
  <link rel="stylesheet" href="demo.css">

Я скачал библиотеку jquery, которая подключает слайдер к сайту.
В примере html страницы сайта со слайдером записан блок с изображениями. При открытии данного сайта можно увидеть данный блок с изображениями и маркированный список с числами, при нажатии на которые осуществляется переключение между изображениями. В консоли код для данного маркированного списка прописан, но в самом файле html кода нет. Где в таком случае его найти?

A: Этот список генерируется самим слайдером. Если Вы откроете неминифицированный скрипт, то там будут следующие строки:
if (settings.pager && !settings.manualControls) {
  var tabMarkup = [];
  $slide.each(function (i) {
    var n = i + 1;
    tabMarkup +=
      "
" +
      "" + n + "" +
      "
";
  });
  $pager.append(tabMarkup);

  ...
}


text:
Q: Dynamically populated form data not posting I've got an HTML form that I have dynamically populated with javascript after pulling the data from an external source, however I've got an issue where there data put into the form via javascript doesn't seem to post to my php script (to insert it to SQL). If I type the data into the form manually it will post fine, only when JS is filling out the form is it not working. How can I get the form to successfully post the data that is put into it via JS?
(ps. I'm new to this so sorry for any basic errors I might have!)
Form:
 <form  id="metadata_form" action="sql_import.php" method="post" enctype="multipart/form-data">

Filename:
<input type="file" name="file" id="file" />

Title: <input type="text" id="title" name="movie_title" class="form_input">

Plot:
 <textarea id="plot" name="movie_desc" style="width: 95%; height: 125px;"></textarea>
Runtime: <input type="text" id="runtime" name="runtime" class="form_input">

Release date: <input type="text" id="released" name="release_dt" class="form_input">

Rated: <input type="text" id="rated" name="rated" class="form_input">

IMDb Link: <input type="text" id="imdbid" name="imdb_lk" class="form_input">

Poster URL: <input type="text" id="poster" name="poster_url" class="form_input">

Poster Preview:

<input type="submit" value="Confirm" style="float:right; clear:both;"/>
</form>

Javascript:

PHP:
//Grab data from input form
$movie_title = $_POST['movie_title'];
$movie_desc = $_POST['movie_desc'];
$runtime = $_POST['runtime'];
$release_dt = $_POST['release_dt'];
$rated = $_POST['rated'];
$imdb_lk = $_POST['imdb_lk'];
$poster_url = $_POST['poster_url'];

//Insert query
$query = "INSERT INTO movies (movie_title, movie_desc, release_dt, rated, imdb_lk, thumbnail_path) VALUES ('$movie_title', '$movie_desc', '$release_dt', '$rated', '$imdb_lk', '$poster_url')";
$result = mysqli_query($db, $query);

A: There are few issues with your code, and few things I changed to make it work. The idea is simple,

*

*User enters a movie title and hits the submit button, which in turn will triggers AJAX.

*Backend PHP code will process the data i.e will fetch the movie details from www.omdbapi.com, insert them into the database and return them back to the AJAX request's success() callback function in json encoded format to populate the HTML form.

*Finally, in success() callback function, it will process the returned data and populate your HTML form.

HTML:
In your HTML code, you just have to change
Poster Preview:

                         ^^^^^^^^^^^^^^

to
Poster Preview:

                         ^^^^^^^^^^^^^^^^

Also, I'd like to point out, these two lines are redundant as per your logic,
Filename:
<input type="file" name="file" id="file" />

Hence, since you're not uploading anything with your form, remove these two lines. Or may be I'm missing something here.
jQuery:
Your jQuery code would be like this,
NOTE: Don't forget to change this url: yourpage.php setting in your AJAX request
// User only enters a movie title and submits the form

PHP:
And finally, this is how you can process the data on PHP side. It will fetch the movie details based the URL it received from the AJAX request, insert them into the database and send them back to AJAX's success() callback function in json encoded format to populate the HTML form.
<?php

    if(isset($_POST['url'])){
        $movieData = file_get_contents($_POST['url']);
        $movie = json_decode($movieData, true);
        echo $movieData;  // to populate your HTML form

        $movie_title = $movie['Title'];
        $movie_desc = $movie['Plot'];
        $runtime = $movie['Runtime'];
        $release_dt = $movie['Released'];
        $rated = $movie['Rated'];
        $imdb_lk = $movie['imdbID'];
        $poster_url = $movie['Poster'];

        // Now construct the query and insert it into your table
    }

?>


text:
Q: Magento 2 Get Customer Data from Order by Email I've created an observer for the event: sales_order_place_after
I'm able to get customer data from the customerId
<?php
namespace MyCompany\MyModule\Observer\Sales\Order;

use Magento\Framework\Event\ObserverInterface;

class Salesrep implements ObserverInterface
{
  public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
  ){
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
   {
     $order = $observer->getEvent()->getOrder();
     $customer = $this->_customerRepositoryInterface->getById($order->getCustomerId());

     $salesrep = $customer->getCustomAttribute('salesrep')->getValue();
     $order->setSalesrep($salesrep);
   }
}

In the case that the customer orders as a guest, how would I get customer details by email?
I've also tried
$customer = $this->_customerRepositoryInterface->getByEmail($order->getCustomerEmail());
but that returns an error.

A: Shortly after posting this question, I was able to figure it out.
Just needed to change this line
$customer = $this->_customerRepositoryInterface->getById($order->getCustomerId());
To
$customer = $this->_customerRepositoryInterface->get($order->getCustomerEmail(), $websiteId = null);