text:
Q: Error disabling serialEvent() for COM3 null In my project I am trying to read a RFID number and amount from Arduino and use Processing to update the database on local host. It gives output for the first time and then gives an error.
Arduino code:
int count = 0;                                          // count = 0
                                         // character array of size 12
char input[12];                                // character array of size 12
String in;
boolean flag = 0;                                       // flag =0
void setup()
{
   Serial.begin(9600);          // begin serial port with baud rate 9600bps
}
void loop()
{
    if(Serial.available())
    {
        count = 0;
        while(Serial.available() && count<12)
        // Read 12 characters and store them in //input array
        {
            input[count] = Serial.read();
            count++;
            delay(5);
        }
        String input1= String(input);
        int value=20;
        String stringOne =  String(value);
        Serial.print (input1 +String("r")+ stringOne + String( ";") + String("r"));
        //Serial.write(in);
    }
}

My Processing code is:
import cc.arduino. * ;
import org.firmata. * ;
import processing.serial. * ;
import de.bezier.data.sql.mapper. * ;
import de.bezier.data.sql. * ;
MySQL dbconnection;
Serial myPort; // The serial port
String inByte = " ";
String inByte1 = " ";
String str2;
int breaker = 0;
String rfid;
int Amount;
int count;
int length;
String cutString;
String rfid12 = "";
int amount = 0;
MySQL akshay;
String UniqueID;
//Sftp sftp;
int rupeescharged;

void setup() {
    // List all the available serial ports
    printArray(Serial.list());
    // Open the port you are using at the rate you want:
    ***myPort = new Serial(this, Serial.list()[0], 9600);    <--- getting error on this line my serialEvent() gets disable for this port
    myPort.buffer(18);***
    String user = "root";
    String pass = "";
    String database = "akshay";
    // connect to database of server "localhost"
    akshay = new MySQL(this, "localhost", database, user, pass);
    if (breaker == 1) {
        Amountfinal(rfid12, amount);
    }
    //setup();
    noLoop();

}

void draw() {

}

void serialEvent(Serial myPort) {

    inByte = myPort.readString();
    String cutString = inByte.substring(0, 18);
    String[] list = split(cutString, ';');
    // print(cutString);
    //print(list[0]);
    String input = list[0];
    String[] init = split(input, 'r');
    rfid = init[0];

    String amt = init[1];
    Amount = Integer.parseInt(amt);
    String rfid1 = rfid.substring(0, 12);
    //println(rfid);
    //print(Amount);
    Akshay(rfid1, Amount);

}

void Akshay(String rfid, int amount) {
    String rfid_1 = rfid;
    int amt = amount;
    rfid_1 = rfid_1.replace("\f", "@");
    rfid_1 = rfid_1.replace(".", "@");
    rfid_1 = rfid_1.replace("\b", "@");
    rfid_1 = rfid_1.replace("\n", "@");
    rfid_1 = rfid_1.replace("\t", "@");

    //   println(rfid_1);
    if (rfid_1.charAt(rfid_1.length() - 1) == '@') {
        rfid_1 = rfid_1.substring(0, rfid_1.length() - 1);
    }
    println(rfid_1);
    //print(amt);
    Amountfinal(rfid_1, amt);
    breaker = 1;
}

void Amountfinal(String rfid12, int amount) {
    String rfid = rfid12;
    println(rfid);

    int rupeescharged = amount;
    if (akshay.connect()) {
        // rfid= "123";

        akshay.query("SELECT * FROM userrfid");
        while (akshay.next()) {
            // replace "first_name" and "last_name" with column names from your table
            String s1 = akshay.getString("rfid");

            int s2 = akshay.getInt("pass");
            int s3 = s2 - rupeescharged;
            akshay.execute("UPDATE userrfid SET pass='" + s3 + "' WHERE rfid='" + rfid + "'");
            print(s3);

        }
    }
    //setup();
}


text:
Q: Distance between point and line layers & spatial index issue I am trying to compute on QGIS the distance from some clusters (ie points) to their closest road (ie lines);  no need for all combinations, just the distance from each cluster to the closest road. To do so, I saw on a forum (on this post) that a good method was to transform lines into points, which I did, and then to compute the distance between both point layers. Nonetheless, when trying to do the last step, I get this error :
"/Applications/QGIS.app/Contents/MacOS/../Resources/python/plugins/processing/tools/vector.py", line 211, in spatialindex
idx = QgsSpatialIndex(layer.getFeatures(request))
Exception: unknown"
I am using a MAC. I tried on both QGIS 2.18.2 and QGIS 3.0.3, and got the same error. I tried, as advised on a page, to export geometric attributes using MMQGIS, and then re-importing them on QGIS, but same error. I also heard that it could be useful to check the validity of points ; nonetheless as I am using all the major roads network in Africa, I get millions of points, and checking them would take hours and hours ... I tried on QGIS3 to compute the distance between points and line centers (which does not give me the answer I want, as it is not the closest distance, but I did so to check if it was working this way), and it worked well, so I guess the issue lays in the transformation of my line layer into points
Has someone faced this issue of spatial index error, and knows what is means exactly? Is there a way to correct the points, to get rid of those not correct if this is the issue ?

A: (1) Collect your lines into single Multipart object.

*

*Open the attribute table of your line layer.

*Create a new field to group all lines. I assume you create a field group with all values set to '1'.

*Run Singleparts to Multipart tool (in Vector | Geometry Tool).

*Open the attribute table of newly created layer Multipart and check if the record (row) is only one in this layer; and there is a group field (it's value is '1' apparently).

(2) Calculate distance

*

*Open the attribute table of your point layer.

*Create a new field (integer or decimal) with following expression:

 distance(
    closest_point(geometry(get_feature('Multipart', 'group', '1')), $geometry), $geometry
 )

A: From QGIS 3.22 you can use the Shortest line between features algorithm that does exactly what you want:

This is the result from a point and a line layer:

On the other hand, you can use the QgsSpatialIndex API to get what you want:
project = QgsProject.instance()

source = project.mapLayersByName('points')[0]
destination = project.mapLayersByName('streets')[0]

index = QgsSpatialIndex(QgsSpatialIndex.FlagStoreFeatureGeometries)
index.addFeatures(destination.getFeatures(), QgsFeatureSink.FastInsert)

features = []

for in_feature in source.getFeatures():

    igeom = in_feature.geometry()

    # 1 is to get only the first and closest feature
    nearest_list = index.nearestNeighbor(igeom, 1)

    request.setFilterFids(nearest_list)

    for dest_feature in destination.getFeatures(request):

        jgeom = dest_feature.geometry()

        shortest_line = igeom.shortestLine(jgeom)
        feature = QgsFeature()

        attrs = in_feature.attributes()
        attrs.extend(dest_feature.attributes())

        feature.setAttributes(attrs)
        feature.setGeometry(shortest_line)

        features.append(feature)

where features il the list with all the shortest lines between each point and the closest line. Then you can write all these features to a new vector layer.
Be aware if your source and destination layers have different CRS!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having issues summarizing years as decades in MySQL I was wondering if someone could spot the reason why my query is returning an error at the very end. The situation I am trying to solve is
For each decade since 1990 (1990, 2000, 2010), list the average MRSP of all books published in that decade, along with a count of copies sold and total sales $.
I was able to figure out the decades part with the following code
SELECT *,
CASE WHEN date_published BETWEEN '1990-01-01' AND '1999-12-31' THEN '1990'
WHEN date_published BETWEEN '2000-01-01' AND '2009-12-31' THEN '2000'
WHEN date_published BETWEEN '2010-01-01' AND '2019-12-31' THEN '2010'
ELSE 'Void'
END AS 'Decade', copies_sold
FROM book

However when I try to bring everything together in
SELECT 'Decade',
SUM(copies_sold) AS 'Copies Sold',
SUM(msrp*copies_sold) AS 'Total Sales',
SUM(msrp/copies_sold) AS 'Avg MSRP'

FROM
(SELECT *,
CASE WHEN date_published BETWEEN '1990-01-01' AND '1999-12-31' THEN '1990'
WHEN date_published BETWEEN '2000-01-01' AND '2009-12-31' THEN '2000'
WHEN date_published BETWEEN '2010-01-01' AND '2019-12-31' THEN '2010'
ELSE 'Void'
END AS 'Decade', copies_sold
FROM book)

FROM book

I get the following error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM book' at line 15"
Can anyone help me close this out? It would be super appreciated! The current fiddle is
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5464a4f1103bd4d6ed98e504be5ed7fe
The final output should look something like
Decade | Copies Sold | Total Sales| Avg MSRP
1990           5            10000          58

A: You should exclude dates earlier than 1990 with a WHERE condition; there's no need to bother with them.
You can calculate decade more easily with just 10*FLOOR(YEAR(date_published)/10).
There's no need for a subquery, and you do need to group by your decade.
SELECT
    10*FLOOR(YEAR(date_published)/10) AS Decade,
    SUM(copies_sold) AS 'Copies Sold',
    SUM(msrp*copies_sold) AS 'Total Sales',
    SUM(msrp/copies_sold) AS 'Avg MSRP'
FROM book
WHERE date_published > '1989-12-31'
GROUP BY 1

A: Errorneous tokens commented.
SELECT 'Decade',
SUM(copies_sold) AS 'Copies Sold',
SUM(msrp*copies_sold) AS 'Total Sales',
SUM(msrp/copies_sold) AS 'Avg MSRP'

FROM
(SELECT *,
CASE WHEN date_published BETWEEN '1990-01-01' AND '1999-12-31' THEN '1990'
WHEN date_published BETWEEN '2000-01-01' AND '2009-12-31' THEN '2000'
WHEN date_published BETWEEN '2010-01-01' AND '2019-12-31' THEN '2010'
ELSE 'Void'
END AS 'Decade' /* , copies_sold */
FROM book)

/* FROM */ book

copies_sold commented because this column is already selected in SELECT *.
FROM commented because book is subquery alias, not data source.


text:
Q: With vanilla JavaScript, how can I access data stored by jQuery's .data() method? And before someone says:
document.querySelector('.myElem').getAttribute('data-*')

No, is not what I'm looking for. jQuery's data() has dual functions. 1) It queries an HTML5 data attribute which can be seen in the HTML code like this:

$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

and 2) the ones that are set by .data(name, value) which are hidden in a jQuery internal Object, to which the documentation only says "to save information under the names 'events' and 'handle'", yet I haven't figured out a way to access them or what actually creates them.
So, my question stands, how can I access the jQuery data values from plain JavaScript?
Just so it's absolutely clear... let me put more emphasis: I don't want the data- HTML attributes, but the jQuery object data.

