Am I performing feature selection correctly?

Question: I'd like to design a feature extraction, selection, and classification scheme to use on novel data sets. For each row in a table I calculate 10 features. I then select which features are relevant (using a training set), and finally predict a label for each row using a Naive Bayes classifier (using a testing set). Ideally, this would be automated such that a user can just load a table and click "go".
Here's my issue. Even with feature selection, classification using a single, known relevant feature can outperform classification on all features. That is, running the classifier using a single feature that we know performs well can yield better predictions than running the classifier on all selected relevant features. I know that classifiers are "garbage in, garbage out", so including irrelevant features can lower the performance. But I thought the feature selector would prevent garbage from going into the classifier.
Am I maybe not being strict enough with my feature selection? Should I include less features in the first place? Is there an obvious error I'm making somewhere else?
Here's a breakdown of what I'm doing in case it's useful.

Calculate 10 features for each row of the table.
Split the table into testing and training in a k-fold scheme.
Select the relevant features using the training data and the criterion fisher-ratio > 0.2. For this I used the function IndFeat.m in matlab, which calculates fisher's ratio between the training labels and the feature of interest. A higher ratio means the feature is more informative about the labels. A description of fisher's ratio is here, and a description of the matlab function is here.
Using the selected features, classify on the testing data.
Repeat steps 2-5 for each k folds.
Comment: Can you say more about step 3?  Im not sure what fisher-ratio > 2 means, and how you are applying that criterion.
Comment: Im also a little confused by " For each row in a table I'd like to calculate features, select which features are relevant...".  Does this mean you are selecting different features on a row-by-row basis?
Comment: Thanks for the comments. I edited the "For each row..." sentence to make it clearer. It should read that I want to select features for an entire training set, not row-by-row. I also edited to make the feature selection step clearer.
Comment: I edited back in the `fisher-ratio > 0.2` part, I think it's important for resolving your situation.  I hope I understood correctly, I'm having a few doubts about my answer : /
Answer: Your feature selection criterion

fisher-ratio > 0.2

has an implicit parameter which you have fixed to a constant.  It would be better to view the 0.2 part as a free tuning parameter

fisher-ratio > lambda

As you say, when you use your criterion for a fixed value of 0.2, the resulting model is always dominated by a model with less predictors.  You should be able to recover this information from a better training procedure.
If you think of lambda as a parameter to be tuned in the algorithm, then cross validation will help you determine a good value of lambda.  To do this, create a grid of lambda you are willing to consider, say [.1, .2, .3, ...] and then train your algorithm on all your folds for each such value of lambda.  Then, the average out of fold error for each such lambda you used is an estimate of the out of sample error of your model when features are selected according to the criterion fisher-ratio > lambda.  This will let you (approximately) select the feature selection strength that results in the best model.
In your case, if everything works out consistently, this should validate your suspicion that you should select a small number of powerful features.
Comment: Thanks. I played around with different lambdas, but I never optimized it. That makes total sense. Just so I'm clear, is this a good method? i) Define lambda grid. ii) Partition data into training and testing. iii) For each value of lambda, train the classifier on the training set, and evaluate on the testing set. iv) Define the optimal lambda value by minimizing testing set error. v) Run the classifier with the optimal lambda.
Answer: Your approach hinges on one crucial assumption: fisher ratio is sufficient as a source of information to determine a variable's importance.
If in your dataset this doesn't hold true this method will not work. One way I could think of to strengthen this approach would be to add a few more criteria in addition to fisher-ratio to determine if a variable should be used. (Even the default stepwise regression could possibly give you some information.)
Comment: Thanks very much. How would I go about combining feature selection methods? Can you point me to a reference?
Comment: I do not have a specific reference but I have used varselrf package in R which utilizes a random forest approach to determine variable importance. From my experience however I haven't yet come across any one size fits all solution. I would advise trying out multiple approaches and ring fence if any sort of domain knowledge can be used to aid the selection process.


Letters order - combinatorics

Question: Question: How many words is it able to create from the letters $LYCANTHROPIES$ so $C$ won't stand next to $A$ won't stand next to $N$ and $N$ won't stand next to T.
I thought about $13! - 3\cdot 2 \cdot 12! - 2 \cdot 10!$, when $13!$ is the maximum number of words I can create with no limitations, $2 \cdot 12!$ is the number of words when two letters stand next to each other (there are 3 options for this situation) and finally the situation when all the "forbidden" letters stand next to each other ($2 \cdot 10!$).
But the answer is $13! - 3 \cdot 2 \cdot 12! + 2 \cdot 2 \cdot 11! + 2 \cdot 2 \cdot 11! - 2 \cdot 10!$
Any idea what am I missing?
Comment: Hint: think about strings like ...CAN... and ... ANT...
Comment: Do you mean so C won't stand next to A, A won't stand next to N, and N won't stand next to T?
Comment: Probably yes, I wrote it as it was written in my book.
Answer: At first we see that $LYCANTHROPIES$ consists of $13$ pairwise different characters.

The number of all words of length $13$ which can be built from these characters is
  \begin{align*}
13!
\end{align*}

Forbidden subwords are the following six words
\begin{align*}
&AC,CA,\\
&AN,NA\\
&NT,TN
\end{align*}

Therefore we have to subtract all words which contain (at least) one of these six forbidden words from $13!$
  \begin{align*}
-3\cdot 2\cdot 12!\tag{1}
\end{align*}

Since some words contain more than one forbidden word, these are counted more than once in (1) and we have to  compensate for it.
We consider two different cases. Words which contain two forbidden subwords consisting of four different characters and words which contain two forbidden subwords consisting of three different characters which do overlap. They are
\begin{align*}
&AC,NT&ANT\\
&AC,TN&CAN\\
&CA,NT&NAC\\
&CA,TN&TNA
\end{align*}

So, we have to add the number of these words giving
  \begin{align*}
+2\cdot 2\cdot 11!+2\cdot 2\cdot 11!\tag{2}
\end{align*}

In (2) we count the words which contain three forbidden words too often and we have to compensate for them. Since each character occurs exactly once, the following two forbidden triplets are to consider
\begin{align*}
CANT, TNAC
\end{align*}

So, we  have to subtract
  \begin{align*}
-2*10!
\end{align*}
and we finally obtain
  \begin{align*}
13!-3\cdot 2\cdot 12!+2\cdot 2\cdot 11!+2\cdot 2\cdot 11!-2\cdot 10!
\end{align*}

Note: This answer follows the inclusion-exclusion principle.
Comment: I understand all but one thing - in the second case (2), shoudn't we consider also the options when $NT$ or $TN$ are the first to appear? for example, the string $NTAC$ does not appear in your calculation.
Comment: @Eusebius: Good question. We consider *all* $11!$ words which contain $\{AC,NT\}$. This subsumes words containing $*AC*NT*$ as well as $*NT*AC*$.
Comment: I see it now. For check, the strings containing two forbidden subwords consisting of three different characters such as $ANT$, another optional order contains ${AN,T} is $TAN$ so I don't need to count it separately?
Comment: @Eusebius: No, this is not correct. The reason is that $TA$ is not a forbidden subword. So $TAN$ is not an overlap of two forbidden words.
Answer: Under the restrictions, there are the following forbidden strings:
$3\cdot 2 = 6$ strings of $2$ letters: $CA$, $AC$, $AN$, $NA$, $NT$, $TN$
$2\cdot 2 = 4$ strings of $3$ letters: $CAN$, $NAC$, $ANT$, $TNA$
$2$ strings of $4$ letters: $CANT$, $TNAC$
Using inclusion-exclusion, we can find the unrestricted option count, then subtract off all those where a pair of letters violates the constraint (by treating that pair as a single letter).
at this point we have removed some cases twice, so we try to add back in all the three-letter sets and all the distinct pairs that have been doubly-removed, and finally subtract off again for the four letter sets that have now been wrongly restored.
This gives the answer as expected of $13!-6\cdot 12!+4\cdot 11!+4\cdot 11!-2\cdot 10!$

Letters order - combinatorics


Graphite, collect metrics with similar names from different hosts

Question: I've installed Graphite+Carbon to collect metrics from several hosts. These hosts send Apache Spark and Java metrics. I can't distinguish metrics from different hosts on Graphite side. What should be the right approach? I want to group metrics by host.

"Master" is located on remote host, "workers" are located on three remote hosts and I can't distinguish incoming numbers. Don't understand what is the right way to add host determinant into metric.
Answer: Graphite has the notion of namespaces. e.g. host.app.metric.dimension If you don't send your metrics in this way you have no way of distinguishing them from one another.
Depending on your library there should be a way to prefix the sent metrics with some kind of identifier. I recommend some unique internal identifier and then going on from it.


pip package error after uploading to test.pypi.org

Question: I have created a pip package as below

my setup.py file
import setuptools

with open('README.md') as f:
    long_description = f.read()

setuptools.setup(
    name="calculator_py",
    version="0.0.1",
    scripts=['scripts/calculate.py'],
    author="xxxxxxx",
    author_email="email@example.com",
    description="",
    long_description=long_description,
    long_description_content_type='text/markdown',
    url="",
    license='MIT',
    classifiers=[
    'Development Status :: 5 - Production/Stable',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3.7',
    'Programming Language :: Python :: Implementation :: CPython',
    'Programming Language :: Python :: Implementation :: PyPy',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',

],
entry_points={
    'console_scripts': [
        'calculate=calculator.scripts.calculate:main',
    ],
}

)

I have uploaded this package to https://test.pypi.org
after I have installed package using
pip install -i https://test.pypi.org/simple/ calculator_py

I have checked package using
pip list

when I try to import this package it gives me below error
ModuleNotFoundError: No module named 'calculator_py'
calculate.py file
class calculate:

def __init__(self):
    pass

def add(self, arg1, arg2):
    return arg1 + arg2

def sub(self, arg1, arg2):
    return arg1 - arg2

def mul(self, arg1, arg2):
    return arg1 * arg2

def div(self, arg1, arg2):
    return arg1 / arg2

if __name__ == '__main__':
     calculate()

how can I solve this issue?
Comment: please fix your indentation.
Comment: `calculator_py` is only the name of the distribution, you have no modules or packages named that so there's nothing to import. Run `pip show -f calculator_py` to see what files are installed. `calculate` executable should be available: check it with `which calculate`. BTW `calculate=calculator.scripts.calculate:main` will not work because there's no module `calculator.scripts.calculate` in your package.
Answer: You probably need a packages=['scripts'] inside your setuptools.setup, eg.
setuptools.setup(
    ...
    packages=['scripts'],
    ...
)

Otherwise pip probably tries to guess it from name="calculator_py" and you don't have a package named calculator_py.
Comment: First, there is `scripts=['scripts/calculate.py'],` It'd be strange to add both `scripts` and `packages=['scripts'],`. Second, `pip` doesn't guess module names from package name.


Pass context in 'persist' to 'after save'

Question: I need to pass context from a Operation Hook (persist) to another (after save), I know the existence of the ctx.hookState but its not working.
ZZ.observe('persist', (ctx, next) => {
      ctx.hookState = "pass this";
      next();
    }).catch(err => next(err));
  });

ZZ.observe('after save', (ctx, next) => {
  console.log(ctx.hookState);
  next()
});

