How to return value to global variable from asyn/await function?

Question: I want to return the user's geolocation to the variable so other function can use it later. I tried using async/await function but it doesn't work. What have I done wrong?
// Getting data
class Data {
  static async getLatitude() {
    let latitude = await navigator.geolocation.getCurrentPosition((position) => {
      return position.coords.latitude;
    });
    return latitude;
  }

}

// Site running
window.addEventListener('load', () => {
  if(navigator.geolocation) {
    let latitude = Data.getLatitude();
    console.log(latitude);

  }
})

Comment: You're almost there. Try `let latitude = await Data.getLatitude();`. What you have will set `latitude` to the promise that resolves to the latitude rather than the latitude itself.
Comment: Your handler needs the keyword await. `await Data.getLatitude()` that will resolve the promise before moving to the next statement
Comment: 3 options you have is, callback, promise or async/await method. It is not practical to store output in a variable while doing async programming. Better look for patterns for working with async functions.
Comment: @ali the OP is already trying to use async await, they're just missing a few keywords
Comment: @PatrickStephansen but I can use await only in async function so it doesn't work
Comment: My mistake. You also need to make the second argument to the `window.addEventListener` function async: `window.addEventListener('load', async () => {`
Comment: @PatrickStephansen yeah, I tried this but it is displaying then the undefined value
Answer: The problem is that navigator.geolocation.getCurrentPosition does not return a Promise. That's why you can't use async/await to get its response. You will have to wrap that into a Promise yourself to be able to use async/await to get the result. Here is the full code:
class Data {
  static async getLatitude() {
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition((position) => {
        resolve(position.coords.latitude);
      }, reject);
    });
  }
}

window.addEventListener('load', async () => {
  if (navigator.geolocation) {
    let latitude = await Data.getLatitude();
    console.log(latitude);

  }
})


How do you find the equations of the lines that intersect a certain line at a $45^\circ$ given that it passes through a certain point?

Question: Let's say there is a line $L$, with an equation $y=mx+b$. We also know that there is a point with coordinates $(p,q)$, which we can call as point $Q$. What are the equations of the lines that intersect line $L$ at a $45^\circ$ and pass through point $Q$(any form is fine, but slope-intercept form would be preferable)?
I was thinking to first find the slope of these lines, and then use the point-slope equation for each slope to get the final equations.
MY APPROACH:
I first found the slope of the final lines. I did so by first finding the y-intercept of $L$, which $(0,b)$. Let's denote this point as $M$. I then drew a circle with center $M$ and radius $1$. I then drew a line perpendicular to $L$ that passed threw $M$. Let's say this line is $P$. I then found the intersection of circle $M$ and the line $P$, which I denoted as $I$. I then drew a circle with center $I$ and radius $1$. I also drew a line parallel to $L$ that passed through $I$. I then found the intersection between this line and circle $I$, which I denoted as $A$ and $B$. I then found the slope of $\overline {AM}$ and $\overline{BM}$, which I will call $m_a$ and $m_b$, respectively. I finally used the point-slope equation with slope $m_a$ and $m_b$ and point $Q$ to find the final equations. Below is an example graph:

Graph Link
Is this the correct approach? Are there other ways to do this? Thanks in advance.
Answer: That certainly works, but for this problem I think it's much more convenient to work with the point-normal form of equation of a line: the line through $P=(x_p,y_p)$ with normal $(a,b)$ has the equation $a(x-x_p)+b(y-y_p)=0$.
The lines that you are tasked with finding are the angle bisectors of the lines through $Q$ that are parallel and perpendicular to $L$. Writing the equation of $L$ as $mx-y+b=0$, we can see that its normal is $(m,-1)$, so an equation of the parallel line through $Q$ is $m(x-p)-(y-q)=0$ and an equation of the perpendicular is $(x-p)+m(y-q)=0$. Using a fairly well-known formula, the equations of their angle bisectors are then $m(x-p)-(y-q)=\pm((x-p)+m(y-q))$, which you can rearrange as desired.
If you don't happen to know the formula for angle bisectors of a pair of lines, you can proceed by first finding the normals to the two bisectors: they will be angle bisectors of the normals of the parallel and perpendicular lines through $Q$. For this, we don't need to know their complete equations. We already know that the normal to the parallel line is $(m,-1)$, so the perpendicular normal is $(1,m)$. These vectors have equal lengths, so their angle bisectors are simply their sum and difference, namely, $(m+1,m-1)$ and $(1-m,1+m)$. Using the point-slope form from above, the equations of the two 45-degree lines are $(m+1)(x-p)+(m-1)(y-q)=0$ and $(1-m)(x-p)+(1+m)(y-q)=0$. I'll leave verifying that the equations derived using these two methods are equivalent to you.
Comment: I don't really know what point-normal form of a line is. Can you briefly explain it to me or maybe provide a link where I can look more into this?(I'm only in the middle school so sorry if it seems trivial)
Comment: And also what is the "fairly well-known formula" stated in your answer?(Just the name is fine, or maybe you could post the formula in a comment)


Blur effect over a QWidget in Qt

Question: Is there any way to blur a widget in Qt? For instance, supose I want to create a 'Loading...' dialog and blur the background (not active window).
Answer: This answer is in a series of my overlay-related answers: first, second, third.
It requires some care if you wish for it to work on all platforms. You can't apply effects directly to top-level windows. The hierarchy needs to look as follows:
ContainerWidget
     |
     +----------+
     |          |
**Target**   Overlay

You apply the effect to the Target widget (say, a QMainWindow). The ContainerWidget is a helper class that keeps the children occupying the full size of the widget. This obviates the need for an explicit zero-margin layout.
The below works, even on a Mac. It wouldn't, had you foregone the ContainerWidget. This works portably on Qt 5 only, unfortunately. On Qt 4, your "cross platform" support excludes Mac :( It works OK on Windows using either Qt 4 (4.8.5) or Qt 5.

// https://github.com/KubaO/stackoverflown/tree/master/questions/overlay-blur-19383427
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif

class OverlayWidget : public QWidget {
   void newParent() {
      if (!parent()) return;
      parent()->installEventFilter(this);
      raise();
   }
public:
   explicit OverlayWidget(QWidget *parent = {}) : QWidget(parent) {
      setAttribute(Qt::WA_NoSystemBackground);
      setAttribute(Qt::WA_TransparentForMouseEvents);
      newParent();
   }
protected:
   //! Catches resize and child events from the parent widget
   bool eventFilter(QObject *obj, QEvent *ev) override {
      if (obj == parent()) {
         if (ev->type() == QEvent::Resize)
            resize(static_cast<QResizeEvent*>(ev)->size());
         else if (ev->type() == QEvent::ChildAdded)
            raise();
      }
      return QWidget::eventFilter(obj, ev);
   }
   //! Tracks parent widget changes
   bool event(QEvent *ev) override {
      if (ev->type() == QEvent::ParentAboutToChange) {
         if (parent()) parent()->removeEventFilter(this);
      }
      else if (ev->type() == QEvent::ParentChange)
         newParent();
      return QWidget::event(ev);
   }
};

class ContainerWidget : public QWidget
{
public:
   explicit ContainerWidget(QWidget *parent = {}) : QWidget(parent) {}
   void setSize(QObject *obj) {
      if (obj->isWidgetType()) static_cast<QWidget*>(obj)->setGeometry(rect());
   }
protected:
   //! Resizes children to fill the extent of this widget
   bool event(QEvent *ev) override {
      if (ev->type() == QEvent::ChildAdded) {
         setSize(static_cast<QChildEvent*>(ev)->child());
      }
      return QWidget::event(ev);
   }
   //! Keeps the children appropriately sized
   void resizeEvent(QResizeEvent *) override {
      for(auto obj : children()) setSize(obj);
   }
};

class LoadingOverlay : public OverlayWidget
{
public:
   LoadingOverlay(QWidget *parent = {}) : OverlayWidget{parent} {
      setAttribute(Qt::WA_TranslucentBackground);
   }
protected:
   void paintEvent(QPaintEvent *) override {
      QPainter p{this};
      p.fillRect(rect(), {100, 100, 100, 128});
      p.setPen({200, 200, 255});
      p.setFont({"arial,helvetica", 48});
      p.drawText(rect(), "Loading...", Qt::AlignHCenter | Qt::AlignTop);
   }
};

namespace compat {
#if QT_VERSION >= QT_VERSION_CHECK(5,4,0)
using QT_PREPEND_NAMESPACE(QTimer);
#else
using Q_QTimer = QT_PREPEND_NAMESPACE(QTimer);
class QTimer : public Q_QTimer {
public:
   QTimer(QTimer *parent = nullptr) : Q_QTimer(parent) {}
   template <typename F> static void singleShot(int period, F &&fun) {
      struct Helper : public QObject {
         F fun;
         QBasicTimer timer;
         void timerEvent(QTimerEvent *event) override {
            if (event->timerId() != timer.timerId()) return;
            fun();
            deleteLater();
         }
         Helper(int period, F &&fun) : fun(std::forward<F>(fun)) {
            timer.start(period, this);
         }
      };
      new Helper(period, std::forward<F>(fun));
   }
};
#endif
}

int main(int argc, char *argv[])
{
   QApplication a{argc, argv};
   ContainerWidget base;
   QLabel label("Dewey, Cheatem and Howe, LLC.", &base);
   label.setFont({"times,times new roman", 32});
   label.setAlignment(Qt::AlignCenter);
   label.setGraphicsEffect(new QGraphicsBlurEffect);
   LoadingOverlay overlay(&base);
   base.show();
   compat::QTimer::singleShot(2000, [&]{
      overlay.hide();
      label.setGraphicsEffect({});
   });
   return a.exec();
}

Comment: Can you paste a Python PyQt5 related answer?
Answer: See QGraphicsBlurEffect Class  and QWidget::setGraphicsEffect().
Answer: You can refer to this article if you want to apply blur effect on an image. After you create your blurred image you can draw it in QWidget::paintEvent() function.

Blur effect over a QWidget in Qt


Regex pattern matching comma delimited values with spaces allowed around comma

Question: I am trying to write a Regex validator (Python 3.8) to accept strings like these:
foo
foo,bar
foo, bar
foo , bar
foo    ,      bar
foo, bar,foobar

This is what I have so far (but it matches only the first two cases):
^[a-zA-Z][0-9a-zA-Z]+(,[a-zA-Z][0-9a-zA-Z]+)*$|^[a-zA-Z][0-9a-zA-Z]+

However, when I add the whitespace match \w, it stops matching altogether:
^[a-zA-Z][0-9a-zA-Z]+(\w+,\w+[a-zA-Z][0-9a-zA-Z]+)*$|^[a-zA-Z][0-9a-zA-Z]+

What is the pattern to use (with explanation as to why my second pattern above is not matching).
Comment: I assume this is a purely academic exercise because judicious use of *split()* and *strip()* would solve this problem with ease. Also, you say you're writing a "validator" which begs the question "What constitutes an invalid string?"
Comment: @Stuart this is part of a Django project - so to an extent it is academic - in the sense that I **could** simply override the `save()` method and do my checks there - but I like the idea of abstracting and encapsulating validation in another class, so it can be used on other fields and other models too. Valid strings are strings that can be split by a delimiter into a list of alphanumeric tokens.
Comment: Therefore the string 'foo' would be considered invalid as there's no apparent delimiter - is that right?
Comment: I'm simplifying things a bit here - but a single alphanumeric string is the exception (bad choice of word), to the general rule I gave previously.
Answer: \w matches [0-9a-zA-Z_] and it doesn't include whitespaces.
What you need is this regex:
^[a-zA-Z][0-9a-zA-Z]*(?:\s*,\s*[a-zA-Z][0-9a-zA-Z]*)*$

