text:
Q: Why do I need to compile DateTime in boost if I am not using to_string or from_string? When compiling a Visual Studio 2005 project that references a mix of c++ managed/unmanaged code, I get the following error:
1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80-mt-1_42.lib'
I have followed the Getting Started Guide.  Of relevance is this snippet:

"Boost.DateTime  has a binary component that is only needed if you're using its to_string/from_string or serialization features, or if you're targeting Visual C++ 6.x or Borland."

I have done a global search for "to_string" and "from_string".  There are no occurrences in the code of these DateTime methods.
In the documentation for the DateTime library itself, there is this snippet:

"The library has a few functions that require the creation of a library file (mostly to_string, from_string functions). Most library users can make effective use of the library WITHOUT building the library, but simply including the required headers. If the library is needed, the Jamfile in the build directory will produce a "static" library (libboost_date_time) and a "dynamic/shared" library (boost_date_time) that contains these functions."

How would I got about resolving this issue?  The easy solution is to build the library or use the Windows binary installer from BoostPro, however it bothers me that the compilred library is being required when according to the documentation I am not in the situation that requires it.
Another question is the DateTime documenation seems to indiciate that its "mostly to_string, from_string)", could my code perhaps be referencing some other function that would require creating the library file?  Does anyone know what other functions are included?  Are there functions that themselves wrap around or call to_string or from_string?
The only inclusion I am using is:
#include <boost/date_time/gregorian/gregorian.hpp>

A: Project compiles and links cleanly after the following troubleshooting:
I defined BOOST_LIB_DIAGNOSTIC - to see what diagnostic output I could get from the auto linker. Not too informative:
1>Linking to lib file: libboost_date_time-vc80-mt-1_42.lib
1>LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc80-mt-1_42.lib'
I then defined BOOST_ALL_NO_LIB=1 - disables all auto linking. Project now compiles and links cleanly.
Boost headers use pragma to signal compilers when to look for a lib file.  While the date_time library does not do this, other headers within boost it depends on do.

A: in my case, this error occurs only on msvc linker. when compiling with clang or gcc, there is no problems at all. By adding
#define BOOST_DATE_TIME_NO_LIB

or
#define BOOST_ALL_NO_LIB

to the header file, the error is gone.

A: Just add:
#define BOOST_DATE_TIME_NO_LIB

before including the boost headers in your code eg:
#define BOOST_DATE_TIME_NO_LIB

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>

....
....

I hope it would help, in my case it works.

A: boost comes with a tool called bcp that can be used to extract exactly the subset you need.
take a look, sounds like you will find it helpful.

A: Possibly you are including a "wrong" header that is triggering the compiler to link with the lib, even though  you don't need it.   Search for a #pragma comment(lib, ...) in the boost headers to find out if that is the case.


text:
Q: Setting only caret of bootstrap nav to toggle dropdown nav and not text Given the below bootstrap navigation, how can I set only the caret (down arrow) to toggle the sub-nav and when the user clicks the text link it takes them to the given page?
HTML

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-nav" aria-expanded="false"> Toggle navigation

      </button>

000-000-0000

24/7 Se habla español

          <input type="text" class="form-control" id="inputPassword3" style="width:100%" placeholder="Search...">

          MAIN LINK

LINK

LINK

LINK

LINK

LINK

                MAIN LINK

LINK

LINK

LINK

LINK

Link

Link

Link

LINK

Link

Link

Link

Link

LINK

Link

Link

LINK

Link

Link

LINK

Link

Link

Link

LINK

Link

Link

Link

Links

          MAIN LINK

LINK

LINK

NEWS

LOCATIONS

CONTACT

FAQs

TERMS & CONDITIONS

EMPLOYMENT

Follow Us

        <input type="text" class="form-control" id="inputPassword3" style="width:100%" placeholder="Search...">

CURRENT STATE: LINK TO FIDDLE

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to edit string as items from QListWidget using with QDataWidgetMapper I am using  QListWidget, QSqlTableModel, QtableView and QDataWidgetMapper. QListWidget is ItemIsUserCheckable.
I am able to save selected items from QListWidget into QtSql table in a single field as string format(converting list items into string as "Green, Green Grapes, Oranges".
But at the same time i want to change the selected item and update the items from QListWidget of the String data. How to do. Is it possible. Or PLease let me know if any other solution.
Below is the Example code:
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(391, 496)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(9, 9, 373, 188))
        self.listWidget.setObjectName("listWidget")
        self.save_btn = QtWidgets.QPushButton(self.centralwidget)
        self.save_btn.setGeometry(QtCore.QRect(100, 230, 75, 23))
        self.save_btn.setObjectName("save_btn")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(9, 203, 27, 16))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(56, 203, 181, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.update_btn = QtWidgets.QPushButton(self.centralwidget)
        self.update_btn.setGeometry(QtCore.QRect(293, 229, 75, 23))
        self.update_btn.setObjectName("update_btn")
        self.edit_btn = QtWidgets.QPushButton(self.centralwidget)
        self.edit_btn.setGeometry(QtCore.QRect(199, 229, 75, 23))
        self.edit_btn.setObjectName("edit_btn")
        self.tableView = QtWidgets.QTableView(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(9, 258, 373, 188))
        self.tableView.setObjectName("tableView")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 391, 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)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("fruites.db")
        if db.open():
            if db.open():
                query = QSqlQuery()
                query.exec_("""CREATE TABLE IF NOT EXISTS store(name TEXT, items TEXT)""")

        self.store_model = QtSql.QSqlTableModel()
        self.store_model.setTable("store")
        self.store_model.select()
        self.tableView.setModel(self.store_model)

        list_ = ["Green", "Green Apple","Green Grapes", "Bananas", "Oranges"]
        list_ = dict.fromkeys(list_, 0)
        for i in list_:
            item = QtWidgets.QListWidgetItem(i)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
            item.setCheckState(QtCore.Qt.Unchecked)
            self.listWidget.addItem(item)

        self.save_btn.clicked.connect(self.save_item)
        self.edit_btn.clicked.connect(self.edit_item)
        self.update_btn.clicked.connect(self.submit_item)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.save_btn.setText(_translate("MainWindow", "Save"))
        self.label.setText(_translate("MainWindow", "Name"))
        self.update_btn.setText(_translate("MainWindow", "Update"))
        self.edit_btn.setText(_translate("MainWindow", "Edit"))

    def save_item(self):
        name = self.lineEdit.text()
        strng = ''
        checked = []
        for row in range(self.listWidget.count()):
            item = self.listWidget.item(row)
            if item.checkState():
                checked.append(item)
        strng = ", " .join(i.text() for i in checked)

        r = self.store_model.record()
        r.setValue("name", name)
        r.setValue("items", strng)
        self.store_model.insertRecord(-1, r)

        self.store_model.select()
        self.lineEdit.clear()
        for i in range(self.listWidget.count()):
            item = self.listWidget.item(i)
            item.setCheckState(QtCore.Qt.Unchecked)

    def edit_item(self):
        selected = self.tableView.selectedIndexes()
        if not self.store_model.rowCount():
            return
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
        else:
            row = 0

        self.store_mapper = QtWidgets.QDataWidgetMapper()
        self.store_mapper.setSubmitPolicy(QtWidgets.QDataWidgetMapper.ManualSubmit)
        self.store_mapper.setModel(self.tableView.model())

        self.store_mapper.addMapping(self.lineEdit, 0)
        self.store_mapper.addMapping(self.listWidget, 1)

        self.store_mapper.setCurrentIndex(row)

    def submit_item(self):
        self.store_mapper.submit()
        self.lineEdit.clear()

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_())


text:
Q: Find number of edges given number of vertices and average path length? A while ago I found this equation, not sure where, for determining the number of vertices $v$ given an average "edges per node" $r$ and an average path length $n$. This assumes a DAG where there's one root node and there are no orphans.
$$
v = \frac{r^{t-1}\left(1 - r^n\right)}{1 - r}
$$
where $t$ = starting path level (usually 1), $n$ = average path length, and $r$ is average outgoing edges per vertex.
I also figured out how to solve for $n$ using a logarithmic identity, but is it possible to solve for $r$? If I have the average path length and the total number of vertices, can I solve for number of outgoing edges per vertex? I can do it with interpolation and a program, just curious if a derived equation is possible.


text:
Q: Why use 0.5 as the binarization threshold in the task of CNN segmentation? Why use 0.5 as the binarization threshold in the task of CNN segmentation?
We often perform binarization after getting the predicted probability graph, like this:
Pred = model(data)

Pred = pred > 0.5

I am confused about why it is 0.5. I have tried setting this threshold to 0.3, 0.4, 0.5, and 0.6. It turns out that 0.4 is the best, and of course different tasks produce different results.
So why do we always use 0.5 as the threshold in image segmentation?

A: The threshold is task-specific.
Therefore, there is not out of the box guaranteed threshold to work best.
The idea is to iterate among different values of threshold(evidently between 0 and 1) and find the threshold which is the most suitable for your problem.
As for your uncertainty: you use a neural network in the process of segmentation; at the moment of writing this comment, researchers are still working on the 'explainability issue' of neural networks.
Nobody will give you an answer to 'why is 0.4 better than 0.5'; there can be only conjectures.


text:
Q: Horizontal sub-menu on one line I would like to display a sub-menu in horizontal on 1 line how on the site https://www.allianz.fr/. I have tried all the settings that are in the wordpress menu but I can't find the solution. Do you have any idea how to make this type of menu?
Thanks in advance


text:
Q: same code, different browser, different behaviour for cookieset() I was learnig how to make a cookie in php, and as first example i wanted to do a visit counter. This works on chrome but not in mozilla. What i have to change in order to make the code works on every browser?
Thank y ou for any help.
<?php
  if(!isset($_COOKIE["counter"])) {
    setcookie("counter",0,time()+3600,"/");
    $var = $_COOKIE["couter"];
  } else {
    $var = $_COOKIE["counter"] + 1;
    setcookie("counter",$var,time()+3600,"/");
  }
  echo $var;
 ?>


text:
Q: Why is the text font-face setting killed/copied along with the text? The case I am presenting right here isn't reproducible everywhere in Emacs but the where I was able reproduce it was in nav when telling it the path of a location to jump to, in both Emacs 24.1.x and 24.3.x.
So the question is why is it that when killing/copying a text, say from the python comments (buffer in python-mode), and yanking/pasting it elsewhere, say the minibuffer, the font-face is also yanked? And why is it that in most cases this is not the case, i.e. the yanked text adopts the font-face of the location where it is yanked?
Another related question: how can we find out which things(meta-data too) were actually killed/copied?

A: It happens because text color and font are just like any other text property. And properties are copied along with their text by default (simply because they could contain information you DO want to copy).
Don't worry too much about it, this information doesn't get saved into the file, and, in the case of font locking, it's usually overridden quite quickly.
For your last question, you can check the detailed contents of any killed string by looking at the kill ring M-x describe-variable RET kill-ring RET.


text:
Q: How to add a link or wrap with a tag the circle using svg.js I am using svg.js to create circles with text inside and centered I was able to do that
let draw = SVG('main');