I don't get anything in console.log(ctx.hookState). What I'm doing wrong?
Thanks.
Answer: You shouldn't overwrite hookState
You can do like this :
ZZ.observe('persist', (ctx, next) => {
      ctx.hookState.foo = "pass this";
      next();
  });

ZZ.observe('after save', (ctx, next) => {
  console.log(ctx.hookState.foo);
  next()
});

Comment: Yeah, make all sense! Thank you.


Unsolvable partial differential equation

Question: I was given the following differential equation:
$$\left\{\begin{matrix}u_t+2u_x=0, \ \ x>0, \ \ t>0, \\ u(x,0)=\arctan(x), \ \ x>0, \hspace{0.15cm} { }\\ u(0,t)=\dfrac{t}{1+t^2}, \ \ t>0. \hspace{0.8cm} { }\end{matrix}\right.$$
But I think that it has no solution. If I'm right, maybe it is very obvious, but I'll give a proof.
Let's consider the reduced problem: $$\left\{\begin{matrix}u_t+2u_x=0, \ \ x>0, \ \ t>0, \\ u(x,0)=\arctan(x), \ \ x>0. \hspace{0.15cm} { }\end{matrix}\right. $$ It is not difficult to check that the function $\widetilde{u}(x,t)=\arctan(x-2t)$ is a solution to this problem. But it is a Cauchy problem, so $\widetilde{u}$ is unique. However, it is clear that the complete solution to the problem (taking $u(x,0)$ and $u(0,t)$), let's call it $u(x,t)$, is also a solution to the reduced problem. By uniqueness of the Cauchy problem, $u(x,t)=\widetilde{u}(x,t)$. But this is absurd, because $\widetilde{u}(0,t)=\arctan(-2t)\not=u(0,t)=t/(1+t^2)$. Then, the complete problem can't have solution.
Finally, am I right? If not, what can be wrong in my proof?
Thanks for the help.
Edit (30/06/22): if possible, the solution I am looking for must be a classical solution.
Answer: The subtle error in the logic above lies in the fact that the solution you find in the reduced problem does not define a solution in the entirety of $(x,t)\in\mathbb{R}^2$, but only in a subset of it, defined by the equation $x>2t$. The reason why this happens is because not all characteristic curves of the PDE above pass through $\mathcal{C}_1=(x,0), x>0$. When combined with $\mathcal{C}_2=(0,t), t>0$, however, it is now the case that all characteristic curves cut through the initial surface and hence define a solution for any point in $\mathbb{R}^2$.
For a complete solution, note that the characteristic passing through an arbitrary point $(x_0,t_0)$ is given by the equation
$$x-2t=x_0-2t_0$$
When $x_0-2t_0\geq 0$ it is the case that the characteristic hits the initial value surface $\partial \Omega=\mathcal{C}_1\star\mathcal{C}_2$ at the point $(x_0-2t_0,0)$ while for $x_0-2t_0< 0$ the intersection point is $(0,t_0-x_0/2)$. Then, given the constancy of $u$ on the characteristic curves, the solution is simply given by
$$u(x_0,t_0)=\begin{Bmatrix}\arctan( x_0-2t_0),&x_0-2t_0\geq 0\\\frac{t_0-x_0/2}{1+(t_0-x_0/2)^2},&x_0-2t_0<0\end{Bmatrix}$$
Note that the solution is continuous on the break line $x=2t$, as dictated by the continuity of the initial condition on the boundary curve.
Comment: For a function to be a solution of a first order PDE continuity is not enough. The classical definition is that this function ,must be $C^1$. Yours is not along the characteristic $x=2t$ and therefore, strictly speaking, is not a solution.
Comment: "Note that the solution is continuous..." and at the same time not differentiable, and hence not really a *classical* solution.
Comment: Never implied it was differentiable! However in this simple problem if the boundary condition was discontinuous (aka had something like a jump at the origin) the solution obtained would not be continuous as well.
Comment: Thank you, @Artem, I forgot to mention that, if possible, the solution I'm looking for should be classic and I didn't check that in DinosaurEgg's answer.
Comment: The solution yielded by the method of characteristics is certainly weak, however it seems to be unique, since there is no ambiguity in the determination procedure. Maybe someone more well versed in uniqueness proofs can show that there is no classical solution to this problem by showing that in the more general weak formulation of the problem, the above is unique.
Answer: $$u_t+2u_x=0, \quad x>0, \quad t>0, $$
The general solution is :
$$u(x,t)=F(x-2t)$$
with arbitrary function $F$ ( as long as no condition is takent into account ).
Initial condition :
$$u(x,0)=\arctan(x), \quad x>0 \implies F(x)=\arctan(x), \quad x>0 $$
Boundary condition :
$$u(0,t)=\dfrac{t}{1+t^2}, \quad t>0 \quad\implies \quad F(-2t)=\dfrac{t}{1+t^2}, \quad t>0$$
Let $X=-2t$
$$F(X)=\frac{-X/2}{1+(-X/2)^2}\quad X<0$$
Thus the function $F$ is a piecewise function :
$$F(X)=\begin{cases}
=X\qquad X>0\\
=\frac{-X/2}{1+(-X/2)^2}\quad X<0
\end{cases}$$
Now the function $F$ is determined. We put it into the above general solution where $X=x-2t$ :
$$u(x,t)=\begin{cases}
=x-2t\qquad x>2t\\
=\frac{t-\frac{x}{2}}{1+(t-\frac{x}{2})^2}\quad x<2t
\end{cases}$$
This is the particular solution which satisfies both the PDE and the conditions.
Not forgetting that $x>0$ and $t>0$ as specified in the wording of the problem.


Facebook v2.8 access token without login

Question: I try to fetch events from a facebook page and it works well with a temporary access token (code below). I've searched lots of QA's for an answer about how to get a permanent access token or something similar.
There is no user-login on my website, it is just about fetching the JSON - no interaction.
Then I found this
https://graph.facebook.com/oauth/access_token?
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN

to "change" my token into a 60day token but I get an Error:
Error validating client secret.
And I can assure you, that my client secret is correct.
So what I have is:

Page ID, App ID, App Secret

And what I do is basically this: (works with the temp access token)
$page_id = "xxx";
$app_id = "xxx";
$token = "xxx";
$object = json_decode(file_get_contents("https://graph.facebook.com/v2.8/".$page_id."/events?fields=id,name&access_token=".$token));

  <?php print_r($object); ?>

What to do now? Did I miss something?
Thanks a lot
Comment: Go use an extended page access token. (Go read up on it in the docs, if that doesn't mean anything to you.)
Answer: It's not about an 'extended page access token' - it's all about the App Token which you can find here: https://developers.facebook.com/tools/accesstoken/
This token gives you access to your App-Data.


How do I use mod_rewite to use a cached copy of a page if available otherwise run a dynamic script?

Question: I would like to save the generated output of php scripts into a folder structure that apache checks first.
<code>/about/index.php <- dynamic should be rendered only if cache below does not exist
/contact/index.php

/public/about/index.html  <- cached should be rendered first if exists
/public/contact/index.html
</code>
How do I create an RedirectCond/RedirectRule set to do this for me?
Comment: What URL is the client actually accessing?
Comment: @ShaneMadden - The user would access www.example.com/about
Answer: Have the website point to the cache directory. Setup a rule that if a file doesn't exist rewrite to a "dynamic" source directory. The dynamic script would have to be responsible for writing to the cache directory as well (assuming you'd want it cached). Something else would have to be responsible for removing stale entries from the cache (cron job etc).
A better idea would be to put an actual caching reverse proxy in front of Apache. It's possible to use Apache as a reverse proxy, but there are better and more appropriate tools like nginx or varnish.


Proving that surjective endomorphisms of Noetherian modules are isomorphisms and a semi-simple and noetherian module is artinian.

Question: I am revising for my Rings and Modules exam and am stuck on the following two questions:
$1.$ Let $M$ be a noetherian module and $ \  f : M \rightarrow M \  $  a surjective homomorphism. Show that $f : M \rightarrow M $ is an isomorphism.
$2$. Show that if a semi-simple module is noetherian then it is artinian.
Both these questions seem like they should be fairly straightforward to prove but I cannot seem to solve them.
Comment: Your two questions are quite unrelated... You could have asked them separately.
Comment: Dear Alex, Regarding your first question, the relevant adjective is *Hopfian*, which has come up several times on this site, eg. [here](http://math.stackexchange.com/a/110248/221).  Regards,
Comment: @user: Dear user, Noetherian modules are Hopfian objects in the category of all $R$-modules.  This is discussed in the last paragraph of the answer I linked to above.  Regards,
Comment: More generally, one has: https://math.stackexchange.com/questions/239364
Answer: $1.$ Let $M$ be a Noetherian $R$ - module. We prove that if $f : M \longrightarrow M$ is a surjective $R$ - module homomorphism from $M$ to itself, then $f$ is an isomorphism. It is easy to see that it suffices to prove that $f$ is injective. Now the kernel of any $R$ - module homomorphism is always a submodule, so we can consider the following ascending chain of kernels
$$\ker f \subset \ker f^2 \subset \ker f^3 \subset ....$$
that must eventually become constant by the Noetherian condition so we may suppose that there is $ n \in \Bbb{N}$ such that
$$\ker f^n = \ker f^{n+1} = \ker f^{n+2} = \ldots = \ker f^{2n}  = \ldots .$$
Now we claim that
$$\ker f^n \cap \operatorname{Im} f^n = \{0\}.$$
Clearly $0$ is in the left hand side so we just need to show the reverse inclusion. Take $x \in \ker f^n \cap \operatorname{Im} f^n$. Then $f^n(x) = 0$ and there exists $y \in M$ such that $x = f^n(y)$. Putting this expression found for $x$ into $f^n(x) = 0$ we get that
$$f^{2n}(y) = 0$$
and hence that $y \in \ker f^{2n}$. But then as noted above $\ker f^{2n} = \ker f^n$ and hence that $f^n(y) = 0$. But  $x = f^n(y)$ and so $x$ itself is zero proving our claim that $\ker f^n \cap \operatorname{Im} f^n = \{0\}$. Now because $f$ is surjective it follows that $\operatorname{Im} f^n = M$. However $\ker f^n \subset M$ so that $\{0\} = \ker f \cap M = \ker f$ so that $f$ is injective, and hence an isomorphism.
$\hspace{6in} \square$
Edit: Supplementary problems:
(1) Prove that any injective $R$ - module endomorphism $\phi : M \rightarrow M$ for $M$ an Artinian module is surjective (and hence an isomorphism). Hint: Consider the descending chain
$$\operatorname{Coker} \phi \supset \operatorname{Coker} \phi^2 \supset  \operatorname{Coker} \phi^3 \supset \ldots $$
(2) Considering an Artinian ring $R$ as a module over itself, prove that if $R$ is an Artinian integral domain then it must be a field (Hint: Consider a suitable $R$ - module endomorphism  and apply (1) above).
(3)  Let $R$ be an Artinian local ring with maximal ideal $\mathfrak{m}$. Prove that $\mathfrak{m}$ of $R$ is nilpotent. Hint: By the Artinian condition we have the descending chain $$\mathfrak{m} \supset \mathfrak{m}^2 \supset \ldots \supset \mathfrak{m}^k = \mathfrak{m}^{k+1} = \ldots $$
for some $k \in \Bbb{N}$. Suppose that $\mathfrak{m}^k \neq 0$ (Yes we are using the same $k$). By Zorn's Lemma one can choose an ideal $I$ in $R$ minimal with respect to the property that $I\cdot \mathfrak{m}^k \neq 0$. This is saying that there exists an element $x \in I$ such that $x \mathfrak{m}^k \neq 0$ and hence by minimality of $I$, $(x) = I$. Considering $(x)$ as an $R$ - module and noting it is finitely generated, conclude that
$$(x)\mathfrak{m}^k = (x)$$
and apply Nakayama's Lemma to get a contradiction.
Comment: @AlexKite Please do the supplementary problems that I have given you above.
Comment: It's hard to believe that $\operatorname{Coker} \phi \supset \operatorname{Coker} \phi^2 \supset \operatorname{Coker} \phi^3 \supset \ldots $ as all these are factor modules of $M$.
Comment: I did not understand this: "Now because f is surjective it follows that Im f^n=M". Please explain. Im f^n is a subset of Im f but how to show reverse inclusion?
Comment: @user89712 I think the correct descending chain to consider should be $Im(\phi) \supset Im({\phi}^2) \supset Im ({\phi}^3) \supset \dots$
Answer: $1.$ Let me give you a proof of  the following astonishing result due to Vasconcelos:
Theorem:
Let $M$ be a finitely generated $R$-module, Noetherian or not, and let $ \  f : M \rightarrow M \  $  be a surjective homomorphism. Then $f : M \rightarrow M $ is injective (hence is an  isomorphism).
Proof:
We use the standard trick of converting $M$ into an $R[X]$-module by defining $X\cdot m=f(m)$.
For the ideal $I=XR[X]$  we have $M=IM$ since for any $m\in M$ we can write by surjectivity of $f$ :  $m=f(n)=X\cdot n$ and $X\in I$.
Since Nakayama says that $$M=IM\implies m=im$$ there exists $i=P(X)X\in I$
with $m=P(X)X\cdot m=P(f)(f(m))$ for all $m\in M$.
So that finally $f(m)=0\implies m=P(f)(f(m))=P(f)(0)=0 \:$: injectivity of $f$ has been proved.
Comment: Yes, it uses commutativity of $R$. I have the algebraic geometer's habit of implicitly assuming rings to be commutative. This can be  dangerous on a generalist site like here (but  for my defense the question was tagged "commutative algebra" ...)
Comment: I had no objection (after all, the OP had commutative-algebra in the tags) I just wanted to be sure not to confuse it for a noncommutative result :) It is definitely a result worth knowing!
Comment: I hadn't seen Dan's answer when I posted mine. I'll leave my answer  since the write up is a bit different (in particular it emphasises a mnemonic I like for Nakayama).
Comment: Vasconcelos' result uses commutativity for sure? The proof makes me think so, I'm just checking to make sure.
Answer: $2.$ A semisimple module $M$ is a direct sum of simple modules. If it is noetherian, there are finitely many summands in that decomposition, and then $M$ has finite length. It is therefore artinian.
Answer: $1.$ Let $\,f:M\to M\,$ be an epimorphism or $\,R\,$-modules, with $\,M\,$ Noetherian.
i) Show that $\,M\,$ can be made into $\,R[t]\,$-module, defining $\,tm:=f(m)\,,\,\forall m\in M$
ii) Putting $\,I:=\langle t\rangle=tR[t]\,$ , show that $\,MI=M\,$
iii) Apply Nakayama's Lemma to deduce that there exists $\,1+g(t)t\in I\,$ s.t. $\,(1+g(t)t)M=0$
iv) Finally, take $\,y\in \ker f\,$ and show $\,y=0\,$ applying (iii)
Comment: Thank you all for the really helpful responses! I think understand how to do both questions now.
Answer: For the first question, look at the following chain of ideals:
$$\ker f\subset \ker f^2\subset \ker f^3\ldots$$
Comment: I'd call them *submodules*.
Answer: I am late to the party but just for future reference:
Consider the following chain of submodules: $\ker f \subseteq ker f^2 \subseteq ...$
Since you have a Noetherian Module there exists an $n\in\mathbb{N}: \ker f^n = \ker f^{n+1} = ...$
Let $A=\ker f^n$, then $A=\{x\in M: f^k(x)=0,\text{for some } k\in\mathbb{N}\}$. Notice that $f(A)=A$ since $f^i(x)=0$ for some $i\in\mathbb{N} \implies f^{i-1}(f(x))=0$ or just $f(x)=0$ if $i=1$ and in the other direction $f^i(f(x))=0$ for some $i\in\mathbb{N} \implies f^{i+1}(x)=0$
Then we obtain that $f^i(A)=A,\forall i \in\mathbb{N}$ but on the other hand for $i=n$ we have that $f^n(x)=0$ for every $x \in A$. This clearly means $\ker f^n=A=f^n(A)=\{0\} \implies \ker f = 0$.
Comment: I think A will not be equal to $A=\{x\in M: f^k(x)=0,\text{for some } k\in\mathbb{N}\}$.
Comment: @James We have $f^k(x)=0 \iff x\in\ker f^k\subseteq \ker f^n=A$ which means $x\in A$. On the other hand obviously $x\in A\implies f^n(x)=0$. The reason for the inclusion is that after $A$ the sequence becomes stationary.


