text:
Q: Как связать файлы в PyQt5? У меня проблема я раньше задавал вопросы на форуме мне отвечали. Теперь я не знаю
как сделать чтоб изменения сделанные в food.py перенести в foody.py. Пожалуйста помогите!!!
foody:
import sys
import subprocess
from PyQt5 import QtCore, QtGui, QtWidgets
from food import Ui_MainWindow

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(849, 600)
        MainWindow.setStyleSheet("QLabel {\n"
"    font-size:14px;\n"
"}\n"
"\n"
"QPushButton:hover{\n"
"    background-color:silver;\n"
"}\n"
"\n"
"QWidget {\n"
"    background-color:white;\n"
"}")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(10, 10, 111, 41))
        self.pushButton.setStyleSheet("QPushButton{\n"
"    background-color:gray;\n"
"}\n"
"\n"
"QPushButton:hover{\n"
"    background-color:silver;\n"
"}\n"
"\n"
"QPushButton:pressed{\n"
"    background-color:white;\n"
"}")
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(140, 30, 241, 21))
        self.label.setStyleSheet("QLabel {\n"
"    font-size:14px;\n"
"}")

        self.dateEdit = QtWidgets.QDateEdit(self.centralwidget)
        self.dateEdit.setGeometry(QtCore.QRect(730, 0, 110, 22))
        self.dateEdit.setObjectName("dateEdit")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(10, 60, 821, 451))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(8)
        self.tableWidget.setRowCount(1)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setText("Имя ученика")
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(7, item)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 849, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.pushButton.clicked.connect(self.tableWidget.doItemsLayout)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Добавить ученика"))

        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Бюджет"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Пн"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "Вт"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "Ср"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "Чт"))
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "Пт"))
        item = self.tableWidget.horizontalHeaderItem(7)
        item.setText(_translate("MainWindow", " Остаток"))

class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, rows):
        super(MyWindow, self).__init__()

        self.rows = rows
        self.setupUi(self)

        self.pushButton.clicked.connect(self.set_row_count)
        self.tableWidget.cellChanged.connect(self.cell_changed)          # +

    def set_row_count(self):
        self.rows += 1
        print(self.rows)
        self.tableWidget.setRowCount(self.rows)

    def cell_changed(self, row, column):
        _sum = 0
        if 1 < column < 7:
            for column in range(2, 7):
                if self.tableWidget.item(row, column) != None:
                    try:
                        _sum +=  int(self.tableWidget.item(row, column).text())
                    except:
                        pass

            _bud = 0
            if self.tableWidget.item(row, 1) != None:
                _bud = int(self.tableWidget.item(row, 1).text())
            ost = _bud - _sum
            self.tableWidget.setItem(row, 7, QtWidgets.QTableWidgetItem(str(ost)))

number_rows = 1

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = MyWindow(number_rows)
    w.show()
    sys.exit(app.exec_())

food:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'food.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(995, 620)
        MainWindow.setStyleSheet("QLabel {\n"
"    font-size:14px;\n"
"}\n"
"\n"
"QPushButton:hover{\n"
"    background-color:silver;\n"
"}\n"
"\n"
"QWidget {\n"
"    background-color:white;\n"
"}")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(10, 10, 981, 581))
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.dateEdit = QtWidgets.QDateEdit(self.tab)
        self.dateEdit.setGeometry(QtCore.QRect(860, 20, 110, 22))
        self.dateEdit.setObjectName("dateEdit")
        self.pushButton = QtWidgets.QPushButton(self.tab)
        self.pushButton.setGeometry(QtCore.QRect(0, 0, 111, 41))
        self.pushButton.setStyleSheet("QPushButton{\n"
"    background-color:gray;\n"
"}\n"
"\n"
"QPushButton:hover{\n"
"    background-color:silver;\n"
"}\n"
"\n"
"QPushButton:pressed{\n"
"    background-color:white;\n"
"}")
        self.pushButton.setObjectName("pushButton")
        self.tableWidget = QtWidgets.QTableWidget(self.tab)
        self.tableWidget.setGeometry(QtCore.QRect(10, 50, 961, 491))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(8)
        self.tableWidget.setRowCount(1)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setText("Имя ученика")
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(7, item)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tableWidget_2 = QtWidgets.QTableWidget(self.tab_2)
        self.tableWidget_2.setGeometry(QtCore.QRect(110, 10, 721, 521))
        self.tableWidget_2.setObjectName("tableWidget_2")
        self.tableWidget_2.setColumnCount(7)
        self.tableWidget_2.setRowCount(1)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setText("Имя ученика")
        self.tableWidget_2.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget_2.setHorizontalHeaderItem(6, item)
        self.tabWidget.addTab(self.tab_2, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 995, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Добавить ученика"))
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Бюджет"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Пн"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "Вт"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "Ср"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "Чт"))
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "Пт"))
        item = self.tableWidget.horizontalHeaderItem(7)
        item.setText(_translate("MainWindow", " Остаток"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Бюджет"))
        item = self.tableWidget_2.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.tableWidget_2.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Хлеб"))
        item = self.tableWidget_2.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "Булочка"))
        item = self.tableWidget_2.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "Горячее"))
        item = self.tableWidget_2.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "Напиток"))
        item = self.tableWidget_2.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "Льгота"))
        item = self.tableWidget_2.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "Сумма"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Питание"))

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

A: Попробуйте так:
foody.py
import sys
#import subprocess
from PyQt5 import QtCore, QtGui, QtWidgets

from food import Ui_MainWindow      #  <-- |
                                    #      |
                                    #      V
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, rows):
        super(MyWindow, self).__init__()

        self.rows = rows
        self.setupUi(self)

        self.pushButton.clicked.connect(self.set_row_count)
        self.tableWidget.cellChanged.connect(self.cell_changed)

    def set_row_count(self):
        self.rows += 1
        print(self.rows)
        self.tableWidget.setRowCount(self.rows)

    def cell_changed(self, row, column):
        _sum = 0
        if 1 < column < 7:
            for column in range(2, 7):
                if self.tableWidget.item(row, column) != None:
                    try:
                        _sum +=  int(self.tableWidget.item(row, column).text())
                    except:
                        pass

            _bud = 0
            if self.tableWidget.item(row, 1) != None:
                _bud = int(self.tableWidget.item(row, 1).text())
            ost = _bud - _sum
            self.tableWidget.setItem(row, 7, QtWidgets.QTableWidgetItem(str(ost)))

number_rows = 1

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = MyWindow(number_rows)
    w.show()
    sys.exit(app.exec_())


text:
Q: Given a matrix $A$ such that $A^{\ell}$ is a constant matrix, must $A$ be a constant matrix? This problem originates from an exercise in Richard Stanley's Algebraic Combinatorics.  The exercise in the text (Chapter 3, Exercise 2(a)) asks

Let $G$ be a finite graph (allowing loops and multiple edges).  Suppose that there is some $\ell> 0$ such that the number of walks of length $\ell$ from any fixed vertex $u$ to any fixed vertex $v$ is independent of $u$ and $v$.  Show that $G$ has the same number $k$ of edges between any two vertices (including $k$ loops at each vertex.

The hypothesis of the problem (that the number of walks of length $\ell$ between any two vertices is the same) tells us that the adjacency matrix $A(G)$ of $G$ raised to the $\ell$ power is a constant matrix
$$ (A(G))^{\ell} = \begin{pmatrix} c & c & \cdots & c \\ c & c & \cdots & c \\ \vdots & \vdots & \ddots & \vdots \\ c & c & \cdots & c \end{pmatrix} $$
for some constant $C$.  We would like to conclude that this means the adjacency matrix itself is a constant matrix (hence, the number of walks of length 1 between any two vertices is the same, i.e., the number of edges between any two vertices is the same).  Update in response to comments below: In this case we also have that $A(G)$ is a symmetric matrix which would eliminate some trivial counter examples.
Does this result follow from something in linear algebra?  What is the proof?  If not, is there some other approach that might be more fruitful?

A: Since $A(G)$ is symmetric, it is diagonalizable.  In particular, this implies that $\ker(A(G)^\ell)=\ker(A(G))$ for all $\ell>0$.  If $A(G)^\ell$ is a constant matrix, then for any $i$ and $j$, $e_i-e_j$ is in its kernel (where $\{e_i\}$ is the standard basis).  Thus $e_i-e_j\in \ker(A(G))$ for every $i$ and $j$, which says that the columns of $A(G)$ are all the same.  Since $A(G)$ is symmetric, this actually implies all the entries of $A(G)$ are the same.

A: If $A^k$ is constant (all entries are the same), then we cannot conclude that $A$ is constant as well. For example,
$$A=\begin{bmatrix}0 & 1 \\ 0 & 0\end{bmatrix}$$
is such that $A^2=0$ (so it is constant), but $A$ is not constant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: REST API filter / sort with flask (and webargs, marshmallow, sqlalchemy) I'm working on my first flask-classful / sqlalchemy / marshmallow REST API. I have a Delivery table in my database with a status enum:

*

*new

*requested

*dispatched

*arrived

*closed

As expected, GET /deliveries/ returns a list of deliveries. Here's a current code extract from the view:
deliveries_schema = DeliverySchema(many=True)  # a marshmallow-sqlalchemy ModelSchema

class Deliveries(FlaskView):
    @use_kwargs(deliveries_schema.fields)
    def index(self, **kwargs):
        deliveries = Delivery.query.filter_by(**kwargs)
        return deliveries_schema.jsonify(incidents)

Yes, I pass webargs parameters straight to filter_by. However let's say for a given screen in the client, I need to see only deliveries with status new or requested. It clearly makes sense to implement some sort of filter grammar, as I'm going to want to perform similar operations on all kinds
Unfortunately the following GETs fail:

*

*/deliveries/?status=new&status=requested returns only deliveries with status=new - in fact it always chooses the first of the two.

*As a fairly random experiment /deliveries/?status=new,requested results in marshmallow-sqlalchemy returning 422 Unprocessable Entity, which is understandable as new,requested is not an option in the status enum. I'm not sure if this is a feature or a bug.

As an aside, I can successfully pass two different filter parameters e.g. /deliveries/?status=requested&user_id=123 works as expected.
Anyway, the same goes for sorting and pagination. At present I have no idea how to handle them in my API. Current issues as I see them:

*

*I'll need to add parameters that don't map to DeliverySchema. This seems to indicate that there will be an impact on the schema code.

*I can't just blindly throw all the parameters to filter_by, because some of the parameters won't be filters. But for this first use case I'd be happy to just be able to filter based on statuses new and requested. Sorting and pagination can come later.

*The grammar logic needs to be implemented somewhere.

I don't even know where in the stack this should be handled, let alone how to implement a solution. Surely this is a pretty common use case, any pointers appreciated.


text:
Q: Salesforce: How to Concatenate multiple fields if they are not blank Problem: I want to concatenate 5 fields which hold user names and separate them with a comma, but only if they are not blank.
I tried:
IF(ISBLANK(Co_Signatory_Number_1__c),"", ", TEXT(Co_Signatory_Number_1__c"))&
IF(ISBLANK(Co_Signatory_Number_2__c),"", ', TEXT(Co_Signatory_Number_2__c"))&
IF(ISBLANK(Co_Signatory_Number_3__c),"", ", TEXT(Co_Signatory_Number_3__c"))&
IF(ISBLANK(Co_Signatory_Number_4__c),"", ", TEXT(Co_Signatory_Number_4__c"))&
IF(ISBLANK(Co_Signatory_Number_5__c),"", ", TEXT(Co_Signatory_Number_5__c"))