// this is for the text
draw.plain(ele.ticket_id).attr({
            x: posX,
            y: posY,
            fill: '#fff',
            'alignment-baseline': 'central',
            'text-anchor': 'middle'
          })
              .font({
                size: Number((radius/2) * .5).toFixed(2)
              });
 // and this creates the circle
 circle.animate(500, 'quadIn').attr({
            fill: '#f06',
            id: element.ticket_id,
            class: element.status,
            cx: posX,
            cy: posY
          });

But I am unsure how to wrap the circle or the text with an a tag so it should be clickable. I don't see any examples in the svg.js documentation.

A: Okay so its just adding a linkTo(url-here) to the element


text:
Q: Issue in Adding Calendar Event in Android M I am using a code to add an event to the device's calendar. The code works fine in all the Android versions except Android M.The event when being added on Android M shows as a birthday instead of an event. Please help on how can this issue be fixed.
The code being used is as follows
     // Add event to calendar
        try {
            ContentResolver cr = context.getContentResolver();
            ContentValues values = new ContentValues();
            values.put(CalendarContract.Events.DTSTART, startDateInMilliSeconds);
            values.put(CalendarContract.Events.DTEND, endDateInMilliSeconds);
            values.put(CalendarContract.Events.TITLE, title);
            values.put(CalendarContract.Events.DESCRIPTION, description);
            if (location != null && (!TextUtils.isEmpty(location))) {
                values.put(CalendarContract.Events.EVENT_LOCATION, location);
            }
            values.put(CalendarContract.Events.CALENDAR_ID, 1);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Calendar.getInstance()
                    .getTimeZone().getID());
            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
            // Save the eventId into the Task object for possible future delete.
            long eventId = Long.parseLong(uri.getLastPathSegment());
            Uri openCalendarEvent = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId);
            Intent calIntent = new Intent(Intent.ACTION_VIEW).setData(uri);
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startDateInMilliSeconds);
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endDateInMilliSeconds);
            calIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(calIntent);

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

        }

A: try below method @ Himmat
public void addReminder() {
        Intent calIntent = new Intent(Intent.ACTION_EDIT);
        calIntent.setData(CalendarContract.Events.CONTENT_URI);
        calIntent.setType("vnd.android.cursor.item/event");
        calIntent.putExtra(CalendarContract.Events.TITLE, e.getName());
        calIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, e.getLocation());
        calIntent.putExtra(CalendarContract.Events.DESCRIPTION, e.getDescription());
        Calendar calStart=Calendar.getInstance();
        if(Validator.isNotNull(e.getStartDate())) {
            calStart.setTime(e.getStartDate());
        }
        calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
                calStart.getTimeInMillis());
        Calendar calEnd=Calendar.getInstance();
        if(Validator.isNotNull(e.getEndDate())) {
            calEnd.setTime(e.getEndDate());
        }
        calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
                calEnd.getTimeInMillis());
        calIntent.putExtra(CalendarContract.EXTRA_CUSTOM_APP_URI,
                e.getRegistrationLink());
        startActivity(calIntent);
    }


text:
Q: Database - Resource usage statistics I would like to find (using SQL DMVs) whether a database is actually in use and if so then how much of that servers resources it is taking.
I need some ideas on how we can properly collect usage statistics on all of these databases across all of these servers and then create a simple report to understand resources usage.
The purpose of this report is to determine what are the critical counters that we need and what is the simplest and least impact method to collect them.
We don't need minute to minute, I'm only looking for summary information once per day or so.
Can you please advise on this?

A: Yes there are DMV's for this like sys.dm_db_index_usage_stats, but that alone will not help in analyzing the unused databases.
Here you can analyse on unused databases with help of SQL Server Audit as explained here by Aaron Bertrand When was my database / table last accessed?
In addition you may need various other methods to track the database usage like:
1) If there are any transactions count going up for the database in question with help of counters info, using below query:
SELECT *
FROM sys.dm_os_performance_counters
WHERE counter_name like 'Transactions/sec%'
and instance_name like 'instance_name_here%';
GO

2) You can also ask the execution plan cache if queries have been running against the database. This query takes advantage of the dm_exec_text_query_plan DMV as explained in the article Querying Information from the Plan Cache, Simplified
3) You can check from the login history as well on those databases using Adam Mechanic's SP_WhoIsActive
Once you have the data collected all together ,and listed databases to be taken offline execute
ALTER DATABASE [database_name] SET OFFLINE;

Monitor for a duration and if an application goes down for the reason being database of that being taken offline, you can simply take those databases back online:
ALTER DATABASE [database_name] SET ONLINE;

A: You can start with the automatic reports: Right click your DB, go to Reports and Standard Reports
https://technet.microsoft.com/en-us/library/cc280385%28v=sql.105%29.aspx
You can also use perfmon
https://msdn.microsoft.com/fr-fr/library/Aa645516%28v=VS.71%29.aspx


text:
Q: How to use UPDATE/DELETE WHERE CURRENT OF in psycopg2? I'm using server-side cursor in PostgreSQL with psycopg2, based on this well-explained answer.
with conn.cursor(name='name_of_cursor') as cursor:
    query = "SELECT * FROM tbl FOR UPDATE"
    cursor.execute(query)
    for row in cursor:
        # process row

