How would I check the csv file for a specifc value in the row and then use that as the header row AND if there is duplicates remove them?

Question: I am using the following function to import csv files to mysql:
function csv_2_mysql($source_file, $target_table, $max_line_length=10000) {
    if (($handle = fopen("$source_file", "r")) !== FALSE) {
        $columns = fgetcsv($handle, $max_line_length, ",");
        foreach ($columns as &$column) {
            $column = preg_replace('/[^a-z0-9]/i', '', $column);
        }
        $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
         while (count($data)<count($columns))
                array_push($data, NULL);
            $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
            mysql_query($query);
        }
        fclose($handle);
    }
}

function quote_all_array($values) {
    foreach ($values as $key=>$value)
        if (is_array($value))
            $values[$key] = quote_all_array($value);
        else
            $values[$key] = quote_all($value);
        return $values;
}

function quote_all($value) {
    if (is_null($value))
        return "NULL";
    $value = "'" . mysql_real_escape_string($value) . "'";
    return $value;
}

The problem is, that sometimes the headers are not on the first row due to cutting and merging of csv files at the source so for example it may end up looking like this:
value1,value2,value3,value4
value1,value2,value3,value4
value1,value2,value3,value4
header1,header2,header3,header4
value1,value2,value3,value4
value1,value2,value3,value4
value1,value2,value3,value4
value1,value2,value3,value4
header1,header2,header3,header4
value1,value2,value3,value4
value1,value2,value3,value4
value1,value2,value3,value4

value1 is unique so I know that there is never a duplicate row except for headers. How can I adjust the function so that the duplicate header rows are removed if they exist and to ensure that the remaining header row is used for $columns? I would just set the column values manually except each csv may have a different number of columns (except header1 and value1 which are always present as it is a unique timestamp).
UPDATE:
Well, I figured it out but it feels wrong using both fopen and file_get_contents. Will I run into problems with this on large csv's?
function csv_2_mysql($source_file, $target_table, $uid, $nid, $max_line_length=10000) {
    if (($handle = fopen("$source_file", "r")) !== FALSE) {
      $handle2  = file_get_contents($source_file) or exit;
      $handle_row = explode("\n", $handle2);
      foreach ($handle_row as $key => $val) {
          $row_array = explode(',', $val);
          foreach ($row_array as $key => $val) {
              $row_array[$key] = trim(str_replace('"', '', $val));
              }
              if(!in_array('header1', $row_array)) {
                unset ($row_array);
              }
              else {
                $columns = $row_array;
              }
          }
        foreach ($columns as &$column) {
            $column = preg_replace('/[^a-z0-9]/i', '', $column);
        }

        $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
         while (count($data)<count($columns))
                array_push($data, NULL);
            $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
            mysql_query($query);
        }
        fclose($handle);
    }
}

function quote_all_array($values) {
    foreach ($values as $key=>$value)
        if (is_array($value))
            $values[$key] = quote_all_array($value);
        else
            $values[$key] = quote_all($value);
        return $values;
}

function quote_all($value) {
    if (is_null($value))
        return "NULL";
    $value = "'" . mysql_real_escape_string($value) . "'";
    return $value;
}

Answer: I guess you could have an array to push the value of the first column (since you say it is unique) and check it for duplicates. If it is a duplicate ignore the line and continue.


How to set intervals between multiple requests AWS Lambda API

Question: I have created an API using AWS Lambda function (using Python). Now my react js code hits this API whenever an event fire. So user can request API as many times the events are fired. Now the problem is we are not getting the response from lambda API sequentially. Sometime we are getting the response of our last request faster than the previous response of previous request.
So we need to handle our response in Lambda function sequentially, may be adding some delay between 2 request or may be implementing throttling. So how can I do that.
Answer: Did you check the concurrency setting on Lambda? You can throttle the lambda there.
But if you throttle the lambda and the requests being sent are not being received, the application sending the requests might be receiving an error unless you are storing the requests somewhere on AWS for being processed later.
I think putting an SQS in front of lambda might help. You will be hitting API gateway, the requests get sent to SQS, lambda polls requests concurrently (you can control the concurrency) and then send the response back.
Comment: can we do something in our react js code ,like to send the request with little delay until the previous response is not received
Answer: You can use SQS FIFO Queue as a trigger on the Lambda function, set Batch size to 1, and the Reserved Concurrency on the Function to 1. The messages will always be processed in order and will not concurrently poll the next message until the previous one is complete.
SQS triggers do not support Batch Window - which will 'wait' until polling the next message. This is a feature for Stream based Lambda triggers (Kinesis and DynamoDB Streams)
If you want to streamlined process, Step Function will let you manage states using state machines and supports automatic retry based off the outputs of individual states.
Comment: Thank you. I have set the SQS and triggered it to my lambda function. But how to change the batch size, currently it is showing 10
Comment: You will have to delete the trigger and recreate it while setting the Batch size to 1. This can be done from the Lambda console.
Answer: As a previous response said, potentially what could help is to put an SQS in front of the Lambda - if order of processing is important, you could also look at setting the SQS queue up as a FIFO queue, which preserves order:
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html
As the other comment said, the other option is to limit concurrency, but even then you're probably best off putting SQS in front as you're then limiting your throughput.


How can I debug a Twig error that occurs after migrating from Drupal 8.9 to Drupal 9+

Question: I am trying migrate my Drupal 8.9 site to Drupal 9+ and I am stuck with an error its cause I am not able to hunt down. On almost every page I get the following PHP exception:
Twig\Error\RuntimeError: The "replace" filter expects an array or

"Traversable" as replace values, got "string" in "__string_template__faabd18c7a37a1e54d0ef10115b24022e72bc201187fff502de48bf58589321f" at line 2. in twig_replace_filter() (line 554 of /var/customers/webs/freigeist/www9/vendor/twig/twig/src/Extension/CoreExtension.php).

__TwigTemplate_75ee113db094d36d71f294529e9d7055b2065bf116719e9a04b7e4795be3121d->doDisplay() (Line: 405)
Twig\Template->displayWithErrorHandling() (Line: 378)
Twig\Template->display() (Line: 390)
Twig\Template->render() (Line: 45)
Twig\TemplateWrapper->render() (Line: 235)
Drupal\Core\Template\TwigEnvironment->renderInline() (Line: 52)
Drupal\Core\Render\Element\InlineTemplate::preRenderInlineTemplate()
call_user_func_array() (Line: 101)
Drupal\Core\Render\Renderer->doTrustedCallback() (Line: 786)
Drupal\Core\Render\Renderer->doCallback() (Line: 377)
Drupal\Core\Render\Renderer->doRender() (Line: 201)
Drupal\Core\Render\Renderer->render() (Line: 157)
Drupal\Core\Render\Renderer->Drupal\Core\Render\{closure}() (Line: 578)
Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 158)
Drupal\Core\Render\Renderer->renderPlain() (Line: 419)
Drupal\views\Plugin\views\PluginBase->viewsTokenReplace() (Line: 1356)
Drupal\views\Plugin\views\field\FieldPluginBase->renderAltered() (Line: 1249)
Drupal\views\Plugin\views\field\FieldPluginBase->renderText() (Line: 1177)
Drupal\views\Plugin\views\field\FieldPluginBase->advancedRender() (Line: 238)
template_preprocess_views_view_field() (Line: 287)
Drupal\Core\Theme\ThemeManager->render() (Line: 436)
Drupal\Core\Render\Renderer->doRender() (Line: 201)
Drupal\Core\Render\Renderer->render() (Line: 1745)
Drupal\views\Plugin\views\field\FieldPluginBase->theme() (Line: 778)
Drupal\views\Plugin\views\style\StylePluginBase->elementPreRenderRow()
call_user_func_array() (Line: 101)
Drupal\Core\Render\Renderer->doTrustedCallback() (Line: 786)
Drupal\Core\Render\Renderer->doCallback() (Line: 377)
Drupal\Core\Render\Renderer->doRender() (Line: 201)
Drupal\Core\Render\Renderer->render() (Line: 717)
Drupal\views\Plugin\views\style\StylePluginBase->renderFields() (Line: 584)
Drupal\views\Plugin\views\style\StylePluginBase->renderGrouping() (Line: 475)
Drupal\views\Plugin\views\style\StylePluginBase->render() (Line: 2170)
Drupal\views\Plugin\views\display\DisplayPluginBase->render() (Line: 1533)
Drupal\views\ViewExecutable->render() (Line: 183)
Drupal\views\Plugin\views\display\Page->execute() (Line: 1630)
Drupal\views\ViewExecutable->executeDisplay() (Line: 81)
Drupal\views\Element\View::preRenderViewElement()
call_user_func_array() (Line: 101)
Drupal\Core\Render\Renderer->doTrustedCallback() (Line: 786)
Drupal\Core\Render\Renderer->doCallback() (Line: 377)
Drupal\Core\Render\Renderer->doRender() (Line: 201)
Drupal\Core\Render\Renderer->render() (Line: 241)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 578)
Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 242)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare() (Line: 132)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse() (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray()
call_user_func() (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch() (Line: 163)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 80)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 57)
Drupal\Core\StackMiddleware\Session->handle() (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 191)
Drupal\page_cache\StackMiddleware\PageCache->fetch() (Line: 128)
Drupal\page_cache\StackMiddleware\PageCache->lookup() (Line: 82)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 717)
Drupal\Core\DrupalKernel->handle() (Line: 19)

I found out that the error might be theme related (I am on Bootstrap). And on some pages I could narrow it down to the system block 'site_branding': Disabling this block makes the error disappear on some pages, but not on all.
My first guess was, that this might be an twig compatibility issue (may be in my bootstrap sub-theme), but it occurs also when I use other themes. So I am completely lost here.
How could I debug this error? Does the error message show, which component could be the cause of the error? Can anybody point out, which change between Drupal 8 and 9 could be responsible of the error?
Comment: What is the question? What is unclear about the error message? BTW the template name looks not like a real Twig template, more like an inline template in PHP. You could try to find it in a full error message with stack trace.
Comment: @4k4 You are right, I did not ask a clear question, I think it was too late yesterday. I tried to make my questions clearer now. Should I use the devel module to stack trace.
Comment: You can enable full error messages in Drupal core: /admin/config/development/logging
Answer: This is the last line in the stack trace before the render pipeline is throwing the error:
Drupal\views\Plugin\views\PluginBase->viewsTokenReplace() (Line: 1356)

