Erro ao usar else: "'else' without a previous 'if'"

Question: Estou tentando fazer um programa básico, mas parei na metade porque deu o erro:

error:'else' without a previous 'if'

#include<stdio.h>
int main()
{
    int med1, med2, med3;
    printf("\nDigite a medida 1 : ");
    scanf("%f", &med1);
    printf("\nDigite a medida 2 : ");
    scanf("%f", &med2);
    printf("\nDigite a medida 3 : ");
    scanf("%f", &med3);
    if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2));
    {
        printf("\n");
    }
    else;
    {
        printf("Medidas não formam um triangulo");
        return (0);
    }
    return(0);
}

Comment: Você colocou um ; ao final do if o que encerrou o comando. Troque
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2)); por
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2)) Idem após o else.
Comment: E tem outro `;` logo depois do `else`, retire-o também
Answer: Você tem diversos problemas em seu algoritmo, irei apontar somente os problemas de sintaxes o qual se refere a sua pergunta:
Linha 16
error: 'else' without a previous 'if'

Qual o problema que está acusando?

O else não possui um if.. Isto porque você está utilizando o carácter ; na palavra reservada if e else, o qual está causando problema com a sintaxe na hora da compilação do algoritmo.

Vamos analisar o seu algoritmo direto ao erro:
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2)); << REMOVA O (;)
{
    //código
} else; // << REMOVA O (;)
{
    //código
}

Para que o compilador entenda a sintaxe do seu algoritmo, você poderá fazer de duas maneiras este trecho do código, as quais são as seguintes:
I) REMOVER O CARÁCTER ; E O RETURN DENTRO DO ELSE, E ALINHA CORRETAMENTE POR BOAS PRÁTICAS AS CHAVES {}
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2)) {
   //código
} else {
   //código
}

II) REMOVER O CARÁCTER ;, E CRIE UM OPERADOR TERNÁRIO COM A ESTRUTURA DE CONDIÇÕES
(med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2) ? printf("\n") : printf("Medidas não formam um triangulo");

NOTA:

PARA ENTENDER MELHOR COMO FUNCIONA O COMPILADOR DE UMA LINGUAGEM DE PROGRAMAÇÃO, VOCÊ DEVE ESTUDAR OS SEGUINTES CONTEÚDOS:

Autômatos Ling. Formais e Computabilidade
Compiladores
Answer: Você colocou erroneamente um ; logo após a condição do if e também logo após o else.
Declarou suas variáveis como int mas utiliza a flag %f na leitura, que se destina a float.
Tem um return (0); desnecessário dentro do bloco else.
#include <stdio.h>
int main() {
    float med1, med2, med3;
    printf("\nDigite a medida 1 : ");
    scanf("%f", &med1);
    printf("\nDigite a medida 2 : ");
    scanf("%f", &med2);
    printf("\nDigite a medida 3 : ");
    scanf("%f", &med3);
    if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2)) {
        printf("\n"); /* Será que não deveria ter mais coisas aqui? */
    } else {
        printf("Medidas não formam um triangulo");
    }
    return(0);
}

Answer: Tem um erro no if e no else, estes comandos em bloco (if-else, for, while, do-while, switch-case..) não levam o ;.
Veja teu if e else:
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2));
{
    // código
}
else;
{
    // código
}

Ele deveria estar assim:
if((med1+med2>med3) && (med2+med3>med1) && (med1+med3>med2))
{
    // código
}
else
{
    // código
}

Basta remover aqueles ;.
Edit.: Outro ponto importante, todo código fora do bloco será executado por padrão, no caso do teu else não há necessidade de colocar return 0; dentro dele, pois o mesmo será executado depois. Imagine que exista mais código após esta condicional, ele simplesmente não seria executado, pois com o return 0; tu finalizou a execução do programa.
O que é return 0;?
Ele é um indicador para o computador de que o teu programa foi executado com sucesso, ou seja, sem erros, o zero é um valor padrão.


Prevent fork bomb inside docker container

Question: I am currently struggling with limiting number of processes for user which I called sandbox.
I configured processes limit inside /etc/security/limits.conf like this:
sandbox            hard    nproc            100

But if I want to connect to container as sandbox user, ssh returns:
shell request failed on channel 0