But this literally returns "'TEXT(Co_Signatory_Number_1__c)" rather than the field ", John Doe"
How do I get the if function to insert the field, rather than the literal text?

A: You are including the function TEXT() in your string literal.
IF(ISBLANK(Co_Signatory_Number_1__c),"", ", "&TEXT(Co_Signatory_Number_1__c))&
IF(ISBLANK(Co_Signatory_Number_2__c),"", ", "&TEXT(Co_Signatory_Number_2__c))&
IF(ISBLANK(Co_Signatory_Number_3__c),"", ", "&TEXT(Co_Signatory_Number_3__c))&
IF(ISBLANK(Co_Signatory_Number_4__c),"", ", "&TEXT(Co_Signatory_Number_4__c))&
IF(ISBLANK(Co_Signatory_Number_5__c),"", ", "&TEXT(Co_Signatory_Number_5__c))


text:
Q: Cannot restart redis-sentinel unit I'm trying to configure 3 Redis instances and 6 sentinels (3 of them running on the Redises and the rest are on the different hosts). But when I install redis-sentinel package and put my configuration under /etc/redis/sentinel.conf and restart the service using systemctl restart redis-sentinel I get this error:
Job for redis-sentinel.service failed because a timeout was exceeded.
See "systemctl status redis-sentinel.service" and "journalctl -xe" for details.

Here is the output of journalctl -u redis-sentinel:
Jan 01 08:07:07 redis1 systemd[1]: Starting Advanced key-value store...
Jan 01 08:07:07 redis1 redis-sentinel[16269]: 16269:X 01 Jan 2020 08:07:07.263 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
Jan 01 08:07:07 redis1 redis-sentinel[16269]: 16269:X 01 Jan 2020 08:07:07.263 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=16269, just started
Jan 01 08:07:07 redis1 redis-sentinel[16269]: 16269:X 01 Jan 2020 08:07:07.263 # Configuration loaded
Jan 01 08:07:07 redis1 systemd[1]: redis-sentinel.service: Can't open PID file /var/run/sentinel/redis-sentinel.pid (yet?) after start: No such file or directory
Jan 01 08:08:37 redis1 systemd[1]: redis-sentinel.service: Start operation timed out. Terminating.
Jan 01 08:08:37 redis1 systemd[1]: redis-sentinel.service: Failed with result 'timeout'.
Jan 01 08:08:37 redis1 systemd[1]: Failed to start Advanced key-value store.
Jan 01 08:08:37 redis1 systemd[1]: redis-sentinel.service: Service hold-off time over, scheduling restart.
Jan 01 08:08:37 redis1 systemd[1]: redis-sentinel.service: Scheduled restart job, restart counter is at 5.
Jan 01 08:08:37 redis1 systemd[1]: Stopped Advanced key-value store.
Jan 01 08:08:37 redis1 systemd[1]: Starting Advanced key-value store...
Jan 01 08:08:37 redis1 redis-sentinel[16307]: 16307:X 01 Jan 2020 08:08:37.738 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
Jan 01 08:08:37 redis1 redis-sentinel[16307]: 16307:X 01 Jan 2020 08:08:37.739 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=16307, just started
Jan 01 08:08:37 redis1 redis-sentinel[16307]: 16307:X 01 Jan 2020 08:08:37.739 # Configuration loaded
Jan 01 08:08:37 redis1 systemd[1]: redis-sentinel.service: Can't open PID file /var/run/sentinel/redis-sentinel.pid (yet?) after start: No such file or directory

and my sentinel.conf file:
port 26379
daemonize yes
sentinel myid 851994c7364e2138e03ee1cd346fbdc4f1404e4c
sentinel deny-scripts-reconfig yes
sentinel monitor mymaster 172.28.128.11 6379 2
sentinel down-after-milliseconds mymaster 5000
# Generated by CONFIG REWRITE
dir "/"
protected-mode no
sentinel failover-timeout mymaster 60000
sentinel config-epoch mymaster 0
sentinel leader-epoch mymaster 0
sentinel current-epoch 0

A: What's the output in the sentinel log file?
I had a similar issue where Sentinel received a lot of sigterms.
In that case you need to make sure that if you use the daemonize yes setting, the systemd unit file must be using Type=forking.
Also make sure that the location of the PID file specified in the sentinel config matches the location specified in the systemd unit file.

A: If you are trying to run your Redis servers on Debian based distribution, add below to your Redis configurations:

*

*pidfile /var/run/redis/redis-sentinel.pid to /etc/redis/sentinel.conf

*pidfile /var/run/redis/redis-server.pid to /etc/redis/redis.conf

A: If you face below error in journalctl or systemctl logs,
Jun 26 10:13:02 x systemd[1]: redis-server.service: Failed with result 'exit-code'.
Jun 26 10:13:02 x systemd[1]: redis-server.service: Scheduled restart job, restart counter is at 5.
Jun 26 10:13:02 x systemd[1]: Stopped Advanced key-value store.
Jun 26 10:13:02 x systemd[1]: redis-server.service: Start request repeated too quickly.
Jun 26 10:13:02 x systemd[1]: redis-server.service: Failed with result 'exit-code'.
Jun 26 10:13:02 x systemd[1]: Failed to start Advanced key-value store.

Then check /var/log/redis/redis-server.log for more information
In most cases issue is mentioned there.
i.e if a dump.rdb file is placed in /var/lib/redis then the issue might be with database count or redis version.
or in another scenario disabled IPV6 might be the issue.


text:
Q: regex - do not collect if formatted numbers before speific word anywhere in text string I do not want to match the regex if any formatted number, such as $1,000 appears anywhere before a specific word in the text string.
In this case the word to find is "expungement" - but only if there is NO formatted value before it.
So I would not want to match this string.
this is some initial text $11,000 recommends the expungement more text following
but this would be accepatable
this is some initial text expungement more text following
Thank you.

A: A pattern you can use is:
^[^\$]*(?!\$[0-9,]+)expungement

To explain:

*

*^ is start of string

*[^$]* means match any character that is not '$', 0 or more times

*(?!x) means negative lookup for x. If x is found in the line, the match is negated

*\$[0-9,]+ is a literal dollar sign followed by any combination of digits and commas

*Your desired string at the end


text:
Q: List view how to manipulate objects of list adapter item View adapterListView = new SpecialAdapter(getBaseContext(),list,R.layout.listview_layout,from,to);

 headerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.jpos_ror_header, null, false);

footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.jpos_ror_footer, null, false);

TextView tin=(TextView)headerView.findViewById(R.id.textViewTinValue);
TextView textViewNameOfPayor=(TextView)headerView.findViewById(R.id.textViewNameOfPayor);
TextView textViewLocation=(TextView)headerView.findViewById(R.id.textViewLocation);