In processing each row, I'd like to update a few fields in the row using PostgreSQL's UPDATE tbl SET ... WHERE CURRENT OF name_of_cursor (docs), but it seems that, when the for loop enters and row is set, the position of the server-side cursor is in a different record, so while I can run the command, the wrong record is updated.
How can I make sure the result iterator is in the same position as the cursor? (also preferably in a way that won't make the loop slower than updating using an ID)

A: The reason why a different record was being updated was because internally psycopg2 does a FETCH FORWARD 1000 (or whatever the default chunk size is), positioning the cursor at the end of the block. You can override this by fetching one record at a time:
updcursor = conn.cursor()
with conn.cursor(name='name_of_cursor') as cursor:
    cursor.itersize = 1  # to make server-side cursor be in the same position as the iterator
    cursor.execute('SELECT * FROM tbl FOR UPDATE')
    for row in cursor:
        # process row...
        updcursor.execute('UPDATE tbl SET fld1 = %s WHERE CURRENT OF name_of_cursor', [val])

The snippet above will update the correct record. Note that you cannot use the same cursor for selecting and updating, they must be different cursors.
Performance
Reducing the FETCH size to 1 reduces the retrieval performance by a lot. I definitely wouldn't recommend using this technique if you're iterating a large dataset (which is probably the case you're searching for server-side cursors) from a different host than the PostgreSQL server.
I ended up using a combination of exporting records to CSV, then importing them later using COPY FROM (with the function copy_expert).


text:
Q: Problem with finding Maximum value My problem states: Show that y:
\begin{equation}
y = e^{-t}sin(2t)
\end{equation}
is a maximum when
\begin{equation}
t =
\frac{1}{2}\tan^{-1}(2)
\end{equation}
and determine this maximum value.
So basically i have to calculate first and second derivatives of function f(t) = y and find some relation with what i must prove. Well, i've almost done it i think. But not quite. Can someone help me by checking out my answer a bit and tell me where i'm wrong, what i should improve, anything that could help me really?
So first i calculate first derivative:
\begin{equation}
\frac{dy}{dt} = -e^{-t}\sin(2t) + 2e^{-t}\cos(2t)
\end{equation}
and i convert the result to a more simplified form
\begin{equation}
\sqrt{5}e^{-t}\cos(2t-0.464)
\end{equation}
which i equate to 0 to find t(which i can't find it here).
And then i calculate the second derivative:
\begin{equation}
\frac{d^{2}y}{dt^{2}} = -\sqrt{5}e^{-t}\cos(2t-0.464)-2\sqrt{5}e^{-t}\sin(2t-0.464)
\end{equation}
which "simplifies" to:
\begin{equation}
5e^{-t}\cos(2(t-\frac{tan^{-1}(2)}{2})-0.4636)
\end{equation}
I doubt i'm right so far but if i am then i'm close. However i don't see exactly how i can prove what is needed from here. If someone could help me a bit i would be most grateful. Thank you in advance.

A: You would have been better off trying to solve for critical points directly in:
$$\frac{dy}{dt} = -e^{-t}\sin(2t) + 2e^{-t}\cos(2t)$$
instead of first simplifying.
$$0 = -e^{-t}\sin(2t) + 2e^{-t}\cos(2t) \implies e^{-t}\sin(2t) = 2e^{-t}\cos(2t)$$
and that gives
$$\tan(2t) = 2$$


text:
Q: Expose port using DockerOperator I am using DockerOperator to run a container. But I do not see any related option to publish required port. I need to publish a webserver port when the task is triggered. Any help or guide will be helpful. Thank you!

A: First, don't forget docker_operator is deprecated, replaced (now) with providers.docker.operators.docker.
Second, I don't know of a command to expose a port in a live (running) Docker container.
As described in this article from Sidhartha Mani

Specifically, I needed access to the filled mysql database. .
I could think of a few ways to do this:

*

*Stop the container and start a new one with the added port exposure. docker run -p 3306:3306 -p 8080:8080 -d java/server.

*The second option is to start another container that links to this, and knows how to port forward.

*Setup iptables rules to forward a host port into the container.

So:

Following existing rules, I created my own rule to forward to the container
iptables -t nat -D DOCKER ! -i docker0 -p tcp --dport 3306-j DNAT \
         --to-destination 172.17.0.2:3306

This just says that whenever a packet is destined to port 3306 on the host, forward it to the container with ip 172.17.0.2, and its port 3306.
Once I did this, I could connect to the container using host port 3306.
I wanted to make it easier for others to expose ports on live containers.
So, I created a small repository and a corresponding docker image (named wlan0/redirect).
The same effect as exposing host port 3306 to container 172.17.0.2:3306 can be achieved using this command.
This command saves the trouble of learning how to use iptables.
docker run --privileged -v /proc:/host/proc \
           -e HOST_PORT=3306 -e DEST_IP=172.17.0.2 -e DEST_PORT=3306 \
           wlan0/redirect:latest

In other words, this kind of solution would not be implemented from a command run in the container, through an Airflow Operator.

As per my understanding DockerOperator will create a new container, then why is there no way of exposing ports while create a new container.

First, the EXPOSE part is, as I mentioned here, just a metadata added to the image. It is not mandatory.
The runtime (docker run) -p option is about publishing, not exposing: publishing a port and mapping it to a host port (see above) or another container port.
That might be not needed with an Airflow environment, where there is a default network, and even the possibility to setup a custom network or subnetwork.
Which means other (Airflow) containers attached to the same network should be able to access a ports of any container in said network, without needing any -p (publication) or EXPOSE directive.

A: In order to accomplish this, you will need to subclass the DockerOperator and override the initializer and _run_image_with_mounts method, which uses the API client to create a container with the specified host configuration.
class DockerOperatorWithExposedPorts(DockerOperator):

    def __init__(self, *args, **kwargs):
        self.port_bindings = kwargs.pop("port_bindings", {})
        if self.port_bindings and kwargs.get("network_mode") == "host":
            self.log.warning("`port_bindings` is not supported in `host` network mode.")
            self.port_bindings = {}
        super().__init__(*args, **kwargs)

    def _run_image_with_mounts(
        self, target_mounts, add_tmp_variable: bool
    ) -> Optional[Union[List[str], str]]:
        """

        NOTE: This method was copied entirely from the base class `DockerOperator`, for the capability
        of performing port publishing.
        """
        if add_tmp_variable:
            self.environment['AIRFLOW_TMP_DIR'] = self.tmp_dir
        else:
            self.environment.pop('AIRFLOW_TMP_DIR', None)
        if not self.cli:
            raise Exception("The 'cli' should be initialized before!")
        self.container = self.cli.create_container(
            command=self.format_command(self.command),
            name=self.container_name,
            environment={**self.environment, **self._private_environment},
            ports=list(self.port_bindings.keys()) if self.port_bindings else None,
            host_config=self.cli.create_host_config(
                auto_remove=False,
                mounts=target_mounts,
                network_mode=self.network_mode,
                shm_size=self.shm_size,
                dns=self.dns,
                dns_search=self.dns_search,
                cpu_shares=int(round(self.cpus * 1024)),
                port_bindings=self.port_bindings if self.port_bindings else None,
                mem_limit=self.mem_limit,
                cap_add=self.cap_add,
                extra_hosts=self.extra_hosts,
                privileged=self.privileged,
                device_requests=self.device_requests,
            ),
            image=self.image,
            user=self.user,
            entrypoint=self.format_command(self.entrypoint),
            working_dir=self.working_dir,
            tty=self.tty,
        )
        logstream = self.cli.attach(container=self.container['Id'], stdout=True, stderr=True, stream=True)
        try:
            self.cli.start(self.container['Id'])

            log_lines = []
            for log_chunk in logstream:
                log_chunk = stringify(log_chunk).strip()
                log_lines.append(log_chunk)
                self.log.info("%s", log_chunk)

            result = self.cli.wait(self.container['Id'])
            if result['StatusCode'] != 0:
                joined_log_lines = "\n".join(log_lines)
                raise AirflowException(f'Docker container failed: {repr(result)} lines {joined_log_lines}')

            if self.retrieve_output:
                return self._attempt_to_retrieve_result()
            elif self.do_xcom_push:
                if len(log_lines) == 0:
                    return None
                try:
                    if self.xcom_all:
                        return log_lines
                    else:
                        return log_lines[-1]
                except StopIteration:
                    # handle the case when there is not a single line to iterate on
                    return None
            return None
        finally:
            if self.auto_remove == "success":
                self.cli.remove_container(self.container['Id'])
            elif self.auto_remove == "force":
                self.cli.remove_container(self.container['Id'], force=True)

Explanation: The create_host_config method of the APIClient has an optional port_bindings keyword argument, and create_container method has an optional ports argument. These calls aren't exposed in the DockerOperator, so you have to copy the _run_image_with_mounts method and override it with a copy and supply those arguments with the port_bindings field set in the initializer. You can then supply the ports to publish as a keyword argument. Note that in this implementation, the expectation is argument is a dictionary:
t1 = DockerOperatorWithExposedPorts(image=..., task_id=..., port_bindings={5000: 5000, 8080:8080, ...})


text:
Q: Pound signs saving as question marks in my SQL database I've searched on this for a while but none seem to be quite relevant enough.
Basically, I have a csv file that is extracted from a program. I wrote a quick python program to convert the csv file to an sql file so I can import it into the database. I then import the .sql file using the windows command prompt to my remote MySQL server.
I have some pound signs (£) in some of the fields in my database. In the csv file, they are showing as £, in the resulting sql file (after conversion) they are showing as \£ because of my use of re.escape - I'm actually thinking this may be the reason (The python code that writes this to the file is:
for row in csvReader:
    ...other stuff...
    sqlfile.write(re.escape(row[6])).
After the file is imported, I view the tables and the pound signs are now showing as ? in the tables, and when the contents is shown on the website using php to query.
The database Server connection collation is utf8_general_ci and I'm connecting to the remote server with thiscommand:
mysql --host=HOST --user=USER --password=PASS --default-character-set=utf8 DATABASENAME < filetoimport.sql
Changing the character encoding on firefox made no difference, as expected - whatever is happening seems to be when the sql dump is imported.
Being honest, I'm not really completely sure I understand how the whole character set things work, I've never really had to try and fix a problem like this before so I'm not really sure what else to try. Any help or even a point in the right direction to search, as my searches so far doesn't seem to be helping me :(
Thank you!

A: Use mysql's escape function.  Mysqldb is something like:
conn.escape_string()


text:
Q: jquery validation not required with custom method This regarding the JQuery validation plugin.  I have a custom method like this.
$.validator.addMethod("USphoneCheck", function(value, element) {
            var phoneNumberPattern = /^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/;
            return phoneNumberPattern.test(value);
        }, "Please enter a valid US phone number.");

This is my function call
 cus_phone: {
                    required: false,
                    minlength: 12,
                    USphoneCheck: true
                },

When I run the code without any value I get "Please enter a valid US phone number" message.
This is not required field, But I want to validate when someone entered a value. Am I doing something wrong? Appreciate your help.
Thanks

A: Blank wouldn't be validated with that regex try adding a if else statement to say if its blank don't run the function or wrap the entire regex in () and place a ? at the end.
(/^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/)?


text:
Q: Chrome [Violation] 'load' handler took 808ms I worked with openlayer3. Now I got this kind of warning:
Console:
[Violation] 'load' handler took 308ms  ol-debug.js.xhtml?ln=js:6967
[Violation] 'load' handler took 808ms
ol.events.bindListener_ = function(listenerObj) {
  var boundListener = function(evt) { // <- Zeile 6967
    var listener = listenerObj.listener;
    var bindTo = listenerObj.bindTo || listenerObj.target;
    if (listenerObj.callOnce) {
      ol.events.unlistenByKey(listenerObj);
    }
    return listener.call(bindTo, evt);
  };
  listenerObj.boundListener = boundListener;
  return boundListener;
};

Is it maybe a bug on Google Chrome?
Thanks

A: The message [Violation] 'load' handler took x ms seems more like a warning that your code took a long time to run, than anything else. Perhaps you should try to move the code execution out of the load handler, and into something else (a button click?).


text:
Q: How to get the html content of a clicked element using jQuery I am trying to get the inner html content of a particularly clicked div, I have a number of div elements.
Look at the code I use below.

$(function() {

    $( "#try" ).click(function() {
        var clickedValue = $(this).find('div').text();
        alert(clickedValue);
    });

});

B

R

Y

B

G

W

I want to do it in a way such that B appears when the div with background color of blue is clicked on but then it seems something is wrong with the way I am doing it. For some reasons, I cannot  give id attribute to those set of div and they must have the same class.
The problem with the code above is that when I click on any of the 6 div elements, the clickedvalue will be BRYBGW.

A: $(this).find('div') will return all the div elements within the #try element, instead you want to target only the clicked div
You can use event.target

$(function() {
  $("#try").click(function(e) {
    var clickedValue = $(e.target).text();
    alert(clickedValue);
  });

});

B

R

Y

B

G

W

But I would recommend targeting the actual child element using the click handler.... either by directly binding the handler to them or by using event delegation

$(function() {
  //or $("#try > div").click(function(e) {
  $("#try").on('click', 'div', function(e) {
    var clickedValue = $(this).html();
    alert(clickedValue);
  });

});

B

R

Y

B

G

W


text:
Q: Why do "This question already has an answer here" links appear slightly lower than "Possible Duplicate" links in duplicate questions? If you were to look really closely at duplicate questions, you find that the header in newer duplicates with "This question already has an answer here" (or "This question is an exact duplicate of") is slightly lower than the old "Possible Duplicate" links in older questions. Examples (use the vote buttons as reference points):

*

*An older question:

*A newer question:
Is this a design bug?


text:
Q: Google cloud or Docker not recognizing folder I have a project with the following strucure :
vineetkalghatgi@vinux:~/personal-projects/bertQA_server$ ls
bert-server-env  cloudbuild.yaml  Dockerfile  main.py  mymodel  Procfile  __pycache__  README.md  requirements.txt  target

My .dockerignore:
Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__pycache__
.pytest_cache
bert-server-env

This is my Dockerfile
FROM tensorflow/tensorflow

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
ADD mymodel .
COPY . .

# Install dependencies
RUN apt-get update \
    && apt-get upgrade -y \
    && apt-get autoremove -y \
    && apt-get clean

# Install production dependencies.
RUN pip3 install -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

I previously just had COPY . . without the ADD and noticed that the 'mymodel' folder was not getting copied.
If i run gcloud build submit . --tag <my-gcr.io-container I get the following error:
Step 5/9 : ADD mymodel .
ADD failed: file not found in build context or excluded by .dockerignore: stat mymodel: file does not exist

And I am able to build the image locally with docker build with no issues.

A: With gcloud build submit, if you have a Dockerfile in the working directory, you don't need a cloudbuild.yaml. Because you have a cloudbuild.yaml, I suspect that it is taking priority.
Q1: What is the content of cloudbuild.yaml?
Cloud SDK uses a .gcloudignore file to ignore files that are e.g. uploaded to Cloud Build.
Q2: Do you have a .gcloudignore file or .gitignore file?
It'd be useful to ls -1a (where 1==one) or l=lowercase L will show hidden files too.


text:
Q: $(window).height() returns strange value I tried following commands to determine the viewport height:
var H1 = document.documentElement.clientHeight,
    H2 = $(window).height();

The result is 8 in all cases. But the viewport is much bigger (> 500).
Supplement:
The difference is between
        H  = $(document).height()
        H1 = $(window).height()

with the Firefox-Browser (24.0/Debian). H = 600  H1 = 8
With Chromium (29.0/Debian)   H = 600   H1 = 600
I don't know why.

A: Are there margins and padding?
Try H2 = $(window).outerHeight(true)

A: If there are margins or paddings, you should look at $(window).outerHeight() .
More info here

A: Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "height" ) rather than .height().


text:
Q: Can't request permissions from Android Facebook SDK I'm attempting to request certain permissions when I log in to Facebook using the Android SDK. Using the following code, the login is successful, but the permissions I wanted are neither granted nor declined. It appears they were not even requested. What's wrong?
    login_button.setReadPermissions(Arrays.asList("user_photos"));
    login_button.setFragment(this);

    LoginManager.getInstance().registerCallback(PicTag.callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            Log.v(PicTag.TAG, "Facebook login success: " + loginResult.toString());
            Log.v(PicTag.TAG, AccessToken.getCurrentAccessToken().getPermissions().toString());
            Log.v(PicTag.TAG, loginResult.getRecentlyGrantedPermissions().toString());

            if (shareFrag!=null){
                shareFrag.shareContent();
                activity.getSupportFragmentManager().popBackStackImmediate();
            }

        }

        @Override
        public void onCancel() {
            // App code
            Log.v(PicTag.TAG, "Facebook login canceled");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v(PicTag.TAG, "Facebook login error: " + exception.toString());
            if (shareFrag!=null){

                activity.getSupportFragmentManager().popBackStackImmediate();
            }
        }
    });
}