Responsive html img background

Question: Hello everyone is looking for days of headlights so that the following image is viewable in full as the background of my menu .. but I can not find a solution .. although I have changed the size of the image, despite the made responsive ..
I am attaching evidence of my code and the photo in question ...

<!DOCTYPE html>
<?php
 session_start();
    if(!isset($_SESSION["username"])){
     header('location: ../index.php');
    }else
    {

?>

    <title>G.E.D.</title>
  <link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    Seleziona un operazione

     Milano
     Roma

<?php } ?>

there is always a small clipping ... or the image is too big and then but go down the page
Comment: try background-size:cover
Answer:

    <title>G.E.D.</title>
  <link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    Seleziona un operazione

     Milano
     Roma

Responsive html img background


Error in applying patch in Apache

Question: Recently i have installing apache 2.2.21 from the source for testing purpose.
After doing clean installation of apache i want to patch it with the patches provided here: http://www.apache.org/dist/httpd/patches/
Anyway when i put the patch command as mention in the page it show this result:

File to patch: CVE-2011-3368.patch
  1 out of 1 hunk FAILED -- saving rejects to file CVE-2011-3368.patch.rej

Is there something wrong with my patch?If not,how could i verified that the patch has been implemented or not?
Comment: Hi - welcome to Server Fault. It's not necessary to add "Solved" to your title. When you can add your own answer and then accept that to show that the problem is solved. In the meantime your comment should suffice.
Comment: Have you tried reading the patch and related files?
Comment: yeah,i had read the documentation but still not quite understand on how the patch works.
Comment: I already solved the problems! Actually after checking through the patches it contain the path that it will change.After moving the patches to the designated path, i run the patch command:

patch -s < CVE-2011-3368.patch

and it works!
Answer: This problem was solved by moving the patches to the correct location before running the command
<code>patch -s < CVE-2011-3368.patch
</code>

Error in applying patch in Apache


How do I create a Twig override for server 500 error?

Question: How do I override the template used for a 500 error?
Is there any way to achieve this from a module?
Comment: error 500 is server error. drupal doesn't compe to play at all.
Answer: This cannot be done in Drupal as a 500 error is a server error. Drupal will never be reached.
However, if you can configure the server, you can accomplish this yourself. This may also work from the .htaccess level in Drupal. I suggest trying it at the server level first if you can.
If you are running Apache, you can use custom ErrorDocument directives.
If you are running Nginx, see How To Configure Nginx to Use Custom Error Pages on Ubuntu 14.04.
Comment: This isn't strictly true - Drupal actually throws a 500 itself when it hits an unrecoverable fatal exception (line 269 of errors.inc), and sets the content of the response (the familiar _The website encountered an unexpected error. Please try again later._ message), bypassing the server's default 500 response page. So theoretically you _can_ override it, even with a Twig file. What makes it less than sensible to do so is that invoking the parts of the page build responsible for rendering the template may actually be the cause of the exception, so you'll end up going round in circles
Comment: Actually replace _isn't strictly true_ with _may not be strictly true, depending on whether the OP means a 500 response that the server has thrown specifically, e.g. when there's a Syntax error in .htaccess on Apache, or whether they mean PHP errors that have resulted in a 500 response from Drupal_
Comment: @Clive, I think the OP means the second, because the first normally doesn't happen after successfully setting up the server environment. For D8 to change the 500 response you need an exception subscriber with a priority higher than the default exception subscriber, see https://drupal.stackexchange.com/questions/235602/how-do-handle-exceptions


A chain of measurable sets has union measurable

Question: Consider a measurable space $(\Omega, \mathcal{F})$ and let $I$ be an arbitrary index set.
Is the following true?

If $\left( A_i \right)_{i \in I}$ is a chain in $\mathcal{F}$ – that is, $\forall i \in I$, $A_i \in \mathcal{F}$ and for all $i, j \in I$, we have $A_i \subseteq A_j$ or $A_j \subseteq A_i$  – then $$\displaystyle \bigcup_{i \in I} A_i \in \mathcal{F}.$$
Answer: This isn't true in general (assuming the axiom of choice).
Let $\kappa$ be the least cardinal of a non-measurable set of reals; let $f$ map $\kappa$ 1-1 onto such a non-measurable set.
Then $\{f\!"\!\alpha \mid \alpha\lt\kappa\}$ (where $f\!"\!\alpha$ denotes the range of $f$ on $\alpha)$ is a chain of measurable sets whose union is not measurable.
To see that the axiom of choice needs to be used in some way, at least for the case of Lebesgue measure on the reals, note that it's consistent with ZF that every set of reals is Lebesgue measurable.
Comment: Even if you have a non-measurable set, I guess you need AC again in order to prove that your mon-measurable set is the union of a chain of sets of smaller cardinality?
Comment: You need to know that there's a non-measurable set that's well-orderable for this argument to work. Once you have that, you can get a function $f$ and a chain as I indicated, and it all works.  I haven't thought about what happens if AC fails in such a way that there are non-measurable sets but none of them are well-orderable. (Nor have I thought about measurable spaces in general, just the reals under Lebesgue measure.)
Answer: No. Consider Lebesgue measure on the real line. Let $\kappa$ be the minimum cardinality of a non-measurable set, and let $A$ be a non-measurable set of cardinality $\kappa.$ Then $A$ is the union of a chain of sets of cardinality less than $\kappa,$ which are of course measurable sets.
Comment: My "of course" referred to the fact that the smaller sets were measurable, not to the fact that $A$ is the union of a chain of smaller sets. That's true for any infinite set, as a consequence of the well-ordering theorem. First, $A$ can be well-ordered. Second, if it can be well-ordered, then it can be well-ordered so that every proper initial segment has strictly smaller cardinality than $A.$ The initial segments are (of course!) nested, and finally, since $A$ is infinite, their union is equal to $A.$
Comment: Why "of course?"
Comment: Because $\kappa$ was defined to be the ***minimum*** cardinality of a non-measurable set, it follows that any set of cardinality less than $\kappa$ must be measurable.
Comment: Sure, but how do you know that the set can be formed as the union of sets with smaller cardinality?
Answer: Within the known axioms of set theory you cannot disprove that $2^{\aleph_0} = \aleph_1.$ Recall that $\aleph_1$ is defined as the cardinality of the set of all countable ordinals and $2^{\aleph_0}$ is the cardinality of $[0,1]$.
Let $A$ be any non-measurable subset of $[0,1]$.  Suppose $|[0,1]| = 2^{\aleph_0} = \aleph_1$.  Since $A$ must be uncountable and since no cardinality lies between $\aleph_0$ and $\aleph_1$ (that much is provable within conventional set theory), we have $|A|=\aleph_1$, so
$$
A = \{ a_i : i \text{ is a countable ordinal} \},
$$
for some indexing $i\mapsto a_i$.  Then let
$$
A_i = \{ a_j : j \le i\}.
$$
Then for each $i$, the set $A_i$ is countable, hence measurable, but
$$
\bigcup_i A_i = A
$$
is not measurable.
Since you can't disprove that $2^{\aleph_0} = \aleph_1,$ you can't prove that your proposed union must be measurable.
Comment: This just shows that it can't be proven in ZFC. In fact, it's false in ZFC, as you can see from my answer and @bof's answer.
Comment: The continuum hypothesis is not provable within conventional set theory.