RegEx Demo
RegEx Details:

^: Start
[a-zA-Z][0-9a-zA-Z]*: Match a text starting with a letter followed by 0 or more alphanumeric characters
(?:: Start non-capture group

\s*,\s*: Match a comma optionally surrounded with 0 or more whitespaces on both sides
[a-zA-Z][0-9a-zA-Z]*: Match a text starting with a letter followed by 0 or more alphanumeric characters

)*: End non-capture group. Repeat this group 0 or more times
$: End


TrustedProxy does not detect User IP

Question: I'm using Laravel 5.3 with PHP7 on an EC2 behind an ELB and Cloudflare and I have a little problem with TrustedProxy package(https://github.com/fideloper/TrustedProxy).
The package doesn't give me the user Ip.
In the trusted config file I have something like this
<code>return [
    'proxies' => '*',
    'headers' => [
        \Illuminate\Http\Request::HEADER_CLIENT_IP    => 'X_FORWARDED_FOR',
        \Illuminate\Http\Request::HEADER_CLIENT_HOST  => 'X_FORWARDED_HOST',
        \Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
        \Illuminate\Http\Request::HEADER_CLIENT_PORT  => 'X_FORWARDED_PORT',
    ],
];
</code>
(I tried with ** too)
But when I do something like $request->ip(),  $request->getClientIp o getClientIps (at the end all this method are using getClientIps()) the IP that appear is the proxy IP.
If I print the $request I can see:
Server bag:
<code>...
"HTTP_X_FORWARDED_PROTO" => "https"
"HTTP_X_FORWARDED_PORT" => "443"
"HTTP_X_FORWARDED_FOR" => "XX.XX.XX.XX" (I removed the real IP)
...
"REMOTE_ADDR" => "10.0.0.53"
</code>
Header bag:
<code>"x-forwarded-proto" => array:1 [
    0 => "https"
  ]
  "x-forwarded-port" => array:1 [
    0 => "443"
  ]
  "x-forwarded-for" => array:1 [
    0 => "XX.XX.XX.XX" (I removed the real IP)
  ]
</code>
But the $request->ip(),  $request->getClientIp and getClientIps return the wrong IP (10.0.0.53).
Does anyone have an idea or clue ?
Thanks!
Answer: Solved.
The main problem (and a bit stupid) is the order in the middelwares. I were using the information in a middleware executed before trustproxy.

TrustedProxy does not detect User IP


Wildcard aliases in postfix?

Question: is there  way to specify wildcard aliases in postfix virtual table?
eg.
email@example.com

gets sent to
firstname.lastname@example.com

in this way i want to achieve that all mails with a firstname.lastname@example.com address get redirected to another server..
thanks!
Answer: Use a regex table or pcre_table as one of your alias_maps (or virtual_alias_maps). You consider using transport_maps if you want the mail delivered to another box without aliasing.
Comment: Please provide an explicit example instead of just references.

Wildcard aliases in postfix?


Jquery keyup multiple inputs

Question: I am trying to make it so when someone uses the input the text that corresponds to it will show.

Content 1

Content 2

Content 3

Content 4

Input 1
<input type="text" name="input1" value="" id="input1" autocomplete="off" maxlength="2"  />

Input 2
<input type="text" name="input2" value="" id="input2" autocomplete="off" maxlength="2"  />

Input 3
<input type="text" name="input3" value="" id="input3" autocomplete="off" maxlength="2"  />

Input 4
<input type="text" name="input4" value="" id="input4" autocomplete="off" maxlength="2"  />

Would I do a keyup function for each input or is there a way to make one keyup function?
Answer: This should do it for your current markup:
$('.addReview input[type="text"]').keyup(function() {
   $('div[class^="content"]').hide();
   $('div.' + this.id.replace(/input/, "content")).show();
});

Demo: http://jsfiddle.net/WD3CU/
But it would be neater if you gave the divs a common class and different ids. E.g., if all the divs had a class "content" and an id in the form "content1" then you could do this:
$('.addReview input[type="text"]').keyup(function() {
   $('div.content').hide();
   $('#' + this.id.replace(/input/, "content")).show();
});

Which looks similar but is much more robust (the way I did it for your current html will likely break if you were to give the divs additional classes).
Demo incorporating my suggested markup changes: http://jsfiddle.net/WD3CU/1/
Also, in my opinion it would make more sense to use the .focus() event rather than .keyup(), so that the appropriate div is shown as soon as the user clicks or tabs into one of the inputs.
Answer: You have to bind to a common selector like this
$('.addReview input:text').keyup(function() { });

demo
Or a class selector like this
$('.addReview .mytextboxclass').keyup(function() { });

demo
Or an attribute selector like in nnnnnn's answer
$('.addReview input[type="text"]').keyup(function() { });

demo
Answer: You'd have to modify your HTML architecture a bit. Change it to this:

Content 1

Content 2

Content 3

Content 4

Input 1
<input type="text" class="input" name="input_1" value="" id="input_1" autocomplete="off" maxlength="2"  />

Input 2
<input type="text" class="input" name="input_2" value="" id="input_2" autocomplete="off" maxlength="2"  />

Input 3
<input type="text" class="input" name="input_3" value="" id="input_3" autocomplete="off" maxlength="2"  />

Input 4
<input type="text" class="input" name="input_4" value="" id="input_4" autocomplete="off" maxlength="2"  />

You can then use the following jQuery code to achieve what you're trying to do:
$(".input").keyup(function() {
    var curId = this.id.split("_")[1];
    $("#content_"+curId).html($(this).val());
    $("#content_"+curId).show();
});

Working JSFiddle demo.
Comment: Thanks for your help mate but thats not really what I was going for. The inputs value is unrelated to what I am trying to do. I want when someone clicks on the input to show a pre selected message to help them to answer the question. Kinda like when you ask a question on stackoverflow, how the right side gives you hints on your title and then body and then tags. Thanks for the help!

Jquery keyup multiple inputs


Property of trace.

Question: Suppose that $\mathbf{Z}$ is a design matrix of a linear regression.
Where  $\mathbf{Z}^{T}\mathbf{Z}$ is a symmetric matrix.
Also suppose that $\mathbf{H}$ is the hat matrix defined as follows:
$\mathbf{H} = \mathbf{Z} \hat{\boldsymbol \beta} = \mathbf{Z} \left( \mathbf{Z}^\textsf{T} \mathbf{Z} \right)^{-1} \mathbf{Z}^\textsf{T}$
According to my textbook we can now we can say that
$trace(\mathbf{H}) = trace(\mathbf{Z}(\mathbf{Z}^{T}\mathbf{Z})^{-1}\mathbf{Z}^{T}) = tr[(\mathbf{Z}^{T}\mathbf{Z})^{-1}(\mathbf{Z}^{T}\mathbf{Z})]$
And the above is due to the following property of traces namely:
$\mathbf{x}'\mathbf{A} \mathbf{x} = trace(\mathbf{A}\:\mathbf{x}\:\mathbf{x}')$
I'm not sure how this property of traces was applied here. Can someone provide clarity in which context the property was used to attain the above-mentioned equality.
Answer: Hint: For $A$ (format $n\times p$) and $B$ (format $p\times n$) we have $\text{tr}(AB)=\text{tr}(BA)$. In your case $A=Z$ and the rest is $B$.
The property below is similar as $\mathbf{x}^T\mathbf{Ax}$ is a scalar and the trace of a scalar is the scalar itself. Hence, we have
$$\mathbf{x}^T\mathbf{Ax} = \text{tr}\left[\mathbf{x}^T\mathbf{Ax}\right]$$
Now, you can apply the same rule.
Comment: So the property:
$\mathbf{x}'\mathbf{A} \mathbf{x} = trace(\mathbf{A}\:\mathbf{x}\:\mathbf{x}')$ is not applied here? Would that be a different approach to the problem? could possibly be a typo in my textbook.

Property of trace.


Calculate the quantile for a mixed pdf

Question: I am trying to draw random numbers that follow a two-part pdf
a) $|x|< x_0: f(x)=\text{constant}\quad \to \quad F(p)=a+(b-a)p$
b) $|x|> x_0: f(x)=\exp(-|x|)\quad \to \quad F(p)=-\ln(1-p)$
that is the probability is constant between $(-x_0,x_0)$ and falls exponentially outside it.
Knowing the quantile functions $F(p)$ ($0\leq p\leq 1$) of the pdf, how can I construct the quantile that describes the above pdf comprised of two parts?
Comment: Your formulas are inconsistent: for instance, in part (b), $F$ is not the quantile function for $f$. ($F$ assigns zero probability to negative numbers whereas $f$ is symmetric around $0$.)  This leaves the question indeterminate.  Please edit your question to fix up the mathematical problems or at least provide more information so that the question becomes unambiguous.
Comment: Take some care. One reason for suggesting you write the cdf was that I was hoping you'd see that your *density* is probably not correctly specified (I suspect you're aiming to have continuity at $\pm x_0$ - is that the case?  If so, your $f$ is wrong. As I said, somewhere earlier, draw it.). If you don't get that right you're wasting your time jumping several steps further along.
Comment: It seems like you're maybe confusing together the cdf with its inverse. First, try drawing a picture of the pdf, the cdf, and the inverse of the cdf (the quantile function). Once you can get the cdf right, it's easier to get its inverse right.
Comment: The way I was trying to do this is as follows: calculate the CDF (by integrating), then find the inverse function. Now I was just confused how to "stick them together" since I only draw p in [0,1].
@Glen_b When I am drawing random numbers accordingly to a given pdf I always use its quantile function. I think this is correct since it is related to the inverse of the pdf but please correct me if I am wrong!
That is of course, correct, I was thinking about calculating only x >0 first, then mirroring it! Would that work?
Comment: Thanks @Glen_b now I understand what you meant! It works like a charm!
Comment: Now that you have it clearly understood, I'll leave more details so the question has an answer.
Answer: Here's the actual pdf required:
$$f(x)=\begin{cases}
  c\quad &|x|\leq x_0\\
   c_1 \exp(-|x|)\quad &|x|> x_0
\end{cases}$$
that is the probability is constant between $(-x_0,x_0)$ and falls exponentially outside it, and where $c_1$ and $c$ are such that the pdf is continuous and integrates to 1.
That is, we have the conditions that $c_1\exp(-x_0) = c$; i.e. $c_1 = c\exp(x_0)$ and that the $\int_{-\infty}^\infty f(x) dx = 1$.
\begin{eqnarray}
\int_{-\infty}^\infty f(x) dx
&=& 2c\left( \int_{0}^{x_0} 1 dx  +  \exp(x_0)\int_{x_0}^\infty \exp(-x) dx \right)\\
&=& 2c\left( x|_{0}^{x_0} - \exp(x_0)\exp(-x)|_{x_0}^\infty \right)\\
&=& 2c\left( x_0 - \exp(x_0)[0-\exp(-x_0)] \right)\\
&=& 2c( x_0 +1 )
\end{eqnarray}
Implying $c=\frac{1}{2( x_0 +1 )}$. Here's $f$ for $x_0=1$ (black) and $x_0=2$ (green):