A: According to "user_photos" Permissions documentation:

If your app requests this permission Facebook will have to review how your app uses it.

This is a new Facebook policy and you will most likely need to sumbit you application for Login Review.


text:
Q: btrfs: Reset `mount -o rw,degraded` count With btrfs, it seems that there is a single opportunity to use:
-o rw,degraded

(eg, if there is a missing disk in a RAID1 configuration)

*

*How can one force the degraded mount to proceed rw a second time?

*How can one edit the filesystem device so as to pretend that it has not yet been mounted rw,degraded?
I understand there are kernel patches which remove various mount checks, however I want to patch the filesystem instead, and have all the checks still in place.

A: Not really an answer, but perhaps some leads...
There is a known gotcha in the wiki which affects btrfs RAID1:

When a raid1 volume is stuck as read-only [...] it can only be recovered by dumping its contents, recreating it and restoring the contents

But that's just the offical line - there is a simple kernel patch which effectively comments out the line:
goto fail_sysfs;

Which will allow multiple rw,degraded mounts.
Please shout if you find a filesystem patch!


text:
Q: Actions on Google - Mac gactions won't run I am trying to set up the Actions sdk as described here:
https://developers.google.com/actions/sdk
I downloaded gactions for a Mac 64-bit machine.  If I try to open the file, it opens as text.  When I am in the folder containing gactions, I try to run gactions init and get the response:

-bash: gactions: command not found

Any thoughts?

A: If you have already setup google-cloud-sdk correctly, then you can drop the gactions file into the google-cloud-sdk/bin folder. Alternatively, you can add a path to bash directly to the folder you have gactions.

A: Try this:

*

*Download Google gactions cli from gaction CLI

*On Mac and Linux, to make the binary executable run from terminal:

$ cd folder_with_gactions
$ chmod +x gactions

*Execute gactions

$ cd folder_with_gactions
$ ./gactions init

Also, you may find this tutorial interesting if you are trying to create an action in Google Home : How to create a custom private Google Home Action with API.AI and Google App Engine. In STEP 8 you can find an example of gactions.

A: To add the gactions command CLI location to the System Paths:

*

*Use "Go to the Folder" option of Finder, to search "~/.bash_profile"

*Open the File "~/.bash_profile"
 in edit mode and add the following command, at the top the file, Save and Close.

export PATH="$PATH:$HOME/gactionsCLI"

Note: Above path refers to the folder which contains the executable
  file "Unix Executable"

*Restart the Terminal and try the commands

A: Download gactions
copy downloaded gactions and put into a local Project folder
and  then go to your project directory cd "project directory"
run following commands :
$ chmod +x gactions

$ ./gactions init

it will create action.json into your folder

A: *

*Ensure you run chmod +x gactions to make the binary executable

*Copy the binary executable into the project directory

*Run ./gactions init from the terminal/command line


text:
Q: Cannot pip-install earlier version (1.15) of TensorFlow, even in Python 3.6 I am trying to install and use a package called FinRL. This package has a dependency, StableBaselines which uses tensorflow. It says in FinRL documentation that FinRL only works with TensorFlow 1.x , so I need to install earlier versions of tensorflow (in their examples, they use tensorflow==1.15.4 ).
I tried doing it in Python 3.9, but I got the error "No matching distribution found for tensorflow==1.15.4" . After some reading through threads like this one , I downloaded Python 3.6.4 to try again. Once again, when I run "pip install tensorflow=1.15.4" in Python 3.6.4 (I ran "python --version" in command prompt, after navigating to the Python folder to make sure I was using Python 3.6.4 ) .
As the thread suggested, I also made sure I was using an upgraded pip, so I upgraded it. Currently using pip 22.1 . However, I notice that it says "pip 22.1 from C:.......Python3.9...  Could this be the issue? I do have both, Python 3.6.4 and Python 3.9 installed on my computer.
Do you have any advice or suggestions for how I can get this package or early TensorFlow installed/working?
Thank you!


text:
Q: Cardinality of a relationship I've created an Entity Relationship Diagram for a Database of an hospital where there is a relationship 'Work' between 'Doctor' and 'Department'. This relationship has the key attribute 'Date' in addition to the identifiers of the  relations 'Doctor' and 'Department'.
The problem is that in general a doctor can work in more departments (for example cardiology, surgery, pediatrics...) but only in one a day (for example if the doctor in the date X works in cardiology, he can't work in other departments in the same date).
What is the cardinality of this relationship?

*

*DOCTOR ---(1,1)--WORK--(1,N)--- DEPARTMENT
OR

*DOCTOR ---(1,N)--WORK--(1,N)--- DEPARTMENT

scilicet, the attribute 'Date' affects cardinality?

A: The cardinalities are the fololowing:
DOCTOR ---(1,N)--WORK--(N,1)--- DEPARTMENT
regardless of presence of date attribute.
That is basically how (N,N) relationship containing extra attributes is presented using an extra entity (WORK in your case).
The date attribute affects only the key of WORK entity, but not cardinalities of relationships.


text:
Q: How can matter be squeezed extremely dense I'm fairly new to physics and currently reading A Brief History of Time by Stephen Hawking. Hawking is talking about black holes being the size of a few miles containing the mass of multiple times the sun's mass. How can matter be squeezed that dense? Isn't there a final point of matter being squeezed?
Maybe a silly example, but if a black hole can be multiple miles in diameter, why can't I compress my daily garbage to the size of a cubic centimeter sized cube with a giant hydraulic press? Or change the density of a steel block with a gigantic press?
So basically, how can an atom be squeezed denser than it already is? I guess that's what happens in black holes at least! I couldn't find a non-physicist easy explained answer, an answer like how Hawking explains things by examples in his books. Thanks!


text:
Q: Selenium 2 - Android Server crashes when trying to SendKeys into a field I'm using WebDriver Selenium-dotnet-2.11.0 and Android server 2.11.0. Tests are run by NUnit.
This works well for navigation around web pages and clicking elements. However, when I try to enter a value in a field (SendKeys), the .apk app on the device (a.k.a. Selenium-server) crashes due to an unknown error.
I'm using a real device HTC Desire Z1 (the one with slide-out keyboard).
The piece of code that leads to the crash is:
IWebElement _element;

_element = _driver.FindElement(By.Id("loginEmail"));
string username = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "Username"];
_element.SendKeys(username);

username is acquired correctly and doesn't contain any special characters, except '@', but I checked that it's not causing the problem.
Device debug log shows following error:
11-04 12:10:24.619: I/dalvikvm(3941): Could not find method android.view.KeyEvent.normalizeMetaState, referenced from method org.openqa.selenium.android.EventSender$2.run
11-04 12:10:24.619: W/dalvikvm(3941): VFY: unable to resolve static method 51: Landroid/view/KeyEvent;.normalizeMetaState (I)I
11-04 12:10:24.629: W/dalvikvm(3941): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
11-04 12:10:24.649: E/AndroidRuntime(3941): FATAL EXCEPTION: main

I wonder what is the cause of the problem. I can't type anything into a field, but haven't found anyone else having this problem. It looks like either I'm doing something wrong or the device.

A: I had the same problem. I just upgrade to android server apk 2.1.3 and the send_keys works fine.


text:
Q: Sorting by Date which may be empty with Telerik Reports Have a column in a report which a string date field in the format of MM/dd/yyyy.  Some of those columns may contain empty strings.  Having a problem sorting a section.  I am about 10 hours in to telerik reporting so I may be missing something obvious.
I initially tried to use a expression like this:
=IIf(Fields.ExpirationDate='', CDate('1/1/1990'), CDate(Fields.ExpirationDate))

Does that look correct?  This threw an error:
An error has occured while processing Report '':
Failed to compare two elements in the array.

------------- InnerException ------------- An error has occured while executing function CDate().
  Check InnerException for further
  information.
  ------------- InnerException ------------- Exception has been thrown by the target of an invocation.
  ------------- InnerException ------------- String was not recognized as a valid DateTime.

Another developer suggested using a custom method so I created inside the report.cs file
    public DateTime EmptyDateToNow( string expirationDate )
    {
        DateTime parsed;
        if (!DateTime.TryParse(expirationDate, out parsed))
            return DateTime.Now;

        return parsed;
    }

and then tried to call with =EmptyDateToNow(Fields.ExpirationDate)
and this throws the error:

An error has occured while processing
  Report '': Failed to compare two
  elements in the array.
  ------------- InnerException ------------- The expression contains undefined function call
  EmptyDateToNow().

A: public static DateTime EmptyDateToNow( string expirationDate )
I think that Telerik Reporting wants your user functions to be static methods.
I am thinking that the problem with the first approach is that CDate(Fields.ExpirationDate) is being executed even if the expression is true thereby causing the exception to be thrown. You might try something like this to get the desired result without defining a user function:
=CDate(IIf(IsNull(Fields.ExpirationDate) Or Fields.ExpirationDate="", "1/1/1990", Fields.ExpirationDate))

I realize this is a bit old, I just wanted to post in case anyone else is having troubles and searching this.

A: Make the user function static (and if the call still fails, make the call fully qualified. e.g. =Myclass.EmptyDateToNow(Fields.ExpirationDate)).
Make the function receive an object as a parameter (not a string or any other data type).
Inside the function, check for null and then (it not null) convert to the proper data type and work with it.


text:
Q: What is the difference between a wait statement and using a while loop in SystemVerilog? I was wondering what is the difference between waiting for a flag to be set using a wait statement or a tradition loop until the flag is set.
wait (flag === 1); //Implementation 1

while ( flag != 1); //Implementation 2

A: The wait statement blocks the current process until the expression becomes true.
The while loop you wrote becomes an infinite zero-delay loop if the expression is true (flag is false). This will hang simulation.