Number of nameserver entries in resolv.conf

Question: How many nameserver entries can I give in /etc/resolv.conf? I have given our ISP's 2 nameserver entries as first and second. But since they have issues sometimes, I would like to add Google public nameserver enry. Does a 3rd & 4th entry make any difference?
This is the resolv.conf on our proxy(squid) server. I understand that Squid uses /etc/resolv.conf for name resolution.
Answer: Actually, you're only allowed three server entries in /etc/resolv.conf.
See: http://linux.die.net/man/5/resolv.conf
Comment: so what if I enter more?
Comment: The man page for resolv.conf points to constant MAXNS in /usr/include/resolv.h.  In RedHat 8 the resolv.h file has no such constant. Anyone have a source for more current information?
Answer: My original solution to overcome the 3 nameserver limit on dual-stack systems was to install dnsmasq, however the work-around increases installation and maintenance costs far too much (I operate many lxc containers), so I needed a simpler solution, which thankfully exists.
I discovered that you can use systemd-resolved which overcomes the 3 nameserver limit. Most modern distros have it all set up by default and ready to go. There's a file /etc/systemd/resolved.conf where you specify nameserver ip's. Edit the conf file and add in your nameservers, then run systemctl restart systemd-resolved. Done!
I noticed someone commented that MAXNS in resolv.h is not there anymore. The source version that I looked at on github also did not have MAXNS, however I remember encountering the 3 nameserver limit not very long ago so it appears to still apply.
Edit: The default /etc/systemd/resolved.conf has commented out entries suggesting that more than 3 DNS servers can be specified, however when looking at /run/systemd/resolve/resolv.conf, I see this comment
"Too many DNS servers configured, the following entries may be ignored."
Followed by the list of additional dns ip's after the first 3.
So it seems we're still stuck with only 3 DNS servers which is rather difficult to understand why. If there's a valid reason for the limit, then at the very least the limit should be spelled out in the default resolv.conf files,and the suggested DNS entries in the file should not go beyond 3, the final case is the resolver should error out when restarted when the DNS entries are invalid.
Answer: You can effectively have as many namservers as you want. Just remember that resolution will fail on the first before going to the second, and so on. It will be some time before name resolution attempts make it to the third and fourth nameservers.
Edit: As explained in the comments on this answer, I was wrong. You're limited to three nameservers by default, and this appears to be a compilation-time option (so not easy to change during runtime).
Comment: It's set by MAXNS in resolv.conf, which is normally 3.
Comment: MAXNS is in `resolv.h`, a file used when software is built, not in resolv.conf.  It's not something you can change on the fly.
Comment: Here it is 2022, twelve years later. I searched resolv.h on a RedHat 8 system (not exactly bleeding edge) and do not see MAXNS.  Is this hardwired limit still in effect?
Comment: I stand corrected. My bad!


Pre-Calculus Vector Problem.

Question: In this question vector i represents a vector due east and vector j represents a vector 1 km due north.

An aircraft flies (at a constant height) with a speed of $800$ km/h. It flies in a fixed direction from $A$ to $B$ for $30$ minutes, and then, in another fixed direction (diagonally), from $B$ to $C$ for $45$ minutes (which forms a triangle ^_^).
(a) Find the distances $AB, BC$.
  The direction from $A$ to $B$ is due east. The direction from $B$ to $C$ is parallel to $24i + 7j$.
(b) Use this information to find the angle theta that the aircraft turns through at $B$. Give your answer in degrees to the nearest tenth of a degree.
(c) Find the Angle $ABC$. Hence find the direct distance from a to $C$.
(d) Another aircraft flies directly from $A$ to $C$.
(i) Show that vector $AC= 976 i = 168 j$.
(ii) Find the angle $CAB$.
(iii) When this aircraft is closest to $B$, how far is it from $A$?

Okay I think I got part A. $AB= 400$ km. $BC= 600$ km.
I am sure that "the direction from $B$ to $C$ is parallel to $24i+7j$" is supposed to help me solve the rest, but I do not know what it means.
Could someone explain that to me and how to solve the rest?
Answer: If the airplane flies from $A$ to $C$ for 30 minutes, then we can claim that the magnitude of the vector would be $400$ as the speed of the airplane is $800 ~ \rm km/h$.  Therefore, the vector would be $400\hat i$ as the the direction is due east.
It is a known fact that for a vector, $|\vec F|\hat F = \vec F $ where $\hat F $ is the unit vector in the direction of $\vec F$.  What is the unit vector in the direction of $\vec{BC}$? Since $\vec {BC}$ is parallel to $24\hat i + 7 \hat j $, it is obvious that the unit vector is $\frac{24\hat i + 7 \hat j}{|24\hat i + 7 \hat j |} = \frac{24}{25}\hat i + \frac{7}{25}\hat j$. Also, the magnitude of $\vec {BC}$ is $800 \times \frac{3}{4} = 600$.
Now, using the relation $|\vec F| \hat F = \vec F$, we get $600 \times \left( \frac{24}{25} \hat i + \frac{7}{25}\hat j\right) = 576 \hat i + 168 \hat j $.
Also, note that $\vec {AC} = \vec{AB} + \vec{BC} = 400 \hat i + 576 \hat i + 168 \hat j = 976 \hat i  + 168 \hat j$.
Comment: Hello! If you are reading my answer, please note that I posted it a little late. The problem has already been solved, but I just wanted to add my two cents here.
Answer: If you choose the origin to be at $A$, point $B$ is $(400,0)$.  You are correct that the length of $BC$ is $600$.  $24i+7j$ is a vector from $(0,0)$ to $(24,7)$.  If you move the starting point to $B$, it is a vector from $(400,0)$ to $(424,7)$.  You need to scale up the vector $(24,7)$ to make the length $600$.  Can you find the length of $(24,7)$?  This should let you find the coordinates of $C$.  Draw a picture.  The turning angle is between the east ($x$) axis and $BC$.  You will need an inverse trig function to find the angle.
Under i, it is not true that $AC=976i=168j$.  The numbers are right, but what you have written says that three vectors are equal and they are not.
Comment: Oh for under i it supposed to Vector AC= 976 vector i+ 168 vector j
Comment: @Chris:  that is correct.  So point $C$ is $(976,168)$  You should be able to find the angles now.  Part iii is the hardest one.  You need to draw a line through $B$ perpendicular to $AC$ and calculate the length.  You have the slope of AC.  The slope of a perpendicular line is the negative reciprocal.
Comment: In addition @Ross Millikan, I am not sure what you mean by scale the vector (24,7), and how to find the length of (24,7). If I chose point B to be the starting point and "scale" the vector by (24,7), does that mean my new vector is (424,7)? If so, what am I supposed to do with that information?
Comment: @Chris: The length of $(24,7)$ is $\sqrt {24^2+7^2}=25$ so you need to multiply by $\frac {600}{25}=24$ to get a length of $600$.  This makes it $(576,168)$.  Adding that to $(400,0)$ gets the $(976,168)$ that are the coordinates of $C$
Comment: Okay, I understand the 576 value, but I still do not understand where the "168" came from.
Comment: @Chris:  It comes from multiplying $7$ by $24$.  It is the northward component of $BC$
Comment: Millikian Oh thanks! Okay then, by using the distance formula, line AC would be 990.3534723, Right? Or is there a way to get a better value? Then after having that value, I would utilize the law of cosines to get one angle, and then I could use law of sines to get the rest correct?
Comment: @Chris:  that is right.  You can also use $\arctan \frac {168}{976}$ for angle $A$

Pre-Calculus Vector Problem.


What's wrong with this argument that the error term cannot be correlated with explanatory variables in a regression?

Question: Obviously, error terms can be correlated with explanatory variables. E.g. see this.
However, I came up with an argument why they cannot be, so I am wondering where the mistake in my argument is.
Assume we have a "true" linear regression model
$$y=\beta_0+\beta_1x_1+\beta_2x_2+\epsilon$$
Where $E(\epsilon|x_1,x_2)=0$
But assume that instead we run the regression
$$y=\beta_0+\beta_1x_1+\eta$$
Where $$\eta = \beta_2x_2 +\epsilon$$
Then $E(\eta|x_1)=E(\beta_2x_2 +\epsilon|x_1)=\beta_2\cdot E(x_2|x_1)$
Now, if we assume that the relation between $x_1$ and $x_2$ is purely linear, then we know that $E(x_2|x_1)=\gamma x_1$, so that $$E(\eta|x_1)=\beta_2\gamma x_1$$
But if this is true, then why can't we simply state the model
$$y=\beta_0+(\beta_1+\beta_2\cdot \gamma)x_1+\zeta$$
so that $E(y|x_1)=\beta_0+(\beta_1+\beta_2\cdot \gamma)x_1$, and $$E(\zeta|x_1)=0$$
In this adjusted model, the error term is uncorrelated with $x_1$, even though we have an omitted variable. So if we do the regression, we will have an unbiased estimator of $\beta_1+\beta_2\cdot \gamma$.
What is wrong with this argument? Is the only reason that this doesn't work simply because we cannot measure $\gamma$ and $\beta_2$?
Comment: Why do you have to assume any (or a linear one specifically) association between $x_1$ and $x_2$?
Comment: Because I think that if there is no correlation between the two, then the ommission of $x_2$ is not problematic in the first place, so then the whole question would be irrelevant.
Answer: You seem to have rediscovered linear projection coefficients.
You are right that $\zeta$ has zero conditional mean given $x_1$, and hence OLS consistently estimates the linear projection coefficient of $y$ onto $x_1$. In terms of your true model, you consistently estimate $\beta_1+\beta_2\gamma$. In terms of your true model, you are however interested in estimating $\beta_1$. So unless $x_2$ is irrelevant for explaining $y$ (i.e., $\beta_2=0$) or $x_1$ and $x_2$ are unrelated ($\gamma=0$), OLS won't estimate the parameter you seek to estimate.


Guitar String Width for Fender CD-60CE Dreadnought