As a quick check on our algebra, via approximate numerical integration the area under both curves seems to be 1 to about the right number of figures.
Now we have the pdf right, we can write the cdf:
$$F(x)=
\begin{cases}
c\exp(x+x_0)&x\leq -x_0\\
1/2+cx& -x_0<x<x_0\\
1/2+cx_0+c(1-\exp(x_0-x))& x\geq x_0
\end{cases}$$
(though there are perhaps better ways to write that last term; I'm not going to investigate that here)
Here are the corresponding cdfs for the above two cases:

Here's the quantile function, $Q(p) = F^{-1}(p)$:
$$Q(p) =
\begin{cases}
\ln(p/c)-x_0  & 0<p\leq 1/2 -cx_0\\
(p-.5)/c      & 1/2-cx_0<p<1/2+cx_0\\
x_0-\ln(1-[(p - 0.5)/c - x_0]) & 1/2+cx_0\leq p<1
\end{cases}$$
and a drawing of the inverse cdf for the same cases as above:

I wouldn't have got these right without drawing diagrams along the way, especially of $f$ and $F$.

Calculate the quantile for a mixed pdf


Setar Valor em um @html.DropDownList

Question: Em um form para Cadastros de endereços, queria fazer o seguinte. o cara digita o cep, então busca o cep, e retorna os dados para preencher nos EditorFor. Até ai tudo bem, está funcionando. Cidade e Estados estão em uma tabela separadas, e são exibidas por DropDownList. Queria que no retorno do Json, os dados além de serem preenchidos nos EditorFor, também ser exibidos no DropdownList de acordo com o CEP digitado. Ex: DropDownList de estados é exibido como Selecione e após digitar um cep que por exemplo Correspondesse à SP o dropdown trouxesse o estado listado, ao invés de permanecer o Selecione
DropDownList

        @Html.LabelFor(model => model.EstadoID, "Estado", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("EstadoID", null, htmlAttributes: new { @class = "form-control", id = "Estado", })
            @Html.ValidationMessageFor(model => model.EstadoID, "", new { @class = "text-danger" })

    </div

Ex de um EditorFor sendo preenchido com a informação do retorno:

        @Html.LabelFor(model => model.Bairro, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Bairro, new { htmlAttributes = new { @class = "form-control", id = "bairro" } })
            @Html.ValidationMessageFor(model => model.Bairro, "", new { @class = "text-danger" })

e aqui, meu objeto de retorno Json:

e por fim o Controller:
    public JsonResult RetornaEndereco(string cep)
    {
        var valor = Regex.Replace(cep, "[^0-9]", "");
        var ws = new WSCorreios.AtendeClienteClient();
        var resposta = ws.consultaCEP(valor);
        try
        {
            System.Console.WriteLine();
            System.Console.WriteLine("Endereço: {0}", resposta.end);
            System.Console.WriteLine("Bairro: {0}", resposta.bairro);
            System.Console.WriteLine("Cidade: {0}", resposta.cidade);
            System.Console.WriteLine("Estado: {0}", resposta.uf);
        }
        catch (Exception ex)
        {
            return Json("Erro ao efetuar busca do CEP: {0}", ex.Message);
        }

       //Alterado Daqui pra baixo
       Estado estado = (from u in db.Estados where u.Sigla == resposta.uf select u).SingleOrDefault();//Busca no banco pelo Estado

        Cidade iDCidade = (from u in db.Cidades where u.Nome == resposta.cidade && u.EstadoID == estado.EstadoID select u).SingleOrDefault();//Busca no banco pela cidade que está no mesmo estado
        Cidade levaCidade = new Cidade();
        if (iDCidade == null)//Se a cidade não estiver cadastrada, insere uma nova cidade.
        {
            Cidade cidade = new Cidade();
            cidade.Nome = resposta.cidade;
            cidade.EstadoID = estado.EstadoID;
            db.Cidades.Add(cidade);
            db.SaveChanges();
            levaCidade.CidadeID = cidade.CidadeID;//Pega o ID da cidade cadastrada
            levaCidade.EstadoID = cidade.EstadoID;//pega o id do estado selecionado
        }
        else
        {
            Cidade cidade = new Cidade();
            cidade.Nome = resposta.cidade;
            cidade.EstadoID = estado.EstadoID;
            levaCidade.CidadeID = iDCidade.CidadeID;//Pega o ID da cidade cadastrada
            levaCidade.EstadoID = estado.EstadoID;//pega o id do estado selecionado
        }
        Endereco levarEndereco = new Endereco();//Cria o objeto para ser transportado pelo Json
        levarEndereco.CidadeID = levaCidade.CidadeID;
        levarEndereco.Numero = levaCidade.EstadoID;//Passando o id do estado na variavel numero para alterar no json
        levarEndereco.Bairro = resposta.bairro;
        levarEndereco.Descricao = resposta.end;
        ViewBag.CidadeID = new SelectList(db.Cidades, "CidadeID", "Nome", levarEndereco.CidadeID);

         return Json(levarEndereco);
        //Alterado até aqui
    }

Console Log conforme @Brunno disse:
Answer: Se o DropDownList já estiver populado, basta fazer o que você fez:
$("#mydropdownlist").val("thevalue");

Você pode também adicionar um .change() caso não reflita o valor
Já se você tem um DropDownList vazio, você vai ter que adicionar a option:
$('#mydropdownlist').append($('<option>', {
    value: 1,
    text: 'Seu valor'
}));

UPDATE:
Se por exemplo você receber um json com as cidades assim:
'[{"id":1,"nome":"São Paulo"},{"id":2,"nome":"Belo Horrrizinte"},{"id":2,"nome":"Manaus"}]'

Você pode fazer o parse para objeto e depois iterar adicionado o mesmo no select, ficaria algo tipo isso:
HTML:
<select id="cidades">
</select>

JS:
var cidades = JSON.parse('[{"id":1,"nome":"São Paulo"},{"id":2,"nome":"Belo Horrrizinte"},{"id":2,"nome":"Manaus"}]');

cidades.forEach(function(cidade) {

  $('#cidades').append($('<option>', {
      value: cidade.CidadeID,
      text: cidade.Nome
  }));

});

Você pode ver funcionando aqui.
Comment: @Bruno eu estou fazendo a inserção de dados de cidades de acordo com o cep. o cara digita um cep, se a cidade não estiver cadastrado no banco, ele insere, e o retorno trás a ID da cidade, no caso precisava dar um refresh no dropdown.
Comment: Legal, então você já tinha todas as cidades no DropDownList :) esse refresh deu utilizando o que ? .change() ?
Comment: acho que vc não entendeu... assim, o cara digita um cep, se na minha base, aquela cidade não tiver, ele insere na base minha, e o dropdownlist não exibe aquele valor, pois preciso dar um refresh apenas nele entendeu? estou aqui buscando uma opção que só atualiza ele..., se eu der um refresh na página inteira o dropdown exibe o valor, se não der não exibe... sabe algo a respeito deste refresh apenas num componente?
Comment: Então, a ideia do .change() é isso, atualizar seu componente. ficaria algo assim: $('#estado').val(data.uf).change(); =]
Comment: Fiz assim **$('#cidade').val(data.CidadeID).change();** mas ele atualiza apenas se a cidade se já tiver sido carregada no load da página. se for uma cidade nova, que foi inserida não aparece durante o processo ele não aparece (só depois do refresh)...
Comment: Me diz uma coisa, quando você cria uma nova cidade como ela vem dentro do data ? a ideia da minha resposta acima é essa mesma, se já existir o .change() vai simplesmente atualizar seu DropDownList, já se não existir, você vai ter que adicionar ela na lista. Agora entra a questão o como adicionar, se você tiver todos os valores {nome e id}, é só adicionar no seu dropdown igual mostrado acima: $('#cidade').append($('', {
    value: data.cidade, //id da cidade
    text: data.cidade // Nome da cidade
}));
Comment: Eu alterei o Controler da uma olhada pra vc ver.... abaixo do Catch
Comment: @FabioSouza, clareou bem agora hehe.. seguinte, o DropDownList ele vai ser carregado com o ViewBag só quando sua Action for carregada a primeira vez. não temos como atualizar ele sem um ajax :( para contornar isso eu aconselho você a fazer o seguinte. Sabe a classe Endereco que você instancia ela com nome *levarEndereco* ? Eu adicionaria um atributo nela com o nome de NovaCidade por exemplo e enviaria nele o nome da nova cidade para adicionarmos no DropDownList utilizando aquele modo que te mostrei acima.
Comment: Uma outra alternativa, particularmente acho mais semântico porem menos performático. Seria dispara um ajax só para atualizar suas cidades. E depois disso setar o resultado =]
Comment: o value 1 seria o ID?
Comment: @FabioSouza, isso .. value é o Id, e o text é o texto que vai exibir para o usuário, no caso o nome da cidade.
Comment: @Bruno, se fosse uma lista de dados, o append funcionaria da mesma forma? ou seria algo a mais ai? um item único ele funciona, mais itens não...
Comment: Não, no caso teria que iterar na lista com um forEach e aí usar o append item a item
Comment: Bruno, no caso eu recebo a cidade em Json como vc disse, mas não entendi como utilizo o parse, pois ai vc inseriu valores fixos, mas no meu caso sempre irá variar
Comment: @FabioSouza, de um console log no seu retorno do ajax e poste na pergunta para eu ver como está chegando.
Comment: não sei se está certo, pois estou aprendendo ainda... está na resposta.
Comment: @FabioSouza, legal vi seu retorno aqui :), então fiz um update lá em cima na resposta e vou te orientar aqui, sabe lá onde faço JSON.parse() e passo uma string dentro ? basta você tirar minha string e passar sua variável que deu console.log(). verifique tmb o Id do seu select se está batendo com id que está no seletor antes do append :)

Setar Valor em um @html.DropDownList


Gradient descent with inequality constraints