Here is my code in getting object id's from my header and footer. how can i get the view of my list view data adapter without onClick event. i want to do some layout manipulation in viewing of my layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:orientation="horizontal"  >

     <!-- here is my data adapter to be display per item in list view  -->

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <RelativeLayout
              android:id="@+id/relativeModeOfPaymentCheck"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:background="#000000" >

      <LinearLayout
          android:id="@+id/linearForCheck"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"

          android:layout_alignParentLeft="true"
          android:orientation="vertical"
          android:paddingTop="5dp" >

          <TextView
              android:id="@+id/textViewModeOfPaymentCheckValue"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Mode of Payment Value check"

              android:layout_marginLeft="15dp"
              android:textStyle="bold"
              android:textColor="#ffffff" />
     </LinearLayout>
          <!-- asdasda -->
          <LinearLayout
              android:id="@+id/linearForAmountModeOfPayment"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/linearCheckDate"
              android:orientation="horizontal"
              android:weightSum="2" >

              <RelativeLayout
                  android:id="@+id/relativeBlock100"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="15dp"
                  android:layout_weight="1"
                  android:background="#000000" >

                  <TextView
                      android:id="@+id/textViewModAmountCheck"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="AMOUNT"
                      android:textColor="#ffffff" />
              </RelativeLayout>

              <RelativeLayout
                  android:id="@+id/relativeBlock101"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:background="#000000" >

                  <TextView
                      android:id="@+id/textViewModeOfPayCheckValue"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_alignParentTop="true"
                      android:layout_centerHorizontal="true"
                      android:textColor="#ffffff" />
              </RelativeLayout>
          </LinearLayout>
          <!-- name of check issued -->
          <LinearLayout
              android:id="@+id/linearForNameCheckIssued"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/linearForCheck"
              android:orientation="horizontal"
              android:visibility="gone"
              android:weightSum="2" >

              <RelativeLayout
                  android:id="@+id/relativeBlock101"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="15dp"
                  android:layout_weight="1"
                  android:background="#000000" >

                  <TextView
                      android:id="@+id/textViewBankNameCheckIssued"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="RIZAL COMMERCIAL BANKING CORP."
                      android:textColor="#ffffff" />
              </RelativeLayout>
          </LinearLayout>

          <!-- CHECK NUMBER -->
          <LinearLayout
              android:id="@+id/linearCheckNumber"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/linearForNameCheckIssued"
              android:visibility="gone"
              android:orientation="horizontal" >

              <TextView
                  android:id="@+id/textViewCheckNumber"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="15dp"
                  android:text="CHECK # : "
                  android:textColor="#ffffff" />

              <TextView
                  android:id="@+id/textViewCheckNumValue"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textColor="#ffffff" />
          </LinearLayout>
         <!-- CHECK DATE -->
          <LinearLayout
              android:id="@+id/linearCheckDate"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              <!-- android:visibility="gone" -->
              android:layout_below="@+id/linearCheckNumber"
              android:orientation="horizontal" >

              <TextView
                  android:id="@+id/textViewCheckDate"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="15dp"
                  android:text="CHECK DATE : "
                  android:textColor="#ffffff" />

              <TextView
                  android:id="@+id/textViewCheckDateValue"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textColor="#ffffff" />
          </LinearLayout>

        <LinearLayout
              android:id="@+id/linearLineForCheck"
              android:layout_width="wrap_content"
              android:layout_height="2dp"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/linearForAmountModeOfPayment"
              android:orientation="horizontal" >

                  <View
                      android:id="@+id/View201"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:background="#ffffff" />
          </LinearLayout>

          </RelativeLayout>
          </LinearLayout>
</LinearLayout>

in this adapter i want to manipulate the view of linearlayouts by having  LinearLAyout.setVisibility(LinearLayout.GONE or VISIBLE);
Here i think i have some lead from my problem from the answer of himanshu. here is my listview special adapter im having problem how can get the view and viewGroup implementation to my special adapter here is my SpecialAdapter..

public class SpecialAdapter extends SimpleAdapter {
    public static TextView tv;
    private int[] colors = new int[] { 0xffcccccc , 0xffffffff };
    private int[] colors2 = new int[] { 0xffffffff , 0xff000000 };
   // Context context;
    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
        super(context, items, resource, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View view = super.getView(position, convertView, parent);
      int colorPos = position % colors.length;
      view.setBackgroundColor(colors[colorPos]);
      //TextView textView = (TextView)view.findViewById(R.id.textViewModAmountCheck);
      //textView.setText("AlvinTest");
      return view;
    }

Could anyoune tell me i am doing right when im implementing mg getView2.

    public View getView2(Context context, int position, View convertView, ViewGroup parent) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);//get your layout inflator;

//LayoutInflater inf = LayoutInflater.from(getContext());
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.listview_layout, null);
        }
        LinearLayout yyy = (LinearLayout) convertView.findViewById(R.id.linearCheckDate);
        yyy.setVisibility(View.GONE);
        return convertView;
    }

    public boolean setViewValue(View view, Cursor cursor, int columnIndex){
        int getIndex = cursor.getColumnIndex("Name");
        String empname = cursor.getString(getIndex);
        tv = (TextView) view;
        tv.setTextColor(Color.WHITE);
        tv.setText(empname);
        if(empname.equals("Any String"))
        {
            tv.setTextColor(Color.rgb(58, 58, 224));
            return true;
        }
        return false;
    }
}

Here's my code when im calling the getView2 from my listAdapter

LayoutInflater inf = LayoutInflater.from(this);
View v = inf.inflate(R.layout.listview_layout, null);

//add magic here bu i don't know how can i get the view of these View and ViewGroup
View itemConvertView = inf.inflate(R.layout.listview_layout, null);
ViewGroup listParent =null; //this.getParent();//(ViewGroup)SelectorView.this.getParent();// null;
adapterListView.getView2(this,0, itemConvertView, listParent);

A: try this:
Hide your Layout:
YourLayout.setVisibility(View.GONE);

Visible your Layout :
YourLayout.setVisibility(View.VISIBLE);

A: If i understood your problem correctly, you want to get the first element of the ListView pro grammatically and change its state (Visibility).
You can get the element in ListView by calling getChildAt(int index) method
e.g
LinearLayout yourFirstView = (LinearLayout) listview.getChildAt(0);

Accessing child of the element that reside in first row of the listview.
ViewType view = (ViewType)yourFirstView.findViewById(R.id.elementId);

setting the visiblity
yourFirstView.setVisiblity(View.Gone); // or View.VISIBLE

A: What I understand from your question is that there is some view in your ListView item which you want to show only if needed. You can do this in the getView method of your adapter where you inflate the custom layout of list item. Something like below
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = get your layout inflator;

    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.XXXX, null);
    }
    LinearLayout yyy = (LinearLayout) convertView.findViewById(R.id.member_name_text_view);
    yyy.setVisibility(View.Gone)
    return convertView;
}


text:
Q: Task.Wait for async method passes during application startup while it causes deadlock in WPF button handler The behavior of Task.Wait() is unexpectedly different depending on the "environment" where invoked.
Calling Task.Wait() during application startup with below async method TestAsync passes (doesn't cause a deadlock) while the same code blocks when called from within a WPF Button handler.
Steps to reproduce:
In Visual Studio, using the wizard, create a vanilla WPF .NET framework application (e.g. named WpfApp).
In the App.xaml.cs file of the app file paste below Main method and TestAsync method.
In the project properties set Startup object to WpfApp.App.
In the properties of App.xaml switch Build Action from ApplicationDefinition to Page.
    public partial class App : Application
    {
        [STAThread]
        public static int Main(string[] args)
        {
            Task<DateTime> task = App.TestAsync();
            task.Wait();

            App app = new App();
            app.InitializeComponent();
            return app.Run();
        }

        internal static async Task<DateTime> TestAsync()
        {
            DateTime completed = await Task.Run<DateTime>(() => {
                System.Threading.Thread.Sleep(3000);
                return DateTime.Now;
            });
            System.Diagnostics.Debug.WriteLine(completed);
            return completed;
        }
    }

Observe that the application starts properly (after 3sec delay) and that the "completed" DateTime is written to debug output.
Next create a Button in MainWindow.xaml with Click handler Button_Click in MainWindow.xaml.cs
    public partial class MainWindow : Window
    {
        ...

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task<DateTime> task = App.TestAsync();
            task.Wait();
        }
    }

Observe that after clicking the Button, the application is deadlocked.
Why can't it pass in both cases?
Is there a way to change invocation (e.g. using ConfigureAwait at the correct task or somehow setting SynchronizationContext or whatever) so that it behaves identical in both invocations, but still synchronously waits for completion?
Update on limitations of the solution.
The async method like TestAsync comes from a library that cannot be changed.
The invocation code of the TestAsync method is nested within a callstack that cannot be changed either, and the code outside the callstck makes use of the returned value of the async method.
Ultimately the solution code has to convert the async method to run synchronous by not changing the method nor the caller.
This works well within UT code (NUnit) and during application startup, but no more within a handler of WPF.
Why?

A: There are a couple of different ways that you can handle this situation, but ultimately the reason there is a deadlock in one situation and not the other is that when called in the Main method SynchronizationContext.Current is null, so there isn't a main UI context to capture and all async callbacks are handled on thread pool threads. When called from the button, there is a synchronization context which is captured automatically, so all async callbacks in that situation are handled on the main UI thread which is causing the deadlock. In general the only way you won't get that deadlock is by forcing the async code to not capture the synchronization context, or use async all the way up and don't synchronously wait from the main UI context.

*

*you can ConfigureAwait(false) inside of your TestAsync method so that it doesn't capture the synchronization context and try to continue on the main UI thread (this is ultimately what is causing your deadlock because you are calling task.Wait() on the UI thread which is blocking the UI thread, and you have System.Diagnostics.Debug.WriteLine(completed); that is trying to be scheduled back onto the UI thread because await automatically captures the synchronization context)

DateTime completed = await Task.Run<DateTime>(() => {
                System.Threading.Thread.Sleep(3000);
                return DateTime.Now;
            }).ConfigureAwait(false);

*You can start the async task on a background thread so that there isn't a synchronization context to capture.

private void Button_Click(object sender, RoutedEventArgs e)
{
    var task = Task.Run(() => App.TestAsync());
    var dateTime = task.Result;
}

*you can use async up the whole stack

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Task<DateTime> task = App.TestAsync();
    var dateTime = await task;
}

*Given how you are using it, if you don't have to wait until the task is done, you can just let it go and it will finish eventually, but you lose the context to handle any exceptions

private void Button_Click(object sender, RoutedEventArgs e)
{
    //assigning to a variable indicates to the compiler that you
    //know the application will continue on without checking if
    //the task is finished. If you aren't using the variable, you
    //can use the throw away special character _
    _ = App.TestAsync();
}

These options are not in any particular order, and actually, best practice would probably be #3. async void is allowed specifically for cases like this where you want to handle a callback event asynchronously.