Question: I've a Fender CD-60CE Dreadnought Acoustic Guitar since 2008.
It's not equal to the site, but it's the closest to mine in the site.
I've changed the strings width of it so much I can't remember the original.
Someone knows it ?
Moreover, is there a problem using or an adjust to be done to use other width than the recommended ?
Answer: String gauge is generally a matter of personal preference.  An acoustic guitar like yours can potentially accommodate sets of strings ranging from extra light gauge which will have a high e string gauge of .010 inches - all the way to medium gauge with a .013 inch diameter high e.  Custom lights might have a .011 inch high e string.  Lights might have .012.
New guitars ship from the factory set up for strings somewhere in the middle of the range in hopes of appealing to a larger percentage of players.  But there is no reason to feel like you are stuck with the gauge the manufacturer decided to ship the guitar with.
A guitar will be "set up" optimally for a particular gauge string.  The main set up parameters include height of saddle, width and depth of nut slots, and truss rod adjustment.  The way these things are adjusted will depend on what type action you prefer - and - what gauge strings you choose.
If your guitar is currently set up for .012 gauge strings but you want to switch to a lighter gauge or heavier gauge, then you will simply need to adjust the set up parameters to accommodate your choice of string gauge. Depending on your current set up, your guitar may play acceptably with more than one gauge string.
Where the set up becomes less tolerant of a change in string gauge is if you have a low action with the minimal amount of relief possible with no fret buzz.  Switching to a lighter gauge lower tension string might result in some fret buzz because the slacker string tension will allow for a wider string oscillation envelope as the string vibrates.
The other thing that may need to be adjusted if you make a large move in string gauge is the size of the nut slot.  If the strings do not sit properly in the slots they can be pinched and muted somewhat.  You don't want the nut slots to restrict the vibration of the string any more than you would want the saddle to restrict the vibration.
A dreadnought guitar should be quite capable of being set up for any gauge string set you desire.  If you want more volume and stiffer strings, go heavier than current gauge.  If you want less string tension and thereby easier to fret strings, go with a lighter gauge set.
Besides string gauge there are other variables that affect tone such as the type metal used on the wound strings or coating applied to the strings to preserve the life.
I personally prefer .011 custom light phosphor bronze D'Addario coated strings and I like my action set as low as possible. At least one of my guitars is set up for heavy bottoms light tops which means my 3 fattest strings are out of a heavier gauge set than my 3 skinniest strings.  But every guitarist is different.  That's why they make so many different gauge and type of strings.
After you decide which string gauge will best suit your playing style and preference, take your guitar to a qualified guitar technician or luthier along with the set of strings you want to use - and have them set up your guitar specifically for that gauge string.  You can tell them if you want the action low (easier to play) or high (more volume but harder to play) or somewhere in between.
A proper set up with your choice of strings should make your playing experience very enjoyable.  Good luck and have fun playing your new strings.
Answer: The word you are looking for is "gauge", not "width". Most dreadnought acoustic guitars would be strung with a set of "12's", typically phosphor-bronze light gauge strings, with the highest string being 0.0120 inch or 0.3000 mm in diameter, and the lowest string being 0.0530 inch or 1.3462 mm in diameter.


Qt matching signal with custom slot

Question: I'm trying to use a QAction (QMenu member entry) to open a new window. Precisely: I want actionAbout signal predefined activated to match MainWindow custom slot open AboutWindow - and that's what I've got trouble with.
I know that I can use either the connect Qt function manually inside the source main_window.cpp file or just click it up in the Qt Creator, but my custom slot doesn't show up so I cannot select it. Maybe my slot function declaration is wrong (invalid parameters) and that's why QtCreator doesn't allow me to choose my custom slot in the GUI signals & slots. Could anyone point me what should I do to make QtCreator display my custom slot in the dropdown and how should the connect function call look like?
This is my main_window.h file content:

#include
#include "about_window.h"

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
   void openAboutWindow();

private:
    Ui::MainWindow *ui;
    Ui::AboutWindow *aboutWindow;
};