So I logged in as root and checked how many processes are running by sandbox user, but it's less than 5.
So what could be preventing me to login through ssh?
Without setting limits ssh login for sandbox user works ok.
Or is there any other way to prevent fork bomb attack?
Answer: any error when connecting to an sshd is logged into /var/log/auth.log (in debian-based OS, or security in redhat-based systems)
If it's not, set LogLevel VERBOSE in /etc/ssh/sshd_config and reload sshd. This will show you why sshd is refusing your connection next.
That said, back to your fork-bomb limiter: docker machines are based on LXC, a container system for Linux. LXC are using CGROUPS to manage resource limits for each container.
in /sys/fs/cgroups, you can setup any limit for a running LXC, and in /Var/lib/lxc/vmname/config, you can setup the limits that will be enforced at boottime.
Limiting the number of processes in a cgroup is done by the task counter subsystem (added in the Linux kernel in 2011 http://lkml.iu.edu//hypermail/linux/kernel/1109.0/01455.html )
With a recent enough linux kernel, limiting the number of allowed processes for a cgroup is therefore done by adding this kind of line into your lxc's config file :
lxc.cgroup.tasks.limit = 1024

for a maximum of 1024 processes
(disclaimer: information not checked on a real machine though, to be confirmed)
Comment: As of today the task counter sub system has still not landed in the official kernel.
Comment: Thanks. For correction latest Docker containers are not based on LXC, LXC is available as driver. Docker containers native driver is based directly on kernel namespaces. But I really like idea with cgroups I did not know that it is possible limit process count. I am definitely going to try it.


How do you represent a single inference rule (rather than a consequence relation) as a mathematical object?

Question: How do you represent a single inference rule as a mathematical object?
The most obvious ways I can think of are to make it a set of consequence relations, or to make it a sequence of symbols. I'll present the former below for concreteness.

The set of all inference rules can be represented as a consequence relation, which is a relation $\vdash \mathop: \mathrm{Set}[\mathrm{Wff}] \times \mathrm{Wff} \to 2$.
$\vdash$ is normally constrained in some way to satisfy some rules. For the definition below I cite Algebraizable Logics from Blok and Pigozzi.
$$ \varphi \; \text{is in}\; \Gamma \;\;\text{implies}\;\; \Gamma \vdash \varphi $$
$$ \Gamma \vdash \varphi \;\;\text{and}\;\; \Gamma \subset \Delta \;\;\text{implies}\;\; \Delta \vdash \varphi $$
$$ \Gamma \vdash \varphi \;\;\text{and it holds for every $\gamma$ in $\Gamma$ that}\; \Delta \vdash \gamma \;\;\text{implies}\;\; \Delta \vdash \varphi $$
$$ \Gamma \vdash \varphi \;\;\text{implies there exists a finite set $\Gamma_0 \subset \Gamma$ such that}\;\; \Gamma_0 \vdash \varphi $$
$$ \Gamma \vdash \varphi \;\;\text{and $\sigma$ is a substitution implies}\;\; \sigma(\Gamma) \vdash \sigma(\varphi) $$
However, $\vdash$ is a representation of all the inference rules taken together as a single unit, (with axioms being a degenerate type of inference rule).
A single inference rule is a slippery concept.
For example, here is modus ponens.
$$ \frac{\varphi \;\;\text{and}\;\; \varphi \to \psi}{\psi} $$
This definition is easy to use in a fixed deductive system, but is hard to study as a mathmetical object.
For example, the rule below is clearly a specialization of modus ponens.
$$ \frac{\varphi \land \chi \;\;\text{and}\;\; (\varphi \land \chi) \to \psi}{\psi} $$
The most obvious way I can think of to turn a single inference rule into an inspectable object is to make it a set of consequence relations.
Let $\mathrm{MP} = \{ (\vdash) : (\vdash) \;\text{is a consequence relation and $(\vdash)$ is consistent with} \; \mathrm{MP} \}$.
Let $\mathrm{WeakMP} = \{ (\vdash) : (\vdash) \;\text{is a consequence relation and $(\vdash)$ is consistent with weak modus ponens} \}$.
$\mathrm{WeakMP}$ is a superset of $\mathrm{MP}$ because it constrains the underlying consequence relation less.
In which case a deductive system specified by inference rules would just be the smallest (by $\subset$) consequence relation in intersection of the inference rules involved, if it exists and is unique.
This would make picking an axiomatization for a consequence relation  roughly analogous to picking a basis in other contexts.
Comment: But the examples in your OP are about sequent calculus, not tableaux systems. (Part of the convenience of sequent calculus in my opinion is that it makes it very easy to talk about individual inference rules.)
Comment: I don't understand the issue here. What's wrong with just thinking of MP as $$\{((\varphi,\psi),\theta)\in\mathsf{Wff}^2\times\mathsf{Wff}: \psi=\varphi\rightarrow\theta\}$$ (where "$=$" is literal equality, not some sort of nuanced equivalence relation), or if you prefer $$\{((\varphi,\varphi\rightarrow\theta),\theta):\varphi,\theta\in\mathsf{Wff}\}$$?
Comment: I cannot think of a single rule which is problematic to display in this way. If you can give an example that might help.
Comment: @NoahSchweber, hmm... I'm not sure, perhaps nothing. That might be general enough to capture all inference rules of interest. When I wrote this, I was also thinking about tableaux calculi which have rules that are kind of similar to inference rules in other calculi.
Comment: @NoahSchweber. The example I had in mind was the or-rule of the tableau calculus for classical logic, which splits $A \lor B$ into a branch for $A$ and a branch for $B$. This thing definitely constrains what the underlying consequence relation of the logic can do, but I don't think it can be represented in the manner above.
Comment: Yes, I made a mistake when posing this question. I was messing around with a simple tableau calculus too shortly before writing this question and somehow came to the conclusion that inference rules were tricky. I think my question is just wrong.
Comment: See also the post [Symbols and notation in propositional logic](https://math.stackexchange.com/questions/3464487/symbols-and-notation-in-propositional-logic)
Comment: No big difference with tableaux; see Raymond Smullyan, [First-Order Logic (1968)](https://www.google.it/books/edition/First_Order_Logic/ZyLyCAAAQBAJ), page 20. The only trick is that tableaux rules work "in reverse" (from conclusion to premises) and thus the rules have only one "input" and one or two "outputs". Thus, instead of the usual form $⟨ \{ \alpha_1, \alpha_2 \},\beta ⟩$ they must be represented as $⟨ \alpha , \{ \alpha_1, \alpha_2 \} ⟩$
Answer: I disagree with the premise of the question that "a single inference rule is a slippery concept." I don't see any issue with treating individual inference rules as straightforward relations on (tuples of) formulas. For example, to me modus ponens seems to be adequately understood as the relation $$\mathfrak{MP}:=\{((\varphi,\varphi\rightarrow\theta),\theta):\varphi,\theta\in\mathsf{Wff}\}\subseteq \mathsf{Wff}^{<\omega}\times\mathsf{Wff}$$ (for simplicity I'm assuming here that we're only interested in finitary inference rules - of course this can be easily altered by modifying "$<\omega$" appropriately).
This is a perfectly well-defined mathematical object. So is the following "weak modus ponens" $$\mathfrak{WMP}:=\{((\varphi\wedge\psi,\varphi\wedge\psi\rightarrow\theta),\theta):\varphi,\psi,\theta\in\mathsf{Wff}\}\subseteq \mathsf{Wff}^{<\omega}\times\mathsf{Wff},$$ which is exactly the same as modus ponens but with the added restriction that the hypothesis must itself be a conjunction. Note that $\mathfrak{WMP}\subseteq\mathfrak{MP}$ in the usual set-theoretic sense, reflecting the fact that $\mathfrak{WMP}$ describes a "sub-rule" of $\mathfrak{MP}$. In general as far as I can tell all the "user-level" observations are straightforwardly reflected by "implementation-level" facts, as one would hope. And at no point do we even have to refer to consequence relations at all.


Show $\sin(\frac{\pi}{3})=\frac{1}{2}\sqrt{3}$

Question: I have to show that
$$\sin\left(\frac{\pi}{3}\right)=\frac{1}{2}\sqrt{3}$$
and
$$\cos\left(\frac{\pi}{3}\right)=\frac{1}{2}$$
Should I use the exponential function?
Comment: No, just draw a triangle with angles $\pi/3$, $\pi/6$, $\pi/2$ and label the edges appropriately as $1$, $2$ and $\sqrt{3}$.
Comment: How does one show that the angles of a triangle with those sides are $\pi/3, \pi/6, \pi/2$ (or *vice versa*)?  That depends on what you're permitted to use in your demonstration.  More context is needed from the OP, perhaps.
Comment: Yes, use exponential function. Let $z:=e^{\frac{i\pi}3}$, $\operatorname{Re}z=\operatorname{cos}\frac\pi 3$ and $z^3=-1$.
Answer: Hint:
It's  a simple geometric result. See the figure and note that the triangle $OPM$ is equilateral.
If $OP =1$ than $\sin (\pi/3)=PH$ and $\cos( \pi/3)=OH$.
Answer: Not to confuse you. But..
$$x=\dfrac{\pi}{3}$$
$$3x=\pi$$
$$\sin 3x=\sin \pi$$
$$3\sin x-4\sin^3x=0$$
$$\sin x=0 \text{ or } \sin x = \dfrac{\sqrt{3}}{2} \text{ or } \sin x = \dfrac{-\sqrt{3}}{2}$$
$$\text{as } 0<\dfrac{\pi}{3}<\dfrac{\pi}{2} \text{, } \sin \dfrac{\pi}{3} = \dfrac{\sqrt{3}}{2}$$
Answer: Without using triangles:
We use the following core formulas to prove this identity:

Pythagorean identity: $cos^2(x) + sin^2(x) = 1$
Angle transformation formula: $sin(x - y) = sin(x)cos(y) - cos(x)sin(y)$
Double-angle formula: $sin(2x) = 2sin(x)cos(x)$

To show: $sin(\frac{\pi}{3}) = \frac{\sqrt3}{2}$
We start by showing the following identity: $sin(\pi - x) = sin(x)$
$sin(\pi - x) \stackrel{2.}{=} sin(\pi)cos(x) - cos(\pi)sin(x)$
$\stackrel{sin(\pi) = 0}{\Rightarrow}$
$\stackrel{cos(\pi) = -1}{\Rightarrow}$
$= sin(x)$
We use $x = \frac{\pi}{3}$ and get: $sin(\frac{2\pi}{3}) = sin(\frac{\pi}{3})$
Now: $sin(2\frac{\pi}{3}) \stackrel{3.}{=} 2sin(\frac{\pi}{3})cos(\frac{\pi}{3})$
$\stackrel{/sin(\frac{\pi}{3})}{\Rightarrow}$
$\stackrel{/2)}{\Rightarrow}$
$\frac{1}{2} = cos(\frac{\pi}{3})$
Finally we use 1. to reach the desired result:
$cos^2(\frac{\pi}{3}) + sin^2(\frac{\pi}{3}) = 1  \Rightarrow sin^2(\frac{\pi}{3}) = 1 - cos^2(\frac{\pi}{3}) \stackrel{\frac{1}{2} = cos(\frac{\pi}{3})}{\Rightarrow} sin^2(\frac{\pi}{3}) = \frac{3}{4} \stackrel{(\sqrt)}{\Rightarrow} sin(\frac{\pi}{3}) = \frac{\sqrt3}{2}$
Answer: Hint. From the picture below and Pythagoras we get
$$h=\frac{\sqrt 3}{2}a\rightarrow \sin\frac\pi 3=\frac ha=\frac{\frac{\sqrt 3}{2}a}{a}=\frac{\sqrt 3}{2}.$$
Answer: consider an equilateral triangle and and construct one hight of this triangle then we have a right triangle and we get $\sin(\pi/3)=\frac{h}{a}$ with $h=\frac{\sqrt{3}}{2}a$ we get  the searched term, where a is the side length of the triangle
Answer: Consider an equilateral triangle of side length $a$. We will compute the area by two different ways to compute the value of $\sin(\pi/3)$.

Method $1$: Since the semi-perimeter is $s = \dfrac{3a}2$, using Heron's formula we have the area of the triangle to be $\dfrac{\sqrt3}4a^2$
Method $2$: The height of the altitude is $a\sin(\pi/3)$ and hence the area is $\dfrac12 \cdot a \cdot a\sin(\pi/3)$.

Comparing the two, we obtain that $\sin(\pi/3) = \sqrt{3}/2$
Answer: Note that:
$sin(3\theta)=3sin(\theta)-4sin^{3}(\theta)$
Let $\theta =\frac{\pi}{3}$ and let $sin(\frac{\pi}{3})=x$
Then:
$0=x(3-4x^{2})$.
Hence either $x=0$ or $x^{2}=\frac{3}{4}$
But since $sin(0)=0$ and the $sine$ function has a period of $2\pi$ then we must conclude that $sin(\frac{\pi}{3})=\frac{\sqrt3}{2}$
Answer: Hint: a the sum of the angles of a triangle is $180^\circ$ (or $\pi$ radians). If all of the angles were equal, what would the angle measure of each angle be? Can you find its altitude?


"best" chord name for a min♭6

Question: As I developed my (guitar) chord vocabulary, the min7 chords were followed by the min6 chords. One was different. In the major key, the iii is what I have called a min♭6. However I have gotten some feedback that it shouldn't be named that. I realize that many chords have multiple names, and that the context is critical, but this is the name that I felt was most sensible in the context of the iii.
So, would you name a chord spelled G - B♭ - D - E♭ anything other than a min♭6?
Answer: You should name it Eb maj7 because that's what it actually is. If the lowest note is G, then it is just the first inversion of Eb maj7.
Answer: You're right that m6 is G-Bb-D-E. It's a bit of a misnomer, but it is a minor triad with a major 6th note added. So I, bIII V VI. The addition of the proper m6 interval clashes with the V, but could be called mb6.It's more commonly found as Ebmaj7, though, and in the order shown would be the 1st inversion - not sounding as good as the root.Sometimes on guitar, it's difficult to keep a simple or tasteful voicing of a particular chord, and quite often the lowest note needs to be the root, unless others are playing too. This is best with Eb at the bottom.

"best" chord name for a min♭6


Given a vector, how to scale to a given length and find components?

Question: Given a vector $\overrightarrow v = <a,b,c>$ of length $l_0$,
How would one scale that vector to a desired length $l$ and find its components again?
Answer: You can take $\vec{v'} = \left\langle \dfrac{la}{l_0},\dfrac{lb}{l_0},\dfrac{lc}{l_0}\right\rangle$, then $|\vec{v'}| = l$, and the components were shown.


Show an operator on $L^2$ is compact

Question: Let $X$ be the complex Lebesgue space $L^2(0,1)$. Let $T:X\to X$ be
$(Tf)(x)=x\int_0^1 \int_0^r f(s)\ ds\ dr-\int_0^x\int_0^r f(s)\ ds\ dr$
Prove that $T$ is compact.
Given a bounded sequence $\{f_n\}$ in $X$, we want to show $\{Tf_n\}$ has a convergent subsequence.
I have shown that $|Tf(x)|\leq 2\lVert f \rVert$. Hence $\lVert Tf_n \rVert \leq 2 \lVert f_n \rVert$. Since $\{f_n\}$ is bounded, then $\{Tf_n\}$ is bounded. Hence there is a weakly convergent subsequence $\{Tf_{n_k}\}$. Then I don't know how to go from weakly convergent to strong convergent.
Answer: Consider $S:L^2[0,1]\to \mathbb{C}$ given by
$$
S(f) := \int_0^1\int_0^rf(s)dsdr = \int_0^1\int_0^1\chi_{[0,r]}f(s)dsdr
$$
Then
$$
|S(f)| \leq \int_0^1\left| \int_0^1 \chi_{[0,r]}f(s)ds\right|dr \leq \int_0^1\|\chi_{[0,r]}\|_2\|f\|_2dr = \|f\|_2\int_0^1rdr = \frac{\|f\|_2}{2}
$$
So $S$ is a bounded linear functional, so the operator $\widetilde{S} : L^2[0,1]\to L^2[0,1]$ given by
$$
\widetilde{S}(f)(x) = S(f)x
$$
is a finite rank bounded operator, hence compact.
Now consider $V:L^2[0,1]\to L^2[0,1]$ given by
$$
V(f)(x) = \int_0^x\int_0^r f(s)dsdr = \int_0^1\int_0^1k(s,r)f(s)dsdr
$$
where
$$
k(x,y) = \begin{cases}
1 &: 0\leq x\leq y \\
0 &: \text{ otherwise}
\end{cases}
$$
Thus, $V$ is an example of a Hilbert-Schmidt operator, and is hence compact. Thus, $T$ is the difference of two compact operators, which is compact.
Comment: Why $\tilde{S}$ is finite rank? I see that it is bounded, but why the rangle of $\tilde{S}$ is finite-dimensional?
Comment: It's range is the one dimensional space spanned by $g(x)=x$.

Show an operator on $L^2$ is compact


Module specific error handling in Angular

Question: I am making use of the ErrorHandler in Angular. It works fine if i am working with only one module. When i am using multiple modules and want to use different error handlers in a specific child module, it does not work. Only the parent error handler is invoked.
RootModule
|--> provides CustomErrorHandler1
|
|--> ChildModule1
|    |--> provides CustomErrorHandler2
|
|--> ChildModule2
     |--> provides CustomErrorHandler1

If an error occures in ChildModule1 or ChildModule2 the error is always handled by the CustomErrorHandler1 instance of RootModule.
I am using lazy-loading to load those modules. Providing different instances of the same service works for all @Injectable()s except for the error handler.
Is it possible to provide those ErrorHandlers so that the errors in each module will be handled by the ErrorHandler provided in their module definition?
I created a sample repository at github. It can be run via ng serve. If you click on "child1" an error is thrown by Childmodule1 and if you click on "child2" an error is thrown by Childmodule2.
Comment: Can you post code of all 3 modules?
Comment: I added a sample repository.
Comment: I think when you define an error handler inside of your `root` module, it will override all other error handlers in it's children, try removing your handler on `app.module.ts` and just extend from `ErrorHandler` from inside of your children
Comment: I made a branch with your suggestions. https://github.com/karsunke/angular-error-handler/tree/nikola_gavric If you remove the root error-handler, there is no error handling at all.
Comment: I'll clone the repo now
Comment: You need to add permissions so I can push to that branch @FranziskusKarsunke
Answer: After some research I found out that

ErrorHandler => Provides a hook for centralized exception handling.

So I registered only 1 ErrorHandler which intercepts all Exceptions then I've delegated the error to the component based ErrorHandlers and handled the data inside of them. Every child component will have it's own Error and based on instanceof we are delegating error to the appropriate ErrorHandler inside of the component.
Note: The downside of this is that any Error that passes error instanceof Error check will be delegated to the Global registered handler aka one inside of app.module.ts
Also I know that this approach might not be the best, but there isn't a possibility of registering multiple ErrorHandlers that are per component but rather one Global one and then handling everything inside of it. Hope that this can help you resolve the issue in a proper way.
Also I've updated the nikola_gavric branch so you can see what I did there
Answer: The answer is, that ErrorHandling just works for RootModules and the Angular Team is not planning to change that:
https://github.com/angular/angular/issues/22197
Comment: They didn't exactly say that. Someone posted a question that wasn't really a big report and the issue was closed after someone else tried to help them. There's no discussion of a feature request nature here.
Answer: Could you share the code from the Modules???
From what you point it doesn't make any sense since Angular when routes are lazyLoaded, creates a hierarchy of injectors in compilation. That should create the effect that your are looking for.
My suggestions are:

Check that your Modules are really been LazyLoaded. The result you are getting is consistent with an eagerLoaded App.
Check that your provide token is correct for example you should be doing:
{ provide: ErrorHandler, useClass: CustomErrorHandlerX }
Comment: I can assure that they are lazy loaded and that they are provided in the same way. All Services have their own instances in their corresponding modules. Only the error handling does not work.
Comment: Did you check that you are using the `{ provide: ErrorHandler, useClass: CustomErrorHandlerX }` for every module where you want a different ErrorHandler?
Comment: I added a sample repository there you can see, that everything is provided correctly and lazyloaded correctly.


How to handle if Drupal site goes down, show a static fallback page instead?

Question: One of my sites went down with the following mysql server down message:

How can I show a basic static page when something fatal like this happens? Are there any modules that do this already? What are some other solutions if a site goes out. I tried cloudflare, but they don't already detect the site going down and still show a fatal message. It would be good if users were shown a static page instead.
Comment: "Are there any modules that do this already? " - Not really possible. List of enabled modules is in database. When database goes down, Drupal can't know you enabled module to handle this situation.
Comment: See here: [How to change my maintenance page?](http://drupal.stackexchange.com/q/76946/16495) - would it help? Is this what you want? I'm not quite sure, but I was under impression that Drupal uses Maintenance Mode theme in situations like this, too.
Comment: I think a possible solution is to code a static page on that page that throws the cannot connect to mysql error. Possibly write a js script that detects that type of message only on that page. The script would only be loaded on that specific page.
Answer: Because Drupal is completely unresponsive when this happens, it's not something you can fix within Drupal.
Setting a static fail page is possible within your web server - most likely Nginx or Apache. If you are using a CDN, you can also configure it to display only cached versions of your pages if your server is unresponsive.
You'll have to consult your server documentation to get your answer.
Answer: In errors.inc line 245 there is this line:
<code>print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));
</code>
And in theme.inc I see this:
<code>/**
 * Process variables for maintenance-page.tpl.php.
 *
 * The variables array generated here is a mirror of
 * template_preprocess_page(). This preprocessor will run its course when
 * theme_maintenance_page() is invoked. An alternate template file of
 * maintenance-page--offline.tpl.php can be used when the database is offline to
 * hide errors and completely replace the content.
 *
 * The $variables array contains the following arguments:
 * - $content
 *
 * @see maintenance-page.tpl.php
 */
</code>
So it seems you can use a template file to customize the error.
Answer: Drupal's default .htaccess has a section, something like:
<code># Set the default handler.
DirectoryIndex index.php index.html index.htm
</code>

The DirectoryIndex directive sets the list of resources to look for,
  when the client requests an index of the directory by specifying a /
  at the end of the directory name. Local-url is the (%-encoded) URL of
  a document on the server relative to the requested directory; it is
  usually the name of a file in the directory. Several URLs may be
  given, in which case the server will return the first one that it
  finds. If none of the resources exist and the Indexes option is set,
  the server will generate its own listing of the directory.

so, by default it looks first for index.php - which it finds, but Drupal has errors and gives you that screen. One option is to change this behaviour like this:
<code># Set the default handler.
DirectoryIndex index.html index.php index.htm
</code>
By switching the first two entries around, you can accomplish a manual override by including an index.html file in the root directory. When the site
is up and running, simply remove the index.html (or rename it) and it will move on to index.php (drupal). If there's an error and the entire site is down, add your
index.html and it will bypass Drupal entirely.  Of course, you will have to actually write an index.html and store it somewhere.


"CSRF validation failed" when try to send POST request in custom module

Question: This is my full codes. I want to create a node with service post method. But I cant post. "CSRF validation failed".
I followed this tutorial: https://www.youtube.com/watch?v=Wz2uaRF9RGc
Anyone suggest something.
<?php
/**
* Block Info
*/
function mymodule_block_info(){
$blocks['mymodule_testing'] = array('info' => t('Mips Testing Block'));
return $blocks;
}

function mymodule_block_view($delta = ''){
$blocks['content'] = '
MIPS Testing Block
';

/* POST Request */
$post_data_results = mymodule_create_requested_data();

return $blocks;
}

/* Create data with POST Method */
function mymodule_create_requested_data(){
$path = $_SERVER['HTTP_REFERER'] . 'serve/node';

$node_type = 'apply';
$node_title = 'This is title ' . date('c');
$node_body = 'Node Body';
$node_format = 'filtered_html';

$node_data = '{
    "type": "'. $node_type .'",
    "title": "'. $node_title .'",
    "body": {
        "und": {
            "0": {
                "value": "'. $node_body .'",
                "format": "'. $node_format .'"
            }
        }
    }
}';

$node_options = array(
    'headers' => array(
        'Content-Type' => 'application/json',
        'Cookie' => mymodule_application_authentication('test', '123'),
        ),
    'method' => 'POST',
    'data' => $node_data
);

return drupal_http_request($path, $node_options);
}