A: From the comments, your motivation to bypass $(...).data seems to be based on the fact that it's causing performance issues.
I totally agree with @meagar on that point, $(...).data shouldn't be expensive enough to cause bottlenecks. However, if you continously re-query and re-wrap DOM elements as jQuery elements (e.g. $('#someEl').data(...) multiple times rather than caching $('#someEl') and do $someEl.data(...), then it might be an issue.
Please also note that if you find yourself attaching a lot of data to DOM elements, you probably got your design wrong. Your data shouldn't live in the presentation layer and you shouldn't have to query the DOM or get a reference to a DOM element to access your data. Obviously, you might in some situations, but these shouldn't be the norm.
If you still want to build your own data feature, then here's an example. It's not optimized, but you should get the idea:
Note that WeakMap is only available in modern browsers, but without it we would be leaking memory, unless you provide a mechanism to destroy the cached attributes expendo object when the associated DOM element gets destroyed.
JSFIDDLE
JSPERF (the test might not be fair, since I'm not sure my implementation does everyting $(...).data does)
var data = (function () {
    var attributes = new WeakMap();

    return function (el, attr, val) {
        var elAttrs = attributes.get(el),
            isSetOperation = arguments.length > 2;

        if (isSetOperation) {
            if (!elAttrs) attributes.set(el, elAttrs = {});
            elAttrs[attr] = val;
        } else {
            return datasetOrCachedAttrsValue();
        }

        function datasetOrCachedAttrsValue() {
            var attrVal = el.dataset[attr];

            return typeof attrVal !== 'undefined'?
                attrVal:
                elAttrs && elAttrs[attr];
        }
    };
})();

var div = document.querySelector('div');

console.log(data(div, 'test')); //test
console.log(data(div, 'notexisting')); //undefined
data(div, 'exists', true);
console.log(data(div, 'exists')); //true

"would be leaking memory, unless you provide a mechanism to destroy the
  cached" - plalx. Well even with WeakMap it still leaks for the same reason why
  jQuery can cause leaks. See this demo. –  dfsq

That was a good concern from @dfsq, but here's a demo that actually shows how WeakMap allows garbage collection once they key is unreachable, as opposed to jQuery's implementation that will hold on data (unless $().remove is used I believe).
Use the profiler and record heap allocations over time and compare the results. Here's what I got from 6 clicks on each button (one type of button per snapshot). We can clearly see that $().data is leaking while the custom data implementation using a WeakMap is not.

*

*try to leak with $().data.

*try to leak with data

A: jQuery uses internal object called $.cache to store event handlers and data values. $.cache is a simple dictionary which can look something like this:
{ 1: { data: { role: "page"}, events: { click: ...} }, 2: { ... }}

The keys are all unique indexes corresponding to some DOM nodes. If your DOM element was previously touched by jQuery (attached events or to some data), you will see that it has a weird property similar to the one below:
jQuery17108624803440179676: 2

Here jQuery17108624803440179676 is a unique string generated by jQuery when it was loaded on the page. This unique identifier is called "expando" and is stored as
$.expando

Now that you know how to access an individual element's internal data by bypassing jQuery's data API...
$.cache[element[$.expando]]

...you may ask why jQuery uses an intermediate object to store all DOM data and events. The reason is that it is a way to avoid memory leaks, which would be the case if data and events handlers were stored directly in DOM elements properties (due to circular references).
Having said all that, I want to emphasize that you should not work with node data objects other than that via the jQuery Data API for the simple reason that it handles all the complex stuff behind the scenes.


text:
Q: ¿Cómo hacer split a un string en java - android Studio? Recibo de un WebService strings similares a este: 19 Y 19-A (son cruzamientos de calles).
lo que necesito, es que pueda quedarme con los valores 19 y 19-A, Eliminando la "Y" de la cadena, de forma que me queden en 2 strings, algo como esto:
String1=19
String2=19-A

Tiene que considerarse que, en algunos registros, la letra "y" puede existir como nombre de alguno de los dos cruzamientos, eso es lo que me está creando este dilema.
Anexo el código que tengo hasta ahora (lógicamente el string lo cambié para ayudar a ejemplificar:
    String string = "19 Y 19-A";
String[] parts = string.split("Y");
String part1 = parts[0]; // 19
String part2 = parts[1]; // 19-A

A: Siempre prefiero el uso de REGEX, pero otra opción valida es definir el separador como " Y " (ya que comentas: "en algunos registros, la letra "y" puede existir como nombre de alguno de los dos cruzamientos"), de esta forma obtendrías los valores requeridos.
  String string = "19 Y 19-A";
  String[] parts = string.split(" Y ");
  String part1 = parts[0]; //obtiene: 19
  String part2 = parts[1]; //obtiene: 19-A

A: Prueba con:
String[] parts = string.split("(?i)\\s+Y\\s+");

Explicación de la expresión regular:
NODO              EXPLICACIÓN
-----------------------------------------------------------------------
  (?i)            establece banderas (case-insensitive)
-----------------------------------------------------------------------
  \s+             espacio en blanco (\n, \r, \t, \f, y " ") (1 o
                  más veces (encontrando la mayor cantidad posible))
-----------------------------------------------------------------------
  Y               'Y'
-----------------------------------------------------------------------
  \s+             espacio en blanco (\n, \r, \t, \f, y " ") (1 o
                  más veces (encontrando la mayor cantidad posible))


text:
Q: Rendering browser through OpenGL I have a browser running on am embedded platform, and I am wondering if there is any advantage to rendering straight to OpenGL.  One that comes to mind is the cross-platform access to hardware acceleration.  Is anyone aware of any other advantages that may make the work worth it?

A: The would depend nearly entirely on the embedded platform in question.  Many embedded platforms have little or no hardware acceleration, in which case, it will not help.
However, if it does, and if the native browsers on your device are not already accelerated, there may be some benefit to this.  You'll have to decide whether the extra work involved is worth any benefits gained, though.


text:
Q: Evaluating $\sum_{0\leq k \leq l \leq n}\binom{k}{2}\binom{l}{k}\binom{n}{l}$ I'm trying to understand the process of evaluating this sum. I know the above equals to:
$$|\{(A,B,C)\mid A\subseteq B \subseteq C \subseteq [n] \wedge |A| = 2\}|$$
...Yet, how can I express this using $n$?

A: For a combinatorial proof, note that there are $\binom{n}{2}$ ways to select $A$ and then 3 independent choices for each of the remaining $n-2$ elements: be in $B\setminus A$, $C\setminus B$, or $[n] \setminus C$.  So the cardinality of your set is $\binom{n}{2}3^{n-2}$.

A: $$
\eqalign{
  & \sum\limits_{0\, \le \,k \le \,l\, \le \,n\;} {\left( \matrix{
  k \cr
  2 \cr}  \right)\left( \matrix{
  l \cr
  k \cr}  \right)\left( \matrix{
  n \cr
  l \cr}  \right)}  =   \cr
  &  = \sum\limits_{2\, \le \,k \le \,l\, \le \,n\;} {\left( \matrix{
  k \cr
  k - 2 \cr}  \right)\left( \matrix{
  l \cr
  l - k \cr}  \right)\left( \matrix{
  n \cr
  n - l \cr}  \right)}  =   \cr
  &  = \sum\limits_{2\, \le \,k \le \,l\, \le \,n\;} {{{k!} \over {2!\left( {k - 2} \right)!}}{{l!}
 \over {k!\left( {l - k} \right)!}}{{n!} \over {l!\left( {n - l} \right)!}}}  =   \cr
  &  = \sum\limits_{2\, \le \,k \le \,l\, \le \,n\;} {{1 \over {2!\left( {k - 2} \right)!}}
{1 \over {\left( {l - k} \right)!}}{{n!} \over {\left( {n - l} \right)!}}}  =   \cr
  &  = {{n!} \over {2!\left( {n - 2} \right)!}}\sum\limits_{2\, \le \,k \le \,l\, \le \,n\;}
 {{{\left( {n - 2} \right)!} \over {\left( {k - 2} \right)!\left( {l - k} \right)!\left( {n - l} \right)!}}}  =   \cr
  &  = \left( \matrix{
  n \cr
  2 \cr}  \right)\sum\limits_{\scriptstyle \left\{ {\matrix{
   {a,b,c}  \cr
   {a + b + c = n - 2}  \cr
 } } \right. \atop
  \scriptstyle \;}  {{{\left( {n - 2} \right)!} \over {a!b!c!}}}  =   \cr
  &  = \left( \matrix{
  n \cr
  2 \cr}  \right)3^{\,n - 2}  \cr}
$$

A: Use ${n \choose p}{p \choose q}={n \choose q} {n-q \choose p-q}$ two times below.
$$S=\sum_{0 \le k\le l \le n}{k \choose 2} {n \choose l}{k \choose k}=\sum_{0 \le k\le l \le n} {k \choose 2} {n\choose k}{n-k \choose l-k}$$
$$\implies S=\sum_{k=0}^{n} {k\choose 2} {n \choose k} \sum_{l=k}^{n} {n-k \choose l-k}=\sum_{k=0}^{n} {k\choose 2} {n \choose k} \sum_{j=0}^{n-k} {n-k \choose j}.$$
Here we took $l-k=j$
$$\implies S=\sum_{k=0}^{n}  {k\choose 2} {n \choose k} 2^{n-k}=\sum_{k=0}^{n}  {n\choose k} {k \choose 2} 2^{n-k}.$$
$$\implies {n \choose 2} \sum_{k=0}^{n}{n-2 \choose k-2}2^{n-k} =\implies 2^{n+2}{n \choose 2} \sum_{m=0}^{n-2}{n-2 \choose m} 2^{-m}={n \choose 2}2^{n-2}(1+1/2)^{n-2}= {n \choose 2} 3^{n-2}$$


text:
Q: Designing a "trial before signup" system securely How can I implement a "trial before signup" user system safely?
My thoughts so far are:

*

*User clicks "Try product"

*

*Controller creates new user

*

*sets is_trial = true

*sets trial_id = UUID()

*Set session/cookie trial_id = user.trial_id

*Future visits check session/cookie for trial_id, load user if present and found else redirect to signup/start-trial page.

I think this will function fine barring two people generating the same UUID, but my worry is a user could edit their cookies trial_id and spoof their way into someone else's (admittedly also trial) account.
I know the chance of someone guessing someone else's UUID is pretty small, but it's not impossible.
Is this how these systems are normally designed? How can I add more security?

A: I believe the method outlined is correct along with adding something such as JTW to either sign (to prevent tampering) or sign and encrypt the cookies.


text:
Q: JSP or .ascx equivalent for Scala? I'm working on a small MVC "framework" (it's really very small) in Scala. I'd like to be able to write my view files as Scala code so I can get lots of help from the compiler. Pre-compiling is great, but what I really want is a way to have the servlet container automatically compile certain files (my view files) on request so I don't have to shut down Jetty and compile all my source files at once, then start it up again just to see small changes to my HTML.
I do this a lot with .ascx files in .NET (the file will contain just one scriptlet tag with a bunch of C# code inside which writes out markup using an XmlWriter) and I love this workflow. You just make changes and then refresh your browser, but it's still getting compiled!
I don't have a lot of experience with Java, but it seems possible to do this with JSP as well. I'm wondering if this sort of thing is possible in Scala.
I have looked into building this myself (see more info here: http://www.nabble.com/Compiler-API-td12050645.html) but I would rather use something else if it's out there.

A: If you want something thats kinda like JSP/ASP/Erb but using Scala code you might want to take a look at Scalate.
Scalate is a Scala based template engine which allows you to use powerful Scala expressions instead of the limited JSP/JSF/JSTL EL expression language - while being completely statically typed so that templates are checked at edit/compile time for errors - and templates are reloaded on the fly as they are edited.
For JSP/ASP style of templates then try the Ssp templates in Scalate which are very JSP-like.
If you are mostly generating HTML/XML markup I'd also recommend giving the  Scaml templates in Scalate a try - they are Scala versions of HAML which lead to really DRY templates

A: This comes up fro me when I skip JSP/frameworks by writing servlets in Scala with embedded xml for templating:
class MyServlet extends HttpServlet {

def get(req) = {
 var title = "hello world"
 var link = "somepage"

   <title>{ title }</title>
   Click

}

def doGet(req: HttpServletRequest, res: HttpServletResponse) = {
 val out = new PrintWriter(res.getOutputStream())
 out.println(get(req))
 out.close
}

}

My solution has two parts:

*

*Use fsc instead of scalac

*Use FireBug, specifically its edit button.

The constant small changes I find myself making are to the style sheet (which does not require restarting Jetty), or playing with possible HTML alternatives. The best way to do that is to right-click the HTML, click Inspect Element, then press the edit button in the firebug console, and edit it on the spot. This means no more recovering of the site's state every time you make a change.
When you get it looking right, copy the changes over to scala and hit make.

A: There are lots of alternatives. One alternative, for instance, is to use JRebel (formely JavaRebel), and a background compilation process on-change (such as mvn scala:cc with Maven, for example).


text:
Q: Can I use app.use inside app.get with different paths I have this bit of code that takes the last 10 url requests in the path '/img' and put it in an array and then I have two conditions. One if the array length is already 10 then delete the last index and add the new one to the beggining of the list. And other if the index of url is already in the array delete that one so I do not have any repeated url in this list. Here is the code:
let recentPaths = [];

app.use('/img', (req, res, next) => {
const index = recentPaths.indexOf(req.originalUrl);
if (recentPaths.length === 10) {
recentPaths.pop();
}
if (index !== -1) {
  recentPaths.splice(index, 1);
}
recentPaths.unshift(req.originalUrl);
next();
});

and then I have this get function which is where I want to have the data from that array. Here is the code:
app.get('/stats/paths/recent' ,sendRecentPaths);
async function sendRecentPaths(req, res) {
  res.json(recentPaths);
}

It is working but my question is, can I do that first block of code inside this get function?
I mean, can I use the app.use() inside app.get() ? Because I want the request from the path '/img' to be sent in an array to the path '/stats/paths/recent'.

A: It's incorrect to put app.use inside app.get because middleware should be defined once, not on every request.
If the intention is to exchange data between middlewares that are executed within same request, they should communicate through response object:

res.locals
An object that contains response local variables scoped to the
  request, and therefore available only to the view(s) rendered during
  that request / response cycle (if any). Otherwise, this property is
  identical to app.locals.
This property is useful for exposing request-level information such as
  the request path name, authenticated user, user settings, and so on.

I.e. an array could be assigned to res.locals.recentPaths middleware and be read in another middleware. The problem with this case is that /img and /stats/paths/recent middlewares aren't executed within same request.
It's incorrect to store data to recentPaths variable because it persists between requests and is global for all users. If data should persist between requests and be specific to users, this should involve session management, a better place to store data is a database, not a variable.


text:
Q: Spring Security Header Based Authentication By default spring security operates by adding the JSESSIONID cookie to your session. And I have used and seen many header based forms of accomplishing the same result(often making use of a filter or two). But I feel this is something I should be able to set in the configuration. In the form of something like this:
config.setTokenLocation(TokenLocationEnum.HEADER)
config.setTokenName("Bearer")

or
config.setTokenLocation(TokenLocationEnum.COOKIE)
config.setTokenName("JSESSIONID")

I would like to try implementing this myself but I'd first like to see if anyone has any objections to the idea and why it is not already implemented.
Thanks

A: You can configure Spring Security as you want. Session management via JSESSIONID is just working out of box. For example, if you want to use Bearer OAuth 2.0 tokens you need to configure AuthServer. This is example of configuration from one of my projects:
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter
{
    private final AuthenticationManager authenticationManager;

    private final InGridSecurityProperties inGridSecurityProperties;

    @Autowired
    public AuthorizationServerConfig(AuthenticationManager authenticationManager, InGridSecurityProperties inGridSecurityProperties, GoogleConnectionFactory connectionFactory) {
        this.authenticationManager = authenticationManager;
        this.inGridSecurityProperties = inGridSecurityProperties;
        this.connectionFactory = connectionFactory;
    }

    @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception
    {
        clients.inMemory()
                        .withClient( inGridSecurityProperties.getClientId() )
                        .secret( inGridSecurityProperties.getClientSecret() )
                        .authorities( "ROLE_TRUSTED_CLIENT" )
                        .authorizedGrantTypes( inGridSecurityProperties.getGrantTypes() )
                        .scopes( inGridSecurityProperties.getClientScope() )
                        .accessTokenValiditySeconds(
                                        inGridSecurityProperties.getAccessTokenValiditySeconds() )
                        .refreshTokenValiditySeconds(
                                        inGridSecurityProperties.getRefreshTokenValiditySeconds() );
    }

    @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
    {
        security.tokenKeyAccess( "isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')" )
                        .checkTokenAccess( "hasAuthority('ROLE_TRUSTED_CLIENT')" );
    }

    @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                    throws Exception
    {
        endpoints
                        .authenticationManager( authenticationManager )
                        .tokenStore( jwtTokenStore() )
                        .tokenEnhancer( jwtAccessTokenConverter() );
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter()
    {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyPair keyPair = new KeyStoreKeyFactory(
                        new ClassPathResource( inGridSecurityProperties.getJwtKeyStore() ),
                        inGridSecurityProperties.getJwtKeyStorePassword().toCharArray() )
                        .getKeyPair( inGridSecurityProperties.getJwtKeyPairAlias(),
                                        inGridSecurityProperties.getJwtKeyPairPassword().toCharArray() );
        converter.setKeyPair( keyPair );
        return converter;
    }

}

More information you can find in Spring Security Documentation: http://docs.spring.io/spring-security/site/docs/current/reference/


text:
Q: Django Model Form Validation not validating Hey I am busy with Django forms working on custom validation etc, so when I test whether this validation is working it does not work I tried watching videos so to know where I am going wrong but I personally do not see the flaw.
I did a password validation and it does not raise the validation error to me even when I write two different passwords.
Code Below: models.py
class UserAccounts(models.Model):

    name = models.CharField(max_length=100, blank=False, null=False)
    last_name = models.CharField(max_length=100, blank=True, null=False)
    phone_number = PhoneNumberField(unique=True)
    email = models.EmailField(blank=False, null=False, unique=True)
    password = models.CharField(max_length=100, blank=False, null=False)
    verify_password = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.name

    def clean_password(self):

        passwd = self.cleaned_data_get('password')
        v_passwd = self.cleaned_data_get('verify_password')

        if passwd != v_passwd:
            raise ValidationError('Passwords do not match')

        return passwd

Code Below: forms.py
class UserAccountsForm(ModelForm):

    class Meta:
        model = UserAccounts
        fields = '__all__'

        widgets = {

            'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'}),

            'last_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}),

            'phone_number': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}),

            'email': forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}),

            'password': forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}),

            'verify_password': forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Verify Password'})

        }

    def clean_password(self):

        passwd = self.cleaned_data_get('password')
        v_passwd = self.cleaned_data_get('verify_password')

        if passwd != v_passwd:
            raise ValidationError('Passwords do not match')

        return passwd