A: From what I understand, in .NET many of the front ends have a single UI thread, and therefore must be written async all the way through. Other threads are reserved and utilized for things like rendering.
For WPF, this is why use of the Dispatcher and how you queue up work items is important, as this is your way to interact with the one thread you have at your disposal. More reading on it here
Ditch the .Result as this will block, rewrite the method as async, and call it from within the Dispatch.Invoke() and it should run as intended

A:
Why can't it pass in both cases?

The difference is the presence of a SynchronizationContext. All threads start out without a SynchronizationContext. UI applications have a special UI thread(s) and at some point they need to create a SynchronizationContext and install it on that thread(s). Exactly when this happens isn't documented (or consistent), but it has to be installed at the point the UI main loop starts.
In this case, WPF will install it (at the latest) within the call to Application.Run. All user invocations from the UI framework (e.g., event handlers) happen within this context.
The blocking code deadlocks with the context because this is the classic deadlock situation, which requires three components:

*

*A context that only allows one thread at a time.

*An asynchronous method that captures that context.

*A method also running in that context that blocks waiting for that asynchronous method.

Before the WPF code installed the context, condition (1) wasn't met, and that's why it didn't deadlock.

Is there a way to change invocation (e.g. using ConfigureAwait at the correct task or somehow setting SynchronizationContext or whatever) so that it behaves identical in both invocations, but still synchronously waits for completion?

We-ell...
This is a rephrasing of "how do I block on asynchronous code", and there's no good answer for that. The best answer is to not block on asynchronous code at all; i.e., use async all the way. Especially since this is GUI code, I'd say for the sake of UX you really want to avoid blocking. Since you're on WPF, you may find a technique like asynchronous MVVM data binding useful.
That said, there are a few hacks you can use if you must. Using ConfigureAwait is one possible solution, but not one I recommend; you'd have to apply it to all awaits within the transitive closure of all methods being blocked on (Blocking Hack). Or you can shunt the work to the thread pool (Task.Run) and block on that (Thread Pool Hack). Or you can remove the SynchronizationContext - unless the code being blocked on manipulates UI elements or bound data. Or there are even more dangerous hacks that I really can't recommend at all (Nested Message Loop Hack).
But even after putting in all the work for a hack, you'll still end up blocking the UI. The hacks are hard precisely because they're not recommended. It's quite a bit of work to give your users a worse experience. The far, far better solution (for your users and future code maintainers) is to go async all the way.