Question: Suppose we are given a convex function $f(\cdot)$ on $[0,1]$. One wants to solve the following optimization problem:
\begin{equation}
\begin{aligned}
& \text{minimize} && \sum_{i=1}^n \alpha_i f(x_i), \\
& \text{subject to} && \sum_{j=1}^n \beta_j g_l(x_j) \leq 0, \text{  for  } l \in \{1,2,...,m\},
\end{aligned}
\end{equation}
where $x_i \in [0,1]$ for $i \in \{1,2,...,n\}$; $\alpha_i$s and $\beta_j$s are also in $[0,1]$. Also, $g_l(\cdot)$ is linear on [0,1], for $l \in \{1,2,...,m\}$.
I am thinking how to use gradient descent method to solve this problem. i.e., assume we repeat updating the variables via, say, $x_i ^{(t+1)} = x_i ^{(t)} - a f^{'}(x_i ^{(t)})$ for the $t$-th iteration, where $a$ is some step size. Since the constraints might be violated after the update, how can we make the constraints satisfied while moving the variables towards the optimum ?
In particular, in each iteration, one has to keep an eye on how the functions in the constraints are going, i.e., one might want to compute also the derivatives of the functions in the constraints. But do we have a general method to control this procedure ?
Answer: Look into the projected gradient method. It's the natural generalization of gradient descent to problems with linear constraints. E.g., https://tlienart.github.io/posts/2018/10/10-projected-gradient-descent (and references at the bottom), or https://web.mit.edu/dimitrib/www/OntheGoldstein.pdf or https://archive.siam.org/books/kelley/fr18/matlabcode.php.
Comment: Link is no longer functional.
Comment: @Brannon I added alternative links.
Answer: In general, these types of problems are naturally harder to solve algorithmically than unconstrained or equality constrained optimization problems, and are often solved by interior point methods. If your constraint and objective functions are 'nice' enough, there are some analytic tools you can use to take advantage of methods used for easier types of problems, to choose descent directions and such.
Chapter 11 of "Convex Optimization" would be a good start (http://www.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf).
Answer: Projected decent as described by Ulbrich worked really well for me:
https://www.springer.com/cda/content/document/cda_downloaddocument/9781402088384-c2.pdf?SGWID=0-0-45-642711-p173830414
I coded everything from scratch previously. However, I am now trying to see if there are easier implementations in TensorFlow, for example.
Comment: Link is no longer functional.


org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/xml;charset=UTF-8' not supported for bodyType

Question: using Java 11, SpringBoot 2, WebFlux, WebClient and Jackson
trying to use Spring WebClient to consume a Web service endpoint that returns XML, content type: 'text/xml;charset=UTF-8'
Jackson XML dependency in the project's pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.9</version>
</dependency>

WebClient code that triggers a request to external API and builds the response:
        WebClient.builder()
                .baseUrl(url)
                .build()
                .get()
                .uri(builder.toUriString(), 1L)
                .accept(TEXT_XML)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_XML_VALUE)
                .acceptCharset(Charset.forName("UTF-8"))
                .exchange()
                .flatMap(x -> x.bodyToMono(ServiceResponse.class))
                .flatMap(x -> buildResponse(x));

ServiceResponse class (a simple POJO):
public class ServiceResponse {

    private String ack;
    private String version;
    private String timestamp;
// .. getters and setters

resulting error:

org.springframework.web.reactive.function.UnsupportedMediaTypeException:
  Content type 'text/xml;charset=UTF-8' not supported for
  bodyType=com.sample.service.model.ServiceResponse at
  org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201)
  ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]     at
  java.base/java.util.Optional.orElseGet(Optional.java:369) ~[na:na]    at
  org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java:197)
  ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]     at
  org.springframework.web.reactive.function.BodyExtractors.lambda$toMono$2(BodyExtractors.java:85)
  ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]     at
  org.springframework.web.reactive.function.client.DefaultClientResponse.body(DefaultClientResponse.java:95)
  ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]     at
  org.springframework.web.reactive.function.client.DefaultClientResponse.bodyToMono(DefaultClientResponse.java:113)
  ~[spring-webflux-5.1.8.RELEASE.jar:5.1.8.RELEASE]

how to properly consume the type of response: Content-type 'text/xml;charset=UTF-8'  ?
Comment: Jackson is for JSON. You need JAXB to work with XML.
Comment: u can try application/xml
https://stackoverflow.com/questions/3272534/what-content-type-value-should-i-send-for-my-xml-sitemap
Comment: @guilhebl I am still facing this error. Did you find a solution for this?
Answer: Jackson XML is not supported at the moment by Spring Framework - see the dedicated issue. In the meantime, you can use Jaxb with Jaxb2XmlEncoder and Jaxb2XmlDecoder.
Answer: Adding
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)

worked for me.
MediaType Represents Internet Media Type that defined in the HTTP specification.
For reference : https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html
When I was trying write tc using WebTestClient in spring webflux, I faced this error.
The unit test is in below section:
@Test
 public void testGetJobSummariesResBody() throws Exception{
 List<JobSummary> responseBody =
                testClient
                .get().uri("<uri-name>")
                .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
                .header(APPNAME_HEADER, "")
                .exchange()
                .expectStatus().isOk()
                .expectBodyList(JobSummary.class)
                .returnResult()
                .getResponseBody();

        assertNotNull(responseBody.get(0).getJobType());
        assertNotEquals(0,responseBody.size());
    }

Answer: I had a similar case, when i was trying to return "plain/text" but the object was being resolved into a json format (so not really a text). I suppose spring was doing some validation of the response contenty-type and body u set. My actual response was like that:
Mono.just(quote.getQuote())
                .flatMap(s -> ServerResponse.ok()
                        .contentType(MediaType.TEXT_PLAIN)
                        .syncBody(s)
                );

but also acceptable was:
Mono.just(jsonQuote)
                .flatMap(s -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .syncBody(s)
                );

Answer: In my case the problem was that I forgot to set the Accept header and the default behavior of the server was to return XML.
Setting it to MediaType.APPLICATION_JSON resolved the issue and the server started returning JSON.
Answer: Another situation when confusing UnsupportedMediaTypeException is thrown.
Lets assume theres producing api that listens both http/80 and https/443. However its configured so that no content is served over http. Instead this returns HTTP 301 redirect message with some html content having content-type text/html. By default WebClient does not follow 301 redirect and instead it tries to parse returned html message into assumed class. This fails obviously and produces UnsupportedMediaTypeException exception.
This may be further confused by the fact that Postman by default follows 301 redirect and does it in a completely transparent way. Leaving impression that you get expected content via http request.
Solution: use https request.


How to remove 'Parent Directory' link from root folder in Apache directory listing

Question: How can I allow directory listing in Apache for a specific (root) folder and its subfolders, but without showing a link to parent of that root folder. When user is in a subfolder, the 'Parent Directory'link is displayed to navigate to its parent, but when user is at the root folder I need to remove/hide this 'Parent Directory' link so that user cannot move above that 'root' hierarchy.
Comment: Just not possible. You could write your own php script to do the directory listing. Don't see any other way. But I would not bother. The link shouldn't be there, but it's not like anything terrible will happen when you click it.
Comment: You are probably not asking the right question:  Regardless of the link, any user can still get to the parent by removing the last folder from the URL.  You need to ensure the server will not return anything on such URL.
Answer: You can hide the "Parent Directory" link by adding the following to your .htaccess file:
IndexIgnore ..

But this will hide it for every directory.
If you have access to the httpd-configs you could try to remove the directive from per-server context:
<DirectoryMatch "^/(?!var/www/your-root/subfolder)">
...
</DirectoryMatch>

As long as there is no IndexIgnore directive in an higher folder it should work for you.
Comment: @itoctopus I agree.  It's simple and clean.  The accepted answer is a kludge.
Answer: I just ran into the same issue, and this was the first search result, so I thought I'd share my solution. I don't have access to httpd-configs in my case, so I went with a different approach.
Because I won't be maintaining the indexed directory tree, I needed a solution that could exist just in the index root without any specific knowledge of its sub-directories. However, it does use an absolute path to the index root, so if your parent folder structure changes a lot, it may not work for you.
What I came up with was using a CSS URL attribute selector to hide the "Parent Directory" link when it led to the parent of the index root. It leaves a blank row, but at least it's not as intimidating as the "403 FORBIDDEN" error a user gets if they click Parent Directory one too many times.
Theoretically, the fix should be as simple as adding one line to your index root's .htaccess file:
IndexHeadInsert ""

However, it seems that simple solution doesn't work in IE because the default doctype of the html that Apache spits out is too old to use attribute selectors.
Instead, we have to surround Apache's generated code with our own doctype using the HeaderName and ReadmeName keywords in the htaccess file. I went with the HTML5 doctype, although there may be a more appropriate one that works.
.htaccess file:
Options +Indexes

IndexIgnore "_index_header.html" "_index_footer.html"

HeaderName "/absolute/path/to/root/index/_index_header.html"
ReadmeName "/absolute/path/to/root/index/_index_footer.html"

IndexOptions +SuppressHTMLPreamble

_index_header.html file:
<!DOCTYPE html>

        <title>title</title>

_index_footer.html file:

(Note that the CSS selector is to the index root's parent)
Works in all of the latest browser versions I tested it on (FF, IE, Chrome, Safari, Opera), and also all the way back to IE 7.
Also, now that you went through all the trouble of creating those files, you might as well make your index more snazzy. The apache doc on mod_autoindex has a bunch of options you can use to tweak things, on top of what you can do with CSS.
Comment: The css approach seems to only hide the link (as you mention). You can use insert a `
Answer: My solution is the following:
<Directory "/www"> Options +Indexes IndexIgnore .. _other </Directory>

<DirectoryMatch "^/www/download/.{1,}"> IndexIgnoreReset ON IndexIgnore _other </DirectoryMatch>

Comment: This is a great option. Works perfectly. The solution will remove the link only in the /www folder but every sub folder within it will be ok. Essentially its almost like you can make your own top level directory visually.
Answer: It seems like you're not asking the right question.
If your point is to prevent users from accessing the upper directory, removing the link won't solve anything for you since anybody can simply strip the last directory from the URL.
For example, if your subfolder is /var/www/secret/hive/subfolder and your DocumentRoot is set to /var/www, and you share link http://your.example.com/secret/hive/subfolder, anybody can still access http://your.example.com/secret/ or http://your.example.com/secret/hive even without that "Parent folder" link.
What you could do is:

Put "empty" index.html in each folder above "subfolder".  Apache will then offer that
file instead of listing, so the users won't know what's in "secret" or "hive".
Disable listing in each folder above "subfolder".  Apache will then refuse to show
the listing, so the users won't know what's in  "secret" or "hive".

However, if users are somehow able to guess names of files, they could still assemble a valid URL like http://your.example.com/secret/password.txt and with enough luck (and/or attempts), they could still get to some non-public information.
What you should do is:

set DocumentRoot to /var/www/secret/hive/subfolder,
or (better) keep DocumentRoot but move everything that is not public out of /var/www.

so http://your.example.com/ will show only the public information and there's no (HTTP) way how users can even ask for anything above.
Answer: There's a working trick to solve this issue, checking the url pathname via JQuery.
Just add this code at the top of your .htaccess file (obviously we can't separate paragraph lines here):
IndexHeadInsert ""
Note:

you may need to change the pathname length value, in my site is "4" because my archive root starts in a secondary subdirectory (if yours starts in the main root, try different values e.g. "3" or "2", or simply check your location.pathname length before all).
the "tr:nth-of-type(2)" css points to the second  record, that is the one supposed to manage the "PARENT DIRECTORY" we want to hide if the url location is our main root.

Have fun!
Comment: no need for jquery. `IndexHeadInsert ""` should work fine. For some reason my "parent directory" is the 3rd row (I have a header row and a separator before the directory listing starts). Change `'/'` to whatever pathname you want to hide the parent link for, eg. `'/builds/'` - it should automagically be hidden for a root pathname anyway.
Comment: I had to change your answer to this `IndexHeadInsert "`  This forces the javascript to execute once the DOM is ready
Answer: For more clarification...
Let we control this stuff from in directory .htaccess file, i.e .htaccess file that exist on the targeted directory. It may take the following configurations:
# STRONG HTACCESS PROTECTION
<Files ~ "^.*\.([Hh][Tt][Aa])">
 order allow,deny
 deny from all
</Files>

<IfModule mod_autoindex.c>
            Options Indexes FollowSymLinks
            IndexIgnore ".." #LOOK AT THIS LINE
            IndexOptions FancyIndexing
            IndexOptions VersionSort
           # IndexOptions HTMLTable
            IndexOptions FoldersFirst
            IndexOptions IconsAreLinks
            IndexOptions IgnoreCase
           # IndexOptions SuppressDescription
            AddDescription "Last generated backup result" backuplog.txt
            IndexOptions SuppressHTMLPreamble
            IndexOptions XHTML
            IndexOptions IconWidth=32
            IndexOptions IconHeight=32
            IndexOptions NameWidth=*
            IndexOrderDefault Descending Name
            HeaderName /index-style/header.html
            ReadmeName /index-style/footer.html
        </ifModule>

For hide the parent directory link, IndexIgnore should be written as shown in the code above. The above snippet has been tested with Apache 2.4.18.
Comment: The [existing answer from 2012](https://stackoverflow.com/a/10348160/369434) already states this. But this does not resolve the problem, since this will also remove the "Parent Directory" link from all subdirectories as well, which is not what the OP is wanting.
Comment: @MrWhite We can workaround this limitation by adding a `.htaccess`  in every subfolder without `IndexIgnore`.


How long would it take to test all possible states of a 64x64x64 cube of bits?

Question: Imagining a solid cube of $64 \times 64 \times 64$ bits (each of which can have exactly two states), how long would it take to test all possible states of one of these? Let's also assume we're using the world's current most powerful supercomputer, which can perform 33.86 quadrillion math operations per second. (mind you, this means you have to account for how many basic operations a calculation takes up: $2\times3$ is one, $2\times\frac 1 3$ is two, etc.)
I tried asking Wolfram|Alpha, but it timed out: http://wolfr.am/1q6fxd9
I ask this question in the name of encryption security as well as randomization seeding uniqueness, and decided to ask it here instead of StackOverflow because it has more to do with math than computing.
Answer: There are $64^3 = 262144$ bits, so that there are only $2^{262144}$ possible cubes, which is around $10^{79000}$.
Thus, it's not very feasible to do any sort of computation involving looping over all possible cubes.
Comment: @Supuhstar - infinity. Take a computer that runs $10^{16}$ operations a second, Notice how $79000$ is so much bigger than $16$? Now take into account that the entire universe is only $10^{17}$ years old, and you get the idea.
Comment: @Supuhstar - Why is this not a real answer? $10^{79000}$ seconds is the approximate time it would take on any machine, no matter how fast, a.k.a infinity.
Comment: @Supuhstar - Do I really have to spell it out? To get the number of seconds, divide the number of operations by operations per second: $10^{79000} / 10^{16} = 10^{78984}$ Which is, as mentioned, equivalent to never.
Comment: @Supuhstar - How un-vague do you want? Isn't $10^{78984}$ seconds good enough?
Comment: @Supuhstar - yes, your problem has an impractical scale. It's not the rounding which is the problem.
Comment: Can I have some sort of time estimate?
Comment: I was hoping for a real answer :/
Comment: you're not even showing any work. All I see are disjoint numbers...
Comment: you're rounding unnecessarily and giving me vague answers such as "infinity" and "never", when that's not the case
Comment: because it's rounded and at an impractical scale
Answer: There are $2^{64\times 64\times 64}=2^{262144} $ possibilities, so at a rate of 33.86 quadrillion per second, it will take $\frac{2^{262144}}{33.86\times 10^{15}}$ seconds.


How to import objects from custom library with deep export

Question: I have update my library structure (adding some directories), and now I can't import types from it.
Here is the structure of the library :
|-dist (builded typescript)
|-src
|--business
|---entities
|----user.ts
|----site.ts
|---usecases
|----user.usecase.ts
|----site.usecase.ts
|---entities.ts
|---usecases.ts
|--infrastructure
|---...
|--index.ts
|-package.json

user.ts and site.ts contains class and interface (same for usecases part).
entities.ts exports these types (same for usecases part) :
export { Site, SiteInterface } from "src/business/entities/site.js";
export { User, UserInterface } from "src/business/entities/user.js";

index.ts exports all from subdirectories :
export * from "src/business/entities.js";
export * from "src/business/usecases.js";

In user.ts, I can import Site like this : import { Site } from "src/index.js";
But when I install my library in another application, I get the above error Module '"<my-lib>"' has no exported member '<my-type>'.
I import it like this : import { Site, User } from '@xxx/<my-lib>';
Here are library's config files :
package.json
{
  "name": "@xxx/<my-lib>",
  "version": "0.0.0-alpha.1",
  "type": "module",
  "main": "src/index.js",
  "scripts": {
    "clean": "rm -rf dist",
    "build": "npm run clean && tsc --build",
    "test": "jest",
    "circular-deps": "madge --ts-config ./tsconfig.json --extensions ts --circular ./src"
  },
  "publishConfig": {
    "registry": "https://gitlab.com/api/v4/projects/<id>/packages/npm/"
  },
  "devDependencies": {
    "@babel/cli": "^7.22.6",
    "@babel/core": "^7.22.8",
    "@babel/preset-env": "^7.22.7",
    "@babel/preset-typescript": "^7.22.5",
    "@types/node": "^20.2.5",
    "babel-jest": "^29.6.1",
    "babel-plugin-module-resolver": "^5.0.0",
    "jest": "^29.6.1",
    "ts-jest": "^29.1.1",
    "ts-jest-resolver": "^2.0.1",
    "ts-node": "^10.9.1",
    "typescript": "^5.0.4"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "composite": true,                                   /* Enable constraints that allow a TypeScript project to be used with project references. */
    "target": "esnext",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "esnext",                                /* Specify what module code is generated. */
    "moduleResolution": "nodenext",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    "baseUrl": ".",                                     /* Specify the base directory to resolve non-relative module names. */
    "paths": {                                           /* Specify a set of entries that re-map imports to additional lookup locations. */
      "@xxx/<my-lib>": ["dist/src/"],
      "@xxx/<my-lib>/*": ["dist/src/*"],
    },
    "resolveJsonModule": true,                        /* Enable importing .json files. */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    "outDir": "dist",                                   /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": ["src/**/*", "package.json"],
  "exclude": ["node_modules/**/*"]
}

Does someone can help me to understand what I do wrong please ?
Comment: You need to generate the type definitions for the library and include it in your library package.
Comment: Hi @rveerd, thank you for your answer.
I have already `x.d.ts`and `x.d.ts.map`in my `dist` folder.
In fact I removed `types` because I do not find any documentation in official documentation (https://docs.npmjs.com/cli/v7/configuring-npm/package-json).

So I'va had in `package.json`:
```"types": "src/index.d.ts",```

But now : `Cannot find module '@xxx/' or its corresponding type declarations`.
Comment: You're src directory should never be referenced in any of your paths. Typescript does not transform these paths which means that the output in the dist folder is going to refer to the src folder
Answer: Ok I have found where was the problem :
Gitlab does not share workspace between stages, so it publish empty package. I have corrected this, and now it works.
I update my package following comments on my question too.
Thank you for your help @rveerd and @aluan-haddad :)


Lambda-Calculus - Alternative proof without fixed point combinator

Question: New chapter in my struggle with Lambda Calculus (previous chapters here and here, with my great thanks to those users who wrote enlightening answers). My problem is now to establish the following result in Example 2.13(ii) from "Introduction to Lambda Calculus":
$$\exists G \ \forall X, \ GX = GG $$
without setting $G \equiv \mathbf{Y} ( \lambda gx.gg)$. Here there is my attempt:

Proof: Let $G \equiv FF$ with $F\equiv \lambda fx.ffff$.
  Thus, from Compatibility Rule 1 we have that $FF = (\lambda fx.ffff)F$, from which $FF = \lambda x.FFFF$.
  Again, apply Compatibility Rule 1 to have $FFx = (\lambda x.FFFF)x$, from which we have $FFx = FFFF$. Finally, by definition of $G$, we have $Gx = GG$ and, since $x$ is arbitrary, $GX = GG$.  $\square$

I wouldn't call this elegant, but I am wondering if it is actually correct. Also, if it is, are there more elegant solutions to the problem that do not use $\mathbf{Y}$?
Any feedback as always will be greatly appreciated.
Thank you for your time.
Answer: Your proof is correct, except for a small detail. You defined $F \equiv \lambda fx.ffff$, which means that $F$ is nothing but a shorthand for $\lambda fx.ffff$. Hence $FF \equiv (\lambda fx.ffff)F$, which means that $FF$ is nothing but a shorthand for $(\lambda fx.ffff)F$ (and for $(\lambda fx.ffff)(\lambda fx.ffff)$ and  $F(\lambda fx.ffff)$ as well), i.e. they are syntactically the same object. In particular, this implies that $FF = (\lambda fx.ffff)F$ by the first equality rule (Def. 2.7 in  your notes), and not by the first compatibility rule.
Concerning a simpler solution of the problem that does not use $\bf Y$, you can repeat your proof by setting $F \equiv \lambda fx.ff$ and $G \equiv FF$. Then,
\begin{align}
G &\equiv FF = \lambda x.FF \equiv \lambda x.G \\
GG &\equiv (\lambda x.G)G = G = (\lambda x. G)X \equiv GX.
\end{align}
Comment: @Kolmin - Exactly, provided that the exponent is $\geq 1$!
Comment: Thanks a lot (and not just for this feedback): I think I am starting to see what's going on and this wouldn't be the case without your previous answers. Thus, basically all the alternative solutions  are obtained by following the same structure modulo proliferation of $f$ according to the power of $2$, right?


How Can You Define Successors Over The reals?

Question: I've been going through Introduction To Modern Set Theory by Judith Roitman, and am confused by her exposition of well orderings. She gives the following proof that every element $x$ of a well-ordered set $X$ is a maximum or has a successor: $$\text{If}\ x\ \text{is not maximum, then}\ {S=\{y \in X\ |\ y > x\} \neq \emptyset}\ \\ \text{The minimum of }S \text{ is the successor of }x.$$
I hit a cognitive roadblock when thinking about such a minimum element in a dense field like the reals. She defines $x$ to be a limit in a well-order $X$ iff $$\forall y \in X, x \neq S(y)$$that is, $x$ is a limit if it is not the successor of some element $y$. She says that every element of $\mathbb{R}$ is a limit, which agrees with my intuition. What I do not understand, specifically, if why the corresponding condition of $\forall y \in X, y \neq S(x)$ does not hold for $\mathbb{R}$ with the usual ordering. If that held, it seems to me to go against the claim that every element of a well-ordered set is a maximum or has a successor (since every element of $\mathbb{R}$ would be neither maximum nor have a successor). Any help in getting around whatever cognitive error it is that I'm making would be much appreciated.
Comment: It is not an error; it is a correct inference.  By definition, any element of a well-ordered set is either a maximum or a successor.  However every element of the reals is *neither* a maximum *nor* a successor.  Therefore... the reals are *not* a well-ordered set.  $\blacksquare$  The reals are ordered; just not well-ordered.
Comment: Where when @Graham says "the reals" he means not the set of real numbers, but the ordered set of real numbers equipped with the usual ordering.
Comment: @fleablood: I don't believe that's true: I'm pretty sure that people *have* defined well-orderings of the reals. What happens is that additional hypotheses are required (e.g. the axiom of constructibility) to prove that the definition gives a total ordering.
Comment: The usual ordering is not a well-ordering.  No-one has defined a well-ordering of the Reals yet.
Comment: @Hurkyl You are quite right and http://math.stackexchange.com/a/6504/176997 gives a great exposition. Favorite points on comments should really count towards something. Good comments are often as important as answers.
Answer: It seems like what you're missing is that the usual order on $\mathbb{R}$ is not a well-ordering.  So there is no problem with the fact that no element of $\mathbb{R}$ has a successor.
Answer: By definition, '$x$ is maximum element' in an ordered set $D$ with ordering relations $<$ iff there is no element in $D$ which is greater than $x$. So if $x$ is not maximal, then there exist elements (at least one) in $D$, which are greater than $x$. They form a subset $S$ of $D$. And that subset inherits the ordering relation $<$ from $D$. If we assume $D$ is well-ordered, so is $S$. And the main property of a 'well-order' is that each non-empty subset has a least element. Name it $q$.
As we chose $S$ to be a set of elements greater than $x$, its least element $q$ is greater than $x$ but it's smaller than all other elements of $S$. So there exists no element between $x$ and $q$, hence $q$ is a successor of $x$.
Note, however, the standard $<$ relations on $\mathbb R$ is not a well-order; there are subsets of $\mathbb R$ which have no least elements. In particular the $\mathbb R$ itself has no least element, similary any open interval $(a,b)$ or a set of integers $\mathbb Z\subset\mathbb R$.


Decoding H264 VideoToolkit API fails with Error -12911 in VTDecompressionSessionDecodeFrame

Question: I'm trying to decode a raw stream of .H264 video data but I can't find a way to create a proper
    - (void)decodeFrameWithNSData:(NSData*)data presentationTime:

(CMTime)presentationTime
{

    @autoreleasepool {

    CMSampleBufferRef sampleBuffer = NULL;
    CMBlockBufferRef blockBuffer = NULL;
    VTDecodeInfoFlags infoFlags;
    int sourceFrame;

    if( dSessionRef == NULL )
        [self createDecompressionSession];

    CMSampleTimingInfo timingInfo ;
    timingInfo.presentationTimeStamp = presentationTime;
    timingInfo.duration =  CMTimeMake(1,100000000);
    timingInfo.decodeTimeStamp = kCMTimeInvalid;

    //Creates block buffer from NSData
    OSStatus status  = CMBlockBufferCreateWithMemoryBlock(CFAllocatorGetDefault(), (void*)data.bytes,data.length*sizeof(char), CFAllocatorGetDefault(), NULL, 0, data.length*sizeof(char), 0, &blockBuffer);

    //Creates CMSampleBuffer to feed decompression session
    status = CMSampleBufferCreateReady(CFAllocatorGetDefault(), blockBuffer,self.encoderVideoFormat,1,1,&timingInfo, 0, 0, &sampleBuffer);

    status = VTDecompressionSessionDecodeFrame(dSessionRef,sampleBuffer, kVTDecodeFrame_1xRealTimePlayback, &sourceFrame,&infoFlags);

    if(status != noErr) {
        NSLog(@"Decode with data error %d",status);
    }

    }
}

At the end of the call I'm getting -12911 error in VTDecompressionSessionDecodeFrame that translates to kVTVideoDecoderMalfunctionErr which after reading this [post] pointed me that I should make a VideoFormatDescriptor using CMVideoFormatDescriptionCreateFromH264ParameterSets. But how can I create a new VideoFormatDescription if I don't have information of the currentSps or currentPps? How can I get that information from my raw .H264 streaming?
CMFormatDescriptionRef decoderFormatDescription;
const uint8_t* const parameterSetPointers[2] =
    { (const uint8_t*)[currentSps bytes], (const uint8_t*)[currentPps bytes] };
const size_t parameterSetSizes[2] =
    { [currentSps length], [currentPps length] };
status = CMVideoFormatDescriptionCreateFromH264ParameterSets(NULL,
       2,
       parameterSetPointers,
       parameterSetSizes,
       4,
       &decoderFormatDescription);

Thanks in advance,
Marcos
[post] : Decoding H264 VideoToolkit API fails with Error -8971 in VTDecompressionSessionCreate
Answer: You you MUST call CMVideoFormatDescriptionCreateFromH264ParameterSets first. The SPS/PPS may be stored/transmitted separately from the video stream. Or may come inline.
Note that for VTDecompressionSessionDecodeFrame your NALUs must be preceded with a size, and not a start code.
You can read more here:
Possible Locations for Sequence/Picture Parameter Set(s) for H.264 Stream
Comment: I sent a bounty for this amazing old answer, @szatmary , thanks!  :)  (We are having a similar problem with "SPS/PPS recognition"  in the 265 era, on iOS builds  :/  )
Comment: Your blog appears to be down.


Fazer pesquisa via POST ao clicar na div

Question: Estou adaptando o seguinte script:

$(document).ready(function(){
    $('#getUser').on('click',function(){
        var user_id = $('#user_id').val();
        $.ajax({
            type:'POST',
            url:'php/getData.php',
            dataType: "json",
            data:{user_id:user_id},
            success:function(data){
                if(data.status == 'ok'){
                    $('#userName').text(data.result.name);
                    $('#userEmail').text(data.result.email);
                    $('#userPhone').text(data.result.phone);
                    $('#userCreated').text(data.result.created);
                }else{
                    alert("User not found...");
                }
            }
        });
    });
});

<input type="text" id="user_id" />
<input type="button" id="getUser" value="Get Details"/>

User Details

Name:

Email:

Phone:

Register Date:

<?php
if(!empty($_POST['user_id'])){
    $data = array();

 /******* Conexão com o bando de dados *******/
 include "../../Conexao/config.php";

 mysqli_select_db($config, $database_config);
 mysqli_set_charset($config,"utf8");
 /******* Conexão com o bando de dados *******/

    //database details
    $dbHost     = $hostname_config;
    $dbUsername = $username_config;
    $dbPassword = $password_config;
    $dbName     = $database_config;

    //create connection and select DB
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    if($db->connect_error){
        die("Unable to connect database: " . $db->connect_error);
    }

    //get user data from the database
    $query = $db->query("SELECT * FROM users WHERE id = {$_POST['user_id']}");

    if($query->num_rows > 0){
        $userData = $query->fetch_assoc();
        $data['status'] = 'ok';
        $data['result'] = $userData;
    }else{
        $data['status'] = 'err';
        $data['result'] = '';
    }

    //returns data as JSON format
    echo json_encode($data);
}
?>

Ele funciona com o evento "click".
Eu preciso que ele funcione com o TAB do teclado ou ao clicar sobre a div, como nessa consulta de cep:
https://viacep.com.br/exemplo/jquery/
Answer: Este efeito é conseguido com o evento blur que ocorre ao perder o foco do campo de texto.
Seria algo como:
$('#user_id').on('blur', function () {
  ...
});

Mais informações
blur (evento)


Why should I transpose coefficient vector in linear regression?

Question: I was reading a basic state-space model that looks like this (here, $\mathbf X$ is a vector of predictor variables):
$$
\begin{align}
&(1) \quad y_t = \mu_t + \tau_t + \lambda_t + \epsilon_t, \epsilon_t \sim N(0,V_{\epsilon})\\
&(2) \quad \mu_{t+1} = \mu_t + \xi_t, \xi_t \sim N(0,W_{\xi})\\
&(3) \quad \tau_{t+1} = \sum_{s=0}^{50}\tau_{t-s}+u_t, u_t \sim N(0, W_{u})\\
&(4) \quad \lambda_t = \beta^T\mathbf{X}_t
\end{align}
$$
My question is: Why is the coefficient vector transposed in the regression component? This seems odd to me. Typically you would see the transpose is made on the data matrix, like here in linear regression:
$$
y = \beta\mathbf{X}^T + \epsilon
$$
or this:
$$
y = \mathbf{X}\beta + \epsilon
$$
Could anybody please explain?
Answer: I don't agree with the notation, but don't get lost in the weeds because I think you can figure out the important bits. Statisticians can get a little loose with their matrix algebra, especially that a matrix with one row or one column is treated like a vector. In several places in the display you posted, I think the author would agree $y + y^T = 2y$.
I am used to seeing the expression for the fitted value as $\hat{y} = X^T \beta$, and consequently $y = \hat{y} + \epsilon$.. The $\beta$ as a matrix is usually thought of as a $p \times 1$ matrix, that's what you get from solving $\hat{\beta} = (X^TX)^{-1}X^T Y$ where $X$ is a $n \times p$ matrix of regressors (with or without an intercept term as a column). Here the $y$ is also thought of as a $n \times 1$ matrix.
Comment: The real issue comes down to showing that definition (4), which involves the design matrix $X,$ is consistent with the $y=\beta X^\prime + \cdots$ formulation.  There does not appear to be any "looseness" in this notation.
Comment: Assuming $\lambda_t$ in (4) is a scalar, the rules of matrix multiplication imply $\beta$ and $X_t$ must be column vectors with as many components as there are predictors.  Consequently, only the second expression $y=X\beta+\cdots$ makes any sense, and that in turn tells us $X_t$ must be the transpose of row $t$ in matrix $X.$  In other words, one works through material like this by taking it on its own terms, rather than approaching it from a preferred perspective.  Conventions vary, but most writers will use vectors and matrices consistently within a document.
Comment: @whuber this is a state space model, so $X_t$ is the design matrix $X$ of dimension $n \times p$ at time $t$, not transposed. I think (thought) OP's confusion was that the fitted value is expressed as $\beta^T X$ which is a $1 \times n$ vector, whereas $X^T \beta$ would be $n \times 1$.
Comment: @whuber could you please elaborate a little bit more? So do you mean if X is defined as is (a vector of predictor variables), it makes sense to transpose the coefficient vector? (perhaps to match the number of rows and columns to allow multiplication?)
Comment: @AdamO actually, it says that Xt is a vector of predictor variables (which I am assuming the dimension is n x 1, n as in the number of variables). I think β should also be a n x 1 vector - that is the only way β transpose would make sense to me...
Comment: @whuber you're right, λt in (4) is a scalar.
Comment: I believe, Kang, that the source consistently uses "vector" to mean a *column vector.*  At any rate, its notation conforms to such a convention.  This agrees with @Adam's comment: the rows of the design matrix $X$ are indexed by $t$ (just as $Y$ is) and, because they are *row vectors,* they will be expressed as the *transposes* of the column vectors $X_t.$  That is, you may visualize $X$ as a stack of rows $X_1^\prime,$ $X_2^\prime,$ down to $X_n^\prime.$
Comment: @whuber again I may have a different interpretation. I think another possibility here is that $\mathbf{X}_t$ represents a whole design matrix at time $t$, i.e. each covariate is evaluated at time $t$. But I can see how the $t$ subscript can indicate a row subset. producing a single vector. Anyway, the ultimate source is the paper or text that this came from, and if it's not clear, not a bad idea to shoot an innocuous note to the author that the notation could do with some sprucing up.
Comment: @AdamO Agreed on all points.  Thank you for those clarifications.


Relation between roots of an irreducible polynomial

Question: Let $K$ be a field, and $\alpha$ be an element of a separable extension of $K$, such that $\alpha^p\in K$, but $\alpha\notin K$, $p$ a prime.
Let $f$ be the minimal polynomial of $\alpha$ over $K$ and $\beta$ be another root of $f$.
Question 1. Is it true that $\alpha$ and $\beta$ differ by a $p$-th root of unity? i.e. if $\epsilon=\alpha/\beta$, the is $\epsilon^p=1$?
Question 2. In general, is it true that any two roots of an irreducible polynomial over a field always differ (multiplicatively) by a root of unity?

Reference: Galois Theory - Ian Stewart, Third Ed., p. 156.
Answer: (1) Let $f(x)$ be the minimal polynomial of $\alpha$. Let $k=\alpha^p$ (note $k\in K$). Since $\alpha^p-k=0$, we must have $f(x)\mid (x^p-k)$, and so $\beta$ is also a root of $x^p-k$, thus $\alpha^p=k=\beta^p~\Rightarrow (\alpha/\beta)^p=1$.
(2) No. There's no reason for them to in general. The needn't be the same size even. For instance, over $\Bbb Q$, the roots of the irreducible quadratic $(x-1)^2-2$ don't have the same size.
In general, the only relations satisfied by roots of a polynomial are Vieta's formulas. (There probably exists some kind of clever formal way to state this idea.)


LilyPond – omit first page-number when numbering formatted by markup

Question: I use this snippet to reformat the LilyPond page numbering:
pagenumcol = \markup {
  \column {
    \vspace #0.5
    \fromproperty #'page:page-number-string
  }
}

copyrightcol = \markup {
  \fill-line {
    \box \fontsize #-4
    \column {
      \line { "Educational copying welcome." }
    }
  }
}

\paper {
  oddHeaderMarkup = \markup \null
  evenHeaderMarkup = \markup \null
  oddFooterMarkup = \markup { \copyrightcol \pagenumcol }
  evenFooterMarkup = \markup { \pagenumcol \copyrightcol }
}

When using this example the first page number gets printed. Does anyone on here know how I can omit this?
I tried to add print-first-page-number = ##f, but it does not take any effect in this scenario.
Answer: By default, the page number is not printed on the first page, so adding print-first-page-number = ##f won't change the default setting.
Rather, you first need to check whether LilyPond would by default print the page number on the relevant page. This can be done with \on-the-fly #print-page-number-check-first (see also the relevant section in the LilyPond documentation on customised footers and headers).
This way, you re-activate the default behaviour of not printing the page number on the first page, which you overrode by defining your custom footer.
The following settings should work:
pagenumcol = \markup {
  \column {
    \vspace #0.5
    \fromproperty #'page:page-number-string
  }
}

copyrightcol = \markup {
  \fill-line {
    \box \fontsize #-4
    \column {
      \line { "Educational copying welcome." }
    }
  }
}

\paper {
  oddHeaderMarkup = \markup \null
  evenHeaderMarkup = \markup \null
  oddFooterMarkup = \markup { \copyrightcol \on-the-fly #print-page-number-check-first \pagenumcol }
  evenFooterMarkup = \markup { \on-the-fly #print-page-number-check-first \pagenumcol \copyrightcol }
}


How to get perpendicular line to an edge of a polygon.

Question: This is a pretty basic geometry question, but I couldn't find an answer clear enough for me on Google (I don't know much about math).
Let's say I have a rectangle. I have the coordinates for the four vertices, thus I have the angles of the rectangle and the lengths of the edges.
I need to find one perpendicular line for each of the shape's edges. How can I do that, the simplest way?
Thanks
Edit:
What I mean: I need to know how to find the lines that come out of the rectangle's edges.
Comment: Will these perpendicular lines need to be different from the other sides of the rectangle?  In particular, by "rectangle" I assume that you mean "a four-sided two-dimensional figure in the plane having all interior angles congruent to $90^\circ$"...
Comment: Please see my edit, it explains what I mean.
Answer: With a straightedge and compass, the lines specified can be constructed as follows:

Take the compass, set the size to draw circles slightly larger than half the length of the long side of the rectangle
With this fixed size, draw four circles, each one centered on one corner of the rectangle
Take the straightedge and line it up with the locations where the circles intersect in four collinear locations
Draw the perpendicular bisectors of each side of the rectangle where the straightedge crosses it

See the picture below for more info.

The colored circles are centered on each of the four corners of the rectangle; the long sides have closer-together circle intersections so it is possible to see all of them and easy to connect them with a line.  For the shorter sides, it may be necessary to construct a second set of four circles that are smaller and have closer-together intersections, depending on the size of the piece of paper you are using.
Alternatively, it is possible to construct these lines using midpoints.  If the four corners of the rectangle are $A,B,C,D$ where $\exists x_A,y_A\in\Bbb R: A=(x_A,y_A)$, etc., then the midpoints of each side are connectable as perpendicular bisectors as well.  Let $M_{XY}$ be the midpoint of side $XY$, then we have coordinates:
$$M_{AB}=(\frac {x_A+x_B}2,\frac {y_A+y_B}2)\\
M_{BC}=(\frac {x_B+x_C}2,\frac {y_B+y_C}2)\\
M_{CD}=(\frac {x_C+x_D}2,\frac {y_C+y_D}2)\\
M_{DA}=(\frac {x_D+x_A}2,\frac {y_D+y_A}2)$$
It is further possible to create these as lines extending beyond each side, using the generic line formula
$$(E_x-S_x)(y-S_y)=(E_y-S_y)(x-S_x)$$
Where $E,S$ are "starting" and "ending" points of the lines in question.
Comment: Sorry if I was unclear. I need to get the *angle* of the perpendicular line to each edge. How can I do that?
Comment: It is the same angle as the adjacent side.  The line perpendicular to side $AB$ has angle congruent to the side $BC$, and so on.
Comment: What if I have a line and I know it's angle. If I simply add 90 degrees to it, will I get the angle of it's perpendicular line?
Comment: That is correct.
Comment: Okay thanks :) .
Answer: EDIT1

Deleted an earlier computational given solution for this construction: Choose a radius more than half the larger side length of the rectangle and draw four circles centered at each corner of the rectangle with this same radius. Join either the outermost (or innermost) points of circle intersection lying on opposite sides of rectangle as shown by the required purple perpendicular bisectors.


Prove that the $\sigma$-sets of the semiring $S$ form a topology for $\mathbb R$.

Question:
Prove that the $\sigma$-sets of the semiring $$S=\{[a,b): a,b, \in \mathbb R, a \le b \}$$ form a topology for the real numbers.

I know that a subset $A$ of $\mathbb R$ is a $\sigma$-set w.r.t. $S$ if there exists a disjoint sequence $\{ A_n\}$ of $S$ such that $\displaystyle A = \bigcup_{n=1}^\infty A_n$.
So in this case, I must show that if $\{[a_n, b_n): a_n,b_n \in \mathbb R, a_n\le b _n\}_{n \in \mathbb N}$ is a sequence of half-open intervals in $S$, then the set $\displaystyle A = \bigcup_{n=1}^\infty\{[a_n, b_n): a_n,b_n \in \mathbb R, a_n\le b _n\}$ forms a topology of $\mathbb R$.
How do I go about showing this though?
Comment: Note that the _family_ of such sets $A$ forms a topology, not just one set.
Comment: @PedroSánchezTerraf . Thanks for pointing that out :). That makes sense :). I still don't know how to show that it forms a topology though. :(
Answer: HINT: The Sorgenfrey line is $\Bbb R$ endowed with the topology generated by the base
$$\mathscr{B}=\{[a,b):a,b\in\Bbb R\text{ and }a<b\}\;.$$
Since $\mathscr{B}$ is closed under finite intersections, this topology $\tau$ is just $\left\{\bigcup\mathscr{U}:\mathscr{U}\subseteq\mathscr{B}\right\}$. Clearly $\tau$ contains all of the $\sigma$-sets of $S$. To complete the argument, you need only show that if $\mathscr{U}\subseteq\mathscr{B}$, then there is a countable $\mathscr{V}\subseteq\mathscr{B}$ such that $\bigcup\mathscr{U}=\bigcup\mathscr{V}$. Let $A=\bigcup\mathscr{U}$.