function mymodule_application_authentication($username, $password){

if(isset($_COOKIE['mymodule_authentication_name']) && isset($_COOKIE['mymodule_authentication_id'])){
    return '' . $_COOKIE['mymodule_authentication_name'] . '=' . $_COOKIE['mymodule_authentication_id'];
} else {
    $login_url = $_SERVER['HTTP_REFERER'] . 'serve/user/login';

    $user_data = '{
        "username" : "'. $username .'",
        "password" : "'. $password .'"
    }';

    $user_options = array(
        'headers' => array('Content-Type' => 'application/json'),
        'method' => 'POST',
        'data' => $user_data
    );

    $result = drupal_http_request($login_url, $user_options);
    if($result->code == '200'){
        $user_data = json_decode($result->data);

        setcookie('mymodule_authentication_name', $user_data->session_name);
        setcookie('mymodule_authentication_id', $user_data->sessid);

        return '' . $user_data->session_name . "=" . $user_data->sessid .'';
    } else return FALSE;
}

}

Comment: you might check to see if a POST requires a token (like a form token). that would be checked before it gets to your code and explains the CSRF error, since that's what it's meant to prevent.
Comment: @avibodha have you any docs/tuts for collect token? It will be much help for me.
Comment: https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities
Answer: You need to get a CSRF token before making your POST call.
function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

and use this in your ajax call as a new header:
  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });

https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities
Comment: I m using drupal 7. And have you any suggestion for my custom module using php?
Comment: yes, suggestion is get a csrf token and put the X-CSRF-Token header in your call to drupal_http_request.
Comment: ;) hahaha... nice suggestion. thanx.
Comment: For drupal 7 get the token from: domain.com/services/session/token


Statements about attributes of given function.

Question: Let $HF(0) = \emptyset$. $HF(n+1) = P_\omega(HF(n))$, where $P_\omega(A)$ - set of all finite subsets of $A$, and $HF = \displaystyle\bigcup_{n\subset\omega}HF(n)$.
Are those statements true?

$HF(n-1) \subseteq HF(n) (\forall n>0).$
$(\forall n>0)HF(n)$ - finite.
$HF$ has no countable sets.

Is there any point in using math induction to prove some of the statements?
Second statement seems true because it can be proven with math induction. If $n = 1$, then it's obvious that $HF(1)$ is finite. Now suggest that $HF(n)$ is finite, then $HF(n+1)$ is a set of all finite subsets of $HF(n)$, and because $HF(n)$ is finite, then $HF(n+1)$ is finite.
I have a problem with third statement. Is it somehow a consequention of second statement?
Answer: The third fact is even easier than Asaf makes it.
Suppose $x\in HF$, then there is some $k\in\omega$ such that $x\in HF(k)$. If $k=0$, then $HF(k)=\varnothing$ which contradicts $x\in HF(k)$. Otherwise $k=n+1$ for some $n$, and therefore $HF(k) = \mathcal P_\omega(\cdots)$ for some "$\cdots$". But that means, by definition, that every element of $HF(k)$ is finite, and therefore also $x$.
Comment: Yeah, for finite subsets it's all the same, $\mathcal P$ and $\mathcal P_\omega$. But I agree, it is slightly simpler.
Answer: The first two statements you can prove by induction quite easily. The third statement follows from the combination of the two:
Suppose that $x\in HF$, then there is some $n$ such that $x\in HF(n)$, therefore $x\subseteq H(n-1)$ (note that $n>0$), and therefore $x$ is a finite set.


I am trying to inflate my recyclerview activity with an adapter

Question: no error appears while building or in logcat but when app runs nothing is being displayed.
Here is my activity xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.courses.EngActivity"
>

<androidx.recyclerview.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/recyclerview"
    >

</androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

My layout to be inflated
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="3dp"
app:cardElevation="3dp"
app:cardUseCompatPadding="true">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <ImageView
        android:id="@+id/college_icon"
        android:layout_width="165dp"
        android:layout_height="125dp"
        android:scaleType="centerCrop"
        android:src="@drawable/iitb" />

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="11dp"
        android:layout_marginStart="11dp"
        android:layout_toRightOf="@+id/college_icon"
        android:layout_toEndOf="@+id/college_icon"
        android:text="Indian Institute of Technology Bombay-IITB"
        android:textColor="#000"
        android:textSize="16sp"
        android:textStyle="bold" />

</RelativeLayout>

</androidx.cardview.widget.CardView>

Main class:
public class EngActivity extends AppCompatActivity {

RecyclerView recyclerView;
MyAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_eng);

    recyclerView=findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter= new MyAdapter(this,getMyList());
    recyclerView.setAdapter(adapter);
}

private ArrayList<Model> getMyList(){
    ArrayList<Model> models= new ArrayList<>();
    Model m;
    m = new Model();
    m.setTitle("Indian Institute of Technology Bombay-IITB");
    m.setDescription("Mumbai, Maharashtra");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹211,400 per year");
    m.setImg(R.drawable.iitb);

    m=new Model();
    m.setTitle("Indian Institute of Technology Delhi-IITD");
    m.setDescription("New Delhi, Delhi NCR");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹224,900 per year");
    m.setImg(R.drawable.iitd);

    m=new Model();
    m.setTitle("Birla Institute of Technology and Science-BITS");
    m.setDescription("Pilani, Rajasthan");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹423,475 per year");
    m.setImg(R.drawable.bits);

    m=new Model();
    m.setTitle("Bennett University");
    m.setDescription("Greater Noida, Uttar Pradesh");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹425,000 per year");
    m.setImg(R.drawable.bu);

    return models;
}
}

Adapter class to add items in the recycler view:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {

Context c;
ArrayList<Model> models;

public MyAdapter(Context c, ArrayList<Model> models) {
    this.c = c;
    this.models = models;
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row,null);
    return new MyHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {

    holder.mTitle.setText(models.get(position).getTitle());
    holder.mDes.setText(models.get(position).getDescription());
    holder.mCourse.setText(models.get(position).getCourse());
    holder.mFee.setText(models.get(position).getFees());
    holder.mImageView.setImageResource(models.get(position).getImg());
}

@Override
public int getItemCount() {
    return models.size();
}
}

After i inflate in Engactivity java class it is just displaying empty activity in the build
How can i solve this?
Answer: You forgot to include ArrayList add method.

add(Object o) : This method appends the specified element to the end
of this list.

ArrayList<Model> models= new ArrayList<>();
    Model m;
    m = new Model();
    m.setTitle("Indian Institute of Technology Bombay-IITB");
    m.setDescription("Mumbai, Maharashtra");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹211,400 per year");
    m.setImg(R.drawable.iitb);

     models.add(new Model(m));

   m=new Model();
   m.setTitle("Indian Institute of Technology Delhi-IITD");
   m.setDescription("New Delhi, Delhi NCR");
   m.setCourse("BE/B.Tech - Bachelor of Technology");
   m.setFees("₹224,900 per year");
   m.setImg(R.drawable.iitd);

    models.add(new Model(m));