And this is main_window.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(actionAbout, SIGNAL(activated()), this, SLOT(openAboutWindow(this));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openAboutWindow(QWidget *parent)
{
   aboutWindow = new Ui::AboutWindow(parent); // Be sure to destroy you window somewhere
   aboutWindow->show();
}

The compiler shouts about both constructor and openAbutWindow:

../Application/main_window.cpp: In constructor 'MainWindow::MainWindow(QWidget*)':
../Application/main_window.cpp:9:13: error: 'actionAbout' was not declared in this scope
../Application/main_window.cpp:9:80: error: expected ')' before ';' token
../Application/main_window.cpp: In member function 'void MainWindow::openAboutWindow(QWidget*)':
../Application/main_window.cpp:19:44: error: invalid use of incomplete type 'struct Ui::AboutWindow'
../Application/about_window.h:7:11: error: forward declaration of 'struct Ui::AboutWindow'
../Application/main_window.cpp:20:15: error: invalid use of incomplete type 'struct Ui::AboutWindow'
../Application/about_window.h:7:11: error: forward declaration of 'struct Ui::AboutWindow'
Answer: ../Application/main_window.cpp:9:13: error: 'actionAbout' was not declared in this scope

The error message says it all, where is the QAction defined?  Should it be ui->actionAbout?
connect(actionAbout, SIGNAL(activated()), this, SLOT(openAboutWindow(this));

openAboutWindow() does not take any arguments, and regardless this is an instance not a type.
Comment: Ok, I changed it to `connect(ui->actionAbout, SIGNAL(activated()), this, SLOT(openAboutWindow(QWidget *)));` and it seems to work, thank you. But still openNewWindow method is invalid:

../Application/main_window.cpp:19:44: error: invalid use of incomplete type 'struct Ui::AboutWindow'

What does it mean that struct Ui::AboutWindow is incomplete and why struct if it's a class?
Comment: It means the compiler has not seen a declaration of the type `Ui::AboutWindow`, because "about_window.h" only has a forward declaration.
Comment: Ok, now I know. I should never create Ui::Class but just Class, since Ui is the internal Qt stuff auto-generated from .ui interface files. Thank you.

Qt matching signal with custom slot


how to run `php artisan queue:work` every minute on cpanel?

Question: I made an cronjob in cpanel for once per minute like this:

and make a command for that like this:

as you see I give the artisan path to that.
and in this path :/home/{projcetname}/laravel/app/Console/Kernel.php
I wrote the commands.
but queue table is full.
how can I run queue:work for always ?
thanks
Answer: You can create an entry in your kernel.php that regularly starts a queue worker with the  --stop-when-empty flag.  I wrote this technique up a little while back and have used it effectively on several sites https://talltips.novate.co.uk/laravel/using-queues-on-shared-hosting-with-laravel
Comment: I followed the instructions. it does not work for me !
where to paste` * * * * * /usr/local/bin/php /home/{account_name}/live/artisan schedule:run` ?
Comment: @arefrazaviyou already did this step in yout original question
Answer: How you can run queue:work is the same of how you ran schedule run, Just define a new cron job
* * * * * /usr/local/bin/php /home/sabbabecom/laravel/artisan queue:work --once >/dev/null 2>&1

But when you say always, Does it mean like you want to run it every time it finishes with the current job. If that so then you need to have a supervisor otherwise you can just use the approach i've wrote and it should works fine. At least that what i've understood from your question.
Comment: The flaw with this approach is that it can only perform one job per minute (due to --once).  If you generate more than 60 jobs per hour, the queue will never empty or will have significant delays.
Answer: the problem was about php version
I change the php command to this and it's work:
/usr/local/bin/ea-php81


Scapy - srp1 does not see the response frame on L2, but tcpdump see it just fine

Question: sending the scapy packet as below over eth3
ans, unans = srp1(REQUEST, iface=self.iface)
print ans, unans

the call never returns, I tried srp too. (send/sendp/sniff too). I see response as None or call just hangs.
However, I could see the request and response on tcpdump just fine
listening on eth3, link-type EN10MB (Ethernet), capture size 65535 bytes
16:52:52.565683 00:26:55:27:1c:a2 (oui Unknown) > Broadcast, ethertype Unknown (0x88f8), length 34:
    0x0000:  ffff ffff ffff 0026 5527 1ca2 88f8 0001
    0x0010:  000b 1500 0000 0000 0000 0000 0000 ffff
    0x0020:  eaf4
16:52:52.576476 00:04:25:1c:a0:02 (oui Unknown) > Broadcast, ethertype Unknown (0x88f8), length 76:
    0x0000:  ffff ffff ffff 0004 251c a002 88f8 0001
    0x0010:  000b 9500 0028 0000 0000 0000 0000 0000
    0x0020:  0000 f1f0 f100 0000 0000 0000 0000 0000
    0x0030:  0000 0000 0000 0803 0087 1634 XXXX XXXX
    0x0040:  XXXX 0000 XXXX XXXX XXXX ffff

Comment: Can you include the code for the request you are sending?
Comment: What exactly are you looking for ? REQUEST is a Packet chunk. I tried a C utility to send the bytes and it goes fine on the interface (eth1).
Comment: I am having the same problem with custom L2 protocol. The problem is that send-n-receive does not recognize answer packet (containing payload different than in request).

I am not sure how to associate answer packet layer
Answer: I figured it out and sharing it -
If you define new protocol with custom payloads, Answer layer should implement "answers" method:
e.g:
class MyAnswer(Packet):
    name = "MyAnswer"
    fields_desc = [ByteEnumField("isOk", 0. BooleanFields)]

    def answers(self, other):
         return isinstance(other, MyRequest)


If $2AB = (BA)^2+I_n$ then $1$ is an eigenvalue for $AB$

Question:
Let $n$ be an odd integer, $A,B$ be $n\times n$ real matrices such that $2AB = (BA)^2+I_n$. Prove that $1$ is an eigenvalue of $AB$.

This was asked at an oral exam. I've been pondering this question for a while without success.
$1$ is an eigenvalue of $AB$ iff $AB-I_n$ is singular, that is $\det(AB-I_n)=0$ which is equivalent to  $\det ((BA)^2-I_n)=0$. That's all I have noted... I'd appreciate any hint.
I know that $AB$ and $BA$ have the same characteristic polynomials, hence the same eigenvalues. So it may suffice to prove that $1$ is eigenvalue of $BA$, or $\det(BA-I_n)=0$.
Answer: The condition implies that $BA$ commutes with $AB$ and hence they are simultaneously triangularisable over $\mathbb C$.
Let $AB$ and $BA$ be simultaneously triangularised. Since $AB$ and $BA$ in general have identical spectra, if $\lambda_1,\ldots,\lambda_n$ are the eigenvalues of $BA$ along its diagonal, then the entries along the diagonal of $AB$ are $\lambda_{\sigma(1)},\ldots,\lambda_{\sigma(n)}$ for some permutation $\sigma$. So, the given condition implies that $f(\lambda_i)=\lambda_{\sigma(i)}$ where $f:z\mapsto (z^2+1)/2$.
In other words, $f$ is a bijection among the eigenvalues of $BA$. As $f$ maps real numbers to real numbers, it must also be a bijection among the real eigenvalues of $BA$.
Since $BA$ is a real matrix of odd dimension, real eigenvalues do exist. Now, as $f(x)\ge x$ on $\mathbb R$, $f$ must map the largest real eigenvalue of $BA$ to itself. Solving $f(x)=x$, we see that this eigenvalue is $1$.

Edit. As the OP points out in his comment, actually we only need to consider the largest real eigenvalue. Let $(\lambda,x)$ be an eigenpair of $BA$, where $\lambda$ is the largest real eigenvalue of $BA$. Then $(\frac{\lambda^2+1}2,x)$ is an eigenpair of $AB$. However, since $AB$ and $BA$ have identical spectra and $\frac{\lambda^2+1}2\ge \lambda$, we must have $\frac{\lambda^2+1}2=\lambda$ and hence $\lambda=1$.
Comment: You don't really need the commutation, no?
Comment: Correct me if I'm wrong but all you need is that $f$ maps real eigenvalues to real eigenvalues. Then the largest real eigenvalue must be $1$. It seems that commutativity, simultaneous reduction and bijectivity of $f$ are useless.
Comment: @user125261 $AB$ is a polynomial in $BA$. Hence it commutes with $BA$.
Comment: Can you elaborate on why we know $BA$ commutes with $AB$?
Comment: @GabrielRomon I think you are right.
Answer: There is no need to deal with commuting, etc.
Let $p(x) = {1 \over 2} (x^2 +1)$. Note that $p(x) \ge {1 \over 2}$ for $x $ real.
We have $AB=p(BA)$ and so if
$\mu$ is any eigenvalue of $BA$, then $p(\mu)$ is an eigenvalue of
$AB$.
Note that$AB$ and $BA$ have the same non zero eigenvalues.
If $BA$ has a real
eigenvalue, then $AB$ has a real strictly positive eigenvalue (and
hence so does $BA$). Hence if
$\lambda$ is the $\max$ real eigenvalue of $BA$ we have $\lambda > 0$ (in particular, non zero). We must have that $\lambda$ is also the $\max$ real eigenvalue of $AB$ and hence any real eigenvalue $\mu$ of $AB$ must satisfy
$\mu \le \lambda$.
Since $p(\lambda)$ is
a real eigenvalue of $AB$ and we must have
$p(\lambda) \le \lambda$.
The only real solution to $p(x) \le x$ is $x=1$.


Function to automatically Link predefined words in joomla using php preg_replace

Question: I am using Joomla/k2 component and I would like to automatically link certain keywords in articles. I did some research and came accross this function on http://coderzone.org/library/PHP-Auto-link-text-with-a-given-set-of_1085.htm
<?php
// list of keywords to auto-link
// list plural forms first
$reserved_word_list = array (

'dogs' => 'http://dogs.com',
'dog' => 'http://dogs.com',
'cat' => 'http://cats.com',
'kitten' => 'http://cats.com',
'horse' => 'http://horses.com'
 }

// search text string and auto-link the words
foreach($reserved_word_list as $word => $rep_string){

if(strpos($some_text, $word)){

    // link the word
    $some_text = preg_replace('/(\s+)('.preg_quote($word).')/i','$1$2',$some_text);

    }
}
?>

I pasted this function in my k2 template overide in joomla,just  above $this->item->maintext in item.php  and ended up with a blank page.
I am sure I have done something wrong but i cannot find out what it it!  Please take  a look at my code and see, thanks.
Comment: `);` not `}` to end the array for one.
Comment: Thanks, let me modify that.
Comment: Now the blank page is gone, but no links!
Answer: There are several syntax errors in the code you've pasted, which is probably why it's not doing anything. Try this:
// set the text here; I've put in some sample text.
$some_text =  "
My favourite animals are cats and dogs, but I can't stand horses -- they suck!
";

// list of keywords to auto-link
// list plural forms first
$reserved_word_list = array (
    'dogs' => 'http://dogs.com',
    'dog' => 'http://dogs.com',
    'cat' => 'http://cats.com',
    'kitten' => 'http://cats.com',
    'horse' => 'http://horses.com',
    'horses' => 'http://alltheprettyhorses.com'
);

// search text string and auto-link the words
foreach($reserved_word_list as $word => $rep_string){
    if(strpos($some_text, $word)){
    // link the word
        $some_text = preg_replace('/\b('.preg_quote($word).')\b/i','$1',$some_text);
    }
}
echo $some_text;
// returns
My favourite animals are cats and dogs,
// but I can't stand horses -- they suck!

You'll need to alter the code so that $some_text is set to the page contents.
Comment: Thanks so much let me test that :), but I would like to replace '$some_text' with the actual k2 content: '$this->item->maintext' (this echos the articles main text)
Comment: Just do `$some_text = $this->item->maintext;`, and then at the end of the script, do `$this->item->maintext = $some_text;`
Comment: I am so happy:) it worked out great, but I realised that am going to have a lot of keywords and I am wondering if its possible to load keywords into the script from an external file. ex. keywords.php
Comment: Yes, of course -- you could have a 'dictionary' file in a set format (e.g. keyword[tab]url), and your script could open the file and parse it to create $reserved_word_list. You would only need to alter the dictionary file in the future, not the script itself.
Comment: Hmm interesting, how can i do that? Shall I ask another qusstion?
Comment: Yes, ask another Q (if you haven't already) since it's a separate topic, although first have a look at the docs for opening/reading files: http://php.net/manual/en/function.fread.php. It should be fairly easy to figure out.


Dynamic section-specific submenu

Question: I have a problem that's driving me bananas on Drupal 7.
My need is very simple. I have a site with a bunch of communities with URLs like
http://domain.example/community/communityname
All of these communities have similar structures with pages like "learning", "blog" etc. which are at URLs such as
http://domain.example/community/communityname/learning
I need to create a navigation menu for each of these communities without actually creating a separate menu item for each. How can this be achieved?
I tried doing this with hook_menu and even after 3 hours of relentless googling and fiddling about I just can't seem to get this working.
Any help is much appreciated.
Here's my non-working code:
function mymodule_menu(){
    $items = array();
    $items['community/%mymodule_arg/learning'] = array(
        'title' => 'Learning',
        'page callback' => 'mymodule_view_page',
        'page arguments' => array(1),
        'menu_name' => 'menu-community-menu',
        'type' => MENU_NORMAL_ITEM,
        'access callback'=>TRUE
    );
    return $items;
}

function mymodule_arg_to_arg($arg) {
    return (empty($arg) || $arg == '%') ? "community-a" : $arg;
}

function mymodule_view_page($context) {
    return drupal_goto("community/" . $context . "/learning");
}

If I replace the wildcard from the items array key and replace it with a static string, the code works. Also if I just return a string from mymodule_arg_to_arg() it works. But I just can't seem to make it dynamic.
Answer: You seem to me trying to make it more complicated as necessary. You can simply use the arg function http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7
in your example domain http://domain.example/community/communityname
arg(0) = community;
arg(1) = communityname;
so why not just use arg(0) and arg(1) in your dynamic link url
Comment: Sorry for being a bit dense, but I don't really understand how the answer maps to my problem. I'm aware of the arg function and I use it for parsing the community from the URL, but how will it help be create the menu?

My current placeholder implementation is to hack my way out with a block that evaluates php-code, but I really think that's not a very good solution, even if it works.

Dynamic section-specific submenu


Javascript to create table based on screen width

Question: I have a 940 pixel wide table that currently contains all of the content to my website.
Using Javascript I'd like to test to see of the width of the browser is greater than 1240 and if so display my existing 940 pixel wide table in a  and display an advertisement in an adjacent  that's 300 pixels wide.
If the browser window is less that 1240 then I would just display my existing 940 pixel wide table.
Is there an way to test the width and set a flag then use Javascript to test that flag and include or not include my

  structure?
Comment: Just a hint: `document.documentElement.clientWidth` ...
Answer: You could use javascript to load different CSS.


How to consume RESTful web services in a custom module?

Question: I have an API which I would like to consume to do specific actions on my Drupal 7 website after getting data from the user via a webform form. I plan to write my own custom module to do that but don't know how where I should start from.
Is there any hook that could help me add supplementary action after getting data from my webform ? How am I supposed to proceed to consume my web services ? Any code snippet, advice, will be appreciated.
Answer: Module RESTClient is for this purpose.
It provides 4 APIs:

restclient_get()
restclient_post()
restclient_put()
restclient_delete()
Comment: @SinanErdem It's documentation is suck. I read its code to find these APIs.
Comment: I successfully tested [RestClient] (https://www.drupal.org/project/restclient) with key/value pairs sent for the query as plain text. However, I couldn't consume my RestFul APIs with which is based on XML queries. So my question now is how to use RestClient module to consume Restful API using XML queries ?
Comment: I guess your problem is how to create xml content with PHP, isn't it?
Comment: Yes, it is. And how to use my XML with RestClient.
Comment: Just put `array('body' => $xml_str)` as the second arguments in the mentioned APIs. You are better to create a new question about constructing xml content with PHP in StackOverflow.
Comment: Where can we find some documentation about Restclient module? I cant find any on the module page.
Comment: Thanks Jimmy Ko, do you know the format or parameters those methods get?
Comment: @SinanErdem Their code comment is pretty well. You can read it from http://cgit.drupalcode.org/restclient/tree/restclient.module
Answer: Most would agree here that there is no need to re-invent the wheel. There are already at least 4 wheels here that can be used. The Services module, which also has support for the Webform module (through another contributed module), is the most popular module for this job:

https://www.drupal.org/project/services
https://www.drupal.org/project/webform_service

The other big players would be the RESTful module, restws and as Jimmy Ko mentioned, RESTClient. Although I don't personally have experience with these last 3, all 4 will have their pros/cons. Each should have sufficient documentation and code examples in the wild to get you started.
Comment: Most modules you listed here is to create restful service but not to consume restful APIs.
Answer: Web Service Clients was the only module I could get to work.
You create a connection via UI. Then you can use the API and make your requests from code.
Example API usage:
// 'my_connection' is the machine name of the connection.
$result = clients_connection_call('my_connection', 'method.name', $param1, $param2, $param_etc);


Scheduler Module crontab job does not publish content

Question: When running the Scheduler lightweight cron through crontab, I am getting a message that the lightweight cron has activated and completed in my D8 log, but content is not publishing. When running the lightweight cron through backoffice, items publish correctly. I've checked the cron log to see if the cron is encountering errors, and am seeing no issues. Is there something I am missing in my crontab command that is causing the cron to run but not update publish status on any of the scheduled nodes?
Comment: did you figure this out? I have the same issue.
Answer: If you use Content Access module, see that issue :
https://www.drupal.org/node/2865787
Enzo
Comment: why, and what does it say?


How to auto expire local storage values in angular js?

Question: I am using localStorage in my application.
I want to clear those values after 20 minutes.
Can u please help me out?
Comment: I think here is the best answer:http://stackoverflow.com/questions/13011944/make-localstorage-or-sessionstorage-expire-like-cookies
Comment: there is no api to set expire time. You can only delete it.
Answer: I wrote an extension for angular-localStorage (https://github.com/grevory/angular-local-storage) that is able to delete entries in localStorage automatically when you provide an optional parameter in the set method.
https://gist.github.com/Kyoss79/8cd37a54679804fdeb6d
Comment: Works great thanks! Should be part of the library. Maybe you could contribute?
Comment: @Kyoss Am i right in thinking this adds an expiry time so you can query localstorage and remove the row if it's too old? I can't see anything that expires the row automatically? Neat addition. Would defintiely be worth having in the core lib. :)
Answer: after bootstraping your module call run and setup an $interval that clears local storage after 20 minutes.
app.run(function($interval){
  $interval(() => {
    delete localStorage[key]
    // delete all the required localStorage variables by specifying their keys
  }, 1000*60*20)
})

Comment: @HarryBosh yes. The page would need to be open for this to work. We would have to store the data along with an expiry timestamp to validate it otherwise. This timestamp can be used while fetching the data and the function being used for this can delete the data and return null if it has expired.
Hope this helps :)
Comment: you cant really 'auto expire' if the page needs to be open
Comment: @HarryBosh that's correct you can't auto expire directly. You can use the workaround mentioned in the above comment.
Answer: According to W3Schools:

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

However, a similar question has already been asked and answered elsewhere: When do items in HTML5 local storage expire?  There were some workarounds mentioned there that may be of use to you.
Answer: You can have a custom generic implementation in one cache service or local storage service. Here is what worked for me.
import { Injectable } from '@angular/core';
// using ionic angular storage
import { Storage } from '@ionic/storage-angular';

export class CachedItem<T> {
  public _value: T | undefined;
  public _expiry: any;

  constructor(private name: string) { }

  public setValue(value: T) {
    this._value = value;
    this._expiry = new Date().getTime() + 1800000; // 30 mins
  }
}

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
  }

  async init() {
    const storage = await this.storage.create();
    this._storage = storage;
  }

  private async CheckStorage() {
    if (!this._storage) {
      this._storage = await this.storage.create();
    }
  }

  // Generic cache with expiry
  public async setCache<T>(key: string, items: T) {
    let cachedItem = new CachedItem<T>(key);
    cachedItem.setValue(items);

    await this.CheckStorage();
    return await this._storage?.set(key, cachedItem);
  }

  public async getCache<T>(key: string) {
    await this.CheckStorage();
    const cashedItem: CachedItem<T> = await this._storage?.get(key);
    if (cashedItem !== null) {
      if (new Date().getTime() > cashedItem._expiry) {
        // If the item is expired, delete the item from storage  and return null
        await this._storage?.remove(key);
        return null
      }
      return cashedItem._value as T;
    }

    return null;
  }

}