Let $U=\bigcup\{(a,b):[a,b)\in\mathscr{U}\}$; show that there is a countable $\mathscr{V}_0\subseteq\mathscr{U}$ such that $\bigcup\{(a,b):[a,b)\in\mathscr{V}_0\}=U$.
Show that $A\setminus U$ is countable, so there is a countable $\mathscr{V}_1\subseteq\mathscr{U}$ that covers $A\setminus U$.

Now just let $\mathscr{V}=\mathscr{V}_0\cup\mathscr{V}_1$.


RecyclerView - No adapter attached; skipping layout

Question: I know this question has already been posted but i tried all solutions and the error still exists.when i call fragment which is loading some data from json and set it in recyclerview, with Debug app i get this error

RecyclerView: No adapter attached; skipping layout

Fragement :
public class Artists extends  Fragment {
    String URL_DATA = JsonData.FirebaseList;
    RecyclerView.LayoutManager layoutManager;
    ProgressBar pb;
    private List<Post_Artist> post_artists;
    private RecyclerView recyclerView;
    private TextView loading;
    private AdapterFor_Artists adapter;
    private AdView mAdView;

    public Artists() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_artists, container, false);
        post_artists = new ArrayList<>();
        recyclerView = v.findViewById(R.id.rc);
        layoutManager = new GridLayoutManager(getActivity(),1);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        loading = v.findViewById(R.id.loadingtext);
        pb = v.findViewById(R.id.loadingP);
        Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(),"ARCADECLASSIC.TTF");
        loading.setTypeface(typeface);
        if (adapter == null) {
        adapter = new AdapterFor_Artists(post_artists, getActivity(), new RecyclerViewClickListenner_ForArtist() {
            @Override
            public void onClick(View view, Post_Artist post_artist) {
                Intent intent = new Intent(getActivity(), ArtistsPage.class);
                intent.putExtra("json_url", post_artist.getJsonUrl());
                intent.putExtra("name", post_artist.getArtistName());
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.fadein, R.anim.fadeout);
            }
        });
        recyclerView.setAdapter(adapter);
        checkInternet();
        return v;
    }

    private boolean checkInternet() {
        if (!isNetworkConnected()) {
            showDialog();

            return false;
        } else {
            refreshContent();
        }
        return true;
    }

    public boolean isNetworkConnected() {
        ConnectivityManager connectionManager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectionManager == null) {
            return false;
        }
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

    private void refreshContent() {
        fetchRemoteData(new DataStatus_For_ArtistsList() {
            @Override
            public void onSuccess(List<Post_Artist> post_artists) {
                loading.setVisibility(View.GONE);
                pb.setVisibility(View.GONE);
                    adapter.getItems().clear();
                    adapter.getItems().addAll(post_artists);
                    adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Exception e) {
                msgError();
            }
        });
    }

    }
    private void fetchRemoteData(final DataStatus_For_ArtistsList callback) {
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        List<Post_Artist> listItems = new ArrayList<>();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray("bgs");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject o = array.getJSONObject(i);
                                Post_Artist item = new Post_Artist(
                                        o.optString("json_url"),
                                        o.optString("name"),
                                        o.optString("cover")

                                );
                                listItems.add(item);
                            }
                            callback.onSuccess(listItems);
                        } catch (JSONException e) {
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callback.onError(error);

                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        requestQueue.add(stringRequest);
    }