text:
Q: Derivatives of eigenvalue with respect to boundary location I have considered the Sturm–Liouville problem in a form of one-dimensional Schrodinger equation with Dirichlet boundary conditions:
$$
\left\{\begin{array}{l}
\displaystyle-\frac{\hbar^2}{2m}\varphi''(x)+V(x)\varphi(x)=E\varphi(x),\quad a\leqslant x\leqslant b,\\
\varphi(a)=\varphi(b)=0.\end{array}\right.
$$
If we obtained some specific eigenvalue $E_n$ and eigenfunction $\varphi_n(x)$, then the eigenvalue $E_n$ should somehow depend on the boundary point locations $a$ and $b$. I have found that
$$
\frac{\partial E_n}{\partial a}=\frac{\hbar^2}{2m}|\varphi'_n(a)|^2,\qquad
\frac{\partial E_n}{\partial b}=-\frac{\hbar^2}{2m}|\varphi'_n(b)|^2.
$$
I suppose this is a well-known result in the theory of differential equations or in the functional analysis, so could anyone give any additional information about this problem (any books or papers, who first obtained this result, what is its higher-dimensional generalizations etc.).

A: I am not so sure about the references you requested. Yet the generalization of your result to higher-dimensional cases is somewhat straightforward.
Consider the following stationary Schrodinger problem
\begin{align}
-\kappa\Delta\varphi+U\varphi&=E\varphi&&\text{in }\Omega,\\
\varphi&=0&&\text{on }\partial\Omega,
\end{align}
where
$$
\kappa=\frac{\hbar^2}{2m},
$$
and $\Omega\subseteq\mathbb{R}^n$ is an $n$-dimensional simply connected domain with piecewise smooth boundary $\partial\Omega$. In addition, $\varphi$, if with more than one component, is by default as a column vector.
Note that the domain $\Omega$ can be characterized by a level set function $\phi=\phi(\mathbf{x})$, i.e.,
\begin{align}
\phi&>0&&\text{in }\Omega,\\
\phi&=0&&\text{on }\partial\Omega.
\end{align}
Thus when considering the continuous deformation of $\Omega$, it suffices to focus on the change of $\phi$.
Using this notation, the stationary Schrodinger problem witnesses an equivalent statement:

Find the stationary points of the functional
  $$
J[\varphi,\phi]=\int_{\left\{\phi>0\right\}}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right){\rm d}V
$$
  for some fixed $\phi$, on condition that
  \begin{align}
\varphi&=0&&\text{on }\left\{\phi=0\right\}
\end{align}
  and that
  $$
\int_{\left\{\phi>0\right\}}\left|\varphi\right|^2{\rm d}V=1.
$$

In this way, the energy eigenvalue $E$ serves as a Lagrangian multiplier to conserve the probability. Obviously, this $E$ depends on $\phi$. Plus, since $E\in\mathbb{R}$, it is a functional of $\phi$. It can be determined as follows.
Suppose $\varphi$ is a solution to the above stationary point problem with some fixed $\phi$. Then $\varphi$ satisfies, for some $E\in\mathbb{R}$,
\begin{align}
-\kappa\Delta\varphi+U\varphi&=E\varphi&&\text{in }\left\{\phi>0\right\},\\
\varphi&=0&&\text{on }\left\{\phi=0\right\},\\
\int_{\left\{\phi>0\right\}}\left|\varphi\right|^2{\rm d}V&=1.
\end{align}
Left-multiply $\varphi^{\dagger}$ on both-sides of the governing equation, and the integration by parts yields
\begin{align}
E&=E\int_{\left\{\phi>0\right\}}\left|\varphi\right|^2{\rm d}V=\int_{\left\{\phi>0\right\}}\varphi^{\dagger}\left(E\varphi\right){\rm d}V\\
&=\int_{\left\{\phi>0\right\}}\varphi^{\dagger}\left(-\kappa\Delta\varphi+U\varphi\right){\rm d}V=\int_{\left\{\phi>0\right\}}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right){\rm d}V.
\end{align}
Therefore,
$$
E[\phi]=J[\varphi[\phi],\phi],
$$
where $\varphi[\phi]$ means that $\varphi$, as a solution to the stationary point problem, depends on the choice of $\phi$.
To examine how the variation of $\phi$ has impact on the change of $E$, it suffices to figure out
$$
\delta E[\phi]=\delta J[\varphi[\phi],\phi].
$$
Due to the difficulty in calculating this variation, consider a family of feasible $\phi$, denoted as
$$
\phi=\phi(\mathbf{x},\tau)
$$
with $\tau\in\mathbb{R}$, i.e., $\phi=\phi(\cdot,\tau)$ is a level set function for each fixed $\tau$, and it switches between different level set functions continuously as $\tau$ changes. With this setting, it suffices to determine
$$
\frac{\rm d}{{\rm d}\tau}E[\phi(\cdot,\tau)]=\frac{\rm d}{{\rm d}\tau}J[\varphi(\cdot,\tau),\phi(\cdot,\tau)].
$$
Here
$$
\varphi(\mathbf{x},\tau)=\varphi[\phi(\cdot,\tau)](\mathbf{x})
$$
stands for the solution to the stationary point problem as the level set function reads $\phi=\phi(\cdot,\tau)$.
Thanks to the Leibniz integral rule (since $\left\{\phi>0\right\}$ is also $\tau$-dependent),
$$
\frac{\rm d}{{\rm d}\tau}E=\int_{\left\{\phi>0\right\}}\frac{\partial}{\partial\tau}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right){\rm d}V+\int_{\left\{\phi=0\right\}}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right)\mathbf{v}\cdot{\rm d}\mathbf{S},
$$
where $\mathbf{v}$ is the normal "velocity" of the moving boundary $\left\{\phi(\tau)=0\right\}$ as $\tau$ changes.
The derivation henceforth would adopt these notations:
\begin{align}
\dot{\phi}&=\frac{\partial}{\partial\tau}\phi(\cdot,\tau),\\
\dot{\varphi}&=\frac{\partial}{\partial\tau}\varphi(\cdot,\tau).
\end{align}
Since $\varphi=\varphi(\cdot,\tau)$ is the solution to the stationary point problem, it satisfies
\begin{align}
-\kappa\Delta\varphi(\cdot,\tau)+U\varphi(\cdot,\tau)&=E[\phi(\cdot,\tau)]\varphi(\cdot,\tau)&&\text{in }\left\{\phi(\cdot,\tau)>0\right\},\\
\varphi(\cdot,\tau)&=0&&\text{on }\left\{\phi(\cdot,\tau)=0\right\}.
\end{align}
Specifically, the second condition implies that
\begin{align}
\dot{\varphi}&=-\mathbf{v}\cdot\nabla\varphi&&\text{on }\left\{\phi=0\right\},
\end{align}
because any front-tracking particle $\mathbf{x}=\mathbf{x}(\tau)\in\left\{\phi(\cdot,\tau)=0\right\}$ with $\dot{\mathbf{x}}(\tau)=\mathbf{v}(\mathbf{x}(\tau),\tau)$ complies with $\varphi(\mathbf{x}(\tau),\tau)=0$, for which
$$
\frac{\rm d}{{\rm d}\tau}\varphi(\mathbf{x}(\tau),\tau)=0\iff\dot{\varphi}(\mathbf{x}(\tau),\tau)+\dot{\mathbf{x}}(\tau)\cdot\nabla\varphi(\mathbf{x}(\tau),\tau)=0.
$$
Thanks to these facts,
\begin{align}
&\int_{\left\{\phi>0\right\}}\frac{\partial}{\partial\tau}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right){\rm d}V\\
&=\int_{\left\{\phi>0\right\}}\left(\kappa\nabla\dot{\varphi}^{\dagger}\nabla\phi+U\dot{\varphi}^{\dagger}\varphi\right){\rm d}V+\text{c.c.}\\
&=\left[\kappa\int_{\left\{\phi=0\right\}}\dot{\varphi}^{\dagger}\nabla\varphi\cdot{\rm d}\mathbf{S}+\int_{\left\{\phi>0\right\}}\dot{\varphi}^{\dagger}\left(-\kappa\Delta\varphi+U\varphi\right){\rm d}V\right]+\text{c.c.}\\
&=\left[-\kappa\int_{\left\{\phi=0\right\}}\left(\mathbf{v}\cdot\nabla\varphi^{\dagger}\right)\nabla\varphi\cdot{\rm d}\mathbf{S}+\int_{\left\{\phi>0\right\}}\dot{\varphi}^{\dagger}\left(E\varphi\right){\rm d}V\right]+\text{c.c.}\\
&=\left[-\kappa\int_{\left\{\phi=0\right\}}\left\|\nabla\varphi\right\|^2\mathbf{v}\cdot{\rm d}\mathbf{S}+\int_{\left\{\phi>0\right\}}\dot{\varphi}^{\dagger}\left(E\varphi\right){\rm d}V\right]+\text{c.c.}\\
&=-2\kappa\int_{\left\{\phi=0\right\}}\left\|\nabla\varphi\right\|^2\mathbf{v}\cdot{\rm d}\mathbf{S}+E\int_{\left\{\phi>0\right\}}\frac{\partial}{\partial\tau}\left|\varphi\right|^2{\rm d}V,
\end{align}
where $\text{c.c.}$ stands for the complex conjugate of its previous term. Further, thanks to the conservation of probability,
$$
0=\frac{\rm d}{{\rm d}\tau}\int_{\left\{\phi>0\right\}}\left|\varphi\right|^2{\rm d}V=\int_{\left\{\phi>0\right\}}\frac{\partial}{\partial\tau}\left|\varphi\right|^2{\rm d}V+\int_{\left\{\phi=0\right\}}\left|\varphi\right|^2\mathbf{v}\cdot{\rm d}\mathbf{S}.
$$
Consequently,
$$
\int_{\left\{\phi>0\right\}}\frac{\rm d}{{\rm d}\tau}\left(\kappa\left\|\nabla\varphi\right\|^2+U\left|\varphi\right|^2\right){\rm d}V=-2\kappa\int_{\left\{\phi=0\right\}}\left\|\nabla\varphi\right\|^2\mathbf{v}\cdot{\rm d}\mathbf{S}-E\int_{\left\{\phi=0\right\}}\left|\varphi\right|^2\mathbf{v}\cdot{\rm d}\mathbf{S}.
$$
This result immediately gives
$$
\frac{\rm d}{{\rm d}\tau}E=\int_{\left\{\phi=0\right\}}\left[-\kappa\left\|\nabla\varphi\right\|^2+\left(U-E\right)\left|\varphi\right|^2\right]\mathbf{v}\cdot{\rm d}\mathbf{S}.
$$
Taking the boundary condition
\begin{align}
\varphi&=0&&\text{on }\left\{\phi=0\right\}
\end{align}
into consideration, the above expression eventually reduces to

$$
\frac{\rm d}{{\rm d}\tau}E=-\kappa\int_{\left\{\phi=0\right\}}\left\|\nabla\varphi\right\|^2\mathbf{v}\cdot{\rm d}\mathbf{S}.
$$

This is the higher-dimensional generalization of your one-dimensional result, where $\varphi$ could have more than one component.
As an example, consider the one-dimensional case, where $\left\{\phi(\cdot,\tau)>0\right\}=\left(a+\tau,b\right)\subseteq\mathbb{R}$. In this case,
$$
\left\{\phi(\cdot,\tau)=0\right\}=\left\{a+\tau,b\right\},
$$
and
\begin{align}
\mathbf{v}&=\frac{\rm d}{{\rm d}\tau}\left(a+\tau\right)=1&&\text{at }x=a+\tau,\\
\mathbf{v}&=\frac{\rm d}{{\rm d}\tau}b=0&&\text{at }x=b.
\end{align}
Further, the outward unit normal of $\left(a+\tau,b\right)$ reads
\begin{align}
\mathbf{n}&=-1&&\text{at }x=a+\tau,\\
\mathbf{n}&=1&&\text{at }x=b.
\end{align}
Thus when $\tau=0$,
$$
\frac{\rm d}{{\rm d}\tau}E=-\kappa\int_{\left\{\phi=0\right\}}\left\|\nabla\varphi\right\|^2\mathbf{v}\cdot{\rm d}\mathbf{S}=-\kappa\int_{\left\{\phi=0\right\}}\left|\varphi'(x)\right|^2\mathbf{v}\cdot\mathbf{n}{\rm d}x=\kappa\left|\varphi'(a+\tau)\right|^2=\kappa\left|\varphi'(a)\right|^2,
$$
which tells the energy variation upon the change of the left end-point of the domain $\left(a,b\right)$. This is in agreement with your result. Likewise, set $\left\{\phi(\cdot,\tau)=0\right\}=\left(a,b+\tau\right)$, and you could figure out the energy variation upon the change of the right end-point of $\left(a,b\right)$, which also agrees with your result.