text:
Q: How to get route name from action I am using MapMvcAttributeRoutes to set routes in my MVC application. Now I have a doubt is it possible to access a route name from action Index?
[HttpGet]
[Route("{language}/Home/Index", Name = "Home.Index")]
public ActionResult Index()
{
      //access route name Home.Index here?
      return View();
}

I wanted to say I tried something, but do not relly know where to start. I did some researching in forums and SO, but did not find any valid answer.
EDIT
In order to fully understand my question here is an example. Each view contains a partial view (header) that generates links for all languages of a current view. Some actions/views use AttributeRoutes and some use default routing from routeconfig. How can I decide when to call RouteUrl and when to call Action?


text:
Q: Large amount of data query I have a partition table, now about 200 multiple partitions, each partition table inside about 12 million data. Now select very slow, table index of the corresponding field has been established, but is still very slow, I see execution plan, found a large number of from the disk to read data, to me, I changed how to adjust and optimize it
   gjdd4=# \d t_bus_position_20160306_20160308
               Table "public.t_bus_position_20160306_20160308"
         Column         |              Type              |     Modifiers
------------------------+--------------------------------+--------------------
 pos_uuid               | character varying(20)          | collate zh_CN.utf8
 pos_line_uuid          | character varying(20)          |
 pos_line_type          | character varying(20)          |
 pos_bus_uuid           | character varying(20)          | collate zh_CN.utf8
 pos_dev_uuid           | character varying(20)          |
 pos_sta_uuid           | character varying(20)          |
 pos_drv_ic_card        | character varying(30)          |
 pos_lng                | character varying(30)          |
 pos_lat                | character varying(30)          |
 pos_bus_speed          | character varying(20)          |
 pos_real_time_status   | character varying(20)          |
 pos_gather_time        | timestamp(6) without time zone |
 pos_storage_time       | timestamp(6) without time zone |
 pos_is_offset          | boolean                        |
 pos_is_overspeed       | character varying(1)           |
 pos_cursor_over_ground | character varying(20)          |
 pos_all_alarms         | character varying(30)          |
 pos_is_in_station      | character varying(1)           |
 pos_closed_alarms      | character varying(30)          |
 pos_dis_to_pre_i       | integer                        |
 pos_odometer_i         | bigint                         |
 pos_relative_location  | real                           |
 pos_dis_to_pre         | real                           |
 pos_odometer           | double precision               |
 pos_gather_time1       | bigint                         |