Comment: Create & set the adapter in `onCreateView`, with no items. In your network response handler, add the items to the existing adapter.
Comment: @siger please see my update post
Answer: You have to set the adapter with your post_artists list in the onCreateView().your adapter is null that's why you have this error.


Git: keep multiple branches checked out

Question: Each time I checkout a branch, I need to rebuild my project. This project has a long build process and I frequently switch branches so this wastes a lot of time. My solution has been to create local clones of the local repo, with different branches checked out in each clone, so that build scripts aren't faced with wholesale changes to the source each time I switch branches. The downside is that I've got to remember to keep the clones up to date.
Is there a better way to deal with this situation? If not, what are the best practices for maintaining multiple local clones?
Thanks!
Matt
Answer: You can try git-new-workdir for working with multiple checked out copies of the same repo. This will let you have a checked out copy of your repo for each branch (with all the build files involved), without the overhead of a full clone.
Comment: Thanks @meagar; git-new-workdir sounds promising. I'll give it a try and report back.
Comment: We're using Windows, so we got this working using [Dan Smith's Windows port of git-new-workdir](https://github.com/dansmith65/git/blob/master/contrib/workdir/git-new-workdir-win) and running Git bash as admin.

Git: keep multiple branches checked out


Perl convert date timezone without datetime module

Question: I have a date in the format:  05/26/2013 06:08:00
The timezone of above date is GMT -7
how can i change the above to GMT date and time and in format:
 26 May 2013 13:08:00 GMT
Note: I cannot install any perl module. I know that i can do this easily via DateTime but i cannot install it.
Thanks.
Comment: What version of Perl? Why not use local::lib and install DateTime for you?
Comment: @MiguelPrz  This is a production machine. There are various reasons behind not installing perl modules. Thanks.
Comment: you are sure you know the fixed offset, that there isn't sometimes daylight savings time?
Comment: @ysth Actually i'm parsing a log file. And it is in GMT -7.
Comment: Wouldn't the GMT time be `26 May 2013 13:08:00 GMT` based on what you have on the first line?
Comment: @doubleDown  Yes, sorry edited it!
Comment: "There are various reasons behind not installing perl modules." All of them bad. If you're not using modules from CPAN then you're not using most of the power of Perl. I suggest you find a better sysadmin, manager or job :-)
Answer: You can use Time::Piece which should be included with your Perl installation.
use Time::Piece;