Answer: In your activity class, inside getMyList() method, Model objects are not added to list, resulting a list with size zero. Add the models to the return list, and notify the adapter.
private ArrayList<Model> getMyList(){
    ArrayList<Model> models= new ArrayList<>();
    Model m;
    m = new Model();
    m.setTitle("Indian Institute of Technology Bombay-IITB");
    m.setDescription("Mumbai, Maharashtra");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹211,400 per year");
    m.setImg(R.drawable.iitb);
    models.add(m);

    m=new Model();
    m.setTitle("Indian Institute of Technology Delhi-IITD");
    m.setDescription("New Delhi, Delhi NCR");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹224,900 per year");
    m.setImg(R.drawable.iitd);
    models.add(m);

    m=new Model();
    m.setTitle("Birla Institute of Technology and Science-BITS");
    m.setDescription("Pilani, Rajasthan");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹423,475 per year");
    m.setImg(R.drawable.bits);

    m=new Model();
    m.setTitle("Bennett University");
    m.setDescription("Greater Noida, Uttar Pradesh");
    m.setCourse("BE/B.Tech - Bachelor of Technology");
    m.setFees("₹425,000 per year");
    m.setImg(R.drawable.bu);
    models.add(m);

    return models;
  }


How to use jQuery to FIND & REPLACE given text with a matching URL instead

Question: Hey there, in short I'm looking to parse a web page and find the text "class abc" and create a url like this: http://www.site.com/code/documentation/classes/classabc/index.html
I'm basically gonna create links from my hosted svn code website to documentation I've generated via doxygen from the same codebase.
Answer: jQuery is great for handling objects and elements in the DOM and might serve as a starting point for what you want to do. This is really more of a basic JavaScript function however. Read up on JavaScript String Replacement over here.
Comment: but I need to traverse the document in the first place and the text lies not neatly in an element. it's the word "Post" here as part of "class post extends...": http://svn.snacksquare.com/filedetails.php?repname=SnackSquare&path=/yii/demos/blog/protected/models/Post.php

I was using one of the nth-child jquery selector: http://docs.jquery.com/Selectors/nthChild#index  to get close, but I need like nth-child plus a next function that grabs the next piece of text after the selected element. I plan to just grab the name of the class and link it to the documentation generated by doxygen.
Answer: I think in this case no need for JQuery, Pure JavaScript language is enough.
Replace Method
Search


Strata in Cox regression

Question: I have a Cox regression as below
w = coxph(Surv(stag, event) ~ a + b, data = df) #
summary(w)

Where Pr(>|z|) of all variables less 0.05
But when I do
w = coxph(Surv(stag, event) ~ a + b + strata(c), data = df) #
summary(w)

Pr(>|z|) of b = 0.09
What does this mean? Should I exclude b from the equation?
Answer: The second model compares survival at different values of b for fixed values of c -- that's what a stratified Cox model does and what the strata() specification asks for.
So either the association between b and survival is weaker when comparing observations with the same value of c (because c explains some of that association), or there is just less information about the association for fixed values of c (because b and c are correlated).
If you were in a situation where it made sense to choose variables based just on $p$-values, and you wanted to include c in the model, you would exclude b. But in most settings it doesn't made sense to choose variables based just on $p$-values.

Strata in Cox regression


How to change color of TabBarItem when its set enabled False

Question: I disabled tabBar item then bar button became grey .
I want to change its color but could not do.its by default grey.
When I setEnabled true then its showing original color white.
[[[[self.tabBarController tabBar]items]objectAtIndex:0]setEnabled:FALSE];

Comment: possible duplicate of [How can I change the text and icon colors for tabBarItems in iOS 7?](http://stackoverflow.com/questions/18734794/how-can-i-change-the-text-and-icon-colors-for-tabbaritems-in-ios-7)
Answer: I have used this in appDelegate it works fine for me.
 [[UIView appearanceWhenContainedIn:[UITabBar class], nil] setTintColor:[UIColor whiteColor]];

 [[UITabBar appearance] setTintColor:[UIColor whiteColor]];

but when i set enable False in viewController class then it will become grey.
Comment: still i have not any solution for that dimmed button of tab Bar.
Answer:   // this will generate a red tab bar
    tabBarController.tabBar.barTintColor = [UIColor redColor];

    // this will give selected icons and text your apps tint color
    tabBarController.tabBar.tintColor = [UIColor redColor];

Update :
self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
self.tabBarController.tabBar.translucent = false;
self.tabBarController.tabBar.tintColor = [UIColor blueColor];

Comment: I would like to disable the currently selected TabBarItem to prevent the user from taping on the same item again .

To do that, I disable the currently selected TabBar Item.
[[[[self.tabBarController tabBar]items]objectAtIndex:currentIndex]setEnabled:FALSE];
My problem is that when I disable the item. It becomes partially dimmed. So the Item is selected and its enabled property is set to FALSE.
Under these conditions, the dimmers (due to the setEnable:FALSE) "wins" and the TabBarItem image dimmed down instead of highlighted.s there a way to prevent the dimmed effect ?
Comment: but when i use
self.tabBarController.tabBar.tintColor = [UIColor whiteColor];
    self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
it look grey after setEnabled False TabBarItem .
Comment: omg u don;t need to disable it , all what u need is when user hit the button again check if user already load this view or set flag userhitMidTap= yes and don;t run your code if yes
Comment: i could not set tag and call delegates, because there are two screens will be open conditionally so i have to disable first tab bar item


Motores de busca ignoram includes no php?

Question: Se tratando de montar uma página web usando outras páginas o iframe é uma das opções mais simples, mas estudando sobre o assunto eu descobri que eles não são recomendados porque os motores de buscas ou leitores de tela ignoram seu conteúdo quando passam pelo frame.
Outra forma de montar uma página usando outras seria usando o include do php, mas aí surge a mesma dúvida: quando um motor de busca ou leitor de tela passa pelo include, ele lê o conteúdo da página/arquivo ou também ignora?
Comment: Isto responde à sua pergunta? [Incluir HTML em HTML sem afetar SEO](https://pt.stackoverflow.com/questions/315553/incluir-html-em-html-sem-afetar-seo)
Answer: O código PHP é processado no servidor. O documento que o browser (cliente) recebe é o resultado desse processamento, portanto os motores de busca não saberão da existência do include.


How do I remove the site name from the head title in drupal 8?

Question: The <title> element in the  of every page currently has the form
page_name | site_name. I would like to make this have the page name only site wide. I've found advice about how to do this in earlier drupal versions (eg here), but not for drupal 8. How is this possible?
Thanks
Answer: Until metatag's module port has not finished you should code a bit for doing that.
If I were you I'll edit YOURTHEME.theme file and add this:
/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function YOURTHEME_preprocess_html(&$variables) {
    unset ($variables['head_title']['name']);
  }


How to find cdf and pdf of exponential random variable?

Question: Let Z ~ Exponential(lambda) and let W = e^Z.
1)Find the CDF of W
2)Use the CDF of W to find the PDF of W
For question 1, I got that P(W <= w) = P(e^Z <= w) = P(Z <= ln(w)) = 1 - e^(-lambda(ln(w))) but Im not too sure if this is in the right direction and would appreciate any guidance.
Comment: You can do math typesetting with mathjax. More information: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: Yes, it is a good start. That is the definition of the CDF of W: $\mathbb{P}(W \leq w)$, where here, $w$ would have to be strictly greater than 0. What you have written so far works given the increasing nature of the exponential function with respect to the inequality.
Note that the exponential term you have in the last expression can be further simplified if you take the $-\lambda$ as a power inside the logarithm, and then cancel the exponential with $\ln$, being inverse functions. This will make developing the PDF (i.e. the derivative of the CDF with respect to $w$) a bit easier.
Do not forget to mention the range of your random variable, as this is also an important part of its distribution.


Why is my nonlinear least squares confidence band so wide?

Question: I have the following dataset:
d = structure(list(x = c(23.1073083778966, 22.9362216327734, 24.4504147133069,
  24.7226685133887, 23.2710364752618, 22.5253827558421, 23.545305003427,
  23.7449683042789, 24.8139647577093, 22.8804536162757, 24.3948588709677,
  25.4304112554113, 25.5500819672131, 25.7243410214168, 26.6003943661972,
  26.0698382492864), y = c(NA, 3.536, 3.867, NA, 4.482, 2.033,
  NA, NA, 2.912, 3.958, 5.445, 6.973, NA, 5.115, 8.382, 4.438)), .Names = c("x",
  "y"), class = "data.frame", row.names = 15:30)

and I am trying to plot the best exponential fit with a confidence band. I'm trying to fit the data to the following relationship:
 mod = nls(y ~ a * exp(b * x), data = d, start = list(a = 1, b = 0.05))

This gives me a nice fit:
preds = data.frame(x = seq(22, 27, by = 0.1))
preds$y = predict(mod, newdata = preds)

ggplot(d, aes(x, y)) +
  geom_point() +
  geom_line(mapping = aes(x, y), data = preds)

However, I'd like to include a confidence band. I found How do I define a confidence band for a custom (nonlinear) function? which gives a nice demonstration of how to do this. The problem is that my confidence band seems unrealistically large:
pa = propagate::predictNLS(mod, newdata = preds)

preds$lcl <- pa$summary[,5]
preds$ucl <- pa$summary[,6]

When I add on
geom_ribbon(aes(x = x, ymin = lcl, ymax = ucl), alpha = 0.3, data = preds, inherit.aes = FALSE)

I get this:

Why is this band so large?
Answer: I do not know what predictNLS does, but this result looks indeed not plausible. I would bootstrap the model residuals to derive confidence intervals.
d <- na.omit(d)
mod = nls(y ~ a * exp(b * x), data = d, start = list(a = 1, b = 0.05))

preds = data.frame(x = seq(22, 27, by = 0.1))
preds$y = predict(mod, newdata = preds)

library(boot)
set.seed(42)
myboot <- boot(d, function(d, ind, mod, preds) {
  d$y <- fitted(mod) + residuals(mod)[ind]
  tryCatch(predict(nls(y ~ a * exp(b * x), data = d, start = list(a = 1, b = 0.05)), newdata = preds),
           error = function(e) preds$x * NA)
}, mod = mod, preds = preds, R = 1e4)

CI <- t(sapply(seq_len(nrow(preds)), function(i) boot.ci(myboot, type = "bca", index = i)$bca[4:5]))
colnames(CI) <- c("lwr", "upr")
preds <- cbind(preds, CI)

library(ggplot2)
ggplot(d, aes(x, y)) +
  geom_ribbon(aes(ymin = lwr, ymax = upr), data = preds, color = NA, fill = "grey80") +
  geom_line(mapping = aes(x, y), data = preds) +
  geom_point()

Note that I calculate the CIs pointwise from the bootstrap results, which neglects dependencies.
Comment: This is very helpful! Thank you. Can you just help me understand why you chose BCa interval?
Comment: @CephBirk It usually provides better coverage: https://stats.stackexchange.com/q/43635/11849


Is this possible to code for iPhone if you use windows?

Question:
Possible Duplicate:
How can I develop for iPhone using a Windows development machine?

I meen possibility to compile the project that could run at for example iPhone4 ?
Comment: I use virtual machine of mac, but it need more memory, does this what you mean
Answer: I was trying to do same thing. I did not find a way.
I don't like how apple is doing it, then I switched to Android.
Answer: I have managed to do this using Adobe CS5 which supports development for iOS. I have managed to create a working app using this. If you need extra info this might help:
http://www.adobe.com/devnet/logged_in/abansod_iphone.html


Gibbs Sampler while fixing one parameter