text:
Q: Veins: I added extra accident message but can not see the data exchange between nodes I added extra event like accident in TraCiMobility.cc including the accident message but I can only see the data exchange between nodes for the accident message and can not see the data exchange between nodes with the new "icyroad" event.
When using only "icy road",  I can see the data exchange between the nodes. Where should I add/edit in Veins so that I can see data exchange when both or more events are active?
The .ini is as follows:

*.node[*].veinsmobilityType = "org.car2x.veins.modules.mobility.traci.TraCIMobility"
*.node[*].mobilityType = "TraCIMobility"
*.node[*].mobilityType.debug = true
*.node[*].veinsmobilityType.debug = true
*.node[*].veinsmobility.x = 0
*.node[*].veinsmobility.y = 0
*.node[*].veinsmobility.z = 1.895

*.node[4].veinsmobility.accidentCount = 1
*.node[4].veinsmobility.accidentStart = 45s
*.node[4].veinsmobility.accidentDuration = 30s  #30s

*.node[3].veinsmobility.icyroadCount = 1
*.node[3].veinsmobility.icyStart = 15s
*.node[3].veinsmobility.icyDuration = 30s

A: The sample simulation that is included in Veins 4a2 uses an application layer that only relays the first message it receives. You will need to change this to a more full-featured application layer to make this work with more than one event type.


text:
Q: Error: javax.ws.rs.NotFoundException: HTTP 404 Not Found I am trying to test my code that gets all the user details from Keycloak using the Keycloak library. But I keep seeing this error. can anyone help me with this?
Test code:
    trait Setup {
        val keycloak: Keycloak = mock[Keycloak]
        val keycloakBuilder: KeycloakBuilder = mock[KeycloakBuilder]
        val service = new NewUserService(conf)
        val restEasy: ResteasyClientBuilder = mock[ResteasyClientBuilder]
        val restEasyClient: ResteasyClient = mock[ResteasyClient]
        val realmResource: RealmResource = mock[RealmResource]
        val usersResource: UsersResource = mock[UsersResource]
      }
      "NewUserService#getAllUsers" should {

        "return all users" in new Setup {
          when(restEasy.build()) thenReturn restEasyClient
          when(keycloakBuilder.build()) thenReturn keycloak
          when(restEasy.build()) thenReturn restEasyClient
          when(keycloak.realm(any[String])) thenReturn realmResource
          when(realmResource.users()) thenReturn usersResource
          when(usersResource.list()) thenReturn List(any[UserRepresentation]).asJava
          whenReady(service.getAllUsers) { result =>
            assert(result.isRight)
          }
        }
      }

NewUserService.scala:
class NewUserService(conf: Config)(implicit val ec: ExecutionContext, logger: LoggingAdapter) {

      def getAllUsers: Future[Either[NewUserServiceError, util.List[idm.UserRepresentation]]] = {
        val keycloakConf = conf.getConfig("keycloak")
        val serverUrl = keycloakConf.getString("realmServerURL")
        val realm = keycloakConf.getString("realmName")
        val userName = keycloakConf.getString("username")
        val password = keycloakConf.getString("password")
        val clientId = keycloakConf.getString("clientId")
        val clientSecret = keycloakConf.getString("clientSecret")
        val keycloakBuild = KeycloakBuilder
          .builder()
          .serverUrl(serverUrl)
          .realm(realm)
          .username(userName)
          .password(password)
          .clientId(clientId)
          .clientSecret(clientSecret)
          .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
          .build()
        val usersList = Future(Try(keycloakBuild.realm("knoldus").users().list()))
        usersList.map {
          case Success(users) =>
            users.asRight
          case Failure(exception) =>
            logger.error(s"Unable to get user details $exception")
            NewUserServiceError.UserNotFoundError.asLeft
        }
      }
    }

    object NewUserService {

      sealed trait NewUserServiceError

      object NewUserServiceError {
        case object UserNotFoundError extends NewUserServiceError

        case object InternalServerError extends NewUserServiceError
      }

    }

I get the connection refused error when i donot start my keycloak server at 8080 port. And when i start it on 8080 port i see user not found error. Please tell me what am i doing wrong.
Error:

Unable to get user details javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:8080 [/127.0.0.1] failed: Connection refused
Unable to get user details javax.ws.rs.ProcessingException: javax.ws.rs.NotFoundException: HTTP 404 Not Found


text:
Q: Como setar o Foco em um Componente do MVC Tenho um MVC modelo 3.
Após a validação de um campo do cabeçalho(formfield), setar o foco para o grid.
Como fazer isso?

A: Não é nada recomendável dar refresh na view dentro de uma validação do modelo. Portanto o correto é utilizar os mecanismos da própria VIEW:
na viewdef....
bBloco := {|oV,cId,cField,xV|MinhaAcao(oV,cId,cField,xV)}
oView:SetFieldAction("CAMPO",bBloco)

Para setar o foco no Grid:
Static function MinhaAcao(oView,cIDView,cField,xValue)
Local oGrid := oView:GetviewObject(cIDVIEW)
oGrid:SetFocus()
return

A: Caso nao tenha resolvido, voce precisa estar o bloco de código no bGotFocus da
FWFORMVIEW():AddGrid(<cViewID >, <oStruct >, [ cSubModelID ], <uParam4 >, [ bGotFocus ])

No bGotFocus eu fiz o trecho abaixo, como isso sempre que o Grid receber o foco ele volta para o campo que eu quero, com isso criei uma variável de controle para o mesmo.
oView:Refresh()
oView:GetViewObj("FIELDZZ5")[3]:getFWEditCtrl("ZZ5_QUANT"):oCtrl:SetFocus()


text:
Q: Cryptographic security of Captcha hash cookie My company's CRM system utilizes a captcha system at each login and in order to utilize certain administrative functions. The original implementation stored the current captcha value for in a server-side session variable.
We're now required to redevelop this to store all necessary captcha verification information in a hashed client-side cookie. This is due to a parent IT policy which is intended to reduce overhead by disallowing use of sessions for users who are not already authenticated to the application. Thus, the authentication process itself is disallowed from using server-side storage or sessions.
The design was a bit of a group effort, and I have my doubts as to its overall efficacy. My question is, can anyone see any obvious security issues with the implementation shown below, and is it overkill or insufficient in any way?
EDIT: Further discussion has led to an updated implementation, so I've replaced the original code with the new version and edited the description to talk to this revision.
(The code below is a kind of pseudo-code; the original uses some idiosyncratic legacy libraries and structure which make it difficult to read. Hopefully this style is easy enough to understand.)
// Generate a "session" cookie unique to a particular machine and timeframe
String generateSessionHash(timestamp) {
    return sha256( ""
        + (int)(timestamp / CAPTCHA_VALIDITY_SECONDS)
        + "|" + request.getRemoteAddr()
        + "|" + request.getUserAgent()
        + "|" + BASE64_8192BIT_SECRET_A
    );
}

// Generate a hash of the captcha, salted with secret key and session id
String generateCaptchaHash(captchaValue, session_hash) {
    return sha256( ""
        + captchaValue
        + "|" + BASE64_8192BIT_SECRET_B
        + "|" + session_hash
    );
}

// Set cookie with hash matching the provided captcha image
void setCaptchaCookie(CaptchaGenerator captcha) {
    String session_hash = generateSessionHash(time());
    String captcha_hash = generateCaptchaHash(captcha.getValue(), session_hash);
    response.setCookie(CAPTCHA_COOKIE, captcha_hash + session_hash);
}

// Return true if user's input matches the cookie captcha hash
boolean isCaptchaValid(userInputValue) {
    String cookie = request.getCookie(CAPTCHA_COOKIE);
    String cookie_captcha_hash = substring(cookie, 0, 64);
    String cookie_session_hash = substring(cookie, 64, 64);
    String session_hash = generateSessionHash(time());
    if (!session_hash.equals(cookie_session_hash)) {
        session_hash = generateSessionHash(time() - CAPTCHA_VALIDITY_SECONDS);
    }
    String captcha_hash = generateCaptchaHash(userInputValue, session_hash);
    return captcha_hash.equals(cookie_captcha_hash);
}

Concept:

*

*The "session_hash" is intended to prevent the same cookie from being used on multiple machines, and enforces a time period after which it becomes invalid.

*Both the "session_hash" and "captcha_hash" have their own secret salt keys.

*These BASE64_8192BIT_SECRET_A and _B salt keys are portions of an RSA private key stored on the server.

*The "captcha_hash" is salted with both the secret and the "session_hash".

*Delimiters are added where client-provided data is used, to avoid splicing attacks.

*The "captcha_hash" and "session_hash" are both stored in the client-side cookie.