Indexes:
    "idx_multi" btree (pos_bus_uuid, pos_gather_time DESC)
    "idx_trgm" btree (replace(to_char(pos_gather_time, 'YYYYMMDDHH24'::text), ' '::text, ''::text))
    "idx_trgm1" btree (to_char(pos_gather_time, 'YYYYMMDD'::text))
    "tp_20160306_20160308_pos_dev_uuid_idx" btree (pos_dev_uuid)
Check constraints:
    "t_bus_position_20160306_20160308_pos_gather_time_check" CHECK (pos_gather_time >= '2016-03-06 00:00:00'::timestamp without time zone AND
 pos_gather_time < '2016-03-09 00:00:00'::timestamp without time zone)

The plan is like this.
    gjdd4=# explain(costs,buffers,timing,analyze) select pos_bus_uuid from    test2 group by pos_bus_uuid;
     HashAggregate  (cost=802989.75..802993.00 rows=325 width=21) (actual time=42721.528..42721.679 rows=354 loops=1)
       Group Key: pos_bus_uuid
       Buffers: shared hit=3560 read=567491
       I/O Timings: read=20231.511
       ->  Seq Scan on test2  (cost=0.00..756602.00 rows=18555100 width=21) (actual time=0.067..27749.533 rows=18555100 loops=1)
             Buffers: shared hit=3560 read=567491
             I/O Timings: read=20231.511
     Planning time: 0.116 ms
     Execution time: 42721.839 ms
    (9 rows)

    Time: 42722.629 ms

A: Your query does not do any real aggregation but merely distinct. If this is what you really want (all distinct pos_bus_uuid values) than you can use a technique called loose index scan:
Here the tailored query assuming pos_bus_uuid has a not null constraint:
WITH RECURSIVE t AS (
    (SELECT pos_bus_uuid FROM test2 ORDER BY pos_bus_uuid LIMIT 1)  -- parentheses required
  UNION ALL
     SELECT (SELECT pos_bus_uuid FROM test2
              WHERE pos_bus_uuid > t.pos_bus_uuid ORDER BY pos_bus_uuid LIMIT 1)
       FROM t
      WHERE t.pos_bus_uuid IS NOT NULL
   )
SELECT pos_bus_uuid FROM t WHERE pos_bus_uuid IS NOT NULL;

Your index pos_bus_uuid should be good enough for this query.

A: Markus Winand's answer is correct - you need to copy the full sql, syntax error is due to your not including last line - 'SELECT pos_bus_uuid FROM t WHERE pos_bus_uuid IS NOT NULL;'
Would have added this as a comment, but reputation too low to comment.


text:
Q: Vertically STACK bootstrap input-group controls So the normal behavior of the input-group controls of bootstrap is horizontal stacking within the 100% of the container. What I'd like to do is stack them on top of each other so instead of having this:

I'll have this:

(If you wonder, the vertical image is done by paint :))
So far I have tried

    One
    <select class="form-control"><option>1</option></select>

    One
    <select class="form-control"><option>1</option></select>

And this (which I don't think is supported by bootstrap)

        One
        <select class="form-control"><option>1</option></select>

        One
        <select class="form-control"><option>1</option></select>

As you can see, it's stacked as I want it to be - only that it is very small (not spanned over 100% of the container) AND the joined part has border-radius.
Must I tamper with/override the css styles of the input-group to achieve my goal is there any other preferred/supported way?

A: I just used this with Bootstrap 4. I added an additional CSS rule in order to remove the thick border between input fields.

.vertical-input-group .input-group:first-child {
    padding-bottom: 0;
}
.vertical-input-group .input-group:first-child * {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}
.vertical-input-group .input-group:last-child {
    padding-top: 0;
}
.vertical-input-group .input-group:last-child * {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
}
.vertical-input-group .input-group:not(:last-child):not(:first-child) {
    padding-top: 0;
    padding-bottom: 0;
}
.vertical-input-group .input-group:not(:last-child):not(:first-child) * {
    border-radius: 0;
}
.vertical-input-group .input-group:not(:first-child) * {
    border-top: 0;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

        <input type="text" class="form-control" id="sao" placeholder="Attention Of">

        <input type="text" class="form-control" id="ad1" placeholder="Line 1">

        <input type="text" class="form-control" id="ad2" placeholder="Line 2">

        <input type="text" class="form-control" id="ad3" placeholder="Line 3">

        <input type="text" class="form-control" id="ad4" placeholder="Line 4">

        <input type="text" class="form-control" id="ad5" placeholder="City">

        <input type="text" class="form-control" id="county" placeholder="County">

        <input type="text" class="form-control" id="postalcode" placeholder="Postal Code">

Vertical Aligned with thin border


text:
Q: Pandas TypeError: can only concatenate str (not "int") to str I have a problem where two almost identical html files create different behavior on the code. If i choose the HTML file in the first picture, pandasGUI will load the dataframe just fine. However if i choose second HTML file, it throws a typeerror as stated in the title. I have tried to fix this on and off for three weeks and i am completely lost. Can anyone help? Code below.
import pandas as pd
from scipy.interpolate import interp1d
from pandasgui import show

pd.set_option('display.max_columns', 100)
pd.set_option('precision', 3)
file = ''

def choose_file():
    global file
    i = input("Please choose an option below: \n"
              "1: Own Team \n"
              "2: Shortlist \n")
    if (i == '1'):
        file = './own_team.html'
    elif (i == '2'):
        file = './shortlist.html'
    return file

file = choose_file()
attribute_view = pd.read_html(file)

map = interp1d([1, 7000], [1, 100])

df = attribute_view[0]

if(file == './shortlist.html'):
    for column in ['Inf', 'Name', 'Age', 'Best Pos', 'Personality', 'Acc', 'Wor', 'Vis', 'Thr', 'Tec', 'Tea', 'Tck', 'Str', 'Sta', 'TRO', 'Ref', 'Pun', 'Pos', 'Pen', 'Pas', 'Pac', '1v1', 'OtB', 'Nat', 'Mar', 'L Th', 'Lon', 'Ldr', 'Kic', 'Jum', 'Hea', 'Han', 'Fre', 'Fla', 'Fir', 'Fin', 'Ecc', 'Dri', 'Det', 'Dec', 'Cro', 'Cor', 'Cnt', 'Cmp', 'Com', 'Cmd', 'Bra', 'Bal', 'Ant', 'Agi', 'Agg', 'Aer']:
        df[column] = df[column].replace('-', 0)
    print(df)

df['Team_dna'] = (df['Agg'] + df['Ant'] + df['Det'] + df['Tea'] + df['Wor'] + df['Acc'] + df['Sta'])

# Sweeper Keeper - Attack
df['sk_at'] = map((df['Aer'] + df['Com'] + df['Fir'] + df['Han'] + df['Pas'] + df['Ref'] + df['TRO'] + df['Thr'] + df['Cmp'] + df['Dec'] + df['Vis'] + df['Acc']) * 40)

EDIT:
Full traceback:
Please choose an option below:
1: Own Team
2: Shortlist
2
Traceback (most recent call last):
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 149, in na_arithmetic_op
    result = expressions.evaluate(op, str_rep, left, right)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\computation\expressions.py", line 208, in evaluate
    return _evaluate(op, op_str, a, b)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\computation\expressions.py", line 70, in _evaluate_standard
    return op(a, b)
TypeError: can only concatenate str (not "int") to str

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/Github/FM20-Analysis/FM.py", line 36, in <module>
    df['sk_at'] = map((df['Aer'] + df['Com'] + df['Fir'] + df['Han'] + df['Pas'] + df['Ref'] + df['TRO'] + df['Thr'] + df['Cmp'] + df['Dec'] + df['Vis'] + df['Acc']) * 40)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\common.py", line 64, in new_method
    return method(self, other)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\__init__.py", line 503, in wrapper
    result = arithmetic_op(lvalues, rvalues, op, str_rep)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 197, in arithmetic_op
    res_values = na_arithmetic_op(lvalues, rvalues, op, str_rep)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 151, in na_arithmetic_op
    result = masked_arith_op(left, right, op)
  File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 94, in masked_arith_op
    result[mask] = op(xrav[mask], yrav[mask])
TypeError: can only concatenate str (not "int") to str

Process finished with exit code 1

A: the second image has values '-' in some columns. This will cast the entire column to a string and you won't be able to run arithmetic operations. This should do!
df = df.replace('-', 0)


text:
Q: How to fix image builder internal exception in android? I imported a project from my friend
but it always had a red cross in the project explore on eclipse
The project was built automatically, thus I check the error log.
and here's the following exception

I googled it but failed to find any solution...
anybody knows why?
BTW, is it okay if my package name contains capitalized word?


text:
Q: There is this unwanted space between my footer and main content I've been stuck on this issue for hours and hours at this point. I've been trying to work through it on my own but I am just unable to figure it out. Someone save me!
Problem: Initially the problem was that my footer wouldn't stick to the bottom of the page, so I followed this popular YouTuber's tutorial on how to fix it using flex. Here's the vid: Easy sticky footer - stop a footer from floating up a short page!. This caused a new issue to arise, now there is this extra white space between my footer and the main content which I think is due to the "margin-top: auto" I added to the footer per the tutorial. This issue isn't apparent in the mobile view of my page but as I expand the page, the main content rises to the top.

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html {
  height: 100%
}

body {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.main__wrapper {
  display: grid;
  grid-template-columns: 1fr;
  grid-auto-rows: repeat(4, 1fr);
  grid-template-areas: "sec1" "sec2" "sec3" "sec4";
}

p {
  margin: 10px 0 10px 0;
}

button {
  border: none;
  border-radius: 4px;
  color: white;
  width: 77px;
  height: 18px;
  font-family: 'Roboto', sans-serif;
  font-size: 8px;
  font-weight: 400;
}

button:hover {
  border-width: 1px;
  border-style: double;
  border-color: rgb(255, 114, 114);
}

.header__text {
  font-size: 17.4px;
}

.header__text span {
  font-size: 0.6em;
}

h3:first-of-type {
  font-size: 8.22px;
  color: #908B87;
}

h3:last-of-type {
  font-size: 9.35px;
  margin-top: 1.3em;
}

.header__wrapper {
  display: flex;
  justify-content: center;
  background-image: url("../images/nycforheader.jpeg");
  background-size: cover;
  background-position-y: 40%;
  font-family: 'Roboto', sans-serif;
  color: white;
  flex-direction: column;
  height: 88px;
  min-height: 12.6vh;
}

.headertext__grouped {
  margin-left: 2em;
}

.navbar__menu {
  display: block;
  border-top: solid #908B87 1.15px;
  border-bottom: solid #908B87 1.15px;
}

#navbar__list {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  height: 4vh;
  width: 50%;
}

#navbar__list li {
  list-style: none;
  font-family: 'Roboto', sans-serif;
  font-size: 6.02px;
}

#navbar__list li a {
  text-decoration: none;
  color: #000000;
}