Question: I came across a problem for Gibbs sampler.
Suppose I want to draw samples from $f(x,y,z)$, Can I use the following scheme to draw samples?
Step 1, draw $f(x^{2t-1},y^t|z^{t-1})$.
Step 2, draw $ f(x^{2t},z^t|y^{t-1})$.
Then, after $T$ steps, we have $2T$ samples for $x$, and $T$ samples for $y$ and $z$.
Is the above procedure appropriate? Could you provide me some references?
Thanks!
Comment: I made a mistake, in step 2, it should be conditional on $y^t$
Comment: The parameter of interest is $x$.
Answer: The method is correct by the following reasoning:
Start with $$(x,y,z)\sim f(x,y,z)$$ and apply Step 1.
$$ (x',y') \sim f(x,y|z)$$
then $$(x',y',z)\sim f(x,y,z)$$
Now apply Step 2
$$ (x'',z') \sim f(x,z|y')$$
then $$(x'',y',z')\sim f(x,y,z)$$
This means $f$ is stationary for this two-step Gibbs algorithm.

Note: the title should be corrected as "fixing one parameter" is
  confusing. You could say Gibbs sampling/sampler with two block
  conditionals.
Comment: @Ryan: can you please change the title?


How to make innodb as default engine

Question: I am trying to make Innodb as my default engine and I changed this in the my.cnf file.
I set default-storage-engine=InnoDB in my.cnf file and restarted mysql but still it's not taking it.
Even after restarting the server, it's still showing default engine as MyISAM.

show engines

+------------+---------+-
| Engine     | Support |
+------------+---------+-
| InnoDB     | YES     |
| MRG_MYISAM | YES     |
| BLACKHOLE  | YES     |
| CSV        | YES     |
| MEMORY     | YES     |
| FEDERATED  | NO      |
| ARCHIVE    | YES     |
| MyISAM     | DEFAULT |
+------------+---------+-
How can I change it to InnoDB ?
Comment: Can you please try default-storage-engine=innobase?
Comment: default-storage-engine=innobase - Nope it did not work..
Comment: @user476554 - check your full command that you used to connect to mysql, Or `show variables like '%engine%';`
Comment: mysql> show variables like "%engine%"
    -> ;
+---------------------------+--------+
| Variable_name             | Value  |
+---------------------------+--------+
| engine_condition_pushdown | ON     |
| storage_engine            | MyISAM |
+---------------------------+--------+
2 rows in set (0.00 sec)
Answer: Make sure you add this line in the proper section of the my.cnf file. It needs to be in the [mysqld]section:
default-storage-engine=InnoDB

Also, comment out any other line in my.cnf that may be setting it to MyISAM.
Comment: This is my my.cnf file

datadir=/var/lib/mysql
user=mysql
table_cache = 2048
innodb_buffer_pool_size = 2G
innodb_file_per_table
innodb_log_buffer_size=8M
innodb_log_file_size=128M
innodb_additional_mem_pool_size=4M
innodb_table_locks = 0
default-storage-engine=InnoDB
join_buffer_size=2M
query_cache_size=512M
sort_buffer_size=8M
read_buffer_size=8M
read_rnd_buffer_size=4M
key_buffer = 512M
key_buffer_size=256M
max_allowed_packet=16M
max_connections=250
long_query_time=5
innodb_autoinc_lock_mode=2
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
Comment: Thank u...I for got to put [mysqld] to start mysqld section in my.cnf file...then I restarted and it worked
Comment: Also modify the [wampmysqld64] section

How to make innodb as default engine


Directx Figuring out where i should put my camera

Question: I'm Still confused about the camera thingy...
I have terrain in X file formate.  It renders perfectly.  The problem is how am i suppose to know how to set up my camera position, look at...  I'm totally lost.
Answer: Well you position your camera where you want it.  Above the terrain would be sensible.  You then set your lookat to the point you want to look at.  Usually this would be at the actual terrain.


shouldOverrideUrlLoading does not work/catch link clicks while page is loading

Question: I am using WebViewClient.shouldOverrideUrlLoading to catch any link clicks in the WebView.  This works about 95% of the time, but sometimes it is simply not called.
I have noticed it in these three circumstances:

When the link points to the page they are already on.  This one isn't a really big deal, and there is a bug reported for it.
While the page is still loading, if the user clicks a link, it rarely catches it.  It will just open the link without ever calling shouldOverrideUrlLoading.
Randomly. While experimenting with this over the last couple months I have noticed that sometimes it just doesn't catch it. It is rare but it does happen.

Now my question is mostly how to fix problem 2, since the others are less of a big deal.  However, if someone has solved either 1 or 3 I would love to hear about it.
Also, I should mention that I have tried different return values in shouldOverrideUrlLoading and I have noticed that always returning true seems to have the best result, but the issues above still happen.
Comment: I've had a similar issue when trying to change the webpage with js on the page that modifies `window.location`. Turns out that modifying the url scheme/protocol makes the webview catch on `shouldOverrideUrlLoading`.
Comment: You say, in a comment on the accepted answer, that the cause of the problem was in your logic. You never mention what the real problem was. I have this problem, and from googling it seems i'm not the only one. Would you care to spare a moment and tell us about how you solved it?
Comment: @mickey, thanks for pointing this out.  Sorry about that! I wrote a response below. (In the accepted answers comments)
Comment: Np! Too bad though that it seems as if my problem isn't the same as yours... :(
Comment: @mickey, what is happening for you? Pretty much as described in this original question or different?
Comment: A bit different. But what you tried to do might have turned out to be a solution to my problem. If you have a spare moment, you're more than welcome to read my question, it remains unanswered at http://stackoverflow.com/questions/9147875/webview-dont-display-javascript-windows-open and at least leave a comforting comment ;)
Answer: If the HTML is your own, you can replace all traditional links with calls to your own Java object, injected into the WebView via addJavascriptInterface(). Then you will no longer be reliant upon shouldOverrideUrlLoading().
Otherwise, perhaps try to prevent the user from interacting with the page until onPageFinished().
I have not run into this problem, but I have not made extensive use of WebView with arbitrary content, either.
Comment: @ThomasW It was a long time ago but I'm pretty sure I found a place where I was returning false.  I believe you must absolutely always return true in shouldOVerrideUrlLoading() to avoid this problem. In that method, if you find you don't need to override the load, just call webview.loadUrl(url) instead of returning false.
Comment: @littleFluffyKitty what are the flaws in the logic you're talking about? You should write them up.
Comment: thanks for the suggestions.  Unfortunately the HTML in this case is not my own and I can't block the user because some pages are "loading" for a while after they are quite usable to the user.  So that would be a pretty frustrating UI experience.  It is pretty much 100% reproducible for me. Load a url into the WebView and while it is loading, press a link, and it just skips over the override call.
Comment: This ended up being a flaw in some logic I had that I didn't catch.  I'll award the answer to you because you had some good suggestions anyhow.  Thanks.
Answer: I've had a similar issue when trying to change the webpage with js on the page that modifies window.location. Turns out that modifying the url scheme/protocol makes the webview catch on shouldOverrideUrlLoading. I know this doesn't help you since you don't own the HTML, but I thought it would help anyone else who stumbles upon this problem.


What are the formulas for topological transformations? How to obtain them?

Question: I'm reading Flegg's From Geometry to Topology, the author says that in Euclidean geometry, translation and rotation are:
$$T:(x,y)\to(x+a,y+b)$$
$$R:(x,y)\to(x \cos \phi - y \sin \phi, x \sin \phi +y \cos \phi)$$
And that reflection can be achieved through arbitrary combinations of reflection and rotation, although he assumes there is a formula for such, he argues that it's easier this way.
Then he argues that in these transformations, some properties are invariant, such as Length, area, the number of sides of a polygon, and so on. And that one of the properties that is not preserved is the orientation.
Then there's a chapter on non-euclidean geometries, and then he gives one example of affine transformation:
$$A:(x,y)\to(ax+by+c,dx+ey+f)$$
And says that some properties such as length, "angle" and shape are not preserved under this transformation but some other properties are. Further, there's also an example on projective geometry where he does the same thing, arguing about what's invariant and what's not.
Then he introduces topological transformations and says that the neighbourhoods are preserved and introduces an example of invariant objects under these transformations:

There are also examples for the transformations I mentioned before, I just decided to omit them in this question. He gives a formula for $T,R,A$, but there are no formulas for the transformation of the triangle in the previous image to an elipse, or a formula that transform any of these objects into another. I've read about it wikipedia, in the article about topology and it's mentioned only that topological transformations are called continuous maps, when opening the article on continuous maps, there's also no mention to a formula for such (or I'm not seeing it). So what's the formula for these transformations and how to obtain them?
The only hint I have at the moment (and I'm not really sure about that, it may be completely wrong!) is that it seems that these tranformations were completely made in set theory, which confuses me a little more.
Comment: No formula you actually want to see, but there are conformal mappings of your six objects to the standard unit disc, look up the Riemann Mapping Theorem. All but one of your shapes are star-shaped around a carefully chosen point, so i can provide a mapping to the unit disc that is only continuous. For those keeping score at home, the final wiggly shape can be taken to a near-disc by the Gage-Hamilton curve shortening, at which time it is star-shaped.
Comment: Actually, thinking again, I'm not at all sure there is a homotopy of the entire shape that goes with curve shortening. So, forget that one. Riemann mapping still works.
Answer: In general, you there need not be a closed formula to describe this kind of map. And even if there is, the formula often is more complex than what you'd want to write down. Furthermore, the map isn't uniquely defined by the shape alone, but instead there will be many possible maps with the required properties.
Let's take this "triangle and ellipse" as an example. Let's assume them to be the sets
\begin{align*}
A&=\{(x,y)^T\;\vert\;x\le1\text{ and }-y\le1\text{ and }2y-x\le1\}\\
B&=\{(x,y)^T\;\vert\;x^2+4y^2\le4\}
\end{align*}
as depicted below.

Then the following function will be one possibility of how to continuously map from $A$ to $B$:
$$f:\begin{pmatrix}x\\y\end{pmatrix}\mapsto
\frac{\max\{x, -y, 2y-x\}}{\sqrt{x^2+y^2}}
\cdot\begin{pmatrix}2x\\y\end{pmatrix}$$
To see that this is really a bijection, here is the inverse:
$$f^{-1}:\begin{pmatrix}x\\y\end{pmatrix}\mapsto
\frac{\sqrt{x^2+4y^2}}{\max\{2x, -4y, 8y-2x\}}
\cdot\begin{pmatrix}x\\2y\end{pmatrix}$$
Both $f$ and $f^{-1}$ are strictly speaking not defined at $x=y=0$. But the singularity there is removable, so you can simply define $f(0,0)^T=f^{-1}(0,0)^T=(0,0)^T$.
The idea behind the formulas is simply the following: consider rays from the origin in every direction. These rays will intersect the triangle at some point, and the unit circle at some different point. Simply apply a linear scaling to all points along the ray with the scale factor chosen such that it will map the point of intersection with the triangle to the point of intersection with the unit circle. Afterwards, the unit circle is stretched by a factor of $2$ in the $x$ direction to obtain the ellipse. This idea of stretching every ray is the reason why Will Jagy in a comment wrote about star-shaped shapes: those are the ones for which this "scale every ray" approach works.
But keep in mind that this is only one of many possible maps, and even for shapes which are not star-shaped, you can still find continuous deformations between them as long as both shapes are of the same topological structure. Writing these deformations down as a formula will usually be more difficult than useful.
Comment: Yes. Thanks. I've imagined that the formula would be something very complicated. I remember that Wolfram Alpha is plotting equations for arbitrary drawings such as [this](http://www.wolframalpha.com/input/?i=batman+curve&a=*C.batman+curve-_*PopularCurve-). I guessed that there is an algorithm for that and that it would yield a very complicated formula, just as the one described in the given link. But I noticed that there might be a difference in both techniques, in the given link, there is a parametric equation. I guess that for that mapping, it would be something different.
Comment: One more thing: There are studies of these formulas, right? I guess that W|A uses some method to convert a drawing into a parametric equation, which seems closely related to what I'm looking for. Do you have any idea of what is this method?


how to get the translated taxonomy term programmatically?

Question: I have tried this
$term = taxonomy_term_load($tid);

and this:
$term = i18n_taxonomy_localize_terms(taxonomy_term_load($tid));

Both return the default language (English) term
I am using D7.
Answer: Try
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

Also, a good place to look for more information: /sites/all/modules/i18n/i18n_taxonomy/i18n_taxonomy.module
Answer: 1. Create translation sets (taxonomy example)

To translate a string, you should use two functions, depending on which i18n mode you use:
Localize mode: i18n_string_translation_update()
<?php
  $result_translation = i18n_string_translation_update(
    array('taxonomy', 'term', $tid, 'name'), // Path where to store source and translation.
    $translated_string,
    $language,
    $source_string
  );
?>

Translate mode: i18n_translation_set_create()
<?php
  // 1. Load or create a translation set.
  $translation_set = ($source_term->i18n_tsid) ?
    i18n_translation_set_load($source_term->i18n_tsid) :
    i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name);

      // 2. Add the full source term in this set.
  $translation_set->add_item($source_term, $source_term->language);

      // 3. Add the full translated term in this set.
  $translation_set->add_item($translated_term, $translated_term->language);
  $translation_set->save(TRUE);