This might be caused by a |replace filter rewriting a Views field in the View you are trying to display as main content of the page.
See the deprecation warning in Drupal 8.9 (Twig 1.x):
function twig_replace_filter($str, $from, $to = null) {
  if (\is_string($from) && \is_string($to)) {
    @trigger_error('Using "replace" with character by character replacement is deprecated since version 1.22 and will be removed in Twig 2.0', E_USER_DEPRECATED);

https://api.drupal.org/api/drupal/vendor%21twig%21twig%21src%21Extension%21CoreExtension.php/function/twig_replace_filter/8.9.x
Drupal 9 has upgraded to Twig 2.x
https://api.drupal.org/api/drupal/vendor%21twig%21twig%21src%21Extension%21CoreExtension.php/function/twig_replace_filter/9.2.x
Comment: The lines above are rendering methods which only run because line 419 of this Views plugin base class is starting a rendering process providing the data to be rendered. So it's very likely that this data is causing the issue, unless a faulty template had been involved in rendering the data. But then the error message had contained the template name, which would have made debugging much easier.
Comment: Great, that helped a lot. It was the one dirty hack, in the main View I forgot about. How did you deduce however, that ´Drupal\views\Plugin\views\PluginBase->viewsTokenReplace() (Line: 1356)´ was the last line before the error?


Update Table1 From table 2

Question: I have two tables in my database and I want to update Table 1 from Table 2
Table 1 looks like this:
id - eventid - hostname   - trigger - startime      - endtime
1     00001  - 10.10.10.1 - PROB    - 2017-08-03 18:33  ?
2     00001  - 10.10.10.1 - PROB    - 2017-08-05 00:33  ?
3     00001  - 10.10.10.1 - PROB    - 2017-08-05 00:32  ?
4     00002  - 10.10.10.2 - PROB    - 2017-08-02 14:58  ?
5     00002  - 10.10.10.2 - PROB    - 2017-08-07 17:59  ?
.
.

And Table 2 looks like this:
id - eventid - hostname   - trigger - startime
1     00001  - 10.10.10.1 - OK    - 2017-08-03 19:22
2     00001  - 10.10.10.1 - OK    - 2017-08-05 03:13
3     00001  - 10.10.10.1 - OK    - 2017-08-05 04:30
4     00002  - 10.10.10.2 - OK    - 2017-08-02 15:08
5     00002  - 10.10.10.2 - OK    - 2017-08-07 19:29
.
.

How can I update Table 1 so I can insert startime from Table 2 into endtime on Table 1?
Comment: Read about update join
Answer: You can join the two tables in your UPDATE query (read about it in the documantation):
UPDATE `Table 1` t1
    JOIN `Table 2` t2 ON t1.ID = t2.ID
SET t1.endtime = t2.starttime

Comment: Actually the id of the two tables are different only the eventid is the same and i used this command but it keeps insert only the first match form table2 for all the rest i mean like this                                               id - eventid - hostname   - trigger - startime                         - endtime
1     00001  - 10.10.10.1 - PROB    - 2017-08-03 18:33       2017-08-03 19:22
2     00001  - 10.10.10.1 - PROB    - 2017-08-05 00:33  2017-08-03 19:22
3     00001  - 10.10.10.1 - PROB    - 2017-08-05 00:32  2017-08-03 19:22
Comment: @wael: If the IDs are different, then how can you be sure which endtime should be inserted in which row in table 1?
Answer: Same query. different join syntax.
The first is old style ANSI, the latter is later ANSI. If you must pick between them, pick the latter.
I wouldn't use either of them due to the limitations of USING (can't be aliased). Instead write as:
UPDATE table1 A
INNER JOIN (SELECT id,COUNT(*) idcount FROM table2 GROUP BY id) as B
  ON B.id = A.id
SET A.Freq = B.idcount
See this Oracle answer as to why USING is not to be preferred: https://stackoverflow.com/questions/456684/mixing-using-and-on-in-oracle-ansi-join

And here is a similar discussion for SQL Server:
In general, get used to writing SQL syntax in a way that is portable. While you may never port your code, you will at least be able to port your skills around to multiple database (Which is generally a cool thing to do to avoid becoming a one-trick pony).

Update Table1 From table 2


How to solve this partial differential equation $\frac{\partial p(k,t)}{\partial t}+k\frac{\partial p(k,t)}{\partial k}+k^2p(k,t)=0$

Question: How to solve this partial differential equation
$$\frac{\partial p(k,t)}{\partial t}+k\frac{\partial p(k,t)}{\partial k}+k^2p(k,t)=0$$
I'm a beginner to PDE, I think I need to construct the characteristic equation but I have no clue.
Comment: Yes, the method of characteristics is the way to go.  Why don't you try it?
Comment: I have no idea how to construct the equation by the method of characteristics. Can you give a hint?
Answer: This method poses an auxiliary system of ODE's for the curves (the characteristics)  forming the solution, in this case and put in form of proportions:
$$\dfrac{\mathbb dt}{1}=\dfrac{\mathbb dk}{k}=-\dfrac{\mathbb dp}{k^2p}$$
You may prefer to solve $\dfrac{\mathbb dt}{1}=\dfrac{\mathbb dk}{k}$ and $\dfrac{\mathbb dk}{k}=-\dfrac{\mathbb dp}{k^2p}$. Giving two equations with an arbitrary constant for each and defining the characteristics (you can get the general solution from here).
Comment: Thx, how to get the proportions listed in your answer?
Comment: It's a standard procedure for quasilinear PDEs:The differentials are divided by their factors following this: $a(x;y,u)u_x+b(x,y,u)u_y=c(x,y,u)$ corresponds with $\dfrac{\mathbb dx}{a}=\dfrac{\mathbb dy}{b}=\dfrac{\mathbb du}{c}$ The theory for this is very easy to find.
Answer: If you have never used this method before you need some help setting you on the correct path.
The problem is well posed if we are given initial data of the form $p(k,0) = f(k)$.
With the method of characteristics we find a family of curves $k(t;\alpha)$ that intersects the $k$-axis in the $kt$-plane at a unique point $(\alpha,0)$ and such that the PDE reduces to an ODE along the curves.
The characteristics here solve the IVP,
$$\displaystyle \frac{dk}{dt} = k, \,\, k(0) = \alpha,$$
with solutions $k(t) = \alpha e^t$.
Taking $v(t) = u(\alpha e^t,t)$ you must determine the ODE satisfied by $v$ and solve by applying the intial condition $v(0) = u(\alpha,0) = f(\alpha)$.  Finally transform back to $(k,t)$ coordinates using $\alpha = ke^{-t}$.
This leaves you with a fair amount of work to do.
The ultimate solution will be
$$ u(k,t) = f(ke^{-t})\exp\left(- \frac{k^2}{2} \right)$$
Comment: Thx, but I don't understand how to get $\frac{dk}{dt}=k$?
Comment: I suggest reading about the method of characteristics for the full story. I tried to convey some of the intuition in my answer.  So the essence of what we are doing here is to find a curve $\hat{k}(t)$ such that along this curve, the PDE reduces to an ODE which is easier to solve.  Notice that $\frac{d}{dt}u(\hat{k}(t),t) = \frac{\partial u}{\partial t} +  \frac{\partial u}{\partial k} \frac{d\hat{k}}{dt}$ and the RHS matches the derivative terms in the PDE when $\frac{d\hat{k}}{dt }= \hat{k}$.  Then we get the ODE $\frac{d}{dt}u(\hat{k}(t),t) + \hat{k}^2(t)u(\hat{k},t) = 0$ which is easy
Comment: Again I have tried to explain why this work and not just give you the mechanical recipe you can find in Wikipedia.  If that doesn't help you then ...
Comment: Also I gave you the solution so that should help you understand the process by working backwards.  Try taking the partial derivatives and see why this satisfies the PDE.
Answer: Correction: I thank RRL for catching my mistake.
Hint: Consider
\begin{align}
u(t, k) = e^{k^2/2}p(t, k)
\end{align}
then check that
\begin{align}
\partial_t u+k\partial_k u = 0
\end{align}
which is just a transport equation.
Comment: @RRL Thanks for your comment. I have made the correction.


Euler class of dual bundle

Question: Let $L^*$ be the dual bundle of complex line bundle $L$. Since the bundle $L\otimes L^* = \text{Hom}(L,L^*)$ has nowhere vanishing section given by the identity map, the first Chern class $c_1(L\otimes L^*) = c_1(L) + c_1(L^*) = 0$, and the $c_1(L) =-c_1(L^*)$. The first Chern class $c_1(L)$ it is Euler class $e(L_\mathbb{R})$. So, $e(L_\mathbb{R}) = -e(L^{*}_{\mathbb{R}})$. There exist an isomorphis between vector bundle and their dual bundle. So, their Euler classes should be equal. Where is the mistake?
Comment: There's an error here to start with. $L\otimes L^*\cong \text{Hom}(L,L)$, not as you said. So, yes, the line bundle has an obvious section and is trivial.
Comment: Thanks. Yea, I meant to say $L\otimes L^{*} = \text{Hom}(L,L)$
Answer: A complex vector bundle and its dual bundle are in general not isomorphic. As your argument shows, if $E \longrightarrow M$ is a complex vector bundle of odd rank $n$, then $c_n(E) = -c_n(E^\ast)$ and $e(E_{\Bbb R}) = - e((E^\ast)_{\Bbb R})$, so that both $E \not\cong E^\ast$ and $E_{\Bbb R} \not\cong (E^\ast)_{\Bbb R}$ (if $c_n(E) \neq 0 \neq e(E)$).
Note that this is in contrast to the case of real vector bundles. A Euclidean metric on a real vector bundle $F \longrightarrow M$ gives an isomorphism
$$F \cong F^\ast = \mathrm{Hom}(F, \underline{\Bbb R}).$$
The difference in the complex case is that a Hermitian metric on a complex vector bundle $E \longrightarrow M$ gives an isomorphism
$$\bar{E} \cong E^\ast = \mathrm{Hom}(E, \underline{\Bbb C}),$$
where $\bar{E}$ is the conjugate bundle of $E$. The conjugate bundle is not necessarily isomorphic to the original bundle.
Answer: I think you're confusing the dual, over the real numbers, of the underlying real bundle $L_{\mathbb R}$ of $L$ with the underlying real bundle of the complex dual of $L$.

Euler class of dual bundle


C++ matrix class operator using std::common_type_t and implementation of complex number

Question: I am writing a matrix class myself and I am trying to make it as "generic" as possible, i.e., I want a matrix<int> + matrix<double> to be able to yield matrix<double>, matrix<double> * matrix<int> able to yield matrix<double>.
So in my operator+, my in-class declaration is
template<typename T>
class Matrix {
public:
    ......
    template <typename TT> Matrix operator+(const Matrix<TT>&);
    ......
private:
    ......
}

and the definition is
template<typename T, typename TT>
Matrix<T> Matrix<TT>::operator+(const Matrix<T> &M)
{
    using C = std::common_type_t<T, TT>;
    Matrix<C> temp(_rows, _cols);
    for (size_t i = 0; i < size(); ++i)
        temp.mtx[i] = mtx[i] + M.mtx[i];
    return temp;
}

However, the compiler complains that

template argument list must match the parameter list

I don't know where is wrong. Can anyone help me out here? Thanks.
As for the implementation of complex number. There are some operations that are incompatible with std::complex, such as max, min, operator<, etc. The solution I came up with is I wrote a new matrix class for complex matrix, but this is stupid. Is there an easy way around this?
======================================================================
My constructor:
template <typename T>
Matrix<T>::Matrix() { allocate(0.0); }    // this is a private function allocating memory

the allocate member
template<typename T>
void Matrix<T>::allocate(T val)
{
    mtx = new T [_rows * _cols];
    if(val) {
        for (size_t i = 0; i < _rows * _cols; ++i)
            mtx[i] = val;
    }
}

Comment: Which one you are referring to?
Comment: @Evg Right right. I just added it.
Comment: Shouldn't `matrix + matrix` and `matrix + matrix` both yield `matrix`?
Answer: You should not mix two templates into one. Try this:
template<typename TT>
template<typename T>
Matrix<T> Matrix<TT>::operator+(const Matrix<T> &M)
{
    using C = std::common_type_t<T, TT>;
    Matrix<C> temp(_rows, _cols);
    for (size_t i = 0; i < size(); ++i)
        temp.mtx[i] = mtx[i] + M.mtx[i];
    return temp;
}

However, the return type is Matrix<T> and you return Matrix<C>. So I suggest you write it like this (don't forget to adjust the declaration accordingly):
template<typename TT>
template<typename T, typename C = std::common_type_t<T, TT>> // pseudocode, see below
Matrix<C> Matrix<TT>::operator+(const Matrix<T> &M) const
{
    Matrix<C> temp(...);
    ...
    return temp;
}

Complete example:
template<class T>
struct Matrix
{
    template<class S, class C = std::common_type_t<T, S>>
    Matrix<C> operator+(const Matrix<S>&) const;
};

template<class T>
template<class S, class C>
Matrix<C> Matrix<T>::operator+(const Matrix<S>&) const
{ ... }

Since C++14 you can use auto return type:
template<class T>
struct Matrix
{
    template<class S>
    auto operator+(const Matrix<S>&) const
    {
        using C = std::common_type_t<T, S>;
        Matrix<C> tmp(...);
        ...
        return tmp;
    }
};

As to your second question, it is not clear what the problem is. Note that template member functions are not instantiated unless they are used. So you can have member functions that employ, e.g., operator<, just don't use them with complex matrices.

The operator> here is incompatible with std::complex. I don't know how to go around it if I use complex matrix.

It is fine to have this member in a template class. Just don't use it with complex matrices. However, I suggest you make it a free function. Then you won't have this concern altogether.
Comment: now it says _no instance of overloaded function matches the specified type_
Comment: @SJH, please include both declaration and definition into your question, i.e. [MCVE](https://stackoverflow.com/help/mcve).
Comment: you mean the declaration/definition for which one? The complex matrix?
Comment: @SJH, I mean the one for which you get an error. I included a complete example in my updated answer, take a look.
Comment: This implementation leads to another series of issues. First, I can't access the private member of that **temp** matrix. Second, my constructor can't convert `int` to `std::common_type`. I'll just attach my construtor above. Please take a look.
Comment: @SJH, do you really need to access private members? How can it be that to form a sum of matrices one needs to access their internals? Maybe you should rethink your interface? If you really need private access, add `template friend struct Matrix;` to friend all matices.
Comment: It's ok if I don't access those private members. That's fine. But still, due to this `common_type`, there are many other problems, one of which is what I just mentioned.
Comment: @SJH, I don't see where `int` to `std::common_type<>` conversion happens exactly. Probably you should redesign your constructors.
Comment: I update my post with one of my private member `allocate`, I think that's where the conversion happens. Could you take a look?
Comment: It just came to me: would it be helpful to add some type-conversion members in my class to avoid this `common_type`?
Comment: @SJH, I doubt it. However, `std::common_type` is not a proper type in the general case. The correct type is given by `decltype(std::declval + std::declval)` and `decltype(std::declval * std::declval)`.


Maximum radius of an image set after linear transformation

Question: Let $A \in \mathbb{R}^n$ be an invertible matrix and let $K_1 \subset \mathbb{R}^n$ be some convex and compact set containing the origin.
Let $K_2$ be a linear transformation of $K_1$
\begin{align}
K_2= \{ x: x= A y, y\in K_1 \}.
\end{align}
Let $r$ be the maximum radius of $K_2$ that is
\begin{align}
r= \max_{ x \in K_2} \|x\|.
\end{align}
Can we find an expression for $r$ in terms of set $K_1$ and matrix $A$?
For example, can this be done when $K_1$ is an $n$-dimensional ball or an $n$-dimensional rectangle.
Comment: Do you mean something other than $\max_{x\in K_1}\|Ax\|$?
Comment: @Aweygan Yes.!!!! I also added. That I would like to look at cases when $K_1$ either a ball or a rectangle.
Comment: In case that $K_1$ is a ball centered at zero, you can consider the eigenvalues of $A$.
Answer: I think what you mean is some kind of simplified expression for the radius, rather than just $\sup_{x\in K} \| Ax \|$ or something. I'm not sure this is possible in general, only specific cases. Mainly we can get bounds.
Say $K_1$ is a ball, then
\begin{align}
\sup_{x\in K} \| Ax \| &= \|A\|\text{rad}(K_1)
\end{align}
by definition. However in general, I think we only have a bound:
\begin{align}
\sup_{x\in K_1} \| Ax \| &\leq \|A\|\text{rad}(K_1)
\end{align}
However, if $\text{span}(K_1)$ is a strict subspace of $\mathbb{R}^N$, then we have:
\begin{align}
\sup_{x\in K_1} \| Ax \| &\leq \|A_{\text{span}(K_1)}\|\text{rad}(K_1)
\end{align}
where $\|A_{\text{span}(K_1)}\|$ is the matrix norm of $A$ restricted to $\text{span}(K_1)$.
Say that $K_1$ is a box. There is an expression -- not sure how useful it is. Let
\begin{align}
K_1 &= \Pi_{i=1}^N[-a_i,b_i]
\end{align}
then
\begin{align}
\sup_{x\in K_1} \| Ax \| &= \max_{\lambda_i\in\{-a_i,b_i\}}\sum^N_{i=1}(\lambda_i A(e_i))
\end{align}
where $e_i$ is the standard basis. Essentially the optimal choice for each coordinate is either going to be $-a_i$ or $b_i$. This is because convex functions are maximized on the boundary of their domain. The norm squared $\|Ax\|^2$ is going to be convex in each coordinate. Hence you only have to check a finite number of combinations.
Comment: Thank you. What do yo mean when you say $A(e_i)$?
Comment: I mean the matrix $A$ applied to the vector $e_i$, which is just a vector of all zeros except for a $1$ as position $i$.


Preventing spam registration /url redirect

Question: im getting more and more spam account registrations. what is the simplest way to handle this if one does not need browser based registration? people register the REST/services way via an app.
can this be achieved without additional modules? e.g. server redirect?
Answer: If you don't need user self-registration then just disable that functionality.
To do this go to :
/admin/config/people/accounts (Admin > Configuration > People > Account Settings)
And for the Who can register accounts? setting choose Administrators only.
If later on you decide that you need that functionality, you can enable it back and then just add a captcha to your user registration form, or integrate something like honeypot or logintoboggan.
Comment: thanks for the suggestion. people can register themselves  - they download the app and register through the app.
Comment: So does your app rely on the drupal registration mechanism ? Or can you just disable the functionality in drupal an let your app handle things ?
Comment: yes, im relying on the drupal registration. im using this masterpiece https://github.com/jbeuckm/drupal-client
Comment: The REST mechanism allows for handing extra fields in the user registration form. (see http://www.thirdandgrove.com/creating-users-in-drupal-with-the-services-modules-rest-api/ at the end of article). See if you can add a captcha. Alternatively, a a rough solution a simple hidden field with an arbitrary value could help you differenciate drupal-client registrations and web interface registrations.
Comment: thx for the suggestions - i can already differentiate with the help of a custom field. in combination with rules its kinda working and im blocking spam accounts. however, they are set up in the first place. would a server-side redirect from the login url somehow work or would it prevent rest registration as well?
Comment: I can't say without a close look at how things are set up. Do try and see how it goes. Also see if logintoboggan can be of any help to you.
Comment: will do. your suggestions and the link in particular is definitely appreciated. thanks


How to structure automated tests for open source API integration that requires client key/secrets?

Question: I am working on an open source project that provides library support for OAuth2 requests/protocols. This project includes examples on how to implement the library with a variety of API providers (Google, LinkedIn, Instagram, etc...)
Currently these examples exist as standalone text files that have variable declarations for the client id and key/secret:
client_id = 'getThisFromOwnerOfApi'
client_secret = 'getThisFromOwnerOfApi'
...
# build request, send, read response etc...

These are made so that the user updates the file manually with their client id/secret. Then runs the file locally to see how the library can be used.
I would like to restructure the examples so that they are more functional, maintainable, easier to use. Each example would come with:

a run file
a test file
a config file (?)
a readme

Ultimately I would like the examples to live in their own directory and have the project pipeline run automated tasks against each example (like the test file) to make sure that the examples are working/up-to-date.
My question is, how could I approach the handling of the API keys to run the automated tests?
Answer: After poking around some, I discovered that github repos have special stores for sensitive data. This section can be found:
github.com/<user>/<repo>/settings/secrets/actions
and the documentation that goes along with this feature:
https://docs.github.com/en/actions/security-guides/encrypted-secrets
As far as generating these id/secrets, unless the resource provider has a testing feature that would allow for public unrestricted access to some test account, the project needs to have their own account with the provider.


Edge Zero II tremolo not parallel to the guitar body

Question: I just bought an Ibanez S520 guitar online which has been fitted with a Edge Zero II tremolo which resembles the Floyd Rose Type tremolo .
Well ,  the tremolo bridge is not parallel to the guitar body . If I try to make the tremolo bridge parallel to the guitar body , the last 3 strings i.e (4,5,6) produce a BUZZING SOUND after 12th FRET . The sound is not at all clear .
I just want to know if it's okay to keep the tremolo bridge not parallel to the guitar body or should I contact a technician to fix it if there's any problem with the guitar ?
Comment: It's not as clear as it needs to be. Picture please. No bridge is ever 'parallel' to the body, as lower strings are thicker so that part will be higher.
Comment: I suppose it's like [this](http://i62.photobucket.com/albums/h90/s2170/Guides/Trem%20guide/ibanez-edgeIII-coda-su.jpg) or [this](http://i62.photobucket.com/albums/h90/s2170/Guides/Trem%20guide/ibanez-edgeIII-coda-giu.jpg), am I correct?
Comment: Sounds like two separate problems. You need to set it up so that when the bridge is in the right position (parallel) you don't get buzz. This will mean truss rod and string height adjustment. As for the bridge, you can adjust the springs to change its angle.
Answer: It does sound like your guitar isn't set up correctly, as the tremolo should be parallel with no buzz. The main problem I see is not so much with the tremolo, but with the fret buzz, though. This leaves you with some options.
Leave the bridge non-parallel:
The first option would be to leave the bridge in a non-parallel position to avoid fret buzz. This is not recommended by Ibanez, though, as tuning stability may suffer. There may also be other downsides like reduced comfort when palm muting amongst others.
I myself would hate to cater to a messed up setup, too, but that might just be me.
Raise the action:
The second option would be to set up the tremolo to be parallel to the body and raise the action (instructions are given in the link above). Raising the action may get rid of the fret buzz, but most players prefer a low action, so that might not be for you.
Adjust the truss rod:
Most fret buzz can be dealt with by adjusting the truss rod, therefore changin neck relief. This is a bit complicated and best left to a professional, though you could do it on your own if you take your time and do some thorough research on the topic.
So what now?:
If you have the monay, I'd go for a professional setup.
If you don't have the money, you can always just raise the action and see how that feels. If that's not for you, it might be time to get to know your guitar a bit better (read: Hours of adjusting, tinkering etc.). Though this might be a very frustrating experience at first, it can also be very rewarding if you're a gear-nut like me :p
Comment: Great answer. One additional point is leaving a knife edge fulcrum at a non- parallel angle can cause irregular wear and ruin the point of contact.
Comment: Yes, of course! Seeing how [replacements are not available](http://music.stackexchange.com/questions/5762/where-can-i-buy-knife-edges-for-a-guitar-tremolo-bridge?rq=1) that might even be the most important reason to keep the bridge set up properly.
Answer: Here is the answer I found out at my own cost, at least this is the only way I could properly set up low action. The key was the angle of the bridge!
I've been having issues with the EZ II since I purchased my Jem, and I even thought about reselling it as I suspected problems with the neck. No matter how I adjusted the truss rod, I always had fret buzz either on the low or on the high end, so I had to compensate by lifting the bridge. I was very surprised, because I also own a Jackson - quite a cheap guitar in comparison - on which I never had problems with setting up low action, even without ever adjusting the truss rod.
Then it came to my mind that since the frets are curved, the bridge must also provide some curvature through the strings, meaning that the two E's are slightly lower than the G and the D strings. This difference is hardly noticeable with the naked eye, at least not by just looking at the bridge.
But this is exactly why these bridges are designed in a way that there is no 100% accurate angle setting on it that suits all neck dimensions! This seems like a clever design feature, and you have to adjust your bridge angle in a way that suits your neck. And this angle may be different on an RG, compared to let's say an S or a Jem.
I have found two types of explanations on the web and also on youtube, one stating that the top of the bridge must be parallel with the body, the other stating that the bottom of the bridge should be parallel. In my case neither was true. By adjusting the spring tensions I tried both configurations, but none was satisfying. For a while I had the top parallel, then I switched to the bottom being parallel, but still could not set up low action properly. So I strengthened the springs again just a little, like 3 quarter turns with a screwdriver, then re-tuned the whole guitar.
Now my bridge angle is exactly between the two mentioned extremes, neither the top, nor the bottom is parallel with the body.
So to summarize it: by adjusting the bridge angle you are effectively changing the string heights relative to each other, sharing a horizontal curvature provided by the nut positions (set up for correct intonation) and a vertical curvature provided by the nut heights. This angle should be set in a way so that the string heights perfectly match your neck's radius. Your only option is making small adjustments to the bridge angle, and check how it affects low action and fret buzz, but beware: the more the bridge is angled towards the body, the more your string heights will follow the horizontal locations of the nuts.
I am not sure how much is visible on this photo but I am adding it anyway:

You can even see it on this photo that the nuts towards the middle are slightly higher. But if the whole bridge is angled towards the body this vertical height pre-set is ruined by the horizontal intonation adjustment position, so your strings will have incorrect heights relative to each other.
So here is a very brief summary: the angle should be anything between slightly angled towards the body to completely parallel with the body, you have to find it out yourself which will match your neck radius better.
Edit:
After further experimenting I've finally ended up with a bridge angle where the top is almost parallel with the body, because this allowed me to further lower the action without any fret buzz. Now the strings are as low as on my Jackson. Again, don't forget that this is a Jem, which may have different neck radius compared to an S.
Answer: The answer and reason for parallel is equilibrium. Parellel is the optimum position because it has the least amount of strain and wants to go back to this position each and every time. This is what will help your guitar stay in tune. String length (intonation), saddle height, neck relief, all play an important role in your guitar performance. Any tech will tell you that... if not find another tech.
Answer: The main question is whether your guitar sounds in tune when playing higher frets.  It's been my experience that the thicker strings call for slightly more string length in order to be reasonably in pitch with the thinner strings on high frets.  This effect will be less pronounced with guitars having a flatter action since the difference in string length likely compensates for the effecton the pitch of the additional tension caused by pushing the string down to the fret.
So never mind "parallel".  The main criterion should be "in tune on high frets".  If that is the case, messing with the bridge will not make things better.
Comment: 'In tune on high frets' is also called 'proper intonation'. As each saddle of an Edge Zero 2 can be moved around to improve intonation, there's no need to fake it by misaligning the tremolo. So please, _do_ _mind_ 'parallel'.
Comment: Parallel is not cosmetic. It makes a difference to action and intonation.
Comment: @Godzillarissa Do mind it why? Nobody has given a reason. Parallel is purely cosmetic. What matters is action and intonation.


Displaying elements inline with HTML?

Question: I am trying to create a web application and in it I want these two fields to display inline(check the Image below). Now the BugID is an <input> element and the Description is a <textarea>. Currently I have this:

Bug ID:*

Enter Description:*

  <input size="8" maxlength="8" name="BugID" type="text" id="BugID" placeholder="Bug ID" style="width:100px" />
  <textarea rows="5" id="Summary" name="summary" placeholder="Please Enter a Summary of the Bug" ></textarea>

And the CSS:
.inputs input, textarea{
      display:inline;
}

Is this wrong? How should I be doing this?
Comment: I thought ``s were inline by default.
Comment: @RocketHazmat Old comment, I know. But `` elements are `inline-block` by default.
Answer: Is this what you want?
   .inputs input, textarea{
          display:inline;
          float:left;

    }

Answer: Try this:
#BugID, #Summary
{
    display: inline-block;
    float: left;
}

.clear
{
    clear: both;
}

And add an extra div after both fields that has class="clear"
Edit: Use the below sample, I've just tested it and it will align the titles and fields inline for you

Bug ID:*

Enter Description:*

  <input size="8" maxlength="8" name="BugID" type="text" id="BugID" placeholder="Bug ID" style="width:100px" />
  <textarea rows="5" id="Summary" name="summary" placeholder="Please Enter a Summary of the Bug" ></textarea>

Answer: I will probably get shot down for this, but personally I would use a table because your layout is looking like a table.
Comment: Tables should only be used for tabular data, not for aligning form elements. :-P
Comment: ahh the CSS purists are coming! Am I allowed to use tables to eat from? :P
Comment: You can eat of the table if you want, I prefer using a plate. :-P
Answer: you can use table tag. In this case you will need 2 rows and 2 columns.
Answer: <input> are inline elements by default.  You need to change the
s to inline (as those are block elements).
I also suggest not using
 tags for anything other than what they are meant for.  They are meant to denote headers/subheaders, not for formatting text.  May I suggest the  tag?

  Bug ID:*
  Enter Description:*

     <input size="8" maxlength="8" name="BugID" type="text" id="BugID" placeholder="Bug ID" style="width:100px" />
     <textarea rows="5" id="Summary" name="summary" placeholder="Please Enter a Summary of the Bug" ></textarea>

DEMO: http://jsfiddle.net/vW3GL/
Answer: I will suggest a better option. Update your markup structure to a more structure one. May  be something like this

Bug ID:*

      <input size="8" maxlength="8" name="BugID" type="text" id="BugID" placeholder="Bug ID" style="width:100px" />

Enter Description:*

      <textarea rows="5" id="Summary" name="summary" placeholder="Please Enter a Summary of the Bug" ></textarea>

Now the fix: CSS
.input { display: inline-block; display: table-cell; vertical-align: top; }

Demo

Displaying elements inline with HTML?


Subject of the formula involving Matrices

Question: I have the following formula:
$$(x_2) ^{\intercal}Fx = 0$$
where $\intercal$ denotes transpose
$F$ is a $3\times 3$ matrix,
$x$ is a $3\times 1$ matrix.
I want to put $(x_2)^{\intercal}$ as the subject of the formula, what should be done please?
Comment: Sorry, what do you want to do exactly? I don't understand the sentence "I want to put $x^T$ subject of the formula".
Comment: Do you mean you want to "isolate" $x$?
Comment: That added $\;2\;$ makes things even more confusing
Comment: @HowDoIMath Thank you for your comments and edit, (as i am new to this hehe). Basically I have the above formula used in multi view geometry. I want to place the matrix $x'^T$ as subject of the formula since I have F and x. x' ([prime) is another 3D point...
Comment: @Timbuc sorry, removed the 2, wanted to show that the first x and second x matrices are different. Denoted them using a x' and x now.
Comment: Them you should have put the $2$ as a subscript like $x_2$.
Answer: If you want to make $x_2$ the subject of the formula, you can transpose first
$$x^TF^Tx_2=0$$
and express the equation as the inner product of two vectors (which will be of size $9$ in your case)
$$vec(F)^T(x\otimes x_2)=0$$
where the $vec$ operation on a matrix is described here and the Kronecker $\otimes$ product is described here.
For the $3\times 3$ matrix, we can work things out by hand (although it is a bit long winded)
$$F=\left(\begin{matrix}f_{11} & f_{12} & f_{13} \\f_{21} & f_{22} & f_{23} \\f_{31} & f_{32} & f_{33}\end{matrix}\right)$$
and vectors $x=[x(1),x(2),x(3)]$ and $x_2=[x_2(1),x_2(2),x_2(3)]$
 the equation is
$$[f_{11}\ f_{21} \ f_{31}\ f_{12}\ f_{22} \ f_{32} \ f_{13}\ f_{23} \ f_{33}]\left[\begin{matrix}x(1)x_2(1)\\x(1)x_2(2)\\x(1)x_2(3)\\x(2)x_2(1)\\x(2)x_2(2)\\x(2)x_2(3)\\x(3)x_2(1)\\x(3)x_2(2)\\x(3)x_2(3)\end{matrix}\right]=0$$
Comment: thanks for your detailed answer. I have followed the steps and I think i've understood most of it. However I haven't understood the last part... The equation i'm looking for needs to be: $x_2$ = bla bla bla. Didn't really understand how variable y got involved
Comment: @LukeZammit: It was an extra set of terms I introduced - I think it has caused more confusion, so I will edit my answer (and remove the extra bits).
Comment: thanks for the edit. Please excuse my understanding in this field, However I can't see how $x_2$ is made subject of the formula? The terms in $x_2$ in my case are all unknowns and i'm trying to find them..
Comment: @LukeZammit Prior to my edit, I expressed the problem as $Ax_2=y$, where $A$ is a matrix in terms of the elements of $F$ and vector $x$ which are known, but $y$ which is unknown (but whose elements sum to $0$). If there was any additional condition we could put on $y$, such that the elements are all $0$, then it would be straightforward to find $x_2$.
Comment: Just to see if i've understood correctly. If i start with $$(x_2) ^{\intercal}Fx = 0$$ and even though I have a 3x3 matrix with values for F and a 3x1 matrix for x, I cannot find values for $x_2$ ?
Comment: @LukeZammit Because $Fx$ is a vector, you will not find a *unique* solution for $x_2$. If, however, you had three equations, $(x_2)^TF_1x=0$ , $(x_2)^TF_2x=0$ and $(x_2)^TF_3x=0$  and the vectors $F_1x$, $F_2x$ and $F_3x$ were linearly independent, then you could find a unique solution to $x_2$.
Comment: Thank you for clarifying all this.


relations between Bessel functions J0 and K0 (to find the Green's function for the 2D screened Poisson equation)

Question: I'm trying to find the Green's function for the screened Poisson equation in two dimensions, i.e. the $G(\mathbf{r})$ that solves
$$(\nabla^2-1/\rho^2) G(\mathbf{r}) = \delta(\mathbf{r}), \qquad \mathbf{r}\in\mathbb{R}^2,$$
via Fourier transform methods. Everything is fine except for the final integral in the inverse transform, which is over the radius $k$ in polar coordinates.
Essentially my question is: "how do you do the last step on the last line of the relevant wikipedia page?" which is:
$$\int_0^\infty dk\frac{k}{k^2+1/\rho^2}J_0(kr) = K_0(r/\rho).$$
I can't find anywhere such a relation between the 0th-order Bessel function of the first kind $J_0(x)$ and the 0th order modified Bessel function of the second kind $K_0(x)$, except on that particular wikipedia page.
Could someone point me to a reputable reference for this integral relation, or otherwise indicate how I might show this result? Thanks!
Answer: For the integral,
$$ I:=\int_0^\infty  \frac{x}{x^2+q^2} \text{J}_0(x\,r)\ dx $$
insert the well-known integral
$$  \frac{x}{x^2+q^2} = \int_0^\infty  e^{-x\,u}\cos{(q\ u)} \ du.$$
Switch integrations.  Many integral tables have
$$ \int_0^\infty  e^{-x\,u} \text{J}_0(x\,r)\ dx = \frac{1}{\sqrt{r^2+u^2}}. $$
Scale and use Digital Library of Mathematical Functions 10.32.6,
$$ \text{K}_0(w)=\int_0^\infty \frac{\cos{(w \ t)}}{\sqrt{1+t^2}} dt.$$
You'll find  $I=\text{K}_0(r\ q), $ equivalent to your question with $q=1/\rho.$  For more rigor, justify the interchange of integrations.
Comment: Thanks! Justifying the exchange of integrations is just by saying that $x$ and $u$ are independent and the limits on neither integral depend on the other variable, right? Or am I missing something subtle?


Using WP_Query to Retrieve ACF Field Value

Question: Can someone please share PHP code to retrieve an ACF field value using WP_Query? The following retrieves the field value, but I would like to accomplish this using WP_Query instead so that it can be used as a Meta Query:
<?php $field = get_field_object('field_64fa6f6063934'); ?> <?php echo $field['value']; ?>
I've also tried
<?php $field = get_field_object('field_64fd4d406393c'); echo $field['value']; ?>
Thank you
Comment: Why on earth wouldn't you google `acf meta query` and find their excellent explanation? https://www.advancedcustomfields.com/resources/query-posts-custom-fields/
Comment: I did, however, the page doesn't provide an example on how to retrieve the field value using wp_query. It provides example on querying posts with the field value (meta value) defined.
Comment: From the site: `Please note these examples use the WP_Query object [...]`. If you want to retrieve an ACF field value by something different than the meta_key, you should probably update your question.
Comment: Please tell me where the page provides an example of retrieving the field value using WP_Query?
Comment: What do you mean by `retrieving`? `WP_Query` holds a collection of `posts` that match certain criteria and the meta query is used to associate these criteria to `meta_key` and/or `meta_value`. When iterating through the resultset, you can use WordPress' functions to retrieve the values with `the_field('key')` or `get_field('key')` just like you do with `the_title()` or `get_the_title()` respectively.
Answer: To retrieve an ACF field value using WP_Query, you can use the meta_query parameter in the WP_Query function. Here's an example code snippet that retrieves the value of an ACF field with the field key field_64fa6f6063934:
$args = array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'field_64fa6f6063934',
            'compare' => 'EXISTS',
        ),
    ),
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $field_value = get_field( 'field_64fa6f6063934' );
        // Do something with the field value
    }
    wp_reset_postdata();
}

In this example, we're querying for posts of type post that have a value for the ACF field with the key field_64fa6f6063934. The compare parameter is set to EXISTS to ensure that we only retrieve posts that have a value for this field.
Inside the loop, we're using the get_field() function to retrieve the value of the field for the current post. You can replace field_64fa6f6063934 with the key of the ACF field you want to retrieve.
Note that you need to call wp_reset_postdata() after the loop to restore the global post data to its original state.


Linux Auditd: Error receiving audit netlink packet (No buffer space available)

Question: I have some Linux servers that are getting errors like the below in the logs...
<code>auditd[1074]: Error receiving audit netlink packet (No buffer space available)
</code>
I know HOW to resolve the issue (tweak the audit buffer setting in audit.rules), but I'm wondering WHAT is the impact of this?
Am I actually losing auditd events in the blog?  Is it failing to write the events when it runs out of buffer space?
I have been Googling, but I haven't found a concrete answer.
Answer: You could try increasing auditd's buffer size. In rhel 8 is would be in/etc/audit/rules.d/audit.rules
Comment: In the end, this is what I wound up doing.  I've been tuning this on a per-server basis.


What is the oldest and active olympic sport?

Question: Wrestling is one of the oldest olympic sport which was removed from olympics since 1904.
I need to know,
What is the oldest olympic sport that continued till now?
Answer:
The only summer sports that have never been absent from the Olympic program are athletics, aquatics (the discipline of swimming has been in every Olympics), cycling, fencing, and gymnastics (the discipline of artistic gymnastics has been in every Olympics).
The only winter sports that were included in all Winter Olympic Games are skiing (only nordic skiing), skating (figure skating and speed skating) and ice hockey. Figure skating and ice hockey were also included in the Summer Olympics before the Winter Olympics were introduced in 1924.

Wikipedia

With regards to those last two:
Ice hockey: since 1920
Figure skating: in 1908 and since 1920, but not in 1912
Answer: user1564's answer covers the modern Olympic games.  However, some of the sports that are included in the Olympics today have their roots in the Olympic games of ancient Greece.  The sports from those games included:

Running/Jumping/Discus Throw/Javelin Throw (Athletics)
Wrestling
Pentathlon (5 events: running, jumping, discus, javelin, wrestling)
Boxing
Pankration (a martial art combining wrestling and boxing, similar to MMA)
Equestrian events

Sources: Olympic.org, Wikipedia
Other than Pankration, all of the other events in some form were included in the modern games.  Many people are upset at the removal of wrestling because it is one of the few sports that traces back to the ancient games.


Tail random variable and extremum

Question: Let $(X_n)_n$ be a sequence of real random variables. Is it true that $\limsup_n\frac{1}{n}\max_{1 \leq k\leq n}X_k$ is tail random variable? $\liminf_n \frac{1}{n}\min_{1 \leq k \leq n}X_k$ ? $\limsup_n\frac{1}{n}\min_{1\leq k \leq n}X_k$?
For the first two, I think the answer is correct, since for $r \in \mathbb{N}^*,$
$$\limsup_n\frac{1}{n}\max_{1 \leq k\leq n}X_k=\limsup_n\frac{1}{n+r}\max_{1\leq k \leq n+r}X_k=\limsup_n\max(\frac{1}{n+r}\max_{1\leq k \leq r}X_k,\frac{1}{n+r}\max_{r+1 \leq k \leq n+r}X_k)=\max(0,\limsup_n\frac{1}{n+r}\max_{r+1 \leq k\leq n+r}X_k)$$ which is $\sigma(\bigcup_{k \geq r}\sigma(X_k))$ measurable.
(I used that $\limsup_n\max(u_n,v_n)=\max(\limsup_nu_n,\limsup_nv_n)$).
The same thing for $\liminf_n \frac{1}{n}\min_{1 \leq k \leq n}X_k.$
I'm stuck on the third one. Do you have any ideas?
Answer: In general: $$\left|\min\left(a,b\right)-\min\left(a',b\right)\right|\leq\left|a-a'\right|$$
So if: $$Z_{n}:=\frac{1}{n}\min_{2\leq k\leq n}X_{k}$$ and: $$Y_{n}:=\frac{1}{n}\min_{1\leq k\leq n}X_{k}=\min\left(\frac{1}{n}X_{1},Z_{n}\right)$$
then: $$\left|Y_{n}-\min\left(0,Z_{n}\right)\right|\leq\frac{1}{n}\left|X_{1}\right|$$
From this we conclude that: $$\limsup Y_{n}=\limsup\min\left(0,Z_{n}\right)$$
showing that $\limsup Y_{n}$ is measurable wrt $\sigma\left(X_{2},X_{3},\dots\right)$.
This can be expanded to find that $\limsup Y_{n}$ is measurable wrt
$\sigma\left(X_{r},X_{r+1},\dots\right)$ for every $r$.

Tail random variable and extremum


How can I change URL of 'Add new comment' link on teaser?

Question: Currently, I have a list of teasers and they have a comment count and an 'Add new comment' link.
That link goes to a dedicated comment page with a URL of the form "/comment/reply/19#comment-form".
However, I want it to go to the actual node which has the comment form at the bottom (eg. "/node/19#comment-form").
Maybe this can be done is the template.php or some other way. Any ideas would be greatly appreciated.
Answer: Go to the admin page for your content type

/admin/structure/types/manage/page

and check Show reply form on the same page as comments under Comment settings.
If you look at comment_node_view() in the comment module, you can see where the comment link is added to teasers.
    if (user_access('post comments')) {
      $links['comment-add'] = array(
        'title' => t('Add new comment'),
        'href' => "comment/reply/$node->nid",
        'attributes' => array('title' => t('Add a new comment to this page.')),
        'fragment' => 'comment-form',
      );
    }

To alter the link you can use hook_node_view_alter() in your module.
function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if (isset($build['links']['comment']['#links']['comment-add'])) {
    // Alter the 'Add new comment' link.
    $build['links']['comment']['#links']['comment-add']['href'] = "node/$node->nid";
    // Fragment is the '#comment-form' part of the url.
    $build['links']['comment']['#links']['comment-add']['fragment'] = 'comment-form';
  }
}

Comment: @WebMW you should be able to render HTML by adding `$build['links']['comment']['#links']['comment-add']['html'] = TRUE;`. You can check the documentation for [theme_links](https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_links/7.x) for more options.
Comment: Thanks for the reply but I've already got the comment form showing on the node page. I want the 'Add New Comment' link on the teaser to go to that node page (and not the dedicated Comment page it currently does go to).
Comment: I added a description how to alter the `Add new comment` link.
Comment: Thank you so much Marcus. This did exactly what I wanted. I had to put single quotes around the #node on the second line, so the line was:
`$node = $build['#node'];`
but otherwise it worked wonderfully, thank you.
Comment: @MarcusAschan this works great, but would you happen to know how to add HTML to the 'title' (that on default renders 'Add new comment')? I'm trying to add a FontAwesome icon () before this and it's currently showing up as plain text.
Comment: @MarcusAschan, you are a savior! I can't express how many hours were put into not only asking this question to Drupal Support on IRC, but on both Stack Exchange & Stack Overflow. THANK YOU! I'd like you to have the credit for those if you could provide your answer: https://drupal.stackexchange.com/questions/246936/why-is-html-rendering-as-plain-text-in-a-simple-title-alteration & https://stackoverflow.com/questions/46477873/why-is-html-rendering-as-plain-text-in-a-simple-title-alteration
Comment: @WebMW glad I could help! :) I answered you two questions.


Appropriateness of mixed effects meta-analysis

Question: I am a bit puzzled about a fundamental problem in mixed effects meta-analysis.
Let us say a researcher wants to assess the impact of training programs on the diagnostic competence of a) teachers and b) physicians. Thus, the outcome variable "diagnostic competence" is pretty much different: teachers assess pupils' performance whereas physicians assess medical symptoms of patients. However, because he/she is interested in the overall effect of training programms on diagnostic competencies, he/she decides to run a mixed effects meta-analysis to obtain a summary effect, but with these subgroups as moderator variables (i.e., assuming the strength of the effect is conditional on the subgroup):
$${{Y}_{i}}=\mu +{{\zeta }_{i}}+{{\varepsilon }_{i}}$$
Thus, the effect Y of a study i (i = 1,…,k) is given by the grand mean, the deviation of the study's true effect zeta from the grand mean, and the deviation epsilon of the study's observed effect from the study's true effect.
Now, here is my question: I always thought the mixed-effects model is only appropriate if we can assume that a study's true effect from the grand mean is due to differences in the method (e.g., questionnaire vs. interview) used to measure the same outcome variable. I think the application of a random-effects model is not appropriate in the present case, even if we include subgroup membership as a moderator. The effect size refers to entirely different outcome variables (diagnostic competence with respect to performance vs. medical symptoms). I think running separate mixed effects meta-analysis per group makes more sense. Help is m
Answer: I think there are two ways of answering this. First there is nothing in the underlying theory preventing you from doing this just as nothing prevents you from adding two forks and two knives to give you four pieces of cutlery or two forks and two fire engines to get four objects. The second answer is based on whether it makes scientific sense. Four pieces of cutlery does seem OK but adding forks to fire engines does not. In your case I would assume that as the expertise of your two groups becomes more similar the procedure becomes more sensible but it is up to you to say whether teachers and physicians are similar and doing a similar task.