#navbar__list li a:hover {
  text-decoration: underline red;
  text-underline-offset: 100%;
}

.landing__container {
  display: flex;
  flex-direction: column;
  box-shadow: #000000;
}

.landing__container h2 {
  font-family: 'Roboto', sans-serif;
  font-size: 13.62px;
}

.landing__container p {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  font-size: 9px;
}

#section1 {
  grid-area: sec1;
}

.section2 {
  grid-area: sec2;
}

.section3 {
  grid-area: sec3;
}

.section4 {
  grid-area: sec4;
}

.your-active-class,
.section3 {
  padding: 14px 0 14px 14px;
  background: radial-gradient(100% 100% at 50% 0%, rgba(233, 211, 160, 0.65) 28.12%, rgba(255, 255, 255, 0) 100%);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 25%);
}

.section2,
.section4 {
  padding: 14px 14px 14px 0;
  background: radial-gradient(100% 100% at 50% 0%, rgba(212, 168, 138, 0.65) 28.12%, rgba(255, 255, 255, 0) 100%);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 25%);
}

.section2,
.section4 {
  text-align: right;
}

#s2_button,
#s4_button {
  text-align: right;
}

#s2_button button {
  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('../images/time-square.jpeg');
  background-size: cover;
  background-position: center;
}

#section3 {
  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('../images/nyc-hotel.jpeg');
  background-size: cover;
  background-position: center;
}

#s4_button button {
  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('../images/statue-liberty.jpeg');
  background-size: cover;
  background-position-y: 21%;
}

footer {
  display: flex;
  justify-content: space-around;
  text-align: center;
  align-items: center;
  height: 9vh;
  margin-top: auto;
  background-color: #908B87;
}

footer a {
  text-decoration: none;
  color: white;
  font-family: 'Roboto', sans-serif;
}

.footer__list {
  line-height: 10%;
}

.footer__list li {
  display: inline-block;
  list-style: none;
  font-size: 8.02px;
  margin-inline: 8px;
}

.social__icons {
  display: inline-block;
  margin-inline: 8px;
  font-size: 0.8em;
}

footer a:hover {
  color: #ffffffcc;
}

/* tablet design */

@media screen and (min-width: 768px) {
  .header__text {
    font-size: 25.4px;
  }
  h3:first-of-type {
    font-size: 12.22px;
    color: #908B87;
  }
  h3:last-of-type {
    font-size: 12.35px;
    margin-top: 1.3em;
  }
  .header__wrapper {
    display: flex;
    justify-content: center;
    background-size: cover;
    font-family: 'Roboto', sans-serif;
    color: white;
    flex-direction: column;
    height: 99px;
    min-height: 12.6vh;
  }
}

New York City Travel Guide

USA

#1 in Best Places to Visit In NYC

Why Go To New York City

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pulvinar interdum ipsum, vel ullamcorper arcu volutpat id. Nullam vel lorem vitae eros tempus aliquam. Nunc at ante non neque vestibulum sagittis. Etiam lobortis massa vitae quam
          eleifend lobortis. Nam non ligula at arcu volutpat fringilla vel iaculis quam. Vivamus non orci nec justo accumsan consectetur. Donec egestas arcu non ligula blandit suscipit. Aenean fermentum ex ac nisi porta iaculis. Ut dapibus eros at quam
          semper aliquam sit amet quis massa. Duis in velit eget risus commodo convallis. Sed at lorem a nibh pulvinar viverra. Aenean varius sed dolor pretium condimentum.

32 Best Things To Do in New York City

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pulvinar interdum ipsum, vel ullamcorper arcu volutpat id. Nullam vel lorem vitae eros tempus aliquam. Nunc at ante non neque vestibulum sagittis. Etiam lobortis massa vitae quam
          eleifend lobortis. Nam non ligula at arcu volutpat fringilla vel iaculis quam. Vivamus non orci nec justo accumsan consectetur. Donec egestas arcu non ligula blandit suscipit. Aenean fermentum ex ac nisi porta iaculis. Ut dapibus eros at quam
          semper aliquam sit amet quis massa.

          <button type="button">Click To View</button>

Best Hotels in New York City

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pulvinar interdum ipsum, vel ullamcorper arcu volutpat id. Nullam vel lorem vitae eros tempus aliquam. Nunc at ante non neque vestibulum sagittis. Etiam lobortis massa vitae quam
          eleifend lobortis. Nam non ligula at arcu volutpat fringilla vel iaculis quam. Vivamus non orci nec justo accumsan consectetur. Donec egestas arcu non ligula blandit suscipit. Aenean fermentum ex ac nisi porta iaculis. Ut dapibus eros at quam
          semper aliquam sit amet quis massa.

        <button id="section3" type="button">Click To View</button>

What to Eat in New York City

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pulvinar interdum ipsum, vel ullamcorper arcu volutpat id. Nullam vel lorem vitae eros tempus aliquam. Nunc at ante non neque vestibulum sagittis. Etiam lobortis massa vitae quam
          eleifend lobortis. Nam non ligula at arcu volutpat fringilla vel iaculis quam. Vivamus non orci nec justo accumsan consectetur. Donec egestas arcu non ligula blandit suscipit. Aenean fermentum ex ac nisi porta iaculis. Ut dapibus eros at quam
          semper aliquam sit amet quis massa.

          <button type="button">Click To View</button>

About Us

Contact

Newsletters

Store

      <ion-icon name="logo-facebook"></ion-icon>

      <ion-icon name="logo-twitter"></ion-icon>

A:
Initially the problem was that my footer wouldn't stick to the bottom
of the page

There are many successful approaches to achieving this effect, but one of the simplest, oldest and most broadly supported is to use absolute positioning on the  and  and apply overflow: auto to the  element.
In the example below you can delete text from (or add text to) the  element. You will see that the  remains positioned at the bottom of the viewport no matter how much or how little text the  element contains.

Working Example 1: (Run Code Snippet and click Full Page)

body {
  margin: 0;
}

header,
footer {
  position: absolute;
  left: 0;
  display: block;
  width: 100vw;
  height: 100px;
  background-color: rgb(127, 127,  0);
}

main {
  height: calc(100vh - 200px);
  min-height: calc(100vh - 200px);
  max-height: calc(100vh - 200px);
  margin-top: 100px;
  padding: 0 18px;
  overflow: auto;
}

header {
  top: 0;
}

footer {
  top: calc(100vh - 100px);
}

h2 {
  color: rgb(255, 255, 255);
  text-align: center;
  text-transform: uppercase;
  height: 100px;
  line-height: 100px;
  margin: 0;
  padding: 0;
}

Header

Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversations?"

So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.

There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh dear! I shall be late!" (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.

In another moment down went Alice after it, never once considering how in the world she was to get out again.

The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.

Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled "ORANGE MARMALADE", but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.

"Well!" thought Alice to herself, "after such a fall as this, I shall think nothing of tumbling down stairs! How brave they'll all think me at home! Why, I wouldn't say anything about it, even if I fell off the top of the house!" (Which was very likely true.)

Down, down, down. Would the fall never come to an end? "I wonder how many miles I've fallen by this time?" she said aloud. "I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think—" (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a very good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) "—yes, that's about the right distance—but then I wonder what Latitude or Longitude I've got to?" (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.)