?>

Strings for other contents and modules
When a module defines its own strings, it must use some additional functions to allow these string to be tracked and updated.
Define the textgroup by implementing hook_i18n_string_info(). This is how it looks (i18n_taxonomy module)
<?php
/**
 * Implements hook_i18n_string_info()
 */
function i18n_taxonomy_i18n_string_info() {
  $groups['taxonomy'] = array(
    'title' => t('Taxonomy'),
    'description' => t('Vocabulary titles and term names for localizable vocabularies.'),
    'format' => FALSE, // This group doesn't have strings with format
    'list' => FALSE, // This group cannot list all strings
    'refresh callback' => 'i18n_taxonomy_i18n_string_refresh',
  );
  return $groups;
}
?>

Read more at: Using the i18n API from other modules
Related:
How to associate programatically the translation of new term to the original existing term?
Answer: i18n_taxonomy_localize_terms works on getting site language
please check
Home » Administration » Configuration » Regional and language » Languages
to ensure the site language detection is working as you wanted
i got this done when site languages change on user language preference
Answer: Here is how to rewrite the Finder menue display with localized tayonomy terms:
<?php
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('name', $display)
->propertyCondition('vid', 3) // Change this to Your ID!!
->execute();

$found_tid = array_shift($result['taxonomy_term'])->tid;
// print $found_tid;

$tid = $found_tid;
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_localize_terms($term);
print $translated_term->name;
?>


How can we know when the limit given result is wrong if we are trying to prove it by its definition?

Question: I am currently learning Real Analysis and we learned about the definition of a convergent limit and did some exercises to apply the definition in order to prove the limit's result (i.e: "Use the definition of a limit to show $\lim_{x\rightarrow\infty}f(x)=L$)
However, my concern is that what if the given result (i.e: $L$) is wrong? It looks to me that I can prove any limit converges to anything this way (I am not worried about this in an exam context or just, that is just some general thoughts).
To examine this, I tried proving a wrong result myself, took this:

Use the definition of a limit to show that
$\lim_{n\rightarrow\infty}\frac{1}{n}=10$

I worked it out just like I did for the real result.
Solution:
Note: $n,n_0\neq 0$
Let $\epsilon>0$ be arbitrary. We search for $n_0 \in \mathbb{N}$ s.t. $n\geq n_o \Longrightarrow |\frac{1}{n}-10|<\epsilon$
$\frac{1-10n_0}{n_0}<\epsilon \iff n_0>\frac{1}{10+\epsilon}$
We can take, $n_0=\left \lfloor{\frac{1}{10+\epsilon}+1}\right \rfloor $
Done.
Obviously, I don't think that I actually proved that this limit converges to $10$, I just think I am missing something in terms of my understanding or the way this was presented to me was wrong which is why I am posting here.
Comment: Double check the line where you have $|\frac1n-10|<\varepsilon$ and go to the line with no absolute values. You should have a $-\varepsilon$ on the other side (which is where the problem will make itself apparent).
Comment: Assuming Real Analysis is consistent, you will **not** be able to prove any limit converges to any $L$
Answer: Let's check if this holds: Let us choose $\epsilon = 1$ and according to your derivation $n_0 = 1$, which means it should hold for $n \geq n_0 = 1$. So let's pick $n=1$. If we plug that into the inequality we get
$$\left | \frac{1}{1} - 10 \right| \leq 1$$
which is clearly wrong. So what went wrong here?
In this case you made a mistake when dealing with the absolute value and the inequality - I've seen this mistake a few times as a teacher, and I can assure you that it is definitely not possible to prove that a converging sequence converges to any arbitary limit:)
So when we try to solve that inequality, we get two cases when it comes to resolving the absolute value:
1. Case: $\frac{1}{n} - 10 \geq 0$: Clearly this cannot happen as $n \geq 1$.
2. Case: $\frac{1}{n} - 10 < 0$:
Then we get  $-\left(\frac{1}{n} - 10\right) < \epsilon$ and I think you can take it from here.
Comment: Non Hausdorff says hi. Jokes aside, yea this sort of thing is quite common for first time analysis students.
Comment: thanks for this!
Comment: You're welcome! Just as a tip I like recommending using the literal *definition* of absolute values for problems like these: $|x| = \begin{cases} x & \text{ if } x \geq 0 \\ -x & \text{ if } x < 0 \end{cases}$.
Comment: By that, do you mean just taking the 2 cases like you did or what exactly?
Comment: Yep exactly, in my experience most errors happen by not considering the second case correctly!
Comment: thanks for the advice!
Answer: Per the comment of Clayton:
$\displaystyle \left|\frac{1 - 10n_0}{n_0}\right| < \epsilon \iff -\epsilon < \frac{1 - 10n_0}{n_0} < \epsilon$
$\displaystyle \iff
-n_0\epsilon < 1 - 10n_0 < n_0\epsilon.$
Above assertion justified by the presumption that $n_0 > 0$.


inverse of a complicated function