You can use it like the one below
async loadData() {

    // gets the cache
    var datas: MyDataType[] = await this.localStorageService.getCache('datacachekey');
    if (datas == null) { // not available in the cache, go fetch and put into the cache

      this.myDataService.getDatasFromApi().subscribe(
        (myData) => {
          // sets the cache
          await this.localStorageService.setCache('datacachekey', myData);

          // work on the data
        },
        () => {
          //error;
        }
      );

    }
    else {
       // work on the data as received from cache
    }
  }


Why doesn't the transition work?

Question: So, I'm trying to make a dropdown menu with a nice transition but can't get it to work as it should. I'm sure theres a simple error somewhere or I ommited something important, but it's my first website and I can't find it...
<code>nav ul li:hover>ul li {
display: inline-block;
visibility: visible;
  -webkit-transition: visibility 1s ease;
  -moz-transition: visibility 1s ease;
  -o-transition: visibility 1s ease;
  transition: visibility 1s ease;
}
ul li ul li{
display: none;
visibility: hidden;
}
</code>
I suppose that's all the important code. Any suggestions?
Answer: You can't animate "display" property. It must be always set to a different value than "none".
Check this demo :
http://shailan.com/demos/css3-transitions-dropdown.html
Comment: Damn :( I tried setting it to display: inline-block already, but then the menu becomes visible when I hover over the place where it should appear, and I want it to appear when hovering on it's parent li element. Any ideas on this one?
Comment: Links can decay and may become invalid in future, it would greatly improve your answer if you edited a summary of the linked page into it.

Why doesn't the transition work?


how to harmonize a melody when the bassline changes to a non-chord tone

Question: I am working on trying to harmonize a tenor and bassline part in 4 part writing and I really like the way they sound together so far but the initial chord I had in mind for this bar was Fm/Ab which would work nicely for the 1st notes but then the bassline changes to compliment the vocal part and I am unsure if I should change the harmony half way through the bar or could the same harmony be used throughout the bar? Does the answer perhaps depend on what the other two voices are doing and where they will be placed? If so, could someone give me an idea or two about how to take the next step here? Lets say I use the next chord over the first of the two quick 16th notes, then should the harmony change there for example or could it be left with the same two top notes? Again, just looking for suggestions and ideas on how to take the next step.
thanks!
Comment: Can you clarify? The only non chord tone appears to be the `G3` in the tenor. Chords being `Fm/A` and `Gm`. The bass seems all chord tones.
Comment: yes but supposing my harmony would stay Fm/Ab for the whole bar then G is a non-chord tone. I initially had this melody over Fm/Ab but then I changed the bassline to suit the melody in the tenor part. Let me know if I should change something in the question please. THank you!
Comment: Analyzing the chords that way wouldn't make sense. Just writing a chord label doesn't make it so.
Comment: ok so if you had these two voices and you liked them could you tell me what your next steps would be... like your thought process. would you then decide where to put the other two voices first rhythmically?
Comment: If I was writing 4 part harmony, I would start with a chord in 4 parts and then move by good voice leading principles. If you are working with one given part, like a chorale tune, then I would harmonize the cadence points first, sketch in important parts of the phrase, especially the soprano, then when the framework seems good, fill in the details.
Comment: It looks like you gave only bar 33, it's hard to say anything about a single bar.
Comment: oh ok. The thing is I always get a melody in my head first and then I figured the next best step was a bassline so that got me up to this point. Now I think about harmony and wonder what upper voices could suit this bar. If I just had a Fm/Ab play a whole note in this bar from the beginning would that be weird?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/126321/discussion-between-armani-and-michael-curtis).
Answer: You may think that by not including more info you are making it easier to answer but so much of music is context so what's going on above, before and after is all relevant. If your chord is Fm/Ab on beats 1 and 2 the notes in the next two beats have nothing to do with that chord so a change in harmony is probably warranted based on what's there, perhaps a C7/G? Ultimately use your ear and do what sounds right to you, there's no wrong choice, unless it's for a 4 part writing assignment ;-)


Linked server sql server 2008 r2

Question: We have two SQL servers and we've setup a them as linked servers. The queries works just fine if I connect remote desktop to one of them and execute query. If I try to execute query from third machine (in same domain as first two) which uses linked servers I get the following error :(
Msg 18456, Level 14, State 1, Line 1
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
This is my current setup:
<code>SELECT @@servername as [SQL Instance]
, s.name as [Linked Server]
, s.data_source as [Remote Server]
, CASE l.uses_self_credential
WHEN 1 THEN 'PASS-THRU'
ELSE ISNULL(p.name, 'UNMAPPED LOGINS')
END AS [Local Login]
, CASE l.uses_self_credential
WHEN 1 THEN 'PASS-THRU'
ELSE l.remote_name
END AS [Remote Login]
FROM sys.linked_logins l
JOIN sys.servers s ON s.server_id = l.server_id AND is_data_access_enabled = 1
LEFT OUTER JOIN sys.server_principals p ON p.principal_id = l.local_principal_id
ORDER BY [Linked Server], [Local Login]
</code>
Result:

SQL Instance   Linked Server    Remote Server   Local Login Remote Login
T-CLSQL-01     T-CLSQL-02\R T-BN-CLSQL-02\R PASS-THRU   PASS-THRU

Thanks in advance!
Answer: This looks like a Kerberos problem, most probably the SPN is not correctly registered so you can't send the credentials through to the remote server. Check out evilhomers excellent post here: SQL Server to sql server linked server setup
Comment: Tried it, but no luck. SQL service account and user has enabled delegation, the computers has enabled delegation, SPN is registered.
Comment: Ok, I'm one step further. Now I can do double-hop with my domain account (tried with ssms), but I cannot do it with my domain service account which runs my web application. The option "account is sensitive and cannot be delegated" is NOT selected. What can I check? Thanks!

Linked server sql server 2008 r2


How can I delete the duplicate objects inside Array when I fetch newsApi

Question: Hi I have some problem fetching specific information based on user choice.
I want to fetch newsAPI , inside array there are objects contain countries.
The user selects the country he wants by using dropdown, but there is an iterative country when I using map() it passes on all countries with duplicates, I tried to delete the duplicate, but it didn't work +
I used reduce() but it didn't work either.
Are there any tips and suggestions, maybe there is something I missed.
html:

Script:

Look at this Picture to Clarify the Problem
Answer: You can filter the array to have only distinct values by using this function:
source.filter((item, index) => source.indexOf(item) === index);

So, in your case, where you are mapping to a list of options, it will be something like this:
function printCards(data) {
        const header = document.querySelector('#seachCountry');
        const countries = data.sources.map(cn => cn.country);
        const distinctCountries = countries.filter((country, index) => countries.indexOf(country) === index);

        header.innerHTML += `
                        <select class='ui fluid selection dropdown select' onchange="getCountry(this.value)">
                        <option>select the country</option>
                        ${distinctCountries.map(country => `<option>${country}</option>`)}
                        </select>`;
}

Comment: Thanks for your reply, but unfortunately nothing has changed
Comment: I've edited with a better description. Hope it helps.
Comment: You are really amazing, I've been trying to solve this code for four days,  now it really working Thank you, it makes more sense now.


Linear Transformation and subspace

Question:
Hi everyone! I need help. I know the rules for subspace.

W is nonempty
closure under multiplication and addition.

But I don/'t know how to show it for this question.
Comment: Hints: (1) For addition, choose arbitrary elements in your set and consider their sum, remembering to take into account the linearity of $T$ and the closure of $\mathbb{R}^n$ (2) Similarly, chose an arbitrary element in the set, and consider scaling it, accounting for the same factors as in (1).
Answer: Hint :
1) Show that $0\in \mathbb{R}^n$ belongs to $T^{-1}(W)$ by showing that $T(0)=0\in W$.
2) Let $x, y\in T^{-1}(W)$ so that $T(x), T(y)\in W$ and $a,b\in \mathbb{R}$. Then we want to show that $ax+by\in T^{-1}(W)$, i.e., $T(ax+by)\in W$ (by the definition of $T^{-1}(W)$).
But $T(ax+by)=aT(x)+bT(y)$ (Why ?) and $aT(x)+bT(y)\in W$ (Why ?). So we are done.

Linear Transformation and subspace


Unity Warning: Ignoring depth surface load action as it is memoryless

Question: I am getting 2 warnings in Unity when trying to make screenshot:
Ignoring depth surface load action as it is memoryless
Ignoring depth surface store action as it is memoryless

I have found this thread but it is referencing to Unity Remote which I am not using.
Basic code to reproduce the warning:
public class test : MonoBehaviour
{
   // Start is called before the first frame update
  void Start()
  {
    StartCoroutine(TakeScreenshotUI());
  }

  public IEnumerator TakeScreenshotUI()
  {
    yield return new WaitForEndOfFrame();
    var tex = ScreenCapture.CaptureScreenshotAsTexture();
  }
}