Presently she began again. "I wonder if I shall fall right through the earth! How funny it'll seem to come out among the people that walk with their heads downward! The Antipathies, I think—" (she was rather glad there was no one listening, this time, as it didn't sound at all the right word) "—but I shall have to ask them what the name of the country is, you know. Please, Ma'am, is this New Zealand or Australia?" (and she tried to curtsey as she spoke—fancy curtseying as you're falling through the air! Do you think you could manage it?) "And what an ignorant little girl she'll think me for asking! No, it'll never do to ask: perhaps I shall see it written up somewhere."

Footer

Alternatively, you can tweak the setup above very slightly to build a display which no longer has an absolutely positioned .
Working Example 2:

body {
  margin: 0;
}

header,
footer {
  display: block;
  width: 100%;
  height: 100px;
  background-color: rgb(127, 127,  0);
}

main {
  min-height: calc(100vh - 200px);
  margin-top: 100px;
  padding: 0 18px;
  overflow: auto;
}

header {
  position: absolute;
  top: 0;
  left: 0;
}

h2 {
  color: rgb(255, 255, 255);
  text-align: center;
  text-transform: uppercase;
  height: 100px;
  line-height: 100px;
  margin: 0;
  padding: 0;
}

Header

Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversations?"

So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.

There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh dear! I shall be late!" (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.

In another moment down went Alice after it, never once considering how in the world she was to get out again.

The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well.

Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled "ORANGE MARMALADE", but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody underneath, so managed to put it into one of the cupboards as she fell past it.

"Well!" thought Alice to herself, "after such a fall as this, I shall think nothing of tumbling down stairs! How brave they'll all think me at home! Why, I wouldn't say anything about it, even if I fell off the top of the house!" (Which was very likely true.)

Down, down, down. Would the fall never come to an end? "I wonder how many miles I've fallen by this time?" she said aloud. "I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think—" (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a very good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) "—yes, that's about the right distance—but then I wonder what Latitude or Longitude I've got to?" (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.)

Presently she began again. "I wonder if I shall fall right through the earth! How funny it'll seem to come out among the people that walk with their heads downward! The Antipathies, I think—" (she was rather glad there was no one listening, this time, as it didn't sound at all the right word) "—but I shall have to ask them what the name of the country is, you know. Please, Ma'am, is this New Zealand or Australia?" (and she tried to curtsey as she spoke—fancy curtseying as you're falling through the air! Do you think you could manage it?) "And what an ignorant little girl she'll think me for asking! No, it'll never do to ask: perhaps I shall see it written up somewhere."

Footer


text:
Q: What is the earliest hook you can piggyback on to check terms/taxonomy for a collection view? I am attempting to set up some conditional logic based on whether or not get_the_terms( $post->ID, 'product_cat' ) has the term 'Photographs' in it. Currently I'm using the wp hook, but that doesn't seem to run until the primary Query has already ran.. which I need to modify.
This has to be done because I basically need what appears to be two different front-end stores, but of course it needs to all be together in the back-end Woo admin.

A: You will find the Codex Action Reference handy - while it doesn't list everything, it gives a good overview of action order which can help locate the correct action if the one you're using runs too late.
In your case, wp does indeed run after the query is run, but looking at that list it appears - depending exactly on what logic you're wanting to run - that pre_get_posts would be a good choice for you. This is actually a commonly used action that, quite powerfully, allows you to modify almost anything about the query before it runs.
Not seeing your code it's a little difficult to anticipate exactly what you want this to perform, but I am guessing you're after something like this:
add_action( 'pre_get_posts', 'wpse202063_photographs_term' );

function wpse202063_photographs_term( $query ){
  if( ! is_admin() && $query->is_main_query() && is_singular( 'product' ) ){
    $post_object = get_page_by_path( $query->query['name'], 'OBJECT', 'product' );
    if( has_term( 'photographs', 'product_cat', $post_object ) ){
      // modify the query here as you need, using $query->set()
    }
  }
}

When you're viewing a single post of the post type 'product', this should allow you to modify the $query object to change whatever you need.1
It's important to note the snippet above is just preliminary - this might not be the fastest way to do what you want to do; it also assumes you're using pretty permalinks.
1 Note that pre_get_posts passes $query by reference, so there is no need to globalise $wp_query to make your changes - you can just make them directly using $query->set( 'query_var', 'value' ); - obviously replacing 'query_var' with the var you want to modify and the 'value' with what you want to set it to (you can use an array also).


text:
Q: iOS Flutter XCode : Module 'file_picker' not found I ran the app nothing wrong happened, but when i tried to Archive, it has an error
Module 'file_picker' not found

Here's where the error happened
#import "GeneratedPluginRegistrant.h"

#if __has_include(<file_picker/FilePickerPlugin.h>)
#import <file_picker/FilePickerPlugin.h>
#else
@import file_picker;
#endif

it was at GeneratedPluginRegistrant.m


text:
Q: Django admin: use checkboxes in list view in list_filter() I have a model Transaction with a ForeignKey to another model (TransactionState) on state field. So in admin.py I have:
class TransactionAdmin(admin.ModelAdmin):
    ...
    list_filter = ('state', )
    ...

In TransactionState I have records like "paid", "unpaid", "delivered", "canceled", Etc. and it works fine but I want to be able to filter using checkboxes to allow multiple selection like "paid" OR "delivered". It's possible?

A: For all models
You can easily override the django admin templates to customize the admin UI.
To edit the sidebar filter, just add a templates/admin/filter.html file, and write your custom HTML with radio buttons.
Note that this will change the sidebar filter for all models.
For a single model
If you want to change the filter for a single model, you can specify a template for a ListFilter:
class FilterWithCustomTemplate(admin.SimpleListFilter):
    template = "custom_template.html"

Example
As a reference example, check is the default template for filter.html.

A: *

*Radio buttons cannot have multiple selection, you would need to make them check boxes.

*What you are looking for is making custom filters. I would suggest instead of overwriting the Filter List to contain a check form with check boxes, add a custom filter with each option as a filter. Use this link and scroll down to the SimpleListFilter and you will be able to code it with 5-10 LOC.


text:
Q: Variants of rigid monoidal category for infinite dimensional spaces It is well-known that the notion of a rigid monoidal category does not interact well with infinite-dimensional spaces.  To be more precise, the category of all vector spaces is not rigid, see for example question 1 or question 2.

Are there any related and/or weaker notions of "rigid monoidal category" which would allow consideration of infinite dimensional vector spaces (for example) in some sense?

I am not a category theorist, but have a functional analysis background.  I would be very happy to have an answer which used extra structure on the spaces (e.g. topology? a (complete) inner-product?)
Update: For example, consider the category of Banach spaces with bounded linear maps (or contractions, if you prefer) and the projective tensor product to obtain a symmetric monoidal category.  This nearly satisfies the conditions to be a star-autonomous category with the usual Banach space dual, as it is true that
$$ \mathcal B(E \widehat\otimes F, G^*) \cong \mathcal B(E, (F\widehat\otimes G)^*). $$
However, the map $*$ is only a faithful functor, not full, as $\mathcal B(E,F) \rightarrow \mathcal B(F^*,E^*), T\mapsto T^*$ is not surjective, in general.  I think one can get further by using the Chu construction.
However, somehow this example feels wrong to me.  I think the reason why is that I'd like to:

Capture both the evaluation ($X^*\otimes X\rightarrow 1$) and coevaluation ($1\rightarrow X^*\otimes X$) maps, in some sense.


text:
Q: Is the chunk size a limit to the max data size that can be associated with a shard key value? I haven't read about the relation between chunk size and the data size associated to a single shard key value in a collection, so, another way to ask the question could be, can a shard key span more than one chunk?

A:
can a shard key span more than one chunk?

No. A chunk in MongoDB is a logical contiguous range of one or more shard key values. A unique shard key value cannot exist in more than a single chunk range, but many documents may have the same shard key. The cardinality for your chosen shard key determines the granularity of documents that can be represented in a chunk range (with the lowest granularity being a chunk that represents a single shard key value).
The relationship between shard key and chunks is illustrated in the following diagram from the MongoDB documentation explaining Choosing a Shard Key:

Is the chunk size a limit to the max data size that can be associated with a shard key value

No. The chunk size determines the approximate size of documents expected to be represented by a chunk range (by default, 64MB). If a chunk range is observed to be approaching (or possibly exceeding) the configured chunk size, MongoDB will attempt to split that single chunk into multiple chunks representing smaller contiguous ranges of the shard key. Chunk splits update the sharded cluster metadata but do not involve copying documents between shards. MongoDB's sharded cluster balancer uses migration thresholds to determine when it is appropriate to migrate chunks and associated documents between available shards.
If MongoDB cannot split a chunk that exceeds the configured chunk size (for example, due to a low cardinality shard key), that chunk will be marked as jumbo. Jumbo chunks are problematic as they will lead to an imbalance of data distribution within your sharded cluster: the balancer will no longer attempt to split or migrate jumbo chunks.
The default chunk size works well for most deployments, however it is possible to modify the chunk size if there is a more appropriate setting for your deployment or use case. A smaller chunk size will lead to more frequent chunk split and migration activity; a larger chunk size will lead to more I/O for individual chunk operations such as migrations. The documentation for modifying the chunk size notes several considerations which are worth reviewing before changing this setting.


text:
Q: Snowflake external function throws "with remote service error: 400" when calling AWS lambda through API gateway Am trying to call AWS lambda function through Snowflake external function via API gateway.
I had followed the snowflake documentation steps and everything works fine(I can retrieve results in snowflake) when I had used the examples which is there in the document.
But upon modifying the lambda code for as per the flow (Trying to replicate
https://medium.com/snowflake/governed-access-to-files-and-data-sharing-using-snowflake-unstructured-data-management-193b6fcda65e
), i could succesfully execute via lambda function only and not through snowflake external function.
It returns:
Request failed for external function GET_PDF_INFO with remote service error: 400"

When calling through AWS lambda function test code,am passing below JSON payload to test,which successfully returns
{
  "body":
    "{ \"data\": [ [ 0, \"<pre signed url>", \"page\" ], [ 1, \"<pre signed url>", \"life, the universe, and everything\" ] ] }"
}

But when called from snowflake i believe the JSON payload looks different as we see from the error:
Request failed for external function GET_PDF_INFO with remote service error: 400 '{ "data":[ [0,<pre signed url>","pdf"] ] }'; requests batch-id: 01a005a8-0000-1a86-0002-0d2e00016abe:2:0; request batch size: 1 rows; request retries: 0; response time (last retry): 1.67186s

Please suggest

A: Apologize my bad!! Issue due to wrong s3 file name been passed to the payload.After correcting it,i could retrieve the output from AWS lambda to Snowflake.


text:
Q: Understanding Linux FAT fs (FAT, VFAT, FAT32, exFAT) support I'm trying to understand which FAT based filesystems my Real Time 2.6 Linux supports. I have tried 3 things:

*

*/proc/filesystems shows vfat among others non-relevant for the question (like ext2, etc)

*/proc/config.gz shows:
# DOS/FAT/NT Filesystems
#
CONFIG_FAT_FS=y
CONFIG_MSDOS_FS=y
CONFIG_VFAT_FS=y
CONFIG_FAT_DEFAULT_CODEPAGE=437
CONFIG_FAT_DEFAULT_IOCHARSET="ascii"
# CONFIG_NTFS_FS is not set

*Commands like ls /lib/modules/$(uname -r)/kernel/fs show nothing as .../fs folder doesn't exist.
So, looking at this, is safe to asume that FAT and VFAT are supported, but what about FAT32 or exFAT? It's not explicitly specified. How can I know?

A: The FAT drivers include support for FAT32; it's treated as a variant along with FAT12 and FAT16. If you see vfat in /proc/filesystems, then FAT32 is supported.
exFAT is supported, in recent kernels, by a specific exFAT driver, with its own configuration option (EXFAT_FS). It's listed separately in /proc/filesystems.
exFAT support is also available as a FUSE exFAT driver.


text:
Q: Delete ptr resolves in an access-violation exception writing to 0 I got the following code in which last statement I try to delete a pointer to dynamically created memory.
But as soon as I get to the instruction a Access Violation exception is raised saying :

Unhandled exception at 0x0094c91f in
  Server.exe: 0xC0000005: Access
  violation reading location 0x00000000.

But when I step through it with the debugger it contains a valid address with valid data in it... I don't realize what I'm doing fatally wrong here...
Any suggestions?
void CServer::HandleAcceptRequest(ACCEPT_REQUEST* pRequest)
{
    //Add the new connection socket to the connection handler
    m_pConnectionHandler->AddConnection(pRequest->m_NewConnection);
    //Associate the new connections´ socket handle with the IOCP
    if(!m_pCompletionPort->AssociateHandle((HANDLE)pRequest->m_NewConnection, 0))
    {
        MessageBox(NULL, "Could not associate a socket handle with the completion port", "", MB_ICONERROR | MB_OK);
        DebugBreak();
    }

    //Create a new COMM_REQUEST and initialize a Recv-Request
    COMM_REQUEST* pCommRequest = new COMM_REQUEST;
    memset(pCommRequest, 0, sizeof(COMM_REQUEST));
    pCommRequest->Socket = pRequest->m_NewConnection;
    pCommRequest->m_RequestType = BASIC_REQUEST::RECV;

    WSABUF* buf = new WSABUF;
    buf->buf = pCommRequest->cBuf;
    buf->len = Inc::COMMUNICATION_BUFFER_SIZE;
    DWORD dwFlags = 0;
    if(WSARecv(pCommRequest->Socket, buf, 1, NULL, &dwFlags, pCommRequest, NULL))
    {
        DWORD dwRet = WSAGetLastError();
        if(dwRet != WSA_IO_PENDING)
        {
            MessageBox(NULL, "WSARecv() failed", "", MB_ICONERROR | MB_OK);
            DebugBreak();
        }
    };

    //Delete the old ACCEPT_REQUEST structure
    delete pRequest;
}

EDIT: I did allocate the memory in another function in the main thread
bool CConnectionHandler::AcceptNewConnection(SOCKET ListenSocket, unsigned nCount)
{
    DWORD dwBytesReceived = 0;
    ACCEPT_REQUEST* pOverlapped = nullptr;

    for(unsigned n = 0; n < nCount; n++)
    {
        dwBytesReceived = 0;
        pOverlapped = new ACCEPT_REQUEST;
        memset(pOverlapped, 0, sizeof(ACCEPT_REQUEST));
        pOverlapped->m_RequestType = ACCEPT_REQUEST::ACCEPT;

        //add the ListenSocket to the request
        pOverlapped->m_ListenSocket = ListenSocket;
        //invalidate the new connection socket
        pOverlapped->m_NewConnection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if(pOverlapped->m_NewConnection == INVALID_SOCKET)
        {
            delete pOverlapped;
            return false;
        }

        // call 'AcceptEx'
        if(m_lpfnAcceptEx(pOverlapped->m_ListenSocket, pOverlapped->m_NewConnection, pOverlapped->cOutputBuffer, 0, sizeof(sockaddr_in) + 16, sizeof(sockaddr_in) + 16, &dwBytesReceived, pOverlapped) == FALSE)
        {
            DWORD dwRet = WSAGetLastError();
            if(dwRet == ERROR_IO_PENDING)
                continue;
            else
                return false;
        }
    }

    return true;
};

EDIT2: the threads code to do with giving the parameter to the function...
unsigned int WINAPI ServerThreadFunc(void* pvArgs)
{
    CServer* pServer = (CServer*)pvArgs;        // pointer to the server object
    DWORD dwBytes = 0;
    ULONG_PTR ulKey;
    OVERLAPPED* pOverlapped = nullptr;
    bool bLooping = true;

    while(bLooping)
    {
        //TODO: Add code (ServerThreadFunc)
        if(!pServer->m_pCompletionPort->GetCompletionStatus(&dwBytes, &ulKey, &pOverlapped, INFINITE))
        {
            //TODO: Set some error variable or flag an error event to notify the main thread
            DebugBreak();
        }

        //check type of request
        switch(((BASIC_REQUEST*)pOverlapped)->m_RequestType)
        {
        case BASIC_REQUEST::ACCEPT:
            {
                // TODO: Handle AcceptEx-request
                pServer->HandleAcceptRequest(static_cast<ACCEPT_REQUEST*>(pOverlapped));

A: Sorry, there's no way to really figure anything out from bits and pieces you provided.
However, in the third piece of code you have this call
pServer->HandleAcceptRequest(static_cast<ACCEPT_REQUEST*>(pOverlapped));

This call will destroy the *pOverlapped object by calling delete on it. (Remember that at the very end of HandleAcceptRequest you do delete pRequest, where pRequest is the parameter of HandleAcceptRequest).
This will make pOverlapped a dangling pointer that points to dead memory. I don't see any place in your code where you would re-initialize that dangling pointer or set it to null.
If you don't re-initialize it, then the next access to *pOverlapped in the cycle will access dead memory (which might appear to "work") and the next attempt to delete it again will most likely crash. If the next delete attempt is the one at the end of HandleAcceptRequest again, then the behavior will probably be exactly as what you originally described.

A: OVERLAPPED* pOverlapped = nullptr;
..
pServer->m_pCompletionPort->GetCompletionStatus(&dwBytes, &ulKey, &pOverlapped, INFINITE);

Ok. It seems you are deleting the wrong pointer. The one you are deleting inside HandleAcceptRequest() is no longer a pointer to an OVERLAPPED, since the pointer has been casted from OVERLAPPED* to ACCEPT_REQUEST*.
Is GetCompletionStatus() your own?


text:
Q: Checking if looped item has a parent inside a shortcode all I want is to check if the custom post item in the loop has a parent. I am using this inside a shortcode. I could not find how to access the property from inside the loop.
Thank you my dears
$q = new WP_Query(array(
    'post_type' => 'my_custom_post_type',

    'posts_per_page' => 5,
    'category' => '',
));

while ($q->have_posts()) {
      $q->the_post();
      ... <- Check if the loop item has a parent
}
wp_reset_postdata();

A: The WP_Post class has an attribute post_parent that you can use for this.
while ($q->have_posts()) {
      $q->the_post();
      $post = get_post();
      if (!empty($post->post_parent)) {
          // do something different
      }
}


text:
Q: .NET Core Runtime without installing Can anyone help as to how to use the run time binaries found in the link below?
https://www.microsoft.com/net/download/windows
Basically, we are moving to .NET Core (we have been using .NET framework 4.0 for many years - so big shift as you can guess). I am kind of nervous to install .NET core on the production server (Windows Server 2012). Is it safe to install .NET Core on a server running .NET framework 4.0? If no, is there any way I can get the .NET Core runtime on to the server without installing them (kind of copying portal libraries) so that I can start with the beta testing of the app. Any help would be much appreciated. Thanks!
EDIT:
It is not duplicate, One of the main questions I had if I can use portable binaries on the server to run my app, without actually installing them (got the answer below, thanks again). Not sure someone down voted this without any reason. It makes the developers nervous to ask a question in StackOverflow. if they can mention the reason that would be great!

A: There are no issues when installing .NET Core and .NET Framework on the same machine. They are designed to allow them to be installed side-by-side.
However you do need to install the .NET Core runtime onto the server to allow the code to be run because the OS has native dependencies that need to be present. See this link for more information.
With .NET Core you can do framework dependent deployments (FDD) and self-contained deployments (SCD). FDD requires any shared assemblies to be present on the server i.e. System.* assemblies etc. but an SCD only requires the basic runtime/native dependencies. For an SCD your app deployment would include any .NET Core shared assemblies in it's deployment package.
You can read more about FDD and SCD here
Also there is more information about the native dependencies on different OS platforms here


text:
Q: Is my understanding of completionHandler blocks correct? Ive read quite bit about blocks by now, Apple's Guide, Cocoabuilder, 3 articles on SO and ive used examples in my code that I basically got from online tutorials.  Im still trying to understand one specific question.  So I decided to make an app with nothing more than a completionHandler example to understand better.  This is what I came up with:
ViewController
- (void)viewDidLoad
[SantiappsHelper fetchUsersWithCompletionHandler:^(NSArray *users) {
    self.usersArray = [NSMutableArray array];

    for (NSDictionary *userDict in users) {
        [self.usersArray addObject:[userDict objectForKey:@"username"]];
    }

    //WHILE TESTING postarray method, comment this out...
    //[self getPoints];
    [self.tableView reloadData];

}];

}

SantiappsHelper.h/m
typedef void (^Handler)(NSArray *users);

+(void)fetchUsersWithCompletionHandler:(Handler)handler {

NSString *urlString = [NSString stringWithFormat:@"http://www.myserver.com/myapp/getusers.php"];
NSURL *url = [NSURL URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];

[request setHTTPMethod: @"GET"];

__block NSArray *usersArray = [[NSArray alloc] init];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//dispatch_async(dispatch_get_main_queue(), ^{
    // Peform the request
    NSURLResponse *response;
    NSError *error = nil;
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];
    if (error) {
        // Deal with your error
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
            return;
        }
        NSLog(@"Error %@", error);
        return;
    }

    NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    usersArray = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];

    if (handler){
        //dispatch_sync WAITS for the block to complete before returning the value
        //otherwise, the array is returned but gets zeroed out
        dispatch_sync(dispatch_get_main_queue(), ^{
        handler(usersArray);
        });
    }
});
}