Question: I need to obtain the inverse, $g^{-1}$, of the following function, $g$.
\begin{align}
u = g\left(x\right) =  2r^2 \cos^{-1} \left(\frac{x}{2r}\right) - \frac{x}{2}\sqrt{4r^2 - x^2}, {\rm{~~}} 0 \le x \le 2r.
\end{align}
As you can see, $u$ is the area of the 'intersection' between two circles with the equal radius of $r$, while $x$ indicates the 'distance' between the two circles.
WolframAlpha is not able to compute the inverse. I wonder if there is any of you who can help me out.
Background:
$x$ is a uniform random variable; and I am trying to obtain the pdf of $U$, via transformation of $f_{U}(u) = f_{X}(x = g^{-1}(u)) \left|\frac{\text{d}}{\text{d}u}g^{-1}(u)\right|$, for which the inverse $g^{-1}$ is needed.
Additional questions:
Is there a way to APPROXIMATE the square root term $\sqrt{4r^2 - x^2}$? Since $u$ is 'area' and $r$ is radius, the $\sqrt{4r^2 - u^2}$ term in $g^{-1}$ yields an imaginary value, which is not desired.
Comment: I suggest differentiating once, then you get an algebraic function. Invert the derivative, then try integrating
Comment: $$g(x)'= -  \frac{2r^2}{\sqrt{4 r^2-x^2}} - \frac{1}{2}\sqrt{4r^2 - x^2}+\frac{x^2}{2 \sqrt{4 r^2-x^2}}$$ $$g(x)'= -  \frac{1}{2} \sqrt{4 r^2-x^2}- \frac{1}{2}\sqrt{4r^2 - x^2}$$ $$g(x)'= - \sqrt{4 r^2-x^2}$$ Can you finish now?
Comment: Derivatives of inverse trig functions are algebraic
Comment: @Yuri S I'm interested in solving equations in closed form. Do you have a name or a literature reference for the method you proposed?
Comment: Thanks for the comment, Yuriy. I just did d/dx g(x), to see an even more complicated form, with acos just replaced with asin. Do you think I did what you had suggested? Would you be able to elaborate?
Answer: My answer is for solving the equation in closed form by only elementary operations and for solving the equation in closed form by only elementary operations with exception of a constant summand.
a)
Because your equation depends on $\arccos(x)$ and $x$ and both are algebraically independent, your equation cannot be solved in closed form by rearranging it only by applying only elementary operations (Elementary functions) that you can derive from the equation.
It is not clear if your equation has solutions that are Elementary numbers.
b)
The method Yuriy S proposed is as follows.
Because it is not possible to solve the equation in the way written in a), we try to calculate the inverse in that way with exception of a constant summand.
All elementary functions (in particular the elementary standard functions) can be represented as compositions of only $\exp$, $\ln$ and/or algebraic functions.
As written in a), $arccos$ disturbs, or $\ln$ because $arccos(x)=i\ln\left(\sqrt{1-x^2}+ix\right)+\frac{\pi}{2}$.
$\arccos$ or $\ln$ can be removed by calculating the first derivative: $\frac{d}{dx}\ln(x)=\frac{1}{x}$.
our strategy:
$g(x)\rightarrow g'(x)$
$g'(x)\rightarrow g'^{-1}(x)$
$\int g'^{-1}(x)dx=g^{-1}(x)+c$
$$\ $$
$$r,x\ge 0$$
$$g(x)=2r^2\arccos\left(\frac{x}{2r}\right)-\frac{x}{2}\sqrt{4r^2-x^2}$$
$$g'(x)=-\sqrt{4r^2-x^2}$$
$$g'(g'^{-1}(x) )=x:$$
$$-\sqrt{4r^2-\left(g'^{-1}(x)\right)^2}=x$$
$$g'^{-1}(x)\colon \left[\sqrt{4\,{r}^{2}-{x}^{2}},-\sqrt{4\,{r}^{2}-{x}^{2}}\right]$$
$c,c_1,c_2$: integration constants
$$\int g'^{-1}(x)dx=g^{-1}(x)+c:$$
$$g^{-1}(x)\colon \left[\frac{1}{2}\,x\sqrt{4\,{r}^{2}-{x}^{2}}+2\,{r}^{2}\arctan\left({\frac{x}{\sqrt{4\,{r}^{2}-{x}^{2}}}}\right)+c_1,-\frac{1}{2}\,x\sqrt{4\,{r}^{2}-{x}^{2}}-2\,{r}^{2}\arctan\left({\frac{x}{\sqrt{4\,{r}^{2}-{x}^{2}}}}\right)+c_2\right]$$
That are the different branches of $g^{-1}$, the partial inverses of $g$.
You have to look for the suitable branch.
Now you have to determine the integration constants $c_1$ and $c_2$. Because $g$ is an elementary function that is not invertible by an elementary function, $g^{-1}$ is not an elementary function, and therefore you cannot calculate the integration constants in closed form in the way written in a). You have to determine them numerically therefore.

inverse of a complicated function


(Krull) dimension of dense open subset of finite type algebra over a domain

Question: Let $D\to A$ be a finite type algebra with $D$ a domain. Suppose $V\subset \operatorname{Spec}A$ is open and dense. Is it true that $\dim V=\dim A$?
I know that if $X\to \operatorname{Spec}\Bbbk$ is an integral scheme of finite type over a field then for any non-empty open $U\subset X$ we have $\dim U=\dim X$. Is this possible to globalize to domains?
Answer: No.  For instance, let $D=A=\mathbb{Z}_p$ (or any other DVR).  Then the open set $V\subset\operatorname{Spec} A$ where $p$ does not vanish is open and dense, but $V=\operatorname{Spec}\mathbb{Q}_p$ so $\dim V=0\neq 1=\dim A$.
Comment: Ah, the Sierpinksi space! Should have thought of it.


if $f(n+1)-f(n)=P(n)$, exist a polynomial $Q(x)$ such that for all $n \in \mathbb{Z}$ : $Q(n)=f(n)$

Question:
Let $f:\mathbb{Z} \to \mathbb{Z}$ such that, exist a polynomial
  $P(x)$:
$$f(n+1)-f(n)=P(n)$$ for all $n \in \mathbb{Z}$
Prove that exist a polynomial $Q(x)$ such that for all $n \in
> \mathbb{Z}$ :
$$Q(n)=f(n)$$
VietNam Math Olympic for college student.

It's my solution, may be not true?
We alaway show that exist $S(x)$ such that $P(x)=S(x+1)-S(x)$ and we have:
$S(n+1)-f(n+1)=S(n)-f(n)$ for all $n \in \mathbb{Z}$
and thus, $S(n)-f(n)=const$ and $f(n)=S(n)+const??$
Comment: If you already have shown that $S(x)$ is a polynomial, then yes, that is enough, since then $S(x)+\mathrm{const}$ is also a polynomial.
Comment: but how to show that $S(x)$ is a polynonial ?
Comment: It was unclear by your language if you were saying you had already proved $S(X)$ was a polynomial or not. @RoadHuman
Comment: Are you familiar with the _binomial basis_ for the space of polynomials?  http://en.wikipedia.org/wiki/Binomial_coefficient#Binomial_coefficients_as_a_basis_for_the_space_of_polynomials
Comment: I am not convinced with my answer , so I want to verify that statement really true ? If not exits polynomial $S(x)$ then i fail :( @ThomasAndrews
Comment: Well, your answer is definitely incomplete, since you haven't proven that $S(x)$ exists, but it is the right direction to go in - it can be proven.
Answer: We will show that $S(x)$ exists for a single polynomial of degree $d$ for each $d$.
Let $P_d(x)=x(x-1)(x-2)\cdots(x-(d-1))$. So $P_0(x)=1$, $P_{d+1}(x)=(x-d)P_d(x)$.
Then $P_d(x)$ is of degree $d$. Show that $P_{d+1}(x+1)-P_{d+1}(x)=(d+1)P_d(x)$.
Thus, letting $S_d(x)=\frac{1}{d+1}P_{d+1}(x)$ we get that $S_d(x+1)-S_d(x)=P_d(x)$.
Now, since the $P_d$ are polynomials of degree $d$, we can write any polynomial $P$ as a sum:
$$P(x)=\sum_{d=0}^D a_dP_d(x)$$
For some real values of $a_d$. Then define:
$$S(x)=\sum_{d=0}^{D} \frac{a_d}{d+1}P_{d+1}(x)$$
And show $S(x+1)-S(x)=P(x)$.
Comment: The comment from Steven refers to another set of polynomials, related, $Q_d(x)=\frac{P_d(x)}{d!}=\binom{x}{d}$. This has the property that $Q_{d+1}(x+1)-Q_{d+1}(x)=Q_{d}(x)$.


Como usar Urls amigaveis?

Question: Atualmente utilizo o MVC no meu projeto e quando eu acesso o meu sistema ele monstra uma url assim:
http://localhost/view/html/cliente.html
o que eu gostaria de obter é:
localhost/cliente pois é o unico arquivo chamado cliente que existe, caso tenha uma nova pasta ficar assim:
localhost/boleto/bradesco
sendo que seria acessado pelo:
http://localhost/view/html/boleto/bradesco.html
Atualmente eu uso jQuery,php,html, cada um separado do outro.
existe alguma solução para criar urls amigaveis de forma dinamica utilizando estas linguagens para obter este resultado?
Comment: Utilizando o exemplo do `.htaccess` do @LeoCBS, acredito que modificar a última linha (`RewriteRule ^(.*)$ index.php?pag=$1`) para `RewriteRule ^(.*)$ view/html/$1.html` resolve o seu problema.
Answer: Olá, você utilizar o arquivo .htaccess para tratar dinamicamente suas urls.
Abaixo um cenário de url amigáveis:
.htaccess
RewriteEngine On
RewriteRule %{REQUEST_FILENAME} !-f
RewriteRule %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?pag=$1

O que esse código faz é manipular a sua URL (para que ele funcione é necessário que a função ModRewrite esteja ativa no seu servidor). A partir de agora, as URL's do seu site podem ser escritas de forma mais simples. Internamente o apache vai interpretar um endereço que está assim: seusite.com.br/noticia/12; como se fosse assim: seusite.com.br/index.php?pag=noticia/12;
Agora vamos criar o arquivo que vai manipular a URL, esse arquivo vai acessar a variável pag. Vamos chamar esse arquivo de url.php
< ? php
//a variavel atual, vai receber o que estiver na variável pag
//se não tiver nada, ela recebe o valor: principal""
$atual = (isset($_GET['isw'])) ? $_GET['isw'] : 'principal';

//aqui setamos um diretório onde ficarão as páginas internas do site
$pasta = 'paginas';

//vamos testar se a variável pag possui alguma "/"
//ou seja, caso a url seja: /noticia/2
if (substr_count($atual, '/') > 0) {
//utilizamos o explode para separar os valores depois de cada "/"
$atual = explode('/', $atual);
/*testamos se depois do endereço do site, o valor da página é um arquivo existente
caso não exista, iremos atribuir o valor "erro" que será uma página de erro
personalizada que existirá dentro da pasta '$pasta', esse arquivo será incluido sempre que um endereço invalido for digitado */
$pagina = (file_exists("{$pasta}/" . $atual[0] . '.php')) ? $atual[0] : 'erro';
//ao que tiver depois da segunda "/" atribuiremos a variavel $id
$id = $atual[1];
//ao que tiver depois da terceira "/" atribuiremos a variavel $busca
$busca = @$atual[2];
} else {
$pagina = (file_exists("{$pasta}/" . $atual . '.php')) ? $atual : 'erro';
$id = 0;
$frame=0;
}

//com o uso de URL amigáveis se torna necessário que arquivos sejam chamados
//com o seu caminho completo, isso porque as imagens levam em consideração a URL
// ex: <img src="<?=$siteUrl?>/pasta/arquivo.png" />
$siteUrl = "http://seusite.com.br";

?>

Arvore de diretórios do nosso site:
www/.htaccess
www/index.php
www/url.php
www/paginas/principal.php
www/paginas/{TODAS AS OUTRAS PAGINAS ITERNAS}
www/imagens

Fonte
Comment: habilitei o rewrite mod restartei o apache, criei o `.htaccess` coloquei o cod, depois criei o url.php e adicionei todo esse codigo, estao na www/.htaccess ,index.html,url.php,view,model,controller
Comment: funcionou as urls?
Comment: não funcionou, eu devo adicionar o url.php para ser executado em algum lugar ? no caso eu não estou trabalhando com a abstração do php estou apenas com o html que fica na pasta view/html/pagina.html

Como usar Urls amigaveis?


CSS renderiza tag BODY mesmo sem a TAG existir

Question: Tenho um arquivo HTML no qual defini do seguinte modo
<!DOCTYPE html>

        <title>Prompt</title>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="style/prompt.css" type="text/css">

No meu arquivo prompt.css estilizei da seguinte maneira
*{margin:0; padding:0;}

body{
    background:#000;
}

Como resultado, o navegador interpretou que a TAG BODY existia e deixou o background em PRETO, como definido no css.
A questão é, por que isso aconteceu ?
Comment: Qual é a ideia de ter uma página HTML sem a tag ``?
Comment: Não é uma ideia, acontece que eu esqueci de colocá-lo. Dai então surgiu a dúvida.
Comment: Os navegadores atuais já adicionam por padrão a tag.
Answer: Mesmo que não adicione a tag  o navegador tenta preencher o que falta do documento, ou seja mesmo que eu faça apenas isto no HTML:

teste

Vai ser gerado algo como (sem doctype):

<title></title>

teste

Talvez você não tenha notado o , porque quando usamos o doctype do HTML5 a altura do  padrão será zero, então basta adicionar um height: 100% que vai notar que o  foi sim gerado:
<!DOCTYPE html>

Veja o resultado:

O teste foi no Opera, mas ele usa a mesma tecnologia do Chrome para renderização

Eu respondi uma pergunta semelhante a esta que falava sobre omitir as tags:

https://pt.stackoverflow.com/a/120146/3635
Comment: Legal. Interessante saber que o navegador influencia diretamente no código.
Comment: Quando eu programava no netscape , nas suas primeiras versões, nunca tinha ocorrido isso, de lá pra cá nunca mais ocorreu, dai resolvi tirar a dúvida.
Comment: @MauroAlexandre acredito que desde o IE5.5 e Mozilla Firefox 1 isso já ocorria, então todos navegadores fazem isto, não será algo para se preocupar ;)


memory leak when parsing data

Question: I am trying to parse a an xml file. I am creating an array of dictionaries and then with these created arrays I am creating array with arrays. I am having memory leaks when I am copying my nsdictionary into array. can any one please help!!
Thanks

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

if(parseMode == 1){
    //        NSLog(@"found this start tag: %@", elementName);
    if ([elementName isEqualToString:@"Group"]) {
        [tInState removeAllObjects];
    }
    else if ([elementName isEqualToString:@"State_Name"]) {
        tData = [[NSMutableDictionary alloc] init];
        xmlItem = 0;
    }
    else if ([elementName isEqualToString:@"T_Name"]) {
        xmlItem = 1;
    }
    else if ([elementName isEqualToString:@"T_Address"]) {
        xmlItem = 2;
    }
    else if ([elementName isEqualToString:@"T_Ph"]) {
        xmlItem = 3;
    }
}

}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

if (parseMode == 1) {
    //    NSLog(@"found this end tag: %@", elementName);
    if([elementName isEqualToString:@"T_Info"]) {
        [tInState addObject:[tData copy]];
        [tData autorelease];
    }
    else if ([elementName isEqualToString:@"Group"]) {
        [tlist addObject:tInState];

    }
}

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

if (parseMode == 0) {
    [self addToStateList:string];
}
else  if (parseMode == 1) {
    //       NSLog(@"found this character: %@", string);
    switch (xmlItem) {
        case 0:
            [tData setValue:string forKey:@"State_Name"];
            break;
        case 1:
            [tData setValue:string forKey:@"T_Name"];
            break;
        case 2:
            [tData setValue:string forKey:@"T_Address"];
            break;
        case 3:
            [tData setValue:string forKey:@"T_Ph"];
            break;
        default:
            break;
    }
}

}
Here tInState, tInState are nsmutablearray which I allocated in viewdidload function and released in releaseMemory. I went through the NScopy documents and it says when we use copy the ownership is transferred. I am releasing all my arrays so why is it still causing the problem??
Please help with this.
Thanks
Comment: I missed to clear the line in didendelement I am not releasing the nsdictionary(tdata). If I release its just crashing.
Comment: Please paste the code in and get rid of the screenshots (which are difficult to read)
Comment: Consider converting to ARC and these kind of issues disappear.
Answer: The reason for your leak is because tData is doing what you told it, returning a copy. Calling autorelease on tData on the next line is autoreleasing the original tData and that will result in an over release. You will need to change that line to this [tInState addObject:[[tData copy] autorelease]]; and remove the autorelease call on the next line.
Answer: On line 81 you are creating a copy of tData but not releasing it so it is leaking.  Instead of creating the copy in the addObject call, assign it to a variable, then pass it to addObject, then release it.
id temp = [tData copy];
[tInState addObject:temp];
[temp release];