EDIT: re:Kobi Thanks for the feedback!
(I would reply in comments, but it doesn't seem to accept the formatting that works in questions?)
Each time they access the login page, the captcha is replaced; This does however assume that they don't simply resubmit without reloading the login form page. The session-based implementation uses expiration times to avoid this problem.  We could also add a nonce to the login page, but we would need server-side session storage for that as well.
Per Kobi's suggestion, an expiration timeframe is now included in the hashed data, but consensus is to add it to the session_hash instead, since it's intuitive for a session to have a timeout.
This idea of hashing some data and including another hash in that data seems suspect to me. Is there really any benefit, or are we better off with a single hash containing all of the relevant data (time, IP, User-agent, Captcha value, and secret key). In this implementation we are basically telling the user part of the hashed plaintext.
Questions:

*

*Are there any obvious deficiencies?

*Are there any subtle deficiencies?

*Is there a more robust approach?

*Is salting the hash with another hash helping anything?

*Is there a simpler and equally robust approach?

New question:
I personally think that we're better off leaving it as a server-side session; can anybody point me to any papers or articles proving or disproving the inherent risk of sending all verification data to the client side only?

A: Assuming no other security than stated here:
It seems an attacker can solve the captcha once, and save the cookie.
She then has her constant session_hash and captcha_hash. Nothing prevents her from submitting the same cookie with the same hashed data - possibly breaking your system.
This can be avoided by using time as part of captcha_hash (you'll need to round it to an even time, possibly a few minutes - and checking for two options - the current time and the previous)
To calrifiy, you said:

The "session_hash" is intended to prevent the same cookie from being used on multiple machines.

Is that true?
On isCaptchaValid you're doing String session_hash = substring(cookie, 64, 64); - that is: you're relying on data in the cookie. How can you tell it wasn't copied from another computer? - you're not hashing the client data again to confirm it (in fact, you have a random number there, so it may not be possible). How can you tell it's new request, and hadn't been used?
I realize the captcha is replaced with each login, but how can you know that when a request was made? You aren't checking the new captcha on isCaptchaValid - your code will still validate the request, even if it doesn't match the displayed captcha.
Consider the following scenario (can be automated):

*

*Eve open the login page.

*Gets a new cookie and a new captcha.

*Replaces it with her old cookie, with hashed data of her old cptcha.

*Submits the old cookie, and userInputValue with the old captcha word.

*With this input, isCaptchaValid validates the request - captcha_hash, session_hash, userInputValue and BASE64_8192BIT_SECRET are all the same as they were on the first request.

by the way, in most systems you'll need a nonce anyway, to avoid XSS, and having one also solves your problem.


text:
Q: Using nested foreach loops from multidimensional arrays in php mysql it would be amazing if someone could help me with this please, I really don't know how to solve it and I've been wracking my brains (and books and internet) for some time without really understanding what I need to do. I'm not a programmer by any means, purely self taught, so please accept my apologies if it seems easy. I've created a database for a fantasy league football site and having got the correct queries for the results and table, I just want to add a query that shows the weekly results by manager, and from this, which players have scored for those managers (no manager's team has the same player), an example such as:
(Table headers: Week > Manager > For > Against > Scorers)
2 Manager1 3-0 (Player a 1, player b 2)
2 Manager2 1-2 (player f 1)
2 Manager3 4-1 (player g 2, player x 2)
I'm using lots of joins to get my results, and have been experimenting with nested foreach loops thinking that I need to do a separate foreach loop to iterate through any player from each team that has scored (ie pull from the list of players who has goals greater than 0), but have had mixed results - none that I need!
Here is my code, from the index controller to the html displaying the foreach loops. If anyone can help or has any ideas, I really would be grateful.
    if (isset($_GET['action']) and $_GET['action'] == 'scorers')
    {
    include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

    $sql = "SELECT Wk.week as ptsweeks, managers.managerid as ID, managers.manager as Manager, CASE when sum(Wk.goals)>GA.goals then '3' when sum(Wk.goals)=GA.goals then '1' when sum(Wk.goals)<GA.goals then '0' END as PTS, sum(Wk.goals) as F, GA.goals as A, case when Wk.goals>'0' then concat(Wk.name,' ',Wk.goals) end as goalscs
from weeks2012 as Wk
    inner join goalsAgainst2012 as GA
    inner join strikers2012 as ST
    inner join defences2012 as DEF
    inner join managers
    on
    Wk.week = GA.week and
    DEF.managerid = ST.managerid and
    ST.playerid = Wk.playerid and
    DEF.defenceid = GA.defenceid and
    managers.managerid = ST.managerid
    where Wk.week = '$weekWK'
    group by managers.managerid";
    $result = mysqli_query($link, $sql);
    if (!$result)
    {
    $error = 'Error updating submitted article.';
        include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
        exit();
    }

    while ($row = mysqli_fetch_array($result))
    {
    $weeks[] = array(
    'table' => array('ptsweeks' => $row['ptsweeks'], 'ID' => $row['ID'], 'Manager' => $row    ['Manager'], 'F' => $row['F'], 'A' => $row['A'], 'PTS' => $row['PTS']),
'gs' => array('goalscs' => $row['goalscs'])
    );

    }

    include 'scorers_html.php';

}

** from scorers_html.php :

    <?php foreach($weeks as $key => $gls): ?>

       <?php echo $gls['table']['ptsweeks']; ?>
       <?php echo $gls['table']['Manager']; ?>
       <?php echo $gls['table']['F']; ?>
       <?php echo $gls['table']['A']; ?>
       <?php echo $gls['table']['PTS']; ?>

      <?php foreach($weeks as $key => $gls): ?>

       <?php echo $gls['gs']['goalscs']; ?>

      <?php endforeach; ?>
     <?php endforeach; ?>

A: First off, you have a syntax error that can be viewed by looking at Stackoverflow's syntax highlighting. Your third line needs to be
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

Upon further review, the below line is also incorrect:
include $_SERVER['DOCUMENT_ROOT'] . /includes/error.html.php';

It should be
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';

You need to encapsulate all strings within quotes or apostrophes.
I would recommend using a code editor that includes syntax highlighting for your language such as KomodoEdit or Netbeans; you will save a lot of headaches.
If this does not help, please post the specific errors/issues you are encountering.


text:
Q: So how do I get the values from the dictionary based on the selected range in the calendar Image of the console
I am new to Javascript, html and css. Any help would be greatly appreciated :)
I have a calendar where you can select a date range. I want to have this range to filter out a dictionary according to the date.
I have created the calendar and the dictionary. Here are the calendar codes and the dictionary codes in my HTML.
I tried debugging using the console.log(). As you can see here, both the key in the dateDict and fromDate are in the same format and also data type, but the dateDict does not recognize fromDate as one of the key  in the dateDict. So how do I get the values from the dictionary based on the selected range in the calendar

      From Date
      <input type="date" name="" max="" id="fromDate">

      To Date
      <input type="date" name="" max="" id="toDate">

      <button onclick="myFunction()">See Data</button>

A: The keys in the dateDict should match the format that is being returned by the date picker, it is currently missing some zeroes. Correct:
var dateDict = {
    "2021-04-01": 1,
    "2021-04-02": 1,
    "2021-04-03": 5,
    "2021-04-04": 1,
    "2021-04-05": 2
  };

Also, a bug that I found in the datePicker is that if you select the to date first and then select the from date, then you can actually mess the logic up, because now to date can be before from date. To fix this what I've done is whenever from date is change the to date will get reset.
And if you want the value corresponding to the date from the dateDict, you can simply do dateDict[fromDate].

      From Date
      <input type="date" name="" max="" id="fromDate">

      To Date
      <input type="date" name="" max="" id="toDate">

      <button onclick="myFunction()">See Data</button>


text:
Q: SQL: multiple groupings needed to track duplicates I have a table, node_saved_data, setup like this:
set_id - node_id - node_value
The values will look something like
2 - 1 - some text
2 - 2 - more text
2 - 3 - a bit more text
2 - 4 - some more text
2 - 5 - even more text

I want to see if there are any duplicate node ids within each set. I tried
SELECT set_id, node_id, COUNT(node_id) c FROM node_saved_data GROUP BY node_id, set_id

but the results were clearly not what I wanted. Any advice? Let me know if you need more information.

A: I determined I only had to reverse the grouping order I was using. After that It gave me the results I was expecting

A: I think you're pretty close. Drop a HAVING clause at the end to check for those combinations with more than 1 entry.
select
  set_id, node_id, count(1)
from
  node_saved_data
group by
  set_id,
  node_id
having
  count(1) > 1


text:
Q: Autoincrement with Grails/Hibernate for different DBs it's not a realy problem, but it surprises me:
when I use Grails with diffrent DBs, I get different counter increments...:

*

*with the ootb hsqldb, every table gets its own counter which is always increased by 1

*with an oracle db, it seems that all tables use the same global counter

*now I am using javadb/derby and the generated id are huge!

where can I find some more information about this behaviour and which one is the best?

*

*hsql seems to keep the counters small

*with oracle, I get a global unique id - also a nice feature

*but what about the derby behaviour?

A: It really depends on the default id generation strategy in the specific dialect. Grails allows you to customize the generation strategy with mapping closure.
The most 'safe' (i.e. being supported by every RDBMS) generation strategy is TABLE, and this is preferred choice of many JPA implementations. This is probably what you get in HSQLDB. However, Oracle support sequences and these objects are generally better optimized for handling key generation -- hence, the dialect for Oracle seems to use one global sequence. I'm not familiar with Derby, but probably there is identity column support there and what you get is some sort of UUID.


text:
Q: Flex макет работает некорректно в Сафари Сделал на пробу макет, который работает как нужно в IE, FireFox и Chrome под Windows, даже под IE11.
Но рано обрадовался. В Safari под Mac и на iPad'е не работает промежуточный вариант с двумя колонками (ширина между 768 и 1199).
Я только начал знакомство с flex и пока вообще не представляю, в чем может быть проблема. Доступ к Mac'у у меня тоже пока ограничен, чтобы поиграться с вариантами.
Буду признателен, если кто-то сможет помочь.

#section-tiles-home {
  margin: 15px;
}

#section-tiles-home .row {
  margin: 0;
}

#section-tiles-home [class^="col-"] {
  padding: 0;
}

#section-tiles-home .tile-img {
  margin: 0 0 15px;
}

.tiles-col-1,
.tiles-col-2 {
  display: flex;
}

.tiles-col-2,
.tiles-col-3 {
  flex-direction: column;
}

.tiles-col-1>.tile-img {
  flex-grow: 1;
}

.tiles-col-2 .tile-img:nth-child(1) {
  flex-grow: 2;
}

.tiles-col-2 .tile-img:nth-child(2) {
  flex-grow: 3;
}

.tiles-col-3>.row {
  flex-grow: 1;
}

.tiles-col-3 .tile-img {
  height: 65vw;
}

.tile-img {
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
}

.tile-img-text-container {
  align-self: stretch;
  color: #fff;
  display: flex;
  flex-grow: 1;
  flex-direction: column;
  justify-content: flex-end;
  overflow: hidden;
  padding: 15px;
  transition: all .3s ease-in-out;
}

.tile-img-text-container a {
  text-decoration: none;
}

.tile-img-text-container a:hover {
  text-decoration: underline;
}

.tile-img-text-container .h3 {
  font-size: 20px;
  margin: 0;
  transition: all .3s ease;
}

.tile-img-text-container .tile-img-text {
  display: none;
  font-weight: bold;
  text-shadow: 0 1px 0 #000;
}

.tile-img-text-container:hover {
  background: rgba(0, 0, 0, 0.5);
}

.tile-img-text-container:hover .h3 {
  transform: translateY(-20px);
}

.tile-img-text-container:hover .tile-img-text {
  animation: slideInUp .3s ease;
  display: block;
}

@media (max-width: 767px) {
  .tiles-col-1 .tile-img {
    height: 100vw;
  }
  .tiles-col-2 .tile-img:nth-child(1) {
    height: 84vw;
  }
  .tiles-col-2 .tile-img:nth-child(2) {
    height: 105vw;
  }
}

@media (min-width: 768px) {
  #section-tiles-home {
    margin: 7px;
  }
  #section-tiles-home>.row {
    display: flex;
  }
  #section-tiles-home .tile-img {
    margin: 7px;
  }
  .tiles-col-2 .tile-img {
    flex-basis: 0;
  }
  .tiles-col-3 .tile-img {
    height: 21vw;
  }
}

@media (min-width: 768px) and (max-width: 1199px) {
  #section-tiles-home>.row {
    flex-flow: wrap;
  }
  .tiles-col-1 .tile-img {
    height: 66vw;
  }
}