Here is what I understand...

*

*I call fetchUsersWithCompletionHandler from my VC & pass it this completion block. That block takes an NSArray users parameter & returns void.

*Meanwhile in the SantiappsHelper Class we have a variable called handler of type ^block which it receives from VC.

*The fetchUsersWithCompletionHandler method runs, taking that CompletionBlock parameter, which itself takes the NSArray users parameter?  a little confusing.

*The webfetch is dispatch_async so it wont block the main thread.  So execution on the main thread continues.  That new thread executes the fetch synchronously that new thread will stall until the response is returned.  Once that new thread receives the response, it fills in the NSHTTPURLResponse.  Once it returns, it fills in usersArray with the NSJSONSerialized data.

*Finally it reaches the if test and it checks for the existence of the PARAMETER handler that was passed in? A little confusing...the parameter passed in was the completionBlock. Wouldnt that handler parameter always and obviously exist since it was passed in?

*Once the handler !NULL then execution is returned to the main thread passing back the NSArray users expected by the block back in the VC.
But if I change the second dispatch to async, the usersArray is properly populated but once handler(usersArray) is sent back to the main thread, its empty or nil!  Why?

A: *

*Correct. The best way to say/think about this is to say that you are invoking a method called fetchUsersWithCompletionHandler:. This method will go away and do some work and at some point in the future it may execute the code you have declared in the block literal and pass in an array of users.