my $datetime = '05/26/2013 06:08:00';
$datetime   .= '-0700'; # attach the timezone offset

my $dt = Time::Piece->strptime($datetime, '%m/%d/%Y %H:%M:%S %z');
print $dt->strftime('%d %b %Y %H:%M:%S');

Comment: It should be noted that `Time::Piece` only became core module with Perl v5.9.5.
Comment: Awesome, thanks! Is this efficient enough to run it for 10000 entries at a time?
Comment: It should be since it's a fast and light module. But it would be best if you tested it yourself.
Answer: Assuming your local time is already set to GMT-7, simply:
use POSIX 'mktime', 'strftime';
my $datetime = '05/26/2013 06:08:00';
my ($month,$day,$year,$hour,$min,$sec) = $datetime =~ m{^([0-9]+)/([0-9]+)/([0-9]+) ([0-9]+):([0-9]+):([0-9]+)\z}
    or die "invalid datetime $datetime\n";
my $formatted_time = strftime '%e %B %Y %T %Z', gmtime mktime $sec,$min,$hour,$day,$month-1,$year-1900,0,0,0;

You may want %d instead of %e and/or %b instead of %B; see http://pubs.opengroup.org/onlinepubs/9699919799/functions/strftime.html and verify that the desired format specifiers are supported on your system.


Why don't we get to indicate the appropriate site for off-topic questions?

Question: When voting to close a question as off-topic in the main site, we have the option to check as reason,

"This question belongs on another site in the Stack Exchange network"

Then a new window opens... and the only option we get is that the question belongs to the meta of economics.se.
I don't know if this is a bug or deliberate, but if it is deliberate, it renders the option totally useless -the point is to be able to select among the SE sites.
I understand that migration itself (decision and execution) is and should be the responsibility of moderators, but we should be able to indicate to them what site we think is the appropriate one, to avoid duplication of effort.
I checked the same feature in Cross Validated, and there, one gets the option, apart from migration to meta, to indicate math.se and stackoverflow.
Then I guess someone, either a moderator or an SE-associate could (and should) add to our choices in the main for off-topic/migration suggestions, the following four sites
https://money.stackexchange.com/
https://quant.stackexchange.com/
https://stats.stackexchange.com/
https://math.stackexchange.com/
Answer: UPDATE:
Based on When should we consider adding a default migration path? and https://meta.stackexchange.com/a/276084/274708
it seems like (1) migration paths are not likely to be added while this site is still in beta, and (2) a migration path is not likely to  be deemed appropriate until we are sending "tens or hundreds" of migrations to a site within each 90 day period (we are currently well short of that level).
For now, please continue to handle migration requests using the flag feature.

Original post
It seems we can have a maximum of four external sites listed, but I couldn't find an option to add them myself. I have asked on Meta.SE to find out how to get this done.
For the record, we don't actually migrate that much. Here is a complete list of every question that has ever been migrated from econ.SE.

My understanding is that sites will be added to the migration target list only on the basis of evidence that there are a significant number of migration candidates for that site. Based on the above list, only Money.SE seems to generate a significant number of questions for migration right now so I think it unlikely that sites other than Money.SE will be added to the list.
In the event of a question that belongs on a site other than Money.SE, the relevant response will probably continue to be flagging the question for moderator attention. The mods can migrate to any site and other migration targets can be added to the list if and when we build up a substantial stream of questions that have been migrated to them.
Comment: Let's see how the migration rate changes once we actually can enforce it automatically.


Clear() e SendKeys() num só método

Question: Tenho os métodos clear e sendKeys e queria "colapsar" os dois num só,
WebElement user = webdriver.findElement(By.id("username"));
user.clear();
user.sendKeys(username);
WebElement passw = webdriver.findElement(By.id("password"));
passw.clear();
passw.sendKeys(password);

Answer: Podes criar um método novo:
public void setNewInputValue(WebElement elem, String value) {
    elem.clear();
    elem.sendKeys(value);
}

Answer: Existem 2 opções que eu conheço, mas acredito que a melhor alternativa realmente seja criar um método para a ação, conforme os exemplos abaixo:
@Test
public void clearSendTest() throws InterruptedException {
    driver.findElement(By.cssSelector("input[title='pesquisar']")).sendKeys(Keys.CLEAR, "php");
    Thread.sleep(3000);
}

public void clearAfterSend() {
    driver.findElement(By.cssSelector("input[title='pesquisar']")).clear();
    driver.findElement(By.cssSelector("input[title='pesquisar']")).sendKeys("java");
}

@Test
public void clearAfterSendTest() throws InterruptedException {
    clearAfterSend();
}

Clear() e SendKeys() num só método


How does the assumption of constant variance affect the inferential tools

Question: I'm learning applied linear regression right now and of course one important topic is constant variance of errors. In Sheather's textbook, it's said that

Ignoring nonconstant variance when it exists invalidates all inferential tools (i.e. p-values, confidence intervals, prediction intervals etc.).

But he doesn't explain the reason. Can someone explain it from a statistical perspective to show how the violation of constant variance assumption will invalidate the inferential tools?
To go more straightforward: Why do we need the assumption of constant variance? I found some relevant answers on Cross Validated like here,  but they seem not able to make me clear.
Thanks!
Answer: The simple regression linear model looks like $y = X\beta + \epsilon$ and among constraints we have independent white noise $\epsilon_i \sim N(0, \sigma^2)$. Fitting with least mean squares gives the know normal equations in the form:
$\hat{\beta} = (X^TX)^{-1}X^Ty$
To optimize with least mean square one does not use any statistical reasoning. However if you ask questions about the statistical properties of your sample statistic $\hat{\beta}$ you start too need those assumptions.
For example if you ask about statistical properties of your sample statistics this is something else. For example if we ask if the $\hat{\beta}$ is biased you might go with:
$E\hat{\beta} = E[(X^TX)^{-1}X^Ty] = E[(X^TX)^{-1}X^T(X\beta+\epsilon)] = E\beta + E[(X^TX)^{-1}X^T\epsilon]$
If we consider X as fixed constant we have that $E\hat{\beta} = E\beta + (X^TX)^{-1}X^TE[\epsilon] = \beta$ only if $\epsilon$ have independent observations.
If we go for variance of $\hat{\beta}$ we see that has a fixed component $\beta$ and a random noise $(X^TX)^{-1}X^T\epsilon$. So to find the variance of our estimator we look for
$Var(\hat{\beta}) = Var[\beta + (X^TX)^{-1}X^T\epsilon]$
Here the $\beta$ in variance have no effect, we can remove it. See properties of variance here: basic properties of variance on wikipedia. We also use the assumption that $X$ is given so it behaves like a constant term which factors out squared. We have then
$Var(\hat{\beta}) = ((X^TX)^{-1}X^T)^2 Var(\epsilon) = (X^TX)^{-1}Var(\epsilon)$
Now the answer to your question is, if we assume that variance is the same for all noise (additionally to independence) then  we can say that
$Var(\beta) = \sigma^2 (X^TX)^{-1}$
And by estimating $\sigma$ you have all the good stuff about coefficients like standard errors, t values, p values, confidence intervals, hypothesis tests and so on. If the variance is not assumed to by heteroskedastic then you have to control it somehow, but things gets more complicated.
Even if the $X$ is not assumed as fixed variable, if is considered random variable a similar assumption on independence like $E[X\epsilon] = 0$ is enough together with heteroskedasticity to have the same results.
Hope that helps.
Comment: It's a very clear explanation, thx!
Answer: When we do linear regression, it's under the assumption of Homoscedasticity, which means that the variance of the errors is constant.
Knowing that $\sigma^2$ is constant, and not a random variable, it's possible to perform inference using the ordinary least squares estimates.
If the assumption it's not valid, meaning thta you have a heterocedastic model, the estimation by ordinary least squares is no longer valid.
I actually think the answer you linked here is quite clear. Can you specify what you didn't understood?
Comment: I think I may need some proofs or formulas telling me how the assumption of constant variance is used. The posts relevant to this question usually explains conceptually or with examples, but not with math..


dollar sign symbol is not working in React

Question: I am building a CRUD app with React. For the Product Edit page where I want to edit a specific product(clicked product), I need to grab the product's Id. I use the dollar symbol in the code but it doesn't get blue(it doesn't work). I need the URL to change the specific product showing its id when clicked. How to do that? What am I doing wrong?
`
<Link className='btn btn-primary m-2'></ Link>
          <Link className='btn btn-otline-primary m-2' to={"/product/edit/${product.id}"}>Edit</Link>
          <Link className='btn btn-danger m-2'>Delete</Link>

`
const onSubmit = async e => {
  e.preventDefault();
  await axios.put('http://localhost:3001/products/${id}', product);
  navigate.push("/");
  };

``
I thought when I clicked the Edit button I could see the Edit page for the specific product but instead it shows like this: http://localhost:3000/product/edit/$%7Bproduct.id%7D. Not an id after the editing part.
Comment: You need to use backticks (`\``) to use a [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). Regular quotes (`"` or `'`) just create a string.
Comment: Now I remembered; Thank you!
Answer: Should be `` not ''
 await axios.put(`http://localhost:3001/products/${id}`, product);

Answer: Template literals are created using the ` symbol, this works:
let x = "def"
console.log(`abc${x}`);
// Prints: "abcdef"

But normal strings don't:
let x = "def"
console.log("abc${x}");
// Prints: "abc${x}"

See MDN Reference to learn more about how template strings work.


Entity Reference with VBO and Rules

Question: I am trying to create a rule which fires after modifying node content. Specifically I want to modify the entity reference field values of all the node entities provided by VBO. So I created a rule and a component as shown in the images below.
My problem is that I can not find a way to empty the entityref list of all node entities before the loop, maybe my whole approach is wrong.
Comment: I cannot upload pictures that way because i do not have the required reputation points but as soon as i reach 10 points i will upload them here.
Comment: Please attach your images to your post using the "Add image" button rather than linking to an external site.  That way, future visitors can have guaranteed access to the images because they will be stored with the *Drupal Answers* site.
Comment: you could hook_node_update instead and an entityfieldquery to look up the entities you want instead of using VBO
Answer: I'm not sure what the Change combine with field action does but if you want to set the value of an entity reference field can't you just use the "Set a data value" action in your product_display loop for the entity reference field?
Comment: I think the same "Set a data value" action should work. Just set value to nothing

Entity Reference with VBO and Rules