Why the field extension $\mathbb{C}/\mathbb{Q}$ is not finitely generated?

Question: I know the extension $\mathbb{C}/\mathbb{Q}$ is not finite, as $\mathbb{Q}$ is countable whereas $\mathbb{C}$ is not.
However, how should I prove that the field extension $\mathbb{C}/\mathbb{Q}$ is not finitely generated?
Comment: If it were, then it would be countable as well.
Comment: It seems you've already proved it: if $F$ is finitely generated over $E$ and $E$ is countable, then $F$ is countable. What more are you looking for?
Comment: @OrShahar For me, the extension $L/K$ is finitely generated if there exist $\alpha_1,\dots,\alpha_n\in L$ such that $L=K(\alpha_1,\dots,\alpha_n)$.
Comment: I think it's due to the fact that there exist infintly many algebraic independent transcendental numbers in $\Bbb{C}$ (I can't find a proof rith know, it's just an idea)
Comment: See also https://math.stackexchange.com/questions/3996903/linearly-independent-set-in-mathbb-r-over-mathbb-q/3996925#3996925
Answer: We just need to show that if $K$ is a field with countable (infinite) cardinality, then any countably generated field $L$ over $K$ is also countable. By induction, it's sufficient to show any simple extension $K(\alpha)$ is countable. And indeed $$K(\alpha)=\cup_{n=1}^\infty \{ \frac{\sum_{i=0}^n a_i\alpha^i}{\sum_{i=0}^n b_i\alpha^i} | a_i, b_i\in K, \sum_{i=0}^n b_i\alpha^i\not=0\}$$
Note that the cardinality of $\{ \frac{\sum_{i=0}^n a_i\alpha^i}{\sum_{i=0}^n b_i\alpha^i} | a_i, b_i\in K, \sum_{i=0}^n b_i\alpha^i\not=0\}$ won't exceed $|K|^{2n}$, hence must be countable as well.
So just to recognize there aren't so many polynomials (or fractions), which was first known to Cantor who proved there exist transcendental numbers this way without exhibiting a single example.