*The method takes an argument called handler of type void (^)(NSArray *users). This type represents a block of code that when invoked should receive and array and return no result.

*The fetchUsersWithCompletionHandler: does some work and at some point may invoke the block passed in with an array of users as the blocks argument.

*Correct

*The if (handler) { checks to see if the handler arguments is not nil. In most cases this would be the case especially if you always invoke the fetchUsersWithCompletionHandler: with a block literal, but you could always invoke the method with [self fetchUsersWithCompletionHandler:nil]; or invoked it passing along a variable from somewhere else as the completion, which may be nil. If you try to dereference nil to invoke it then you will crash.

*Execution is not "passed back" to the main thread, you are simply enqueueing a block of work to be performed on the main thread. You are doing this with dispatch_sync call which will block this background thread until the block completes - this isn't really required.
The array being nil could be a consequence of you declaring the usersArray with __block storage. This is not required as you are not modifying what usersArray is pointing to at any point you are simply calling methods on it.


text:
Q: Angular 6 dynamic components I am working on a project where I need to create the component dynamically and add them to a tab, but initially I created a small project with two components and I want to load those two components dynamically inside a div
App.module.ts
import { BrowserModule } from '@angular/platform-browser';
 import { NgModule, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';import{RouterModule, Router, NavigationEnd, ActivatedRoute}from "@angular/router";
import { AppComponent } from './app.component';
import { TestOne, TestTwo } from './my.component';

@NgModule({
  declarations: [
    AppComponent,
    TestOne,
    TestTwo
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(
      [{
        path:"first",component:TestOne
      },{
        path:"second",component:TestTwo
      }]
    )
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule {

}

my.component.ts
import { Component } from "../../node_modules/@angular/core";

@Component({
    selector: 'test-one',
    template: '
Test One
'
  })
  export class TestOne {}

  @Component({
    selector: 'test-two',
    template: '
Test Two
'
  })
  export class TestTwo {}

app.component.ts
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '../../node_modules/@angular/router';
import { TestOne, TestTwo } from './my.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  entryComponents:[TestOne,TestTwo]
})
export class AppComponent {
  title = 'app';
  @ViewChild('container', { read: ViewContainerRef }) _vcr:ViewContainerRef;

constructor(private componentFactoryResolver: ComponentFactoryResolver,
  private route:ActivatedRoute,private router:Router){
    router.events.subscribe(e => {
      if(e instanceof NavigationEnd){
        console.log((<any>route.firstChild.component).name);
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory((<any>route.firstChild.component).name);
        this._vcr.createComponent(componentFactory);
      }
    });

  }
}

app.component.html

test one

test two

I am getting the error: ERROR in TestOne cannot be used as an entry component.
I added those two components as entryComponents in the app.module, and also in the app.components but each time I face the same problem.
Can anyone please let me know what I am missing ?


text:
Q: I am designing a table in angularjs with multi text filtering option for each column like in excel I am designing a table in AngularJS with many rows and columns. I need to add a filter button ![filter button][1]for each of the columns. When clicking on the  filter button it should expand to something like in exce, which lists all the elements in the column and pick the necessary data to filter. Is there a way to do this in AngularJS? Any ideas would be greatly appreciated. Thanks so much!

A: Lets use this sheet as an example
A B C
2|4|1
3|2|2
 | |3
7| |4
 | |2
 | |3
 | |2

Lets build the internals of the spreadsheet in javascript. You can move the columns object to a json file to read in for persistence.
var sheet = {
    columns = [
        [2, 3, null, 7], // A
        [4, 2], // B
        [1, 2, 3, 4, 2, 3, 2] // C
    ],
    maxRowCount: function () {
        var max = 0;
        columns.forEach(function (item) {
            max = Math.max(max, item.length);
        });
        return max;
    }
};

function filterHandler(filterOptions, colIndex) {
    // pass in an array of the values you want to show
    var rowsToShow = [];
    var i;
    for (i = 0; i < sheet.maxRowCount(); i++) {
        if (sheet.columns[colIndex] in filterOptions) {
            rowsToShow.push(i + 1); // for one based rows.
        }
    }
    return rowsToShow;
}

From here you need to do some stuff with the dom. Use something like a list of check boxes to mark what items you want to filter for. pass it into the filterHandler. It will return an array of indices to show. Hide all others.
To filter Column C on values 2 and 4 do the following
var showRows = filterHandler([2, 4], 2);
// showRows == [2, 4, 5, 7]

So hide all rows who's indicies are not in the showRows array.


text:
Q: Why should you use a 2D array of structs? I`m curious about if there are cases to use a 2D array of structures, like f.e.:
typedef struct
{
 //member variables
}myStruct;

myStruct array2D[x][y];
//Uses cases of array2D[x][y]? Do we need them?

Why should you use a 2D array of structs?

A:
Why should you use a 2D array of structs?

A defined structure is basically just a type like any other (though of course, any type is different from the other and there is a difference between private and standard datatypes; not even mentioning the differences in memory allocation between objects of that types) with which you can declare objects.
You could also ask: Why should you use a char,int or double two-dimensional array?
It is not only a structure own kind of thing.
It depends on the context and its worth to have a clear "structure" in ones code; So to code in this way can help you to make your code more readable and clear, if you need a huge amount of objects of a certain type, in this case a structure.
Maybe you even want to group some objects and/or want to treat them differently. In this case, multiple array dimensions are beneficial because you can address objects of each dimension explicitly and separately.
As @buysbee mentioned in the comments:
One obvious example, where it is beneficial to store structure objects in a two-dimensional array is to storing the pixels of a picture. It is better to store the "pixel" structure objects in a two-dimensional array because this emulates how a picture is constructed of naturally.

A: We can add more questions: why we should use 3D, 4D. 5D ...... 10000000D arrays of something.
Data structures used in a project depend on the problem to be solved and the algorithm chosen.


text:
Q: knockout textinput modify observeable not updating text i´m using textinput data-binding off the latest knockout version.
 on an input like:
 <input type="text" placeholder="name" data-bind="textinput:vm.found().term">

and it works just like a charme, problem:
when i modify the value with some other script like:
vm.found().term("somecontent")

the input does not change?
i need the value of the textinput to change when i change the observable
the doc says nothing about textInput

A: You should never have raw, deeply nested bindings like you have there.  Assuming the found value has changed, it the text box will still be bound to the previous found object.  You probably should be using a with binding somewhere.
<div data-bind="with: vm.found">
    <input type="text" placeholder="name" data-bind="textinput: term">
</div>


text:
Q: Deezer API: Search result is empty I've got a problem. I'm making something with the Deezer api. When I try to search with the api I'm always getting an empty result.
To test it I'm using this code:
<?php
echo file_get_contents('https://api.deezer.com/2.0/search?q=Avicii');
?>

When I visit the url in my browser it works fine. But when I visit the PHP-file it outputs:
{"data":[],"total":0}

I'm also getting data from a Deezer playlist and that works fine!
I searched the web for it but I've got no idea what's wrong.
Thanks in advance!


text:
Q: Flash app with a Search function through a MySql Database (using php) I need some help with a flash app im currenctly programming.
I have a management flash app that does some operations in a MySql databases. I have had some problems, but for the most part, I have been able to press on. I'm a flash AS3 newb, so bear that in mind.
My actual problem is that I need to do a "Search" module, and I need it to print several results at once. I am although unsure how to get the results on flash. what I have been doing now is calling a php script that, after doing its operation, does something like (for example):
print "Name=".row[1]."&ID=".row[0];

Then, the flash grabs the return value for the several fields. What I now need, would be to get the Name1=something&Name2=somethingelse&Name3=EvenSomethingElse , but I see no way of that happening. I also believe that I am overcomplicating something that should be fairly simpler than this. I would like to ask how do I get a search with several entries at once. This is a dynamic search, so I need to do something that is able to function with 1 result only or several at a time.
I am asking a bit losely because I really dont think my code is the best at the moment. What I have been doing was finding out how many entries would be positive (for example, how many users called marco) and then would call the php once inside a cicle while i

So, help me out please, maybe link to a tutorial or something, because I believe there is a simpler way to do this.
Thank you.
Marco Roberto.

A: Here is a video tutorial:
http://gotoandlearn.com/play.php?id=20
It uses actionscript 2 but it should be trivial to adapt to as3. Basically the solution is to write a for-each look in php and output an XML string with all results from the query. Once you have this structured data set back in flash you can do whatever your hearts desire with it.

A: If I understand you correctly, you need to fetch some results from a MySQL database and return the values to Flash. The best way to do this would be to get all the results from the database with PHP, the basic way would be to use the mysql_query functions and the more advanced way would be to use PDO.
Using PHP, you could create a file which returns an XML structure which you could then parse with AS3. As far as I know, AS3 has good built-in functions for parsing XML so that should be an easy task.
PHP Example code:
<?php
    $content = '<?xml version="1.0"?><items>';

    $results = mysql_query("SELECT id, name FROM items WHERE name = '$searchQuery';");
    while ($row = mysql_fetch_assoc($results){
        $content .= '
            <item>
                <id>'.$row['id'].'</id>
                <name>'.$row['name'].'</name>
            </item>';
    }

    $content .= '</items>';
    echo $content;
?>

This is what the output could look like:
<?xml version="1.0"?>
<items>
    <item>
        <id>1</id>
        <name>Result one</name>
    </item>
    <item>
        <id>2</id>
        <name>Result two</name>
    </item>
    <item>
        <id>3</id>
        <name>Result three</name>
    </item>
</items>

As for the search query, you can send it to the PHP file using the URLRequest library which you can find more information about here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLRequest.html
Here is a demo on how to send variables to the PHP file using URLRequest and AS3:
http://rickydoesit.com/actionscript-3/how-to-connect-to-php-with-actionscript-3-and-post-variables-to-php/
And here is some help regarding parse the XML file with AS3:
http://blog.six4rty.ch/tutorials/flash-cs3-loading-an-xml-with-as3/


text:
Q: From a software standpoint how does bluetooth work? I'm trying to develop a wireless transfer system (like bluetooth) from scratch and I wanted to first get an understanding of how Bluetooth worked. So what steps take place from when I click "Turn on bluetooth" on my mac to when I finish sending the PDF to my LG Env Touch?
What software is running (ex. Protocols)?

A: This is a really broad question, and not one that I think can be answered well in this format. I'd suggest digging up some documentation on Bluetooth, like these:
https://www.bluetooth.org/en-us/training-resources/white-papers