Also, I'm assuming that the [tData autorelease] is actually meant to release the copy.  If so, that's not necessary.
Comment: Yeah, but it's shorter, cleaner code and lets you skip creating a temporary. The overhead of `-autorelease` is extremely low--avoiding it tends to be premature optimization.
Comment: @Jonathan - sure, but not much point in putting it in the autorelease pool if you know you don't need it anymore.
Comment: Thanks It worked. So is that when we make copy it should into any id??
Comment: You either have to assign the copy to a variable that you can call release on or, as @Jonathan pointed out, use the shorter, cleaner `[[tData copy] autorelease]` pattern.

memory leak when parsing data


views expose filter by taxonomy

Question: I have this structure :

mobile

Lg

V10
V20

Samsung

A7
J5

Nokia

1100
1110

laptop ...
tablet ...

How can I create that with view expose filter? (step by step filter)
Comment: You get the Taxonomy structure out of the box in an Exposed Filter if you choose the Dropdown option. What exactly do you want to do that is different from what is available? What do you mean "step by step"?
Comment: step by step : when i select mobile .. views show all mobile.
when i select mobilr -> lg ... views show all lg phone ..
Answer: You can do this with the special type of filter Has taxonomy terms (with depth).

Add a new Filter Has taxonomy terms (with depth)
Select your Vocabulary in the new filter settings,
Selection type: Dropdown
Show hierarchy in dropdown
Depth 2 (this will include 2 levels of children of a chosen term)
Expose this filter to visitors, to allow them to change it and Apply

You will get a drop-down that shows your terms with hierarchy.
If you don't want a dropdown you can use a module like Better exposed filters to use radio buttons instead.
Comment: At first we must add "Content : Taxonomoy term on node" as relationship ?
Comment: Do your nodes already have the Taxonomy field on them? They probably do (Entity reference field). Then you don't need Relationships, Taxonomy information is already available in that View. If you can add a Field showing Taxonomy terms on your nodes, you can also add a Filter for those terms, without any Relationships.
Relationships are used to include extra related information from other database tables, but Taxonomy should already be available. If it isn't you have to share more about your node-taxonomy structure.
Comment: yes. it have taxonomy field
Comment: No, you don't need any Relationships in this case ;).

views expose filter by taxonomy


Min and Max of:$\sqrt{ab}+\frac{5}{4}\sqrt{bc}+\sqrt{ca}$

Question: Let: $a,b,c\geq 0$ such that $a+b+c=25$.
Find the Min and Max value of:
$$\sqrt{ab}+\frac{5}{4}\sqrt{bc}+\sqrt{ca}$$
For the minimum, I don't know how to do that. The problem is from this original problem which I have changed the variable:
$x,y,z$ are real numbers such that: $9x^2+4y^2+4z^2=25$. Find the Min Max value of: $$6xy+5yz+6zx$$
For the maximum value, I tried this:
Suppose when the maximum value happened: $x=my=nz$
So get this: $$6xy+5yz+6zx = \frac{1}{m}x(my)+\frac{1}{mn}(my)(nz)+\frac{1}{n}(nz) \leq (\frac{1}{2m}+\frac{1}{2n})x^2+ (\frac{m}{2}+\frac{m}{2n})y^2+(\frac{n}{2}+\frac{n}{2m})z^2$$
Then from this, we have to find $m,n$ such that:
$$\frac{\frac{1}{2m}+\frac{1}{2n}}{9}=\frac{\frac{m}{2}+\frac{m}{2n}}{4}=\frac{\frac{n}{2}+\frac{n}{2m}}{4}$$
which is unsolvable
Answer: For a maximal value smoothing helps.
We need to find a minimal value of $k$, for which the inequality $$ab+\frac{5}{4}bc+ca\leq k\frac{a^2+b^2+c^2}{25}$$ is true for any positives $a$, $b$ and $c$.
It's obvious that such $k_{min}$ is positive.
Let $b+c=constant$.
Thus, we obtain:
$$a(b+c)+\frac{5}{4}bc+\frac{2kbc}{25}\leq\frac{k(b+c)^2}{25},$$ which says that it's enough to solve our problem for a maximal value of $bc$, which happens for $b=c$.
Let $a=xb$.
Thus, we need to find a minimal value of $k$, for which the inequality $$\frac{k}{25}x^2-2x+\frac{2k}{25}-\frac{5}{4}\geq0$$
is true for any positive value of $x$, which gives
$$1-\frac{k}{25}\left(\frac{2k}{25}-\frac{5}{4}\right)\leq0$$ or
$$k\geq\frac{125+75\sqrt{17}}{16}.$$
The equality occurs for $b=c$ and $a=\frac{25}{k}b$, where $a^2+b^2+c^2=25$ and $k=\frac{125+75\sqrt{17}}{16},$ which says that $\frac{125+75\sqrt{17}}{16}$ is a maximal value.


How would I get the largest portion of valid HTML code given invalid input in Python?

Question: I would like to make some sort of HTML parser which takes in some code that is invalid: i.e. has a start tag without an end tag or vice versa, and return the largest portion of valid HTML.
Example Input:

asdf

p1

p2

asdf2

p1

Output:

asdf

p1

p2

asdf2

p1

I considered using some sort of stack-like representation combined with Python's HTMLParser but I'm not sure how I would implement it. I'm using Python 2.7
Answer: Something with a tag stack and a content stack:

opening tag: push tag on tag stack
content : push on content stack
closing tag: pop and output opening tag, pop and output content, output closing tag
Comment: yeah that's along the lines of what I was thinking but the nested structure makes actually printing it difficult. It would work for this example but if you had a  tag before the segment, you couldn't print out the body tag very easily
Comment: I think you need to specify the problem better then, you didn't say you wanted to output unmatched opening tags. I assumed if you don't want unmatched closing you also do not want unmatched opening. As it is, the problem is incompletely specified.
Comment: no you were correct in your initial assumption. in the example above if you had a body tag before everything in the input, it would be matched to the  tag


Automatically granting full disk access for osquery in mac

Question: I am customizing the plist file to start osquery through my code. I have taken the osqueryd file and renamed it to testosqueryd now through my plist, io.testosquery.agent.plist. I am just loading testosqueryd. It is osquery is loading but. But now I am using es_process_events table in my code to get process events. But according to documentation from osquery it requires full disk access.
https://osquery.readthedocs.io/en/stable/deployment/process-auditing/
As I am going to install osquery silently I need to give full disk access automatically.

codesign  -dr - /opt/osquery/lib/osquery.app/Contents/MacOS/osqueryd
Executable=/opt/osquery/lib/osquery.app/Contents/MacOS/osqueryd
designated => identifier "io.osquery.agent" and anchor apple generic and certificate 1[field.1.2.840.1136220.127.116.11.6] /* exists / and certificate leaf[field.1.2.840.113618.104.22.168.13] / exists */ and certificate leaf[subject.OU] = "3522FA9PXF"

According to documentation above should be the output of

codesign -dr -

but problem is it is pointing to io.osquery.agent but my plist name is io.testosquery.agent. In my scenario I also have to support coexistence of osquery as well as testosquey.
Can anyone help me how to silently install customized osquery with full disk access functionality implementation.
Answer: The one can't enable FDA automatically, and it is made so by Apple intent.
You may show some popup and open System Preferences, but it is up to the user to grant the FDA for your app or not.
Only user with his actions (or some vulnerabilities :) ) can do this.
For all of the silent installed for admin purposes stuff the officical (and only supported) way is to connect the device to some MDM server, which could manage some things like this, however last time I checked this was the way only for a big USA-registered companies.
Other option, is to disable SIP on a target mac, but I don't think it is the way you want too.
Answer: As Arthur says, you cannot do this automatically. Except through an MDM.
But, I think there are a lot of oddities in your question. Forgive list form, but:

io.osquery.agent is the bundle id. You'd have to resign things to have that work. I'm not sure what plist means here
Osquery isn't going to work if you rename the binary itself. That's baked in pretty deeply


Vuex+Laravel: Can't send multiple files with FormData and axios to server side. Always getting null on server side. What's going on?

Question: The information which I got by my previous question Vuex + Laravel. Why axios sends any values but only not that one, which come's with method's parameter?
works only for situation when I pass only one argument in axios. I also found how to successfully pass multiple files with one argument, but in my situation, I have to use object, to be able to pass more than one argument. So instead of
const response = await axios.post('/posts', data)

I have to use the next one
const response = await axios.post('/posts', {
                formData:data,
                body:postBody
            })

I thought it would be easy, but now is the 5-th hour that I can't find the solution.

controller
public function store(Request $request)
    {
        $files = $request->all();
        return var_dump($files);
    }

I tried many things, included $request->allFiles() and getClientOriginalExtension() experiments. No results.
What versions do you have? How this problem can be fixed?
Important!
I use Laravel, vuex, axios.
I use text not in FormData cause it's textArea. And if I can combinate textarea in FormData to make one argument axios call, anyway it still very important to me to know what's the problem which I described above.
Updated
Here's chrome's payload tab
Comment: Well, the short answer is "you can't". In terms of "logically correct" why would you send a `post` payload with some data that do not regard the post-action itself?
Comment: Are you completely sure that files are sent to the endpoint? Could you share your request payload from chrome's dev console?
Comment: @Luciano no. It's just very strange. Without object method as a single argument everything works, but as object — Nothing. I updated the question. You can watch the screenshot you wanted.
Comment: Why don't you just send everything within formData object? Why would you want to send a formData and also data?
Comment: @Luciano as I see, it's not logically correct to send all data with only one FormData. Cause formData means data, which belongs to form context. Textarea maybe we can  take as a form data, but what if I want to send another data too?
Answer: It's not pretty clear why you don't send everything you need within  formData object.
You could do something like:
const formData = new FormData()

formData.append(body, postBody)
formData.append(files, fileList)
formData.append(otherData, someOtherData)

const response = await axios.post('/posts', formData)

Then in your server side you will be able to do
 $body = $request->body;
 $files = $request->files;
 $otherData = $request->otherData;

Comment: That's helpful,, so I marked it as useful.


How to get count on how many times a term is used on a node

Question: I'm about to create a Tag cloud module that shall have a block showing a list of all terms. The most used terms shall be in big text; the terms that not used often shall be in small text, as in the following screenshot.
I want to have a $count variable that holds the count of how many times each term is used.
I think that I can do so:
$database = \Drupal::database();
$terms_count = $database
->query('SELECT COUNT(tid) FROM {taxonomy_index}')
->execute();

foreach($terms_count as $term_count) {
  print $term_count;
}

But it doesn't show anything.
Comment: Possible duplicate of [How to get a count on how many times each term is used on a node?](https://drupal.stackexchange.com/questions/246046/how-to-get-a-count-on-how-many-times-each-term-is-used-on-a-node)
Comment: Yes absolutely. It is much easier to see what you need now. :)
Comment: Actually I felt the other one was more clear. This post contains a lot of data, where you are really only after the query. Simpler narrow scoped questions are often preferred.
Comment: I have corrected it now, do you think that this is more clear?
Comment: By the way, I think you should wrap your query in quotes, like this `query('SELECT ... ')`.
Comment: Is there something in your table ?

taxonomy_index only lists references to nodes. Relations of all other entities are in their corresponding field table.
Answer: Here's the query you're going for.
SELECT count(*) AS count, tid FROM taxonomy_index GROUP BY tid ORDER BY count DESC LIMIT 100;

You'll need to use AddExpression to get the count in there.
$query = $this->database->select('taxonomy_index', 'ti');
$query->addField('ti', 'tid', 'tid');

$query->addExpression("count(*)", 'count');
$query->groupBy('ti.tid');
$query->orderBy('count', 'DESC');
$query->range(0, 50);

$data = $raw_data = $query->execute()->fetchAll();

Here's how you might convert the data to a render array:
$term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');

$build = [];
foreach ($data as $count_group) {
  $term = $term_storage->load($count_group->tid);
  $label = $term->label();
  $link = $term->toLink();
  $link->setText($this->t($label . ' (' . $count_group->count . ')'));
  $build[] = $link->toRenderable();
}

return $build;