Remover timezone em requisição com node.js e express.js

Question: Tenho uma API com node.js e express.js. No banco de dados os campos do tipo datetime estão salvos corretamente, porém na resposta de uma requição GET os campos de data vêm com 3 horas à mais devido ao fuso horário.
Estou fazendo esta requisição e consumindo o json em uma aplicação web e em um app android nativo.
Gostaria de saber como eu poderia resolver. Existe alguma possibilidade de remover o timezone na API, ou deveria configurar alguma coisa no banco de dados ou no servidor? Estou usando MySQL.
Exemplo:
**DB:** 2017-10-02 10:58:34

**JSON:** "2017-10-02T13:58:34.000Z"

Comment: Podes colocar aqui o exemplo dessa string que vem do GET? não tem fuso horário na string?
Comment: Atualizei com o exemplo.
Comment: Ok, mais duas perguntas: tens controlo sobre a criação da data do GET? qual é o timezone da data da BD?
Comment: Tenho sim. `@@system_time_zone: BRT`, `@@global.time_zone: SYSTEM`, `@@session.time_zone: SYSTEM`.
Answer: Sugiro usar uma biblioteca para a conversão. Por exemplo a extenção do moment.js para timzones, o moment-timzone.
Para fazer de maneira nativa podes usar UTC e somar a diferença para o teu horário, ou formatar a data com o .toLocaleString('pt-br', {timezone: 'Brazil/brt'}).  Os problemas que podem surgir são nos dias de mudança entre horário de verão e inverno que não tenho a certeza que o browser sabe essa informação.
Por exemplo tendo a data do JSON repara nos que podemos extrair:

var json = "2017-10-02T13:58:34.000Z";
var date = new Date(json);

console.log('Dia:', date.getUTCDate(), 'Hora:', [date.getUTCHours(), date.getUTCMonth() + 1, date.getUTCMinutes()].join(':'));

console.log(date.toLocaleString('pt-br', {timezone: 'Brazil/brt'}));
Comment: Então o único jeito é tratando campo à campo mesmo? Não há uma maneira de remover ou alterar o timezone direto na aplicação, certo?
Comment: @FernandoZabin Sim, como não tens controlo sobre que país ou timezone o utilizador está, tens de gerir isso assim. O melhor talvez é fazer a conversão no momento de inserir.
Comment: Entendi. Fiz um teste rápido na aplicação web e formatando a data com o moment.js padrão, ele já corrige o fuso horário, não tinha observado antes. Acho que a solução para o app android seria adicionar uma conversão ao receber os dados também. Obrigado.
Comment: @FernandoZabin exato podias converter no ajax, assim o que chega ao servidor está normalizado


Dúvida - Winforms sobre a respeito na segunda tela

Question: Form1 criei panel com fundo preto e label com propriedade:

AutoSize = False
Dock = Fill
Tamanho da letra(Size) = 20
E 2 botões para avançar ou voltar letras

Form2 só tem form preto e um label com propriedade:

AutoSize = False
Dock = Fill
Tamanho da letra(Size) = 40

Segue código como eu mostro na segunda tela(monitor):
telaSecundaria = new SegundaTela();
Screen[] telas = Screen.AllScreens;
Rectangle bounds = telas[1].Bounds; // pode ser outro índice.
telaSecundaria.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height);
telaSecundaria.StartPosition = FormStartPosition.Manual;
telaSecundaria.Show();
telaSecundaria?.ChangeLabel(label.Text);

Maior problema é a resolução de monitor, fiz teste de vários monitores aqui e são tudo diferente. As letras não são a mesma do Form1, exemplo:
No Form1:

Todo mundo quer ser legal, e todo mundo se ferra na empreitada. É
  difícil ser legal o tempo inteiro. A gente consegue ser legal a maior
  parte do tempo, mas aí faz uma besteira e pronto: tudo o que você fez
  de bom é imediatamente esquecido e você se torna apenas aquele que fez
  a grande besteira. Aí você precisa de mais uns dois meses sendo
  exclusivamente legal para todo mundo esquecer da besteira. E quando
  eles esquecem, você faz outra, claro.

No Form2(monitor):

Todo mundo quer ser legal, e todo mundo se ferra na empreitada. É
  difícil ser
           legal o tempo inteiro. A gente consegue ser legal a maior
  parte do tempo, mas
   aí faz uma besteira e pronto: tudo o que você fez
  de bom é imediatamente
     esquecido e você se torna apenas aquele que fez
  a grande besteira. Aí você
      precisa de mais uns dois meses sendo
  exclusivamente legal para todo mundo
     esquecer da besteira. E quando
  eles esquecem, você faz outra, claro.

Como posso corrigir as posições de cada palavra ? Aqui no monitor e a tela do cliente está ok. O problema é monitor diferente (resolução diferente). Eu quero que Form2 fica a mesma do Form1.
Segue a foto (cliente):

E do monitor:
https://s1.postimg.org/5gyzn0lc6n/20171109_212331.jpg
Answer: Fiz um código pra ajustar a fonte do label automaticamente pelo tamanho do Form, veja se funciona e depois comento o código explicando tudo
  Timer tSize = new Timer() { Interval = 300, Enabled = false };
  private void Form1_Load(object sender, EventArgs e)
    {
        label1.Text = @"Todo mundo quer ser legal, e todo mundo se ferra na empreitada. É difícil ser legal o tempo inteiro. A gente consegue ser legal a maior parte do tempo, mas aí faz uma besteira e pronto: tudo o que você fez de bom é imediatamente esquecido e você se torna apenas aquele que fez a grande besteira. Aí você precisa de mais uns dois meses sendo exclusivamente legal para todo mundo esquecer da besteira. E quando eles esquecem, você faz outra, claro.";

        tSize.Tick +=  (s,arg) => {
             ((Timer)s).Enabled = false;
             SetLabelSize();
        };
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        tSize.Enabled = false;
        tSize.Enabled = true;
    }
    private void label1_TextChanged(object sender, EventArgs e)
    {
        tSize.Enabled = false;
        tSize.Enabled = true;
    }
    private void SetLabelSize()
    {
        this.SuspendLayout();
        label1.Dock = DockStyle.Top;
        label1.AutoSize = true;
        label1.MaximumSize = new Size(this.Width, 0);
        label1.Font = new Font("Consolas", 12);
        float size = label1.Font.Size;
        int limite = this.Height - 30;
        while (label1.Height < limite- label1.Font.Height)
        {
            size += 0.1f;
            label1.Font = new Font("Consolas", size);
        }

        this.ResumeLayout(false);
    }

Edit:
Conforme pedido, para manter a tela (label) na proporção 4:3 basta trocar algumas linhas no código.
Remova: label1.MaximumSize = new Size(this.Width, 0);
e coloque:
label1.MaximumSize = new Size(this.Height + this.Height /4 , 0);
panel2.Padding = new System.Windows.Forms.Padding((panel2.Width - label1.Width) / 2, 0, 0, 0);

Onde panel2 é onde o label está inserido. Ou seja, é o Parent do label.
Resultado:

Coloquei o label com fundo de outra cor para diferenciar do form.
Comment: ser tela secundária não importa. Deixou passar algo
Comment: pode até deixar no form, só trocar `panel2` por `this`


Cannot invoke 'decode' with an argument list of type '(GenericDM.Type, from: String?)'

Question: I've been using app.quicktype.io to generate the code to decode JSON. I'm facing a problem now that I have not seen before.
First, I have this simple struct:
import Foundation

struct GenericDM: Codable {
    let status, statusMessage: String
    let result: [Result]

    enum CodingKeys: String, CodingKey {
        case status
        case statusMessage = "status_message"
        case result
    }
}

struct Result: Codable {
    let applicationID, applicationName, applicationType, suFirstName: String
    let suMiddleName, suLastName, suAge, suDob: String
    let suRace: String
    let suAddress: SuAddress
    let createdTime, updatedTime: Int