I am getting same warnings in Unity 2019.2 and 2020.1.2.
Can someone help me figure out what the problem is?
UPDATE: warning is appearing only on MacOS with Metal Graphic API
Comment: I'm getting the same error but there is another problem which might be linked with it. In my 2D game touch is not working on device. @David Ndckr have you found any solution?
Comment: Yes and no, @M.ShuaibImran, I have found out that this warning is happening only on Mac and with Graphic API sets for Metal (Project Setting / Player / Other Settings ). Using OpenGLCore as Graphic API is prevent the warning when making scrrenshots in game. Unfortunately  it is crashing whole system instead on a random occasion when I am in editor mode. So this is not solution for me.
Answer: Unity spits out a lot of warnings. I would just ignore them if your code is working.


How to download, transform and upload multiple files in parallel using Google Kubernetes Engine?

Question: I have a large collection of data stored in google storage bucket with the following structure:
gs://project_garden/plant_logs/2019/01/01/humidity/plant001/hour.gz. What I want is to make a Kubernetes Job which downloads all of it, parses it and upload the parsed files to BigQuery in parallel. So far I've managed to do it locally without any parallelism by writing a python code which takes a date interval as input and loops over each of the plants executing gsutil -m cp -r for download, gunzip for extraction and pandas for transforming. I want to do the same thing but in parallel for each plant using Kubernetes. Is it possible to parallelise the process by defining a job that passes down different plant id's for each pod and downloads the files for each of them?
Comment: Is using k8s a mandatory requirement? If not, I'd probably do this differently by using writing a Cloud Dataflow pipeline that reads your files in GCS, parses them and writes directly to BigQuery. This way, Cloud Dataflow will automagically parallelise the work for you. You don't need to be concerned about it.
Answer: A direct upload from Kubernetes to BigQuery is not possible, you can only upload data into BigQuery [1] with the following methods:

From Cloud Storage
From other Google services, such as Google Ad Manager and Google Ads
From a readable data source (such as your local machine)
By inserting individual records using streaming inserts
Using DML statements to perform bulk inserts
Using a BigQuery I/O transform in a Cloud Dataflow pipeline to write data to BigQuery

As mentioned in the previous comment the easiest solution would be to upload the data using DataFlow, you can find a template to upload text from Google Cloud Storage (GCS) to BigQuery in link [2]
If you have to use Google Cloud Engine (GKE) you will need to perform the following steps:

Read the data from GCS with GKE. You can find an example of how to mount a bucket in your containers in the next link [3]
Parse the data with your code as mentioned in your question
Upload data from GCS to BigQuery, more info in link [4]

[1] https://cloud.google.com/bigquery/docs/loading-data
[2] https://cloud.google.com/dataflow/docs/guides/templates/provided-streaming#gcstexttobigquerystream
[3] https://github.com/maciekrb/gcs-fuse-sample
[4] https://cloud.google.com/bigquery/docs/loading-data-cloud-storage


Entity Framework - How to configure the User Roles Many to Many Relationship

Question: Below is the definition of the User entity, there is a navigation property Roles
    public class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Id { get; set; }

        public string Username { get; set; }

        public virtual ICollection<Role> Roles { get; set; }

Below is definition of the Role entity
public class Role
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

What i want is to define the many to many relationship and generate a relationship table UserRole which use UserId as the left key and RoleId as the right key, so how to write the configuration code?
Answer: User:
public class User
{
    public User()
    {
        Roles = new List<Role>();
    }

    public string Id { get; set; }
    public string Username { get; set; }
    public virtual ICollection<UserRole> Roles { get; set; }
}

Role:
public class Role
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

UserRole:
public class UserRole
{
    public string Id { get; set; }
    public string UserId { get; set; }
    public string RoleId{ get; set; }

    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
}

Override the OnModelCreating method in your dbcontext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>()
        .HasMany(c => c.Roles )
        .WithMany()
        .Map(x =>
        {
            x.MapLeftKey("UserId");
            x.MapRightKey("RoleId");
            x.ToTable("UserRoles");
        });
}

Comment: Is the UserRole class needed?


Why is $a+(a+r)+(a+2r)+\cdots+(n-2r)+(n-r)+n=\frac{(n+a)\cdot(n-a+r)}{2r}$?

Question: Let $a, k, p, r$ and $n$ be all members of $\mathbb{Z}$. $p$ is an arbitrary number such that $a+pr=n$
Why does the statement below hold true?
\begin{align}
\sum_{k=0}^{p}(a+kr)
&=a+(a+r)+(a+2r)+\cdots+\left(a+(p-2)r\right)+\left(a+(p-1)r\right)+(a+pr)\\
&=a+(a+r)+(a+2r)+\cdots+(n-2r)+(n-r)+n\\
&=\color{red}{\frac{(n+a)\cdot(n-a+r)}{2r}}
\end{align}
I don't understand the highlighted transformation. I understand that $(n+a)$ should be a factor as it is the sum of two numbers, one from the lower and other from the higher end, e.g. $(n-r)+(a+r)=n+a$.
However, I was unable to keep up with the rest of the operation. Any help would be appreciated. Thanks.
Comment: Uh...where did the $p$ go?
Comment: $n$ is the last term of the finite sum, so $n=a+pr$.
Comment: Ah, ok.  Forgot about that :)
Answer: One may note that
$$\sum_{k=0}^pa=\underbrace{a+a+a+\dots+a}_{p+1}=a(p+1)$$
and likewise,
$$\sum_{k=0}^pkr=r\left(1+2+3+\dots+p\right)\\=r\frac{p(p+1)}2$$
Comment: Thanks for the input! The sum of the two would essentially be the same thing that @Kiran found, only a different representation, no?
Comment: @Glycerius Yup.  But it should come out to be the same with some greasing.
Comment: Understood. Thank you and have a nice day!
Comment: :D You too!  :-)
Answer: Use formulas of arithmetic progrssion. The given sequence is an arithmetic progression; first term $=a$, last term $=n$, common difference $=r$
$\text{number of terms }\\=\dfrac{\text{last term}-\text{first term}}{\text{common difference}}+1\\=\dfrac{n-a}{r}+1$
$\text{Sum }\\=\dfrac{\text{number of terms}}{2}(\text{first term}+\text{last term})\\=\dfrac{\dfrac{n-a}{r}+1}{2}(a+n)\\=\dfrac{n-a+r}{2r}(a+n)$
Comment: Thank you for the layman's explanation, that made things much easier to understand. Have a great day!


Spring properties file as xml

Question: I have properties file config.properties where are stored some application wide properties. And I have imported it using property placeholder:
<context:property-placeholder location="classpath:/config.properties" />

I need to store properties in XML file to pass some XML schema validations.
My question is how to import XML file as properties file in spring,?
Thanks,
Arsen
Answer: PropertyPlaceholderConfigurer already supports xml property files via the DefaultPropertiesPersister
The xml file format for the properties is as below.
   <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
        <entry key="key1">Value 1</entry>
        <entry key="key2">Value 2</entry>
    </properties>

you can use
  <context:property-placeholder
  location="classpath:/com/myProject/spring_prop.xml" />
      <bean id="bean" class="org.MyBean">
         <property name="key1" value="${key1}" />
      </bean>

Answer: In addition to the other answer here, I have also seen xml properties loaded directly as named properties files:
The spring file contains:
<util:properties id="myXmlProps" location="classpath:/com/myProject/spring_prop.xml" />

This can then be accessed via springs expression language as:
"#{myXmlProps['key1']}"

And injected into Strings in classes with:
@Value("#{myXmlProps['key1']}")
private String aValueForKey1;

Spring properties file as xml


React Native Base disabling button doesn't change color

Question: I'm using the React Native Base Button component.
When I pass it the disabled prop, it successfully disables it, but (unlike in the documentation) the color doesn't change at all to indicate the disabled state. Any idea if I need to do something else or am doing something wrong?
Answer: The disabled prop does disable the button, but if you look closely at the documentation it's using a different prop, isDisabled. That prop disables it and affects the color.
<Button isDisabled> Press Me </Button>


Identification possibility of sorting an array by deleting not more than one element

Question: Program gets a number of int arrays with size [2; 2000]. The question is: can that arrays get sorted after deleting not more than one element.
Examples:
2 16 3 3 - after deleting '16' it would be non-increasing array.
4 16 3 15 - there is no way to make it sorted.
Simple way: deliting first incorrect element and checking the fact of sorting. It takes too much time if there is a great number of arrays or that arrays are big-sizes.
Except cases, there incorrect element is first or last, and there array size is less than 4, in what way cheking that possibility can be accelerated
Comment: *Can someone write algorithm*: This is not a code-writing service.
Answer: simply iterate through the array, and if you notice N_x > N_x+1 remove N_x, and mark that you removed 1 number...
in case you found another N_y > N_y+1 where y!=x, then it can't be sorted.
I'll leave the implementation for you, as it is your homework after-all.
Comment: But there is a number of different situations:

5 4 5 5 2 1 or 5 4 5 4 2 1 so what do we need to delete? Checking all the cases needs a lot of time.

I did not ask someone, before i tryed ewerything I can. I thought someone knows simplier algorithm.
Comment: yeah, repeating N_x is an issue, but you can get around it easily, by checking it when removing N_x... check that N_x-1 != N_x
Comment: That was not problem of my example, in (5 4 5 5 2 1) deleting 4 will make it non-incresing, at second example deleting 5 will make it non-incresing, there was no situation where N_x-1 == N_x is true.

In case of array is big-sized, deleting one element and verification whole array takes too much time, and it can be non-increasing and non-deceasing, checking all the variants takes double time
Comment: i c, stand corrected...
Comment: I could made a mistake while asking question. More correct question is: what is good way of checking this possibility if there are a lot of big-sized arrays.


Trouble with maximum registrants for RNG

Question: I've tried to create an event with a maximum of 5 registrants and a maximum of 5 registrations to limit my tests on these modules. I was unable to limit the number of registrants to 5 when users can create multiple people registrations for an event.
Could you explain how to set an event with authenticated users able to register several other users without going out of the maximum registrant? I've already tried to set the Conflicts on Maximum registrants without success.
Answer: The current minimum and maximum registrant fields as found in RNG 1.5 are per registration.

Perhaps you are looking for maximum registrants per event?
Comment: Furthermore, **conflicts** are for field values. Its not what you are looking for. For example if you set conflict on maximum registrant, you would not be able to register for another event with the same maximum registrant **field value**.
Comment: Hi Daniel, thanks a lot for your time, I agree you I'm looking for a solution limiting a maximum number of registrants per event wile allowing multiple registrants per registration and I'm sure to not be alone in this case, will it be possible to extend your module to fit this need in a near future ? I don't know if I could be able to help you doing that but if you need any help from me I could be able to provide, it will be a pleasure.
Comment: It is an accepted feature request. If you want to pitch in, sponsor, or follow progress then do so in Github PR [dpi/rng#130](https://github.com/dpi/rng/issues/130).


how to add image to the html log in Robot Framework?

Question: how to add image to the html log in robot framework? I want to add some picture into the html log in Robot Framework. Could any one have some ideas about it?
Answer: Keyword Log from the BuiltIn library has html argument which can possibly do what you need. See doc: http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Log
Comment: Thanks for your answer, I will try it later
Answer: Keyword is as follows.
Log                    html=true

Assuming the example.png file is in the same folder as the logs.