@media (min-width: 992px) {
  .tile-img-text-container .h3 {
    font-size: 24px;
  }
  .tile-img-text-container .tile-img-text {
    font-size: 18px;
  }
}

@media (min-width: 1200px) {
  .tiles-col-3 .tile-img {
    height: 16vw;
  }
  .tile-img-text-container .h3 {
    text-transform: uppercase;
  }
}

@media (min-width: 1600px) {
  .tile-img-text-container .h3 {
    font-size: 30px;
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" integrity="sha256-j+P6EZJVrbXgwSR5Mx+eCS6FvP9Wq27MBRC/ogVriY0=" crossorigin="anonymous">

Tile 1

                  Lorem ipsum dolor sit amet

                  Lorem ipsum dolor sit amet

                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus adipisci distinctio ducimus ipsa modi neque quia quod rerum vel! Culpa nihil nisi numquam perspiciatis quam quod reiciendis repellat saepe? Pariatur!

              Link

Tile 2

              Link

Tile 3

              Link

Tile 4

                  Link

Tile 5

                  Link

Tile 6

                  Link

A: Хм, кажется нашлось решение. На решение натолкнул этот вопрос/ответ тёзки:
проблема с flex-wrap + bootstrap3 на safari 9
Добавил в CSS это и все заработало:
#section-tiles-home .row:after,
#section-tiles-home .row:before {
    display: inherit;
}


text:
Q: Вывод списка в Python в формате 2**(N-1) Помогите пожалуйста решить задачу!
Имеем список . Как вывести его элементы в таком виде в столбик:
шаг1
n
шаг2
n,n
шаг3
n,n,n,n
шаг4
n,n,n,n,n,n,n,n
........................
т.е. в каждой строке количество элементов равно 2 **(N-1), где N номер строки вывода.

A: итерируешься по циклу и умножаешь строки на формулу свою. строки прекрасно умножаются.


text:
Q: when i read PDF data and bind image at new page the first page get different size from other page when i read PDF data and bind image at new page the first page get different size from other page
I used below mentioned to for read data
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
        {
            document.SetPageSize(reader.GetPageSizeWithRotation(1));
            PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
            int rotation = reader.GetPageRotation(pageNumber);
            //cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
            cb.AddTemplate(page, 0f, 0f);
            document.NewPage();

        }


text:
Q: CMAKE_INSTALL_RPATH_USE_LINK_PATH without any effect I would like to automatically add the path of libraries at link time to RPATH. After reading a bit I thought CMAKE_INSTALL_RPATH_USE_LINK_PATH should do the job. Unfortunatly, the following MWE does not do the job:
cmake_minimum_required(VERSION 3.9)

cmake_policy(SET CMP0060 NEW)
set(CMAKE_SKIP_BUILD_RPATH  FALSE)
# set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
# set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

find_package(Boost COMPONENTS serialization REQUIRED)
# Setting CMAKE_INSTALL_RPATH explicitly works
# set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_RPATH};${Boost_LIBRARY_DIRS}")

add_executable(app main.cxx)

target_include_directories( app
    PUBLIC ${Boost_INCLUDE_DIR})

target_link_libraries( app
    PUBLIC Boost::serialization)

install(TARGETS app DESTINATION bin)

The output of readelf -d install/bin/app for the example above shows the dependencies but no RPATH:
0x0000000000000001 (NEEDED)             Shared library: [libboost_serialization.so.1.65.1]
0x0000000000000001 (NEEDED)             Shared library: [libstdc++.so.6]
0x0000000000000001 (NEEDED)             Shared library: [libm.so.6]
0x0000000000000001 (NEEDED)             Shared library: [libgcc_s.so.1]
0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

The commented lines is some stuff that I tried so far. Setting CMAKE_INSTALL_RPATH explicitly works. But setting CMAKE_INSTALL_RPATH_USE_LINK_PATH seems to have no effect. This is the case for both binaries, the build and the installed one.
Do I misunderstand what CMAKE_INSTALL_RPATH_USE_LINK_PATH is doing or can someone spot the mistake?
CMake 3.13, CentOS 7

A: I still do not understand exactly whats going on but here and here I found the hint that the environment variable LIBRARY_PATH (probably also CPATH and CPLUS_INCLUDE_PATH) influences which directories are added to RPATH if CMAKE_INSTALL_RPATH_USE_LINK_PATH is set. Those variables were set in my case by easybuild.  My guess is directories provided in LIBRARY_PATH at compile/link time are not added to RPATH. Unsetting LIBRARY_PATH solved my problem.


text:
Q: React: How to show loading on table every time I submit button? I have a react-Flask app that you add an input and it will load a table based on the input.
The first search I do when the page loads it shows my loading circles perfectly fine and makes the API call and loads my data all fine.
But when I hit the search button again to search for something different I still see the same table and it doesn't show the loading circles again.
The API call is working fine in the back end and I at some point I get the new result back, but for a user, it will not know that the back end is running and it will look confusing, I want to make sure they know its loading.
How can I make it so that it shows the loading circles every time I hit the search button?
Here is my code:
class Home extends Component {

// This is to make the table appear when clicking
// Setting state false so that it doesnt appear
constructor() {
    super();
    this.state = { showMessage: false }
  }

  _showMessage = (bool) => {
    this.setState({
      showMessage: bool
    });
  }

//Input sending data and Calling API back
  state ={
  data: []
}
//this gets triggered on line 85
  search = e => {
    e.preventDefault();
    //Here we send the input that we add on line 90 value to Flask
    axios.post("/results",{search_question: document.getElementById("buscar").value})
    //Then we call it back
    .then((res) => {
      // console.log(res.data)
      //We create data variable with our returned data
      const data = res.data
      //Empty variable to pass all values from data
      const question = []
      // for loop that goes into data and pused everything to questions variable.
      for(var i in data)
        {question.push(data[i])}
      //console log to make sure our API returned the correct data and we saved in question
      console.log(question)
      //creating the state of paa and selecting the second index in question
      this.setState({paas:question[1]})

    })

    }

}

  render() {

    //empty variable and set is a state
    const{paas = []} = this.state

    return (

            <form onSubmit={this.search}  method="post">

                          <input type="input" class="form__field" placeholder="Search" id='buscar' required />
                           E.g Food delivery

                           <AwesomeButton
                           //useless button that waits 15 seconds
                              type="primary"
                              size="medium"
                              action={this._showMessage.bind(null, true)}> Search
                            </AwesomeButton>

              </form>

{this.state.showMessage &&(
   <Container>
     <Legend />

                        Question
                        Sentiment
                        Magnitude

                {paas.length ? paas.map(paa => (

                      {paa.Questions}
                      {paa.Sentiment}
                       {paa.Magnitude}

                  ))
                :
                (
<Loading />
                 <Loading />
                 <Loading />
)
                      }

                 <CSVLink data={paas}>
                 <AwesomeButton
                  size="large"
                  type="secondary">
                  Download Data
                </AwesomeButton>
                 </CSVLink>
                  </Container>)
}

<Content/>

    );
  }
}

I tried adding a setTimeout() on showMessage but the It will make all my table dissapear.

A: You need a boolean flag to show the state of table is loading or not. Your state should be something like this:
this.state ={
  showMessage: false
  isLoading:false
}

and your search function:
e.preventDefault();
 this.setState({isLoading:true})
    axios.post("/results",{search_question: document.getElementById("buscar").value})
    .then((res) => {
      const data = res.data
      const question = []
      for(var i in data)
        {question.push(data[i])}

      console.log(question)
      this.setState({paas:question[1],isLoading:false})
      })

As you can see, everytime your search function will be called, loading becomes true and after fetching api we set it to false
Only thing you should do is to check if isLoading is true, render yoyr loading indicator


text:
Q: How to implement RC override and make it stop at certain conditions/seconds in Ardupilot? I'm a little bit confused about this one. As what I understood, rc channel_overrides are one-liner codes that sends a command for three seconds (as what I've observed. I tried running only the rc channel overrides and the commands are implemented for three seconds, too.)
I tried doing loops to see if it stops once the loop is finished, however, it does not. There will always be an offset of three seconds (my estimation) until it stops even though I have overridden the RC signal by 1500. My min and max values are 1100 and 1900. Here's the sample code.
counter = 0
while counter != 1000:
    vehicle.channels.overrides = {'3':1900}
    counter += 1

vehicle.channels.overrides = {'3':1500}

Now, when I tried doing recursive function, it works. Here's my sample code:
def forward(seconds):
if seconds <= 3:
    vehicle.channels.overrides = {'3':1900}
    time.sleep(seconds)
    vehicle.channels.overrides = {'3':1500}
else:
    vehicle.channels.overrides = {'3':1900}
    time.sleep(3)
    forward(seconds - 3)

Now, I'm curious why it doesn't work under while loops and works in recursive functions. Also, I'm trying to send an rc signal and make a full stop once a condition is met that's why I need to understand the problem with using the loops. Thanks

A: Your implementation of the "while" loop does not work because your logic is wrong.
Look at the first two lines of logic in your first example. First, you set counter to 100. Then, you say if the counter is not 100, then override the rc channel to the 1900 max. The line that reads vehicle.channels.overrides = {'3':1900} is not run because the value of counter is set to 100.
Also, be aware that overriding the rc channels is a bit of a "hacky" solution. Per the dronekit-python docs:

Channel overrides (a.k.a. "RC overrides") are highly dis-commended (they are primarily intended for simulating user input and when implementing certain types of joystick control).
Instead use the appropriate MAVLink commands like DO_SET_SERVO/DO_SET_RELAY, or more generally set the desired position or direction/speed.
If you have no choice but to use a channel-override please explain why in a Github issue and we will attempt to find a better alternative.

Because of this, I would also advise you to not rely on the RC override lasting for 3 seconds.


text:
Q: Control power of several devices from an ESP32 I need to control the power (on/off) of several devices (all at a time, not one by one) from the output of an ESP 32.
So, the goal is to turn on/off the 5V power supply for :

*

*1 LED (using a 270 ohm resistor) : about 10mA

*8 "ITR9608" optointerrupter (each using a 270 ohm resistor) : about 8x10mA

*8 "SG90" 9G mini servo : about 8x100mA max

*1 "MCP23017" : 8 LED outputs, 8 sensors inputs : about 200mA max

So the total should be 1.1A, maybe should say 1.5A as a security factor ?
Are these calculations correct ?
This circuit will be controlled from an ESP32 dev board : it's a 3.3V outputs, about 40mA max.
I've found this circuit : http://www.instructables.com/id/DIY-Motor-Driver-With-ESP32-Controller/
Which kind of circuit should I use ?

*

*A switch using a TIP120 like this ? https://hackaday.com/2017/11/23/building-a-skyrim-quest-marker/

*A NPN transistor like this ? http://www.instructables.com/id/DIY-Motor-Driver-With-ESP32-Controller/

*A darlington array like this ? http://www.ti.com/lit/ds/symlink/uln2803a.pdf
I'm a software enginner, but a newbie to electronics, so I'ma little lost in front of all the switching circuit examples that we can found on the internet...
Thanks