    enum CodingKeys: String, CodingKey {
        case applicationID = "application_id"
        case applicationName = "application_name"
        case applicationType = "application_type"
        case suFirstName = "su_first_name"
        case suMiddleName = "su_middle_name"
        case suLastName = "su_last_name"
        case suAge = "su_age"
        case suDob = "su_dob"
        case suRace = "su_race"
        case suAddress = "su_address"
        case createdTime = "created_time"
        case updatedTime = "updated_time"
    }
}

struct SuAddress: Codable {
    let addrLine1, addrLine2, stName, addrCity: String
    let addrState, addrCounty, addrPin: String

    enum CodingKeys: String, CodingKey {
        case addrLine1 = "addr_line_1"
        case addrLine2 = "addr_line_2"
        case stName = "st_name"
        case addrCity = "addr_city"
        case addrState = "addr_state"
        case addrCounty = "addr_county"
        case addrPin = "addr_pin"
    }
}

func newJSONDecoder() -> JSONDecoder {
    let decoder = JSONDecoder()
    if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
        decoder.dateDecodingStrategy = .iso8601
    }
    return decoder
}

func newJSONEncoder() -> JSONEncoder {
    let encoder = JSONEncoder()
    if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
        encoder.dateEncodingStrategy = .iso8601
    }
    return encoder
}

// MARK: - URLSession response handlers

extension URLSession {
    fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
        return self.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else {
                completionHandler(nil, response, error)
                return
            }
            completionHandler(try? newJSONDecoder().decode(T.self, from: data), response, nil)
        }
    }

    func genericDMTask(with url: URL, completionHandler: @escaping (GenericDM?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
        return self.codableTask(with: url, completionHandler: completionHandler)
    }
}

Then, I read a JSON file and try to decode the data from a different class:
    let bundle = Bundle.main
    let path = bundle.path(forResource: "MockGenericData", ofType: "json")
    let jsonData = try? String.init(contentsOf: URL.init(fileURLWithPath: path!))
    let genericDM = try? newGenericDMJSONDecoder().decode(GenericDM.self, from: jsonData)

I temporarily need to read from that mockup file before I can get it from the backend.
However, I'm getting Cannot invoke 'decode' with an argument list of type '(GenericDM.Type, from: String?)' and I don't understand why.
Anybody has any idea?
Comment: Probably unrelated, but you don't have to use `CodingKeys` for your specific need, just set decoder's `keyDecodingStrategy` to `convertFromSnakeCase`. It converts for example `status_message` to `statusMessage`
Comment: What is `newGenericDMJSONDecoder`?
Comment: You need to pass a data object not a string
Comment: Btw naming a string object as jsonData is very misleading
Comment: You just need to use Data contentsOf URL instead of String init
Comment: Thank you folks. Yes, I had this stupid mistake of using String instead of Data. The code above will eventually be used with a URL Session but for the time being, I use JSON data from a file.
Answer: Assuming decode is the normal Decoder decode method. The from parameter expect Data, not an optional String.
let url = Bundle.main.url(forResource: "MockGenericData", withExtension: "json")!
do {
    let jsonData = try Data(contentsOf: url)
    let genericDM = try newGenericDMJSONDecoder().decode(GenericDM.self, from: jsonData)
} catch {
    print(error)
}


Is it possible to boot an existing windows installation from hard disk with VirtualBox in Linux?

Question: I have a dual boot system windows 7 and Linux Ubuntu 10.4, I want to clarify if it is possible to load the windows installation through Linux VirtualBox from the existing installation at hard disk?
Answer: Windows will see the hardware as having changed. At best, it will complain loudly. Most likely, however, is that it won't work.
Comment: I manage to open my image successfully from my ubuntu with virtualbox there was an issue with a specific version of the kernel. Windows didn't complain at all.
Answer: Yes it actually is, and the procedure was quite straightforward, the most recent version of VirtualBox supports loading a native installation in the virtual machine.


Airflow run task if some of direct upstream are not triggered

Question: I have a DAG, it has 5 tasks A,B,C,D,E. and 5 tasks triggered by failed tasks above, one for each, A_f, B_f, C_f, D_f and E_f (and similarly five on success). And at last, task X, which writes failure results to a database.
Lets say, if 2 of first five tasks failed (A and D), only A_f and D_f get triggered. What can I do to run task X?
Will all_done work? even if some of the upstream tasks were never triggered? I am not so sure about it.
Answer: Yes all_done should work. As long as none of Task X's upstream tasks have a state of None, which for any given dag run shouldn't be possible because tasks' states are inferred from previous tasks' states (i.e. skipped state is propagated or any children of a failed task are set to upstream failed), then the all_done trigger will work.


Find A Cell In Sheet1 Then Copy The Entire Row That It Is In To The First Empty Row in Sheet2

Question: I receive a "subscript out of range" at the line starting:  Sheets("Sheet1").Cells("A", i).EntireRow.Copy . How do I copy and paste the row to the first open row in Sheet2.
Sub IDwalkups()
Dim endRow As Long
Dim Match1() As Variant
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
ICount = 0
endRow = Sheet1.Range("B999999").End(xlUp).Row