text:
Q: How to specify timeout in d3 xhr send request I want to set a timeout value so that if the server does not respond in that particular time frame then the UI should move ahead and not wait for response. I have used the below syntax so far but it does not restrict the UI to listen for the specified time.
      d3.xhr(my_url)
        .header('Content-Type', 'text/xml')
        .header('timeout', 2000)
        .send(this.my_method, my_xmlData, function(error, data) {
        }

I read here that d3 xhr supports timeout feature now. Could anyone please tell me how to use that correctly?

A: Just pass the time (in milliseconds) to timeout (in version 4.x):
.timeout(time)

Here is an example. I'll load a JSON file without timeout:

var url = "https://mysafeinfo.com/api/data?list=englishmonarchs&format=json";

d3.json(url)
  .get(callback);

function callback(data) {
  console.log(data)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

Now the same code, using 1 millisecond in the timeout (a very little time):

var url = "https://mysafeinfo.com/api/data?list=englishmonarchs&format=json";

d3.json(url)
  .timeout(1)
  .get(callback);

function callback(data) {
  console.log(data)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

As you can see 1 millisecond is too little time to get the file, and the callback will return null, as expected.


text:
Q: LDAP port forwarding or proxy I am trying to find a way to locally access an OID server (via LDAP) that is usually only accessible from my app's staging server. I have login credentials for the staging box. I do not have login credentials on the machine that is running the OID server. If I did I would simply use an ssh tunnel. What I think I want to do is forward my local outgoing LDAP request through the staging server to the OID server. How can this be done? Am I thinking about this correctly?

A: If you have an SSH server running on your staging box and your LDAP server is reachable via unencrypted LDAP on the standard port, you could try the following:
ssh -L 10389:yourldapserver:389 username@yourstagingserver

which will connect port 10389 on your local machine (127.0.0.1) with port 389 on your LDAP server.
yourldapserver is the hostname or IP of your LDAP server as seen by the staging machine, yourstagingserver is the hostname or IP of your staging server as seen by your local machine and username is your login name on that box.


text:
Q: Remove quotation marks around a number (while leaving other quotes) I want to replace all text like this:
"latitude": "32.336533",

with this:
"latitude": 32.336533,

I'm using Notepad++.

A: Using Regex use the following pattern:
"([0-9]+\.{0,1}[0-9]*)"

and Replace with:
\1

This worked for me with replace all function of notepad++.  It would find "12." too and remove the double quotes.  For a more comprehensive search use this Regex pattern:
"(\-{0,1}[0-9]+(\.[0-9]+){0,1})"

which actually will find negative numbers as well and matches floats only with digits after the decimal point.
Explanation:
it will match
    "             ; a leading double quote
    (             ; followed by the outer subpattern (in backreference \1:
      \-{0,1}       ; an optional minus sign
      [0-9]+        ; followed by 1 or more decimal digits (could be replaced by \d)
      (             ; followed by the next subpattern
         \.           ; a decimal point
         [0-9]+       ; followed by 1 or more digits
      ){0,1}        ; maximal 1 occurrence of this subpattern, and it's optional
    )             ; end of the outer subpattern
    "             ; followed by the trailing double quote

Backreference \1 includes everything in the outer subpattern including the inner one, if it exists. You could use \d for the [0-9] classes and use the question mark ? instead of the last {0,1} group. Remember that the use of the ? may change the greediness of patterns.

Example:
the text in notepad++ with following lines
"latitude": "-32.336533",
"latitude": "32.336533",
"foo": "14"
"bla": "12."
"to7": "12.a"

will be changed  after applying "Replace all" to
"latitude": -32.336533,
"latitude": 32.336533,
"foo": 14
"bla": "12."
"to7": "12.a"

A: Regex match
"([\d\.]+)"

Replace with
\1


text:
Q: Projecting multiple fields to a POJO Is there a way in hibernate-search 6 to project multiple fields and map them directly to a POJO object or I should handle it by myself. I'm not sure that I understand the composite method described in the documentation. For example I can do something like that:
SearchResult<List<?>> result = searchSession.search(indicies)
.select(f -> f.composite(f.field("field1"), f.field("field2"), f.field("field3"),f.field("field4")))
.where(SearchPredicateFactory::matchAll)
.fetch(20)

And then I can manually map the returned List of fields to a POJO. But is there a more fancy way to do that without the need to manually loop through the list of fields and set them to the POJO instance?

A: At the moment projecting to a POJO is only possible for fairly simple POJOs, with up to three fields, using the syntax shown in the documentation. For more fields than that, you have to go through a List.
If you're using the Elasticsearch backend, you can theoretically retrieve the document as a JsonObject and then use Gson to map it to a POJO.
There are plans to offer more fancy solutions, but we're not there yet.


text:
Q: Struts2  with 'value="true" not rendered as preselect if has Angular `ng-model` I have observed a very peculiar behavior of <s:checkbox> rendering along with Bootstrap 3 and AngularJS.
I have these two <s:checkbox> in my page, wrapped by some elements of Bootstrap 3 styles:

            <s:text name="actividad.busqueda.activa"/>
                <s:checkbox class="form-control" id="activaCheck" name="activaCheck" ng-model="formData.activaCheck" value="true"></s:checkbox>
                <s:checkbox class="form-control" id="activaCheck2" name="activaCheck2"  value="true"></s:checkbox>

As you can see, the only difference between them, is that the first has attribute ng-model = "xxx", while the second doesn't.
And, in my page, they are rendered differently, although they both are supposed to be pre-selected, because I set value="true". And when we inspect in FF, we can see the first <s:checkbox> has checked="checked", but is not rendered. I have tested in Chrome and FF, same.
I have also tested with <input type="checkbox" /> with ng-model set and checked="checked", the same: not checked when rendered in page.

So I am thinking about AngularJS is taking over part of rendering job which Struts 2 is responsible of, at least in this case. I want some explanation from developers of AngularJS, or this is the expected result?

A: I got the problem with unchecked checkbox. Because it has ng-model attribute the input control is bound to Angular's $scope. And if the scope doesn't define the property value for the above named checkbox it's not checked. Assumed that AngularJS modifies DOM as soon as it initializes.
I have created plnkr to demonstrate it.
You are right AngularJS starts working after document is loaded. At this time Struts has already done its work and returned html document to the browser. Now Angular continues to prepare the page to work only on one page. Both complement each other, but if Struts use to render
<input type="checkbox" ng-model="checkboxModel.value1" checked="checked">

Angular removes the checked state, because the value is commented
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  $scope.checkboxModel = {
   //value1 : true,
   value2 : 'YES'
 };
}]);


text:
Q: multiple definition of `login::GetEventHashTable() const' i got this error
multiple definition of `login::GetEventHashTable() const'
can anybody tell me, when it occour...

A: Please share code snippet, as rough guess, did you forget semi colon ; in at the end of class declaration in header file? like
class abc
{
}; --> here

A: Multiple definitions often occur when multiple copies of an include file are included.  This problem can be most easily avoided by adding
#pragma once

at the top of every include file.

A: as my experience said, it is happening because of multiplicity of same header files
write
ifndef HANDLER_H_
define HANDLER_H_
at the top(u can change the header file name, i have handler.h
and
endif
at the bottom of any header file


text:
Q: Unable to start service in window 10 by using NSSM I have create a small script file to test.
This my script.bat file.
sc create myService binpath= C:\Users\Admin\Desktop\test.bat start= auto

This is my test.bat file.
echo "Welcome to Wizard"

Problem Statement
I am unable to start the service from control panel Service section.
I get following error.
[SC] StartService FAILED 1053:
    The service did not respond to the start or control request in a timely fashion.
That is why I am using nssm.
NOW what happening is that when I run following command on powershell
.\nssm install myService, I dialogue box appears. I give it the path of my script file and click on install service.
After successfull installation of service. I go to control panel -> Service -> click on start against myService but it get paused and following dialog box appears
Window could not start myService service on Local Computer. The service did not return an error. This could be windows error or internal service error.
If problem persist contact to your system administrator.

*

*How can I fix this?

*Is there anyother way to do it without doing manual steps and not using third party tool.

*I am doing all this on window 10. Do I need any server to perform this task?

NOTE: I cannot use Always up or window scheduler in my case.

A: The NSSM behaviour is caused by the script terminating almost instantly. Try the following script:
echo Hello World
pause

This should allow the service to start, but you will not necessarily see a console window. Even if you tick 'allow service to interact with desktop', it will not be your desktop that it interacts with!
Using SysInternals Process Explorer, you will be able to see the NSSM service running with a CMD child process that is executing the script.
Windows implements 'session zero isolation' as a security feature, and this essentially prevents services interacting with end user desktops.
In terms of a solution, it's possible to write Windows 'service' applications fairly simply using Visual Studio. It's outside my area of expertise, but based on the Windows applications I'm familiar with, you would generally have a user-mode application running to provide desktop interaction. The user-mode application can interact with services hosted by the service application.

A: A Windows Service is an executable program which must support a few standard events (OnStart OnStop, OnPause, OnContinue for example). A .bat file is not an executable and you will never get it to actually run as a service.
When you run the bat file, the actual program that runs is cmd.exe - but that doesn't support the event required.
You could write a Windows Service (using something like C++ or C# or many other languages) and you could then program the service to run a bat file in cmd.exe. However, your bat file would not work as a service does not have access to the screen or the keyboard.
TL;DR: it's just not going to work. Perhaps if you raise another question about what you're actually trying to do? It sounds like you see a service as a solution, and you haven't described the problem.

A: FYI, you can set up logging on nssm to help track down the problem. Logging helped me resolve a similar issue:
nssm set [SERVICE_NAME] AppStdout [APP_PATH_INSTALL]\logs\service.log
nssm set [SERVICE_NAME] AppStderr [APP_PATH_INSTALL]\logs\service-error.log


text:
Q: Executing a FOR loop outside a function in PgAdmin fails with "syntax error at or near "for"" Why am I unable to just execute the following in PgAdmin with F5 (Run):
for temprow in
   select * from recalls_t where user_id in (select id from users_t where user_name like '%PRF15D%')
loop
   for r in 1..50
   loop
       insert into events_t (id, gui_event_id)
                   values (nextval('seq'), temprow.id);
    end loop;
end loop;

Error:
ERROR:  syntax error at or near "for"
LINE 2: for temprow in
        ^
SQL state: 42601
Character: 7

My goal is  to insert dummy rows in a FOR loop. I don't need a function or anything else.

A: Because plpgsql is not executable SQL. You want to use the DO statement. For documentation, have a look here: https://www.postgresql.org/docs/current/sql-do.html
You can use this like a "one time function".

A: PL/pgSQL code can only be run in the context of a PL/pgSQL function or do block.
But you don't need a loop to begin with:
insert into events_t (id, gui_event_id)
select nextval('seq'), id,
from recalls_t
where user_id in (select id
                  from users_t
                  where user_name like '%PRF15D%')


text:
Q: Word for "A feeling of lethargy experienced after eating a meal" From this link, I found the word to be "the Itis".
Is there a synonym for this word?

"I got the worst case of ______ after that cheese steak with fries".

A: Post-prandial somnolence, post-prandial sleepiness, or post-prandial fatigue. (The hyphen is optional.)
Food coma
See Wikipedia:

Postprandial somnolence (colloquially known as the itis, food coma, after dinner dip, or postprandial sleep) is a normal state of drowsiness or lassitude following a meal.


text:
Q: convert serialized form to individual post items how would i go about converting a serialized form into individual post items? It is a dynamic form and I will never know exactly what the fields will be.
I am trying to convert it to an array and then loop thorugh and build the $.post that way but its failing to do it, this is what i have at the moment.
  var data = $('#report_manager_frame_report #reportForm').serialize();
  //var data example:
  //"hotelid=7696&date=2016-03-01&exportSelect=HTML4.0&parameters=&exportName=&reportName=%2Fwelcome_reports%2FDaily+Revenue+Report&reportName=&hotelid=7696&date=&exportSelect=HTML4.0&parameters=false&exportName=&reportName=%2Fwelcome_reports%2FDaily+Revenue+Report&hotelid=7696&date=&exportSelect=HTML4.0&parameters=false&exportName=&reportName=%2Fwelcome_reports%2FDaily+Revenue+Report"
  var data_split = data.split('&');
  var data_count = data_split.length;
  for (var i = 0; i < data_count; i++) {
    var values = data_split[i].split('=');
    var datavals =+ "'"+values[0]+"':'"+values[1]+"'";
  }
   $.post('c/lib/ssrs/GetReports.php',{datavals})
   .done(function(data){
     $('#report_manager_frame_report').html(data);
   })

the output i need is $.post('LINK',{key:name,key:name,key:name})
Thanks for any help anyone can offer


text:
Q: Combination of exponentional and uniform distribuion problem Let $X$ be uniform distributed in $[0, 1]$. Let $Υ$ be exponenential distributed with $θ = 1$. Let $Y$ that is defined by tossing a fair coin and if tails comes up then $Z=X$, else if heads comes up, then $Z=Y$.
Any hint on how can i calculate $P(Z<0.5)$?

A: Hint:
$$
\mathbb P(Z < 1/2) = \mathbb P(Z < 1/2 \mid \text{heads})\times\mathbb P(\text{heads}) + \mathbb P(Z < 1/2 \mid \text{tails})\times\mathbb P(\text{tails}).$$


text:
Q: R : ggplot2 extend plot background beyond axes I am using charts generated by ggplot2 as image inputs for a knitr document. I wish to extend the background color beyond the axes/plot area and legend, as seen in the LaTeX chart on the right hand side (linked)
R vs LaTeX Plot:

R Code:
data example from Timely Porfolio Horizon Chart
require(ggplot2)
require(reshape2)
require(quantmod)
require(PerformanceAnalytics)
require(grid)
require(scales)

data(edhec)
origin = 0

#get 12 month rolling return of edhec indexes
roc <- as.xts(apply(cumprod(edhec+1),MARGIN=2,ROC,n=12,type="discrete"),order.by=index(edhec))

roc<-roc[complete.cases(roc),]
roc.df <- as.data.frame(cbind(index(roc),coredata(roc)))[c(1:20),c(1,8,9,10)]
colnames(roc.df)<-gsub(" |\\/","",colnames(roc.df))

roc.melt <- melt(roc.df,id.vars=1)
roc.melt[,1] <- as.Date(roc.melt[,1])
roc.df[,1] <- as.Date(roc.df[,1])
names(roc.melt)[1]<-"date"
names(roc.df)[1]<-"date"

Rbgcol<-"#E7EAEC"

ggplot(roc.melt,aes(x=date,y=value,color=variable))+geom_line() + scale_y_continuous(limits = c(-0.1,0.3)) + labs(title="R Plot")+

theme(
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="bottom",
legend.title=element_blank(),
legend.background= element_rect(fill=Rbgcol, colour=NA),
legend.key = element_rect(colour = NA, col = alpha(Rbgcol,0.1), size = .3, fill = alpha(Rbgcol,0.1)),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks = element_blank(),
panel.margin = unit(0,"null"),
plot.margin = rep(unit(0,"null"),4)
)

Any pointers would greatly help,thanks.

A: You can use argument plot.background= inside theme() to set color for plot background.
 +theme(plot.background=element_rect(fill="grey90"))


text:
Q: Show that the hitting time of an open set for a right-continuous process is a stopping time Let

*

*$d\in\mathbb N$

*$(\mathcal G_t)_{t\ge 0}$ be a complete right-continuous filtration on $(\Omega,\mathcal A)$

*$(Y_t)_{t\ge 0}$ be a $\mathbb R^d$-valued $\mathcal G$-adapted almost surely right-continuous stochastic process on $(\Omega,\mathcal A,\operatorname P)$

*$H\subseteq\mathbb R^d$ be open

(1) How can we show that $$\tau:=\inf\left\{t\in[0,T]:Y_t\in H\right\}$$ is an $\mathcal F$-stopping time?

Let $t\in[0,T]$. Since $\mathcal G$ is complete and right-continuous, it's sufficient to show that $\left\{\tau<t\right\}\in\mathcal F_t$.
(2) Let $N\in\mathcal A$ with $\operatorname P[N]=0$ such that $Y(\omega)$ is right-continuous for all $\omega\in\Omega\setminus N$. If I'm not terribly wrong, it's even sufficent to show that $\left\{\tau<t\right\}\cap(\Omega\setminus N)\in\mathcal G_t$. Why? Well, $\left\{\tau<t\right\}\cap N$ is a $\operatorname P$-null set and hence $\mathcal G_0$-measurable by the completness assumption on $\mathcal G$. Am I right?
(3) By (2) we can assume that $Y$ is surely right-continuous and by the $\mathcal G$-adaptedness of $Y$ and the right-continuity of $\mathcal G$ all we need to show is $$\left\{\tau<t\right\}=\bigcup_{s\in\mathbb Q\cap[0,\:t)}\left\{Y_s\in H\right\}\;.$$ "$\supseteq$" is trivial. How can we show the other inclusion? I know that $$\inf_{x\in[a,b]}f(x)=\inf_{x\in[a,b]\cap\mathbb{Q}}f(x)$$ for a continuous function $f:[a,b]\to\mathbb R$ ($-\infty<a\le b<\infty$) and I suppose we need to use something similar here.

A: For fixed $\omega \in \{\tau<t\}$ there exists $\tau(\omega) \leq s < t$ such that $Y_s(\omega) \in H$. As $H$ is open, there exists some $\epsilon>0$ such that $B(Y_s(\omega),\epsilon) \subseteq H$. Since $r \mapsto Y_r(\omega)$ is right-continuous, there exists $\delta>0$ such that
$$\forall r \in [s,s+\delta] : |Y_r(\omega)-Y_{s}(\omega)| < \frac{\epsilon}{2},$$
which implies
$$Y_r(\omega) \in H \qquad \text{for all} \, \, r  \in [s,s+\delta].$$
As $\tau(\omega)\leq s<t$ and $\mathbb{Q}$ is dense, we can find $q \in [0,t) \cap \mathbb{Q}$ such that $Y_q(\omega) \in H$. Hence,
$$\{\tau<t\} \subseteq \bigcup_{q \in \mathbb{Q} \cap [0,t)} \{Y_q \in H\}.$$


text:
Q: Is there a way to get an exact match in a javascript filter I'm looking for a way to get an exact match in a javascript filter. I've been following the lessons here at w3. When I search "1" now it still displays results for 1, 11 & 14. However I would like to only display 1 for 1, 11 for 11 etc... Is this possible?
<!DOCTYPE html>

<title>Dublin Transport History</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href="w3.css" rel="stylesheet">
<link href="default.css" rel="stylesheet">

Title

    <input id="myInput" onkeyup="myFunction()" placeholder="Search Number..." title="Type in a Number" type="text">

            A
            B
            C
            D
            E
            F

            1
            John
            Smith
            Green
            Boat
            House

            11
            Adam
            Smith
            Pink
            Car
            Apartment

            14
            Nelson
            Tower
            Red
            Bicycle
            Cottage

I have tried a few different things but I am new to Javascript and can't really find a good solution.

A: In this case you may compare the equality between txtValue and filter itself instead.
if (txtValue.toUpperCase() === filter) {...}

A: To filter on the exact string, you need to change this :
txtValue.toUpperCase().indexOf(filter) > -1

with this :
txtValue.toUpperCase() == filter

and make sure to do validation for that input. if filter is empty, then all data will be displayed. Try This :

<!DOCTYPE html>

<title>Dublin Transport History</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href="w3.css" rel="stylesheet">
<link href="default.css" rel="stylesheet">

Title

    <input id="myInput" onkeyup="myFunction()" placeholder="Search Number..." title="Type in a Number" type="text">

            A
            B
            C
            D
            E
            F

            1
            John
            Smith
            Green
            Boat
            House

            11
            Adam
            Smith
            Pink
            Car
            Apartment

            14
            Nelson
            Tower
            Red
            Bicycle
            Cottage


text:
Q: Delete using CTE slower than using temp table in Postgres I'm wondering if somebody can explain why this runs so much longer using CTEs rather than temp tables... I'm basically deleting duplicate information out of a customer table (why duplicate information exists is beyond the scope of this post).
This is Postgres 9.5.
The CTE version is this:
with targets as
    (
        select
            id,
            row_number() over(partition by uuid order by created_date desc) as rn
        from
            customer
    )
delete from
    customer
where
    id in
        (
            select
                id
            from
                targets
            where
                rn > 1
        );

I killed that version this morning after running for over an hour.
The temp table version is this:
create temp table
    targets
as select
    id,
    row_number() over(partition by uuid order by created_date desc) as rn
from
    customer;

delete from
    customer
where
    id in
        (
            select
                id
            from
                targets
            where
                rn > 1
        );

This version finishes in about 7 seconds.
Any idea what may be causing this?

A: The CTE is slower because it has to be executed unaltered (via a CTE scan).
TFM (section 7.8.2) states:
 Data-modifying statements in WITH are executed exactly once, and always to completion, independently of whether the primary query reads all (or indeed any) of their output.
Notice that this is different from the rule for SELECT in WITH: as stated in the previous section, execution of a SELECT is carried only as far as the primary query demands its output.

It is thus an optimisation barrier; for the optimiser, dismantling the CTE is not allowed, even if it would result in a smarter plan with the same results.
The CTE-solution can be refactored into a joined subquery, though (similar to the temp table in the question). In postgres, a joined subquery is usually faster than the EXISTS() variant, nowadays.
DELETE FROM customer del
USING ( SELECT id
        , row_number() over(partition by uuid order by created_date desc)
                 as rn
        FROM customer
        ) sub
WHERE sub.id = del.id
AND sub.rn > 1
        ;

Another way is to use a TEMP VIEW. This is syntactically equivalent to the temp table case, but semantically equivalent to the joined subquery form (they yield exactly the same query plan, at least in this case). This is because Postgres's optimiser dismantles the view and combines it with the main query (pull-up). You could see a view as a kind of macro in PG.
CREATE TEMP VIEW targets
AS SELECT id
        , row_number() over(partition by uuid ORDER BY created_date DESC) AS rn
FROM customer;

EXPLAIN
DELETE FROM customer
WHERE id IN ( SELECT id
            FROM targets
            WHERE rn > 1
        );

[UPDATED: I was wrong about the CTEs need to be always-executed-to-completion, which is only the case for data-modifying CTEs]

A: Using a CTE is likely going to cause different bottlenecks than using a temporary table. I'm not familiar with how PostgreSQL implements CTE, but it is likely in memory, so if your server is memory starved and the resultset of your CTE is very large then you could run into issues there. I would monitor the server while running your query and try to find where the bottleneck is.
An alternative way to doing that delete which might be faster than both of your methods:
DELETE C
FROM
    Customer C
WHERE
    EXISTS (SELECT * FROM Customer C2 WHERE C2.uuid = C.uuid AND C2.created_date > C.created_date)

That won't handle situations where you have exact matches with created_date, but that can be solved by adding the id to the subquery as well.


text:
Q: Creating a Powershell variable from an object with multiple values I'm attempting to create a script that will use "Set-ADFSRelyingPartyTrust -TargetName X -Identifier []" to add an additional Identifier to the ones that already exist. Since running the command as is only replaces the existing Identifiers, I need to find a way to create a variable from the existing Identifiers and then add the new Identifier on top of that.
One thing I tried is running this:
$ID = Get-ADFSRelyingPartyTrust -Name "X" | select-object identifier
Set-ADFSRelyingPartyTrust -TargetName "X" -Identifier $ID,NewID

But when I use this variable when adding Identifiers, it gets added as @{Identifier=System.Collections.ObjectModel.ReadOnlyCollection`1[System.String]},NewID
If I run this instead:
$ID = Get-ADFSRelyingPartyTrust -Name "X" | Select @(Name=Identifier";Expression={(_.identifier)}}

Then, when I use this variable when adding Identifiers, it gets added as "@{identifier=System.Object[]}" if there were multiple Identifiers configured, or "{@{identifier=[IdentifierName]} if there was only one identifier configured.
Let's say I currently have Identifiers of EntityID1, EntityID2. How do I write this so that those are the output of this variable?


text:
Q: React Native Version Mismatch with Native older, with RNFirebase I am getting the Version Mismatch with JavaScript version at 0.53.3 and Native sitting at 0.50.4.
Ran watchman watch-del-all as instructed and re-run react-native run-ios again with no luck.  Also did cd ios && pod install for many times each time showing Pod installation complete! There are 11 dependencies from the Podfile and 25 total pods installed..
Have found solutions about the Version mismatch which most of them are Native higher than the JavaScript so updating package.json would work.  However, how may I update the Native so that it matches the JavaScript Version?
I am not currently using Expo.
Regarding "downgrade RN", I updated as there was a Firebase [[DEFAULT]] problem and one of the suggested fix is to update RN (re-downloading GoogleServices-Info.plist didn't help).  Thus I am looking for instructions for keeping RN at this version.

A: The issue of mismatch is related to the changing of your react-native version without properly updating peer dependencies and native projects.
Since you aren't using Expo, try following the upgrade guidelines here offered from Facebook.
Upgrading to new React Native versions
Found under.. "Projects built with native code"
I personally found success using the "Alternative" steps, and then confirmed my project
** BUILD SUCCEEDED ** correctly by both...

*

*on the console using react-native run-ios

*and then from within Xcode


text:
Q: Unable to update dynamic JSON element in called feature I am trying to create a shared utility feature which will edit a named element in a JSON structure.
In my main scenario outline, I can read and set the field using the field_name variable:
Feature: Main Feature

  Background: Setup
    * json req_body = {"event_id": "0123456789", "name": "my name"}

  Scenario Outline:
    * print "Value of field: ", req_body.<field_name>
    * set req_body.<field_name> = "New Value from main"
    * print "Value of field: ", req_body.<field_name>
    * karate.call(read('call_test.feature'))

    Examples:
      | field_name    |
      | event_id      |
      | name          |

Feature: call_test.feature

  Scenario:
    * print "req_body: ", req_body     # Gives the correct values
    * print "field: ", field_name
    * print req_body['#(field_name)']  # Doesn't work
    * def current_field = "req_body." + field_name
    * print "field contents (via get): ", karate.get(current_field)

In the called feature I was able to read the field by constructing a string of the JSON structure name and the field name connected by a dot, then passing that to karate.get. However, I am unable to set the named field in the called feature.
What am I missing?  What's the correct way to do this?


text:
Q: Windows Azure Powershell 'you MUST specify a certificate' Allright, so I'm getting started with Windows Azure Powershell through my MSDN premium account.
I've got a management certificate in my management portal, and I did the Set-Executionpolicy, Get-AzurePublishSettingsFile, Import-AzurePublishSettingsFile and got the message:
Setting 'myemailaddress@hotmail.com' as the default and current subscription ... etc

Seems to work fine until here. Then I hit Get-AzureSubscription and I get the error message:
Get-AzureSubscription : You MUST specify a certificate. Call Set-AzureSubscription and Select-AzureSubscription first.

I repeated the steps in this document a few times, but I can't get it to work. PowerShell is running in Admin mode, Azure Powershell extensions are installed.
Didn't I install the cert by running the Import command?
EDIT:
Yes it is, I checked certmgr and it's installed under Personal.

A: I met the same issue.  Just configured it manually with the guide here:


text:
Q: Using a temporary table on SRSS report I have a stored procedure which works without a problem at the sql server side. However, when I feed a SRSS report with this stored procedure, I am having an error such as; Invalid object name '##tempTable'.
Here is my stored procedure;
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
    -- Add the parameters for the stored procedure here
    @StoreId int,
    @StartDate date,
    @EndDate date
AS

BEGIN

DECLARE @QUERY nvarchar(MAX);

SET @QUERY = N'SELECT * INTO ##tempTable ' +
           N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' +  CONVERT(varchar(10),@StoreId) + ','  + '''' + QUOTENAME(CONVERT(varchar,@StartDate,112),'''') + '''' + ',' +  '''' + QUOTENAME(CONVERT(varchar,@EndDate,112) + '''','''') + ')';

           EXEC sp_executesql @QUERY;

    SET NOCOUNT ON;

    SELECT * FROM ##tempTable
    drop table ##tempTable
END

GO

How can I solve this issue? Thanks.

A: A Table referenced in a Dynamic statement can only be referenced inside that dynamic statement. Take this simple query:
EXEC sp_executesql N'SELECT 1 AS I INTO #temp;';

SELECT *
FROM #temp;

Notice the statement fails with:

Msg 208, Level 16, State 0, Line 3
  Invalid object name '#temp'.

It seems, however, you don't need to temporary table, and this will work fine:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
    -- Add the parameters for the stored procedure here
    @StoreId int,
    @StartDate date,
    @EndDate date
AS

BEGIN

    DECLARE @QUERY nvarchar(MAX);

    SET @QUERY = N'SELECT * ' +
                N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' +  CONVERT(varchar(10),@StoreId) + ','  + '''' + QUOTENAME(CONVERT(varchar(8),@StartDate,112),'''') + '''' + ',' +  '''' + QUOTENAME(CONVERT(varchar(8),@EndDate,112) + '''','''') + ')';

    EXEC sp_executesql @QUERY;

END;

A: Try doing this
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
    -- Add the parameters for the stored procedure here
    @StoreId int,
    @StartDate date,
    @EndDate date
AS

BEGIN

    DECLARE @QUERY nvarchar(MAX);

SET @QUERY = N'SELECT * INTO ##temp_global ' +
       N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' +  CONVERT(varchar(10),@StoreId) + ','  + '''' + QUOTENAME(CONVERT(varchar,@StartDate,112),'''') '''' + ',' +  '''' + QUOTENAME(CONVERT(varchar,@EndDate,112) + '''','''') + ')';

 EXECUTE (@QUERY)

 SELECT * FROM ##temp_global

 DROP TABLE ##temp_global
END

A: I think I had this once and I had to create the temp table initially with the column names specified and then insert into it, so that your dataset would be able to pick up the column names. So something like this may work:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
    -- Add the parameters for the stored procedure here
    @StoreId int,
    @StartDate date,
    @EndDate date
AS

BEGIN

DECLARE @QUERY nvarchar(MAX);

CREATE TABLE ##tempTable ([ColumnOne] VARCHAR(10), [ColumnTwo] DATETIME) --Add required columns here

SET @QUERY = N'SELECT * FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' +  CONVERT(varchar(10),@StoreId) + ','  + '''' + QUOTENAME(CONVERT(varchar,@StartDate,112),'''') + '''' + ',' +  '''' + QUOTENAME(CONVERT(varchar,@EndDate,112) + '''','''') + ')';

INSERT INTO ##tempTable ([ColumnOne],[ColumnTwo])
EXEC (@QUERY);

SET NOCOUNT ON;

SELECT * FROM ##tempTable
DROP TABLE ##tempTable
END

GO


text:
Q: Get JSON object from AJAX call I'm new to AJAX and javascript. In my project, I have to get a json object in my javascript file. I've used spray-json and it shows me the json object in the url. http://localhost:8081/all-modules
{
  "status": "S1000",
  "description": "Success",
  "results": ["module1", "module2", "module3"]
}

My Ajax call
  $.ajax({
        url: 'http://localhost:8081/all-modules',
        dataType: 'application/json',
        complete: function(data){
            alert(data)
        },
        success: function(data){
            alert(data)
        }

It returns an alert [object Object]. What is the issue in here?

A: If you wish to see all the data in the JSON object, use JSON.stringify
Refer here for more details
Hope that helps.

A: just console.log(data) you will see your object.
you can access your value by something like this
data.id //will give you id

it also depend on you json how you are creating check this out for explanation
// if it simply json then access it directly
//Example => {"id":1,"value":"APPLE"}
data.id; // will give you 1

// if it json array then you need to iterate over array and then get value.
//Example => [{"id":1,"value":"APPLE"},{"id":2,"value":"MANGO"}] then
data[0].id;  // will give you 1

so your code will be like this
 $.ajax({
    url: 'http://localhost:8081/all-modules',
    dataType: 'application/json',
    complete: function(data){
        alert(data.status);// S1000
        alert(data.description);// Success
        // for results you have to iterate because it is an array
        var len =  data.results.length;
        for(var i=0;i<len;i++ ){
            alert(data.results[i]);
        }
    },
    success: function(data){
        alert(data)
    }
})

A: Try the following;
var data = '{"name": "John","age": 30}';

var json = JSON.parse(data);

alert(json["name"]);
alert(json.name);

You can also check out this link: How to access JSON object in JavaScript

A: try console.log() it will log on the console. alert doesnot displays the object.
 $.ajax({
    url: 'http://localhost:8081/all-modules',
    dataType: 'application/json',
    complete: function(data){
        console.log(data)
    },
    success: function(data){
        console.log(data)
    }

A: data is no longer in JSON format, it is a Javascript Object. You do not need to use function like jQuery.parseJSON anymore.
It is one common mistake for beginners.
If you want to see this Javascript Object, try alert(JSON.stringify(data));

A: i think you just printing the object.Try someting like this
$.ajax({
    url: 'http://localhost:8081/all-modules',
    dataType: 'application/json',
    complete: function(data){
        alert("status = "+data.status+"descripttion"+data.description);
    },
    success: function(data){
         alert("status = "+data.status+"descripttion"+data.description);
    }

A: Try data[0].status;. Your data are in an object now. At console.log(data) you can see that


text:
Q: Modelo Dinámico Bom dia!
Estou com o seguinte problema, eu preciso de criar um modelo com campos cujos valores e tipos são definidos no resultado de utilização de outro modelo. Gostaria de saber se é possivel isto, basicamente eu faço uso de um modelo e queria utilizar os resultados dos campos para criar um novo modelo.
        "field_name": "project_name",
        "field_type": "varchar2",

        Objectivo ir ao fild_type e atribuir um novo elemento de um Model com o tipo que la estiver declarado e dar lhe o nome do project name

            public field_type.value field_name.value { get; set; }

algo deste genero...
Obrigado desde já!


text:
Q: "sudo pip install requests" and directories issues? still advancing in my tutorial to learn python, I am told to do that :
sudo pip install requests

here is what I get in return :
"

The directory '/Users/gui/Library/Caches/pip/http' or its parent
  directory is not owned by the current user and the cache has been
  disabled. Please check the permissions and owner of that directory. If
  executing pip with sudo, you may want sudo's -H flag. pip is
  configured with locations that require TLS/SSL, however the ssl module
  in Python is not available. The directory
  '/Users/gui/Library/Caches/pip' or its parent directory is not owned
  by the current user and caching wheels has been disabled. check the
  permissions and owner of that directory. If executing pip with sudo,
  you may want sudo's -H flag. Collecting requests   Could not fetch URL
  https://pypi.python.org/simple/requests/: There was a problem
  confirming the ssl certificate: Can't connect to HTTPS URL because the
  SSL module is not available. - skipping   Could not find a version
  that satisfies the requirement requests (from versions: ) No matching
  distribution found for requests

"
--> would you know what I would need precisely to correct (I'm a newbie so if you can be very detailed in your help explanation it would be awesome) ?
thanks a lot in advance

A: Normally you should be able to install the modules using the below commands:
-> sudo pip install requests
but incase if you get some errors stating "'sudo' is not recognized as an internal or external command,
operable program or batch file.", then go with below command and give a try.
-> easy_install requests and this will help you fulfill your requirement by installing the required "requests" module.

A: So as it says in the error message you may want to try sudo -H pip install requests.
This -H options sets the HOME environment variable to the superusers home instead of your users home. As when you run a command with sudo it is run as a superuser not as your standard user
You could also try running the command without sudo at the front as that may not be required


text:
Q: C# Custom generic struct with same compiler behavior as Nullable Behold the following example with System.Nullable<T> in C#.
int x = 5;
int? y = 3;
int? result = x + y; //no compiler warning

It makes sense that the compiler can figure out that T is an int, thus it can use the operator.
Also in
int x = 5;
int? y = 3;
bool result = x == y; //no compiler warning

it makes sense, if x was null, the expression would be false. The compiler doesn't mind.
Now I'm trying to create a lookalike Nullable<T> class. Let's call it Lookable<T>.
[Serializable]
public struct Lookable<T> where T : struct
{
    public Lookable(T value)
    {
        Value = value;
    }

    public T Value { get; }

    public override bool Equals(object other)
    {
        return other != null && Value.Equals(other);
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    public static implicit operator Lookable<T>(T value)
    {
        return new Lookable<T>(value);
    }

    public static explicit operator T(Lookable<T> value)
    {
        return value.Value;
    }
}

The idea here is straight from .NET's source code. In my case I'm just omitting the HasValue property.
Now this example would work:
int x = 6;
Lookable<int> y = x;
Lookable<int> z = 4;

The compiler can infer the types here because of the implicit operator correct?
What I don't understand is that this example will make the compiler unhappy:
int x = 5;
Lookable<int> y = 3;
var result1 = x + y; //compile error
var result2 = x == y; //compile error

The compiler is giving me the message:

Operator cannot be applied to operands of type 'int' and 'Lookable<int>'.

Why not? And why is it possible with Nullable<T>? I can't find it anywhere in the source code. Would it also be possible for Lookable<T>?

A: The code for this isn't in Nullable<T> - it is in the C# compiler, in particular "lifted operators" in the specification, and how they apply specifically to System.Nullable<T>. The specification references are in this answer.
You cannot reproduce the Nullable<T> behaviour in your own types. It has special handling by both the compiler and the runtime (boxing, etc).


text:
Q: How to draw a simple Gantt chart in latex? I wanted to draw a simple Gantt chart like the following picture, but I saw that many instructions about Gantt charts on the Internet are much more complicated than I expected.

A: A simple tikzpicture (not really Gant diagram):
\documentclass[margin=3mm]{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[
node distance = 0pt,
G/.style = {draw, fill=gray!30, text width=2*#1mm, align=center,
            inner xsep=0pt, outer sep=0pt,
            anchor=south west},
tck/.style = {font=\scriptsize, below}
                    ]
\foreach \n/\i [remember=\i as \j (initialy 0),
                evaluate=\i as \k using \i-\j] in {P_4/3, P_1/9, P_3/16, P_2/24}
{
\node[G=\k]     at (\j/5,0) {$\n$};
    \node[tck]    at (\i/5,0) {\i};
\ifnum\j=0
    \node[tck]    at (0,0) {\j};
\fi
}
\end{tikzpicture}

\end{document}


text:
Q: TinyMCE not submitting content I am trying to implement TinyMCE in my ruby on rails app
I was getting the error content cannot be blank, so I found on another question that I needed to use javascript to save but now its just complaining about my script
I suspect im doing the script wrong because I have almost zero javascript knowledge

   <%= f.label :content %>

   <%= text_area_tag :content, "", :class => "tinymce", :id => "editor" :rows => 20, :cols => 80 %>
   <%= tinymce :plugins => ["wordcount","image","autoresize","media","lists","link","save","searchreplace"] %>

A: Turns out it didnt require javascript saving after all, finally found the answer deep on youtube
the text_area_tag line needed to be changed because the previous code is for a model-less implementation
To make it work for a model:
<%= f.text_area :content, :class => "tinymce", :id => "editor" :rows => 20, :cols => 80 %>

I really wish that they would include that on the tinymce-rails page


text:
Q: Why do I need to pass (req, res, next) to bodyParser in Express? I had originally been using bodyParser as so:
app.use(bodyParser.json());

However, now I want to conditionally use bodyParser:
app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json()(req, res, next);
    }
});

When I try to remove (req, res, next), the parser does not work. That is,
app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json();
    }
});

does not work.
Why do I need (req, res, next) after bodyParser.json()?

A: https://github.com/expressjs/body-parser/blob/master/index.js#L108
function bodyParser (options) {
  var opts = {}

  // exclude type option
  if (options) {
    for (var prop in options) {
      if (prop !== 'type') {
        opts[prop] = options[prop]
      }
    }
  }

  var _urlencoded = exports.urlencoded(opts)
  var _json = exports.json(opts)

  return function bodyParser (req, res, next) {
    _json(req, res, function (err) {
      if (err) return next(err)
      _urlencoded(req, res, next)
    })
  }
}

Body parser is a middleware that needs access to res, req and next.
It parses your request using req and in order to pass control to the next middleware, it needs access to the next function.
Here app.use(bodyParser.json()); are passed (req, res, next) by default as
bodyParser.json() returns return function bodyParser (req, res, next) { .. }
so it becomes --> app.use(function bodyParser (req, res, next) { .. });
but in your case, you are creating a middleware by your self and you are responsible to pass the parameters to bodyParser so it can have access to the required arguments.
app.use((req, res, next) => {
    if (req.originalUrl === '/hooks') {
        next();
    } else {
        bodyParser.json()(req, res, next);
    }
});

See how app.use works below
https://github.com/expressjs/express/blob/master/lib/application.js#L187-L242


text:
Q: How to make Azure batch see my data files? I am new to Azure batch. I am trying to use R in parallel with Azure batch in rstudio to run code on a cluster. I am able to successfully start the cluster and get the example code to work properly. When I try to run my own code I am getting an error that says the cluster nodes cannot find my data files. Do I have to change my working directory to Azure batch somehow?
Any information on how to do this is much appreciated.

A: I have figured out how to get Azure batch to see my data files. Not sure if this is the most efficient way, but here is what I did.

*

*Download a program called Microsoft Azure Storage Explorer which runs on my local computer.

*Connect to my Azure storage using the storage name and primary storage key found in the Azure portal.

*in Microsoft Azure Storage Explorer find Blob containers, right click create new container.

*Upload data files to that new container.

*Right click on data files and go to copy URL.

*Paste URL in R like this  model_Data<-read.csv(paste('https://<STORAGE NAME HERE>.blob.core.windows.net/$root/k',k,'%20data%20file.csv',sep=''),header=T)


text:
Q: Is it possible hide/show choice items related another field? is it possible to hide/show column items based on another field in SharePoint 365?
Example:
In first column I have:

*

*Item 1

*Item 2

*Item 3

In second column I have:

*

*Item A

*Item B

*Item C

*Item D

I need when I select the item in first column, in the second only appaers some of them:

First Column
Second Colum

Item 1
Item A

Item 1
Item B

Item 2
Item C

Item 3
Item D

PS: I don't have "admin center" access and I can't use Power Apps in this case.

A: You can refer to this article to create two lists (First list and Second list) to store the item values of the two columns, and then reference them in the main list through the lookup column. Add a Content Editor Web Part to implement changes using HTML (require editing the page in classic mode).
Script details: column choice based on the value of another column choice

A: If you are using SharePoint online modern experience, you cannot do this using SharePoint default capabilities.
You have below options:

*

*Easiest way: Use Power Apps to customize list forms and cascading dropdowns. I know you mentioned you can't use Power Apps - but this is easiest way (check other options below)
a. Working with Cascading Lists in SharePoint and Power Apps
b. Create dependent drop-down lists in a canvas app

*Completely customize list form using SPFx form customizer: Build your first Form customizer extension - lot of development work needed

*Use JSON formatting - You can use list JSON view formatting to add new items from within list view if you have less number of fields to submit while creating new items.
Example: Dependent-DropDown


text:
Q: Ruby on Rails single table inheritance sample form i'm a super newbie in rails and i need to see a sample code on how to implement Single table iheritance, i have a model called Listing as a super class, and i have subclasses LawFirms and Paralegal, these all extend the Listing model, now i need to be able to create a new listing, but when i am creating i need the form to have an option to select either Law Firm or Paralegal, when Law Firm option is selected, it should show a form for creating a LawFirm object which is different from the Paralegal Object because a law firm has advocates and a paralegal wont have advocates.
So far my models look like this
class Listing < ActiveRecord::Base
end
class LawFirm < Listing
 has_many :advocates
end
class Paralegal < Listing
end
How do i create the controller? and the form?

A: I'm not sure that inheritance is the right solution for this. Inheritance is used for an is-a relationship. For example, a Nissan is a car so Nissan would inherit from the car class. You might be better off having LawFrim or Paralegal as objects in a Listing using a nested resource in rails. You could then add some checks in the controller to make sure it only has one or the other of those objects.


text:
Q: Ajax undefined error when calling ASMX <html>
<script src="json.js";/>
<script src = "jquery.js"/>
<script type="text/javascript">
    function PopulateBlendSpecification() {

    var data = new Object();
    data.Message = "message";
    alert(JSON.stringify(data));
    $.ajax({
        url: "Test.aspx/Test",
        type: "POST",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (result) {
            var listItems = [];
            var blendSpecItems = JSON.parse(result.d);

            for (var key in blendSpecItems) {
                listItems.push('<option value="' + blendSpecItems[key].BlendSpecID + '">' + blendSpecItems[key].BlendName
                            + '</option>');
            }

            var lBox = $('select[id$=lbBlendSpecs]');
            $(lBox).append(listItems.join(''));
        }
    })
}

Test.aspx.cs
      [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public  static string  Test(string message)
    {
       return message;
    }

This works fine when I try this within one project.
However, when I move the webmethod into a separate prjoject within the same solution I get an ajax error:
Error in: http://localhost/Test/MyWebService/Test.asmx/Test
 error: undefined
 type: ajaxError
 readystate: 4
 status: 500

A: Webmethod is case sensitive.In your code function is public  static string  Test(string message) in parameter message is in small letter and you have to pass data.Message M is capital so method is unable to find function in code side.
So if you change code like below your code will work fine
    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string Test(string Message)
    {
        return Message;
    }

A:
when I move the webmethod into a separate prjoect within the same solution

Did you move it into a web service project and trying to consume in a web project, if that's the case this error would happen due to Cross site scripting restrictions. If you still need to have them in separate project, you will have to use jsonp and return jsonp friendly response.
You can find more info about JSONP + ASMX @JSONP & ASMX Web Service.

A: do you have this header [System.Web.Script.Services.ScriptService] in your asmx file.