Match1 = Sheet1.Range("E3:E" & endRow)
For i = LBound(Match1) To UBound(Match1)
    If Match1(i, 1) = "W" Then

    Sheets("Sheet1").Cells("A", i).EntireRow.Copy Destination:=Sheets   ("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)

    Else
   End If
Next i
End Sub

Answer: The three errors you have are:

using " and " instead of ".  For instance, "Sheet1" is a valid variable name and can be used in statements such as "Sheet1" = 5 * 2.  Syntactically, it is quite different to "Sheet1" which is a string literal.
Using Cells("A", i) instead of Cells(i, "A") - the first parameter of Cells is the row, and the second parameter is the column.
Not qualifying which sheet you are referring to when using Rows.Count (but there is a good chance that this would have worked anyway)

So
Sheets("Sheet1").Cells("A", i).EntireRow.Copy Destination:=Sheets   ("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)

should have been
Sheets("Sheet1").Cells(i, "A").EntireRow.Copy Destination:=Sheets("Sheet2").Range("A" & Sheets("Sheet2").Rows.Count).End(xlUp).Offset(1)

Answer: I see 2 errors.
First the Copy & Paste are two steps (2 commands). Second, if you use Cells, you have to give row and column as Number-Parameter. You have to change it to Range.
    If Match1(i, 1) = "W" Then
        Dim sourceRange As Range, destRange As Range
        Set sourceRange = ws.Range("A" & i).EntireRow
        ' or Set sourceRange = ws.Cells(i, 1).EntireRow
        sourceRange.Copy
        Set destRange = Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)
        destRange.PasteSpecial
    End If

Comment: `Cells("A", i)` is incorrect, but `Cells(i, "A")` would be OK - the column doesn't need to be numeric, it can be a string
Comment: Hey YowE3K, I'm using VBA since years and use `.Cells` all the time, but never realized that.
Comment: I only learnt that when I started hanging around SO about 10 months ago, and I think I have been using VBA since it first came out!
Comment: Oh - Copy/Paste don't have to be two operations - what the OP did is fine, so the two errors are the incorrect quotation marks, and the row/column switch in `Cells`
Comment: @FunThomas  both your answer works. Thank you your help is much appreciated.
Comment: @YowE3K your answer also works and is the solution I went with. Thank you your help is much appreciated.


O que é um Webhook?

Question: Vi algumas perguntas aqui que falam sobre o termo o Webhook. Gostaria de saber melhor do que se trata esse termo na programação.
Comment: https://i.stack.imgur.com/nB3M0.png
Comment: Exemplo: https://pt.stackoverflow.com/q/44760/101
Answer: Os Webhooks são, basicamente, um meio de comunicação entre suas aplicações. Com eles, uma aplicação é capaz de enviar dados à outras aplicações. Desse modo, webhooks enviam dados mediante o acontecimento de um evento específico, geralmente em tempo real. Em suma, um autêntico callback estabelecido através do protocolo HTTP.
A aplicação que implementou o webhook irá enviar requisições HTTP às aplicações que se inscreveram. Por esse motivo, também são chamados de "web callbacks" ou "reverse API".
Como o webhook enviará uma requisição HTTP à outras aplicações, se a sua aplicação irá "receber" os dados, ela deverá estar preparada para receber e interpretar os dados, que geralmente são enviados sob o método POST com um payload em JSON. A aplicação receptora configurará, desse modo, um endpoint HTTP (geralmente no método POST), para receber os dados.

Acima temos um simples diagrama para exemplificar o funcionamento de um webhook. Nesse caso, "Twitter Server" é a aplicação que enviará os webhooks e "Your Server" é a aplicação que irá recebê-los. Dessa maneira, mediante o acontecimento de eventos no Twitter, a sua aplicação receberá requisições HTTP (os webhooks), enviadas pelo Twitter. Por isso, a aplicação que receberá esses callbacks deve estar preparada para lidar e interpretar essas requisições.
Há também formas de autenticação no meio de webhooks. Como a aplicação que irá receber os dados deverá manter um endpoint para receber os dados da aplicação que enviará o webhook, pessoas com más intenções podem usar esse endpoint para enviar informações falsas. Desse modo, algum meio de autenticação poderá ser configurado entre as duas aplicações para que esse problema seja evitado. Entre os meios mais comuns de autenticação, podem ser citados:

A criação de uma lista-branca com IPs pré-configurados;
Autenticação HTTP Basic;
Tokens diversos, que podem ser incluídos em cabeçalhos HTTP. O GitHub, por exemplo, utiliza essa técnica.

Webhook × API
Muitas pessoas confundem webhooks com APIs. No entanto, apesar de fornecerem dados à um cliente, fazem isso de formas distintas. Basicamente, um webhook irá enviar os dados para as aplicações inscritas em tempo real (em "push"), enquanto uma API irá enviar os dados quando forem solicitados pelo cliente.
Além disso, o propósito das APIs é fornecer uma extensa quantidade de ferramentas para os clientes, como um CRUD. Os webhooks, por outro lado, na maioria das vezes tem a função de notificar o acontecimento de um evento, podendo também enviar dados relativos ao evento. Há um artigo em Inglês que elabora bem mais essas diferenças.
Referência
Recursos que usei para elaborar essa resposta:

Webhook;
What's a Webhook?
Answer: Um Webhook é uma forma de permitir que seja executada uma ação após o acontecimento de um evento.
Geralmente é utilizado para permitir que aplicações externas possam se utilizar dos dados de um evento no exato momento em que ele acontece.
Exemplos disso seriam por exemplo a integração do github com o slack, do trello com o discord, e por aí vai.
O conceito resume-se em:
  - Uma parte que proverá esses dados, e portanto precisa permitir que sejam cadastrados os "listeners" para os eventos selecionados
  - Uma outra parte que saberá utilizar essas informações da forma como for desejada
Answer: Webhook é uma forma de receber informações, e elas só são passadas quando ocorre um evento.Na prática, é uma forma de troca de informações entre dois sistemas, mas apenas quando há de fato uma informação a ser passada. É uma maneira prática para um app ou sistema fornecer informações em tempo real.
Você pode conhecer o webhook também como um retorno de chamada HTTP.
Nesse link aqui você pode encontrar mais detalhes até de como criar ou implementar um webhook.
Answer: Webhook é um recurso que envia informações em tempo real, tornando o desenvolvimento de sistemas mais fácil.
Neste link você poderá saber mais sobre webhook.
link: https://blog.tecnospeed.com.br/webhook-o-que-e/
Answer: Um webhook em desenvolvimento Web é um método de ampliar ou alterar o comportamento de uma página da Web, ou aplicação da Web, com callbacks personalizados.

O que é um Webhook?


Adding Placeholders for PHP variables

Question: When creating a query using db_query in my module I want to make sure it's as secure as possible. So I'd like to use placeholders in my 'WHERE' clauses. The problem I'm having is how to use placeholders when the array values to be used are PHP variables. So for example:
WHERE el.field_experience_level_value='$level'

Is what I'm normally using and it works fine. But then I changed it to the following and added the array part at the end like so:
WHERE el.field_experience_level_value=':level'
...some more code
array(':level' => '$level')

I get no error but it doesn't return those results. So my main question is, how do I add a php variable such as $level above (already defined in previous code, not here) to a placeholder?
Answer: Better to use PDO for DB related operations in Drupal like db_select(),
db_insert(), db_update() and db_delete().
Here you no need to worry about place holder and other injections.
Ex:
   $result = db_select('node', 'n')
    ->fields('n')
    ->condition('nid', $node->nid,'=')
    ->condition('status', 0,'>')
    ->condition('uid', array(1,5,7),'IN')
    ->execute()
    ->fetchAssoc();
Note from db_query() API page : Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.
Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.
Answer: Ok so I solved this already. You just have to NOT put quotes around the placeholder in the SQL query, so like this works:
WHERE el.field_experience_level_value=:level

Adding Placeholders for PHP variables


How to display images using the MINST dataset in keras

Question: I imported the minst dataset from keras, and want to display some images from it. But since I imported the dataset from keras internally, how should I use matplotlib to display some images?
<code>%matplotlib inline

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# this creates a training set and test set
(x_train, y_train), (x_test, y_test) = mnist.load_data()

img=mpimg.imread('x_train[1]')
imgplot = plt.imshow(img)
plt.show()
</code>
Answer: You can do it like this
<code>import matplotlib.pyplot as plt
image=x_train[1]
plt.imshow(image)
plt.show()
</code>
Comment: I get this error if I do this: ValueError: ('Expected image array to have rank 3 (single image). Got array with shape:', (28, 28))
Comment: @Daphne sorry forgot they are greyscale. let us do it with matplot. Check the edited ans
Comment: that works! so import matplotlib.image as mpimg is not necessary?
Comment: @Daphne Nope you dont need. Please upvote and accept the answer if it helped you


Solve $x''+x=\epsilon x^2$ as $\epsilon\to0$ using the Poincaré-Lindstedt method

Question: I'm self studying some asymptotic techniques to deal with my engineering problems.
Given $\frac{d^2x}{dt^2}+x=\epsilon x^2,~x(0)=1,~x'(0)=0$. I want to use the Poincaré-Lindstedt method to solve it as $\epsilon\to0$. First I let $x(t)=X(t)$ and $\theta=\Omega(\epsilon)t$, $\Omega(0)=\omega_0$.
Then I have $$\Omega^2\frac{d^2X}{d\theta^2}+X=\epsilon X^2,~X(0)=1,~\Omega\left.\frac{dX}{d\theta}\right\vert_{\theta=0}=0$$
Expand $X=X_0(\theta)+\epsilon X_1(\theta)+\epsilon^2X_2(\theta)+\cdots$. Then I have
$$\Omega^2\left(X_0''(\theta)+\epsilon X_1''(\theta)+\epsilon^2X_2''(\theta)+\cdots\right)+\left(X_0(\theta)+\epsilon X_1(\theta)+\epsilon^2X_2(\theta)+\cdots\right)=\epsilon\left(X_0(\theta)+\epsilon X_1(\theta)+\epsilon^2X_2(\theta)+\cdots\right)^2$$
However, I don't know how to keep going. The reference I am using did some strange steps in collecting the $O(\epsilon^1)$ terms, which make me confused.
Answer: You also need to insert the expansion of $Ω(ϵ)=1+ϵΩ_1+ϵ^2Ω_2+...$ so that you get
$$
(1+2ϵΩ_1+..)(X_0''+ϵX_1''+..)+(X_0+ϵX_1+...)=ϵ(X_0^2+2ϵX_0X_1+...)
$$
Comparing coefficients then gives in the first two orders of $ϵ$
$$
X_0''+X_0=0\\
2Ω_1X_0''+X_1''+X_1=X_0^2\\
$$
As $X_0^2$ will have frequencies $0$ and $2$, there are no secular terms to compensate, so set $Ω_1=0$. Then in the $ϵ^2$ terms you get
$$
2Ω_2X_0''+X_2''+X_2=2X_0X_1\\
$$
The product $X_0X_1$ consist of terms with frequencies $2\pm1$ and $0+1$, so there will be secular terms of frequency $1$ that can be compensated by the $X_0''$ term, giving $Ω_2$ a non-zero value.

In detail, $X_0=\cos(θ)$, resulting in $X_0^2=\frac12(1+\cos(2θ)$, which gives per "undetermined coefficients"
$$X_1=A(1-\cos(θ))+B(\cos(2θ)-\cos(θ)),$$
with $A=\frac12$ and $-3B=\frac12$.
Now
$$
2X_0X_1=\frac12(2\cosθ-1-\cos(2θ))-\frac16(\cos(3θ)+\cosθ-1-\cos(2θ))
$$
thus $-2Ω_2=1-\frac16=\frac56$.
Comment: https://math.stackexchange.com/questions/3370184/perturbation-methods-multiscale has a book by H. Holmes, which is also cited in other places.
Comment: Thanks! It's pretty clear. Btw, do you know what books in asymptotic analysis are clear and are recommended?


Using multisite for a ReSTful API and Auth Strategy

Question: My Situation
I have a small app with a public interface. I'm interested in making an API for this to be used in a mobile environment and even eventually as a public API. I want to keep it simple with the priority on aspects like security and performance.
My Plan
Why Drupal? Well, I know Drupal and I can envision a setup where I have 2 sites. www.mygui.com (default) and api.mygui.com (API). All database structure is determined by the work done in the default site. Using the Drupal Services Module (and only a few other necessary core modules) on the API site I plan to allow authenticated updates to the database by way of JSON and the drupal_internal_api.
My Problem
I already have a prototype (not in drupal) that uses tokens. I'm new to services and don't really know all its limits and capabilities yet. This looks promising but still in the pipeline: Drupal Services Auth Token Module. I would like advice or resources regarding a good authentication strategy. For example, which is best? Keep the user base the same with assigned "API Uer" roles or have a completely separate user base specifically for the API site? Keeping in mind that an API username is a long term setup where the username/password or token should not change until the API user is ready with a new app release? Can I have a nice GUI for users to manage their API site credentials on the default site?
Comment: Do you absolutely need your API endpoints on a different subdomain? This would probably be a lot easier if you could settle on something like www.mysite.com/api as your endpoint, then you won't have to worry about setting up multiple sites with access to the same database. You could even do an apache rewrite from api.mysite.com to mysite.com/api if you need to
Comment: Could be. I don't think the multisite is the issue here though. In fact it might be beneficial to keep my gui users and api users separate. I'm interested in hearing from anyone who's traveled down this road before and knows the caveats of one way or the other.
Comment: I can't comment on the separate method I'm afraid (never tried that), but I've set up services on dozens of sites in the way I've described above and it's always worked well
Answer: This can certainly be achieved without any multisite. Meaning you could always house the API on the same site and proxy the path api.mysite.com to mysite.com/api thus allowing it to be invisible to the user. (Make sure your webhost supports mod_proxy or you have some external proxy you can use for this task)
As for the actual authentication, I don't bother with tokens. Use credentials. This way people can get and keep a session (in line with however long you want them to based on session_lifetime in your settings.php) - After an initial call to a log in path, they can then subsequently call the API over and over again by passing the unique session they are assigned.
Go with the single site approach and use web proxy magic to make it look like a different domain. Easy enough.


How to make friends ajax with dynamically created links?

Question: I created leaflet map, when you hover the marker in popup window is a reference to the content.

I wrote module that loads ajax content in the custom region. For dynamic links added class use-ajax, but Drupal does not process them as I needed.
I check and found that static links with class use-ajax have additional class ajax-processing.
My dynamic link looks like:
засорение реки

Static link looks like:
node

As I understand Ajax Drupal does not work with dynamic links.
I found issue in what asks in what need to change the href attribute of a link and make the ajax call to the new url.  Change 'href' attribute in AJAX enabled links
Wrote JS code but it doesn't work for me.
(function ($) {
  Drupal.behaviors.test_module = {
    attach: function (context, settings) {
        $("#jslink").click(function(){
            var href = $("#jslink").attr("href");
            Drupal.ajax['jslink'].options.url = href;

        });
    }
  };
})(jQuery);

Is it possible to somehow make Drupal to work with dynamic links?
What am I doing wrong?
Comment: What is the actual question here?
Comment: @Kevin Question is how to do so ajax started working with dynamically created links?
Answer: I found solution, for loading balloons I use module IP Geolocation Views & Maps it has js file ip_geoloc_leaflet_goto_content_on_click.js
where I add line Drupal.attachBehaviors();
Now it works as designed.
jQuery(document).bind('leaflet.feature', function(event, marker, feature) {
  // marker is the feature just added to the map, it could be a polygon too.
  // feature.feature_id is the node ID, as set by ip_geoloc_plugin_style_leaflet.inc
  // Need to set this up for code below.
  // The same code is used for cross-highlighting. See ip_geoloc_leaflet_sync_content.js
  if (feature.feature_id) {
    marker.feature_id = feature.feature_id;
  }
});

jQuery(document).bind('leaflet.map', function(event, map, lMap) {

  if (map.settings.gotoContentOnClick) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('click', function(e) {
        var id = e.target ? e.target.feature_id : null;
        if (!id && e.layer) id = e.layer.feature_id;
        if (id) {
            //document.location.href = Drupal.settings.basePath + 'node/' + id;
            document.location.href = Drupal.settings.basePath + 'load_node/' + id;
        }
      });
    }
  }
  if (map.settings.openBalloonsOnHover) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('mouseover', function(e) {
        this.openPopup();
         Drupal.attachBehaviors(); <<<<--------ADDED LINE
      });
    }
  }

});


Solving coupled system of ODEs with python

Question: I have to numerically solve a coupled system of ODEs of the following form:
$$\begin{align}
\begin{cases}
\dot{c}(t) = R(t)f(t)\\
\dot{R}(t) = R(t)G(t),
\end{cases}
\end{align}$$
where $c(t), f(t) \in \mathbb{R}^3, R(t), G(t) \in \mathbb{R}^{3 \times 3}$.
I usually solve ODEs with solve_ivp from scipy.integrate and matrix valued ODEs with the wrapper from the odeintw package. Is there a wrapper for coupled systems too?
Answer: Are you thinking about some general wrapper or of how to construct your own wrapper like
def odesystem(t,u):
    c, R = u[:3], u[3:12].reshape([3,3])
    dc = R.dot(f(t))
    dR = G(t).dot(R)
    return np.concatenate([dc, dR.flatten()])

You could also use odeintw with a $4\times 3$ array as state object, where then c is the first row and R the second to fourth row, c,R=u[0],u[1:4].