why the variable value changed to array into function scope ? PHP

Question: why the variable $ replaced changed to array in a function ?
foreach ($rowset as $row)
{
    $replaced = str_replace('$uid',$this->bbcode_uid,$row['first_pass_replace']);
    echo $replaced; // this is a test of the variable error and it's ok
    $this->bbcodes[$row['bbcode_tag']] = array(
        'bbcode_id' => (int) $row['bbcode_id'],
        'regexp'    => array($row['first_pass_match'] => function($replaced){
                return $replaced; //this is not working
            }
            )
        );
}

Comment: It's not clear what you're trying to do, but you seem to be trying to assign a function as an element of an array. It's very unlikely that's really what you want to do. But in any case, even if it *is* what you want to do, the parameter `$replaced` has local scope, limited to that function; it has nothing to do with the variable named `$replaced` that you are using *outside* that function.
Comment: Try to look at scope of variables in php
Comment: the problem is I was debugging error of /e modifier is deprecated ,use preg_replace_callback() instead inside message_parser.php in a phpbb forum so I had to provide the callback function (replacement) as the second element of array that is used by the main preg_replace_callback () function to output transformed bbcode to html again in the post preview page
Answer: I honestly have no idea what you are trying to accomplish but to make it "work" you need:
...
'regexp' => array(
    $row['first_pass_match'] => function() use($replaced) {
        return $replaced;
    }
)
...

You use use() to achieve closure and bring an external variable into the function without explicitly passing it in as a parameter.


Django Python - import error: No module named 'views'

Question: I am trying to run a webserver in Django using this tutorial series: https://www.youtube.com/watch?v=Rpi0Ne1nMdk&list=PLPSM8rIid1a3TkwEmHyDALNuHhqiUiU5A
I get an error when I try and import the script 'landing.views' inside urls.py, here is the error in it's entirety:
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create
    import_module(entry)
  File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'views'

Here is the code that generates the error seen above in urls.py:
from django.urls import path
from landing.views import Index

urlpatterns = [
    path('', Index.as_view(), name='index'),
]

I have also tried looking at posts that other users have created like these: ImportError: cannot import name 'Index' from 'landing.views', Django error in urlpatterns: No module named views, Cannot import name views, however, the first link is currently not answered, and the latter few are not really related to the code that I am currently using. I have also tried other methods like using
sys.path.insert(1, 'C:/Users/trevo/OneDrive/Desktop/VegaAiTest/ChattingPlatform/src/VegaPlatform/landing/urls.py') and sys.path.append("C:/Users/trevo/OneDrive/Desktop/VegaAiTest/ChattingPlatform/src/VegaPlatform/landing/urls.py") as well as using the SET PYTHONPATH= command in my powershell application. What exactly am I doing wrong that might be causing these errors? Any help would be much appreciated, thank you!
Answer: Move views.py from project directory to application directory. If you don't understand the difference, show me ls -laR output.
Have you renamed site from landing to something else? Update from landing.views import Index if so.
Comment: I'm not sure what the ls -laR  command is exactly but I have the ls output: Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        10/20/2021  11:37 PM                landing
d-----        10/20/2021  11:37 PM                social
d-----        10/20/2021  11:30 PM                templates
d-----        10/19/2021  11:17 AM                VegaPlatform
-a----        10/20/2021  11:58 PM         143360 db.sqlite3
-a----        10/19/2021  11:17 AM            690 manage.py
Answer:
Solution 1
     import landing.views

     urlpatterns = [
     path('', landing.views.Index.as_view(), name='index'),
    ]

Solution 2
from landing.views import Index

urlpatterns = [
path('index/', views.Index.as_view(),name='index'),
]

Solution 3: Inside landing app create urls.py an add
from views import Index

urlpatterns = [
path('index/', views.Index.as_view(),name='index')
]

and in project/urls.py add

from django.urls import include, path

    urlpatterns = [
    path('landing/', include('landing.urls') ),
    ]


SOLVED - exercise involving the exponential distribution and conditional probabiliy.

Question: I have a box with two types of elements A and B. There are 7 elements in total. 1 of type A, and 6 of type B.
Both types of elements have some property Z that's exponentially distributed.
The expectation value of Z for type A is 11
The expectation value of Z for type B is 18.5
I pick an element from the box at random.
Given that Z for the element I've picked is 15 or greater, what is the probability that I picked an element of type B?
--
I can do this problem "in reverse", e.g.:

Given that I pick an element of type B the probability that Z is greater than 15 is 0.444.
Given that I pick an element of type A the probability that Z is greater than 15 is 0.255.

but I don't understand how to proceed with the stated problem.
Comment: Initially are you equally likely to pick a type A element versus a type B element?
Comment: @paw88789
No. Initally there's an 6/7 chance of picking an element of type B. I've updated the original question.
Answer: This looks like a Bayes theorem problem:
$$ P(B | Z > 15) = \frac{P(B) P(Z>15 | B)}{P(Z>15)} = \frac{P(B) P(Z>15 | B)}{P(A)P(Z>15 | A) + P(B)P(Z>15 | B)} .$$
You know that $P(A)$, $P(B)$ are $1/7$ and $6/7$, and you've already calculated $$P(Z>15|A) = 0.255, $$ $$ P(Z>15 | B) = 0.444 \quad .$$
Comment: Thank you for a very helpful and quick reply.


Select query to return locations of map when users click

Question:
I work on the map and keep the locations in the database.
There are different locations of the map on the table. There are many locations within the table.
Now different users come and click on different position on the map, so I have to select a query in the database to find each location. Is this correct? That means I run a query for every click.
In my opinion, specify a dimension(area), and whenever these dimensions are loaded, I select all the locations within those dimensions to avoid additional query select to database.
What is the best optimization way?
Comment: as you know lngitude and langitude you cqan select all location that a in a spehre of a certain size lets say 200 m, mysql 8  has spatial indexes that you can use
Comment: Tnx @nbk. I don't know spatial index.
Answer: What is a location on a map?  Is it a single point?  Or is it a region, such as a country, county, province, etc?
In the former case the problem is to "find the nearest" item on the map to the mouse click point.  I cover that here
For the latter case, you need to turn each region into a polygon and enter it into a geographic object that is indexed with a SPATIAL index.
It is beyond the scope of this forum to provide all the details for either of your cases.  If you have trouble, come back with a more specific question, including the steps you have taken so far.


Compare values of P and K

Question: I am preparing for GRE. These two problems are from Manhattan 5lb book. I am finding absolute value equations very daunting. Sometimes it is time consuming, sometimes it seems very difficult to me. Following two are comparison problems. You have to compare quantity A with quantity B (i.e. if Quantity A> Quantity B, Quantity A< Quantity B, Quantity A= Quantity B, or it cannot be determined from the given information )

Prolblem 1:

If $p+|k|>|p|+k$, compare
Quantity A: $p$
Quantity B: $k$

Problem 2:

If $|x|+|y|>|x+z|$, compare
Quantity A: $y$
Quantity B: $z$

My solution approach

a) p $(+ve)$ and k $(+ve)$ --> not possible
b) p $(+ve)$ and k $(-ve)$ --> possible (In this case, Quantity A> Quantity B)
c) p $(-ve)$ and k $(+ve)$ --> not possible
d) p $(-ve)$ and k $(-ve)$ --> possible if $|k|>|p$| (In this case, Quantity A> Quantity B)
e) p =0 and k $(+ve)$      --> not possible
f) p =0 and k $(-ve)$      --> possible (In this case, Quantity A> Quantity B)
g) p $(+ve)$ and k =0,     --> not possible
h) p $(-ve)$ and k =0,     --> not possible
In all three possible cases, Quantity A> Quantity B. so, Quantity A> Quantity B is the answer.
I also solve problem 2 in a similar way. Can you show me the easier approach or the right approach to deal with these problems?
Comment: Not clear what a) says.  Is there a notational convention from the book you are using?

For Problem 1, I would first rewrite the inequality in the more symmetric form:
$$
|k|-k > |p| - p.
$$
Thus, at least one of $p, k$ must be negative; otherwise, we would get $0 > 0$.  That leads to two cases: (i) only one of $p, k$ is negative, and (ii) both are negative.  Case (i) can be only $k < 0$, which makes the inequality $-2k > 0$ and gives no information about $p$.  Case (ii) implies that $-2k > -2p$ and allows the desired comparison.
Answer: Add symmetry to the first equality by rewriting as:
$$
p -|p| > k - |k|
$$
Now define the function:
$$
f(x) = x - |x| = \begin{cases} 2x & \text{if } x < 0 \\ 0 &\text{otherwise} \end{cases}
$$
and graph it. Then the question reduces to:

Does $f$ ever go both down and up, or does it never go down, or does it never go up?

Since $f$ is an increasing function (never goes down, just up or flat), we observe that $f(p) > f(k) \implies p > k$.

I want to compare $y$ with $z$, so my first instinct was to eliminate the other variable by setting $x = 0$ and seeing what happens. This yields $|y| > |z|$, which immediately leads to at least two conflicting counterexamples: we could have $y = 5$ and $z = 2$ (leading to $y > z$) or $y = -5$ and $z = 2$ (leading to $y < z$).
Answer: If $|p| + k < p + |k|$, then $|k| - k > |p| - p$. Now, for this to happen, note that $k$ must be negative, so that $|k|-k > 0$, and $p$ must be non-negative, so that $|p|=p $ and hence $|p|-p=0$, implying $|p| - p < |k|-k$. Thus, $p > k$ anyway.
For the second question, have a hunch, and see the result. Put $x=0$, which results in $|y| > |z|$. This is of course not decidable in general : if $y = 2, z=-1$ then it is true, but if $y=-1,z=2$ then it is not true, for example. Hence the second question is not decidable.
As a general tip, since you are giving the GRE which is a heavily time constrained exam, when possible try to partially substitute obvious values into your expression, as we did above, to get a clue of the answer. In the first problem, we used a clever trick, and that unfortunately comes with practice, but at least you have been acquainted with it here.
Comment: Ah, good point. Thank you, @MahmudulHasan.
Comment: Thank you very much. However, in problem 1, can you elaborate a bit "p  must be non-negative, so that |p|=p and hence |p|−p=0, implying |p|−p<|k|−k. Thus, p>k anyway." Because I find, p can also be negative. For example p= -1, k=-2

Compare values of P and K


OLS Estimator for ARMA(1,1)

Question: We consider the ARMA(1,1) model:
$$
y_t = \beta y_{t−1} + \varepsilon_t + \theta \varepsilon_{t−1}.
$$
I would like to demonstrate that $y_{t-2}$ provides an instrumental variable estimator for $\beta$.
How can I do that ?
Thank you!
Answer: First of all, ARMA(1,1) process can be rewritten in this way:
$y_t$ = $\epsilon_t$ + ($\beta$+$\theta$)$\sum_{j=1}^{\infty}$$\beta^{j-1}$$\epsilon_{t-j}$
Therefore,
A
= E[$y_{t-2}$$\epsilon_t$] =
E[$\epsilon_{t-2}$$\epsilon_t$ + ($\beta$+$\theta$)$\sum_{j=3}^{\infty}$$\beta^{j-3}$$\epsilon_{t-j}$$\epsilon_t$] ---------- eq.(1)
Because $\epsilon_t$ is white noise, E[$\epsilon_{t-2}$$\epsilon_t$]=0, and similarly for other terms in eq.(1). Overall A=0.
Likewise, if you calculate
B
= E[$y_{t-2}$$\epsilon_{t-1}$], you will get zero,
which means that $y_{t-2}$ is not correlated with error term $u_t$ = $\epsilon_t$ + $\theta$$\epsilon_{t-1}$. We also know that $y_{t-2}$ is correlated with $y_{t}$ through $y_{t-1}$. This all points to $y_{t-2}$ as a reliable instrument for $y_{t-1}$.
Comment: nice answer. just two quick things: 1) In your second to last sentence, you meant not correlated with the error term $u_t$. 2)  what I don't get about instrumental variables is the following: I understand that, by using $y_{t-2}$, you then meet the OLS assumption of uncorrelatedness with the error term so the regression is "legal".  But doesn't the IV coefficient have totally different meaning since $y_{t-1} is gone ? Why is the IV helpful to the original model ? Thanks and apologies for the possibly stupid question.
Comment: Hi, thanks for the comment. Yup, I meant 'not correlated' and edited it accordingly. I am not sure what you mean by $y_{t-1}$ is gone. In this example, the estimate for $\alpha$ would be sum($y_{t-2}$$y_{t}$)/sum($y_{t-2}$$y_{t-1}$). There would still be $y_{t-1}$ in the formula for IV estimation. If I remember correctly, IV estimates generally tend to be larger than OLS estimates. But I have no idea if this continues to hold in time-series although I am inclined to say yes.
Comment: Thanks. I'm going to have review IV so don't worry about my question. Your answer to the OP was fine. I'm just vague on the IV specifics but I have a book that covers IV quite nicely so I'll dig it up. I'll also put the title of it in another comment once I dig up the book.

OLS Estimator for ARMA(1,1)


Como é feita e armazenada a criptografia de uma SecureString?

Question: A classe SecureString é utilizada para representar um texto que deve ser mantido como confidencial na memória (senhas, números de cartões, saldos e etc.), e realiza a sua correta exclusão da memória quando o referido texto não for mais necessário.

Como é feita essa criptografia? Como é armazenada a chave?
Answer: Só usá-la não adianta muito. E achar que ela dá total segurança é bobagem. Leia mais em Como, quando e por que usar "SecureString" no C#?.
A implementação é detalhe, então varia dependendo do runtime usado e da versão dele e não deve se prender a ela. Então não tem como responder a pergunta feita. E esta é a resposta.
Mas posso dar algumas informações:

o .NET Framework tem uma forma complexa de decidir o que fazer e delega para outras partes do framework cuidar da criptografia, usa muito código de baixo nível e API do Windows.

o .NET Core delega para outra biblioteca, dá para tentar achar a implementação. Também e a parte específica para Unix.

o Mono usa o Encript() dele próprio, tem que ir lá ver como este método faz.

Pelo que entendi usam chaves internas do framework ou do sistema operacional, que é mais seguro.
Comment: Estava pesquisando sobre como um anti-cheat pode proteger dados importantes na memória, e lembrei que o SecureString seria um bom ponto de partida para me basear.
Comment: Não existe *anti-cheat* eficaz em software cliente. E é por isto que o SS também não é seguro.
Comment: Sim, concordo que nada substitui um servidor autoritativo. Porém, há ocasiões em que o custo desta implementação se torna impeditivo, ou mesmo quando não temos tempo suficiente para implementá-la. Como exemplo, posso citar um advergame voltado para uma campanha publicitária com um curto tempo de vida. Dentre as técnicas que penso em empregar seria a criptografia das variáveis e sua constante troca de endereços na memória.


How to reload environment variables from within a script

Question: I would like to be able to regenerate the value held by the environment variables inside my testing environment, and have the new values be read by PHP-FPM.
I have written a script that regenerates the environment variables, writes them to a file, and restarts PHP-FPM
# make errors error
set -eufx -o pipefail

# Generate the env settings file
php bin/cli.php genEnvSettings dev /etc/profile.d/imagickdemos.sh

# reload the env values
set +u
source ~/.bashrc
source ~/.bash_profile
set -u

#restart PHP-FPM
/etc/init.d/php-fpm restart

Running this script does not change the environment variables that PHP-FPM receives.
If I run the following commands directly from the CLI after running the above script:
source ~/.bash_profile
/etc/init.d/php-fpm restart

Then the new values for the environment variables are available to PHP-FPM. i.e. it's as if source ~/.bash_profile inside the script has no effect.
How can I reload the environment variables inside that script, rather than having to run the reload directly from the command line? Or is there a better way to make a newly written env settings file be picked up when restarting a service?
I am using Centos 6.4 in case that makes any difference.
Answer: My guess is that your .bash_profile has a condition like if [ -n "$PS1" ] which makes it effective for interactive shells only. The way to test it is to set -x in the script and inspect the trace output for the assignments.
As to your other question: the usual way to set a server's environment is to write the export assignments to /etc/sysconfig/servername or /etc/default/servername (whichever one is sourced directly by the init.d script).
Answer: It sounds like sourcing the env scripts from within the init.d script is the standard practice, but the actual issue that was stopping the env script being reloaded for me was the set -f flag.
In the file /etc/bashrc it looks like it should be sourcing the files no matter what:
for i in /etc/profile.d/*.sh; do
    if [ -r "$i" ]; then
        if [ "$PS1" ]; then
            . "$i"
        else
            . "$i" >/dev/null 2>&1
        fi
    fi
done
unset i

But the -f flag turns off file-globbing. I've removed the -f flag and instead changed to shopt -s failglob which errors on failed globbing.


Argument of type "const char*" is incompatible with parameter of type "char*". But why? :(

Question: I am learning some data structure stuff and I faced a problem that I did not even expected because normally I can solve this kind of error.
#include <iostream>
using namespace std;

struct Avion {
    char* numePilot;
    int nrPasageri;
};

struct nodDublu {
    Avion info;
    nodDublu* next;
    nodDublu* prev;
};

struct ListaDubla {
    nodDublu* first;
    nodDublu* last;
};

Avion creareAvion(char* numePilot, int nrPasageri) {
    Avion avion;
    avion.numePilot = (char*)malloc(sizeof(char)*(strlen(numePilot) + 1));
    strcpy_s(avion.numePilot, strlen(numePilot) + 1, numePilot);
    avion.nrPasageri = nrPasageri;

    return avion;
}

nodDublu* creareNod(Avion info, nodDublu* next, nodDublu* prev) {
    nodDublu* nou = (nodDublu*)malloc(sizeof(nodDublu));
    nou->info = creareAvion(info.numePilot, info.nrPasageri);
    nou->next = next;
    nou->prev = prev;

    return nou;
}

ListaDubla inserareInceput(ListaDubla lista, Avion avion) {
    nodDublu* nou = creareNod(avion, lista.first, NULL);
    if (lista.first) {
        lista.first->prev = nou;
        lista.first = nou;
        return lista;
    }
    else {
        lista.first = nou;
        lista.last = nou;
        return lista;
    }
}

void main() {
    ListaDubla lista;
    lista.first = NULL;
    lista.last = NULL;

    Avion avion = creareAvion("Ionescu", 34);
}

I put here the entire code, but obv the problem is somewhere at "creareAvion" which is the funct for creating Avion I guess. That "Ionescu" is not working because of that error.
Comment: Well, what happens if you try to dereference `numePilot` and modify it? How should the literal `"Ionescu"` be modified?
Comment: You're using C++, so forget about `malloc` and use `std::string` instead of `char*`. Or if you really insist on using C in C++, change parameter `char* numePilot` to `const char* numePilot` in `creareAvion`
Answer: You are passing string literal "Ionescu" to a function that takes a char* as argument. In C++, in contrast to C, string literals will decay to pointers of type const char*, so this is simply a type mismatch.
To overcome this, I'd suggest to change your function to take a const char*, since you actually do not modify the contents of the passed parameter in the body:
Avion creareAvion(const char* numePilot, int nrPasageri) {
  ...

And: If you are using C++, switch to the metaphors of C++ (and get rid of those from C); C++ offers, for example, std::string, which avoids a lot of errors that can happen when coping with malloc/free ... in conjunction with copyable/moveable objects.
Comment: @Andreea do what you have to do to pass the class, but know that you are begin taught C rather than C++. This is unfortunately a common problem. If it continues, I recommend that you supplement your education with [a few good C++ references](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and some extra study when you have the opportunity so that you don't suffer so nasty a shock when you find yourself expected to actually know C++. At a job interview for example.
Comment: Technically, a string literal is not a pointer at all. It is an array.
Comment: The thing is that this is not really my choice. I am a student and they want us to use those things.


Preserving an Algebraic Structure

Question: What does it mean that a homomorphism preserves algebraic structure of a group ?
What does it mean algebraic structure? Can someone please explain in simpler and detailed terms.
Comment: If you have a homomorphism between groups $G$ and $G'$ then things (as in the binary operator) "works the same way" in both $G$ and $G'$". It doesn't matter if you use the binary operator on two elements from $G$ and then map the result to $G'$ or if you map two elements from $G$ to $G'$ and then use the binary operator from $G'$. The result will be the same.
Comment: This might be of interest http://math.stackexchange.com/questions/147632/isomorphisms-preserve-structure-operation-or-order?rq=1
Answer: The definition of a homomorphism $\varphi:G \to H$ for groups $G, H$ is given by the following axiom:
$\varphi(gg') = \varphi(g)\varphi(g')$ for $g,g' \in G$,
It can be shown that $\varphi(1_G) = 1_H$, the units of $G$ and $H$ respectively and $\varphi$ maps inverses to inverses by $\varphi(g^{-1}) = \varphi(g)^{-1}$
What do all of these mean?  In the first axiom, our homomorphism takes the composition of any two elements in $G$ and sends it to the composition of two elements in $H$, $\varphi(g)$ and $\varphi(g')$.  Furthermore, it preserves identity: $1_G$ is mapped to $1_H$ and it preserves inverses.
Hence, we can see that the homomorphism maintains the "group structure" by, in a sense, preserving the law of composition, identities, and inverses; the homomorphism is "translating" the structure of a group G to the structure of another group H.
When there exists a bijective homomorphism, an isomorphism, between two groups then we can consider the two groups nearly the same as they have the same properties; the homomorphism translating the properties of the first group to the ones of the second can be inverted, so there is little distinction between the two groups.
Disclaimer: I don't claim to be an expert, just throwing in my own insights
Comment: Note that the implications of homomorphisms probably go much deeper than this, especially once one goes into branching fields.  I haven't gotten any further than algebra myself, so I can't give you any examples, sorry.

Preserving an Algebraic Structure


IIS not sending ASP.Net cookies to IE10 (and only to IE10)

Question: I have IIS 7.5 server running ASP.Net application, which for some reason doesn't send ASP.Net authentication cookies to IE10. This happens only when request comes in from IE10 browser and only over network (i.e. not when browsing from web server itself). All other browsers (Firefox, Chrome, Safari, IE9) work absolutely fine.
The problem is clearly in browser identification, because when I switch IE10 into IE9 mode, the cookie does arrive. On the other hand, when I force other browsers (for example Firefox) to impersonate IE10 using agent-overriding plug-ins, the cookie is not sent.
This happens regardless of the protocol (http vs https) and server's host name (happens with IP address as well).
So far I ruled out the problem in the server application code, because I have similar setup on another IIS with exact same application, which doesn't exhibit the symptoms, so I assume it's likely something in IIS configuration. By comparing IIS configurations between two systems, I only see the following difference which is possibly relevant:
<code><system.web>
  <clientTarget>
    <add alias="ie5" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)" />
    <add alias="ie4" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; Windows NT 4.0)" />
    <add alias="uplevel" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.1)" />
    <add alias="downlevel" userAgent="Generic Downlevel" />
  </clientTarget>
</system.web>
</code>
I want to try to change these settings, but I can't find what this corresponds to in IIS Manager UI.
Comment: I ran into an issue with IE10 and my ASP.Net application which turned out to be a bug in ASP.Net, except my symptoms had nothing to do with cookies.  It was driving me insane because it would only happen on one of the servers.  I ran into this [article](http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx) by Scott Hanselman, and applied the hotfix to the server.  The hotfix has now been shipped as a regular update.  It's a stretch, but maybe you should try running updates on your server.
Comment: @Tung Thanks, that did it. Please copy everything you said into a proper answer - you deserve credit for it.
Answer: (Converting comment to answer)
I ran into an issue with IE10 and my ASP.Net application which turned out to be a bug in ASP.Net, except my symptoms had nothing to do with cookies. It was driving me insane because it would only happen on one of the servers. I ran into this article by Scott Hanselman, and applied the hotfix to the server. The hotfix has now been shipped as a regular update. It's a stretch, but maybe you should try running updates on your server.
Comment: This was a bug in .Net Framework 4.0; here's direct link to Microsoft patch which fixed the problem for me: http://support.microsoft.com/kb/2600088


pushwoosh init(); give me error

Question: I am using phonegap pushwoosh for notification. I follow the instruction but i stack on some place.
i did  as instruction now i have to put the below code in some where
function init() {
document.addEventListener("deviceready", initPushwoosh, true);

//rest of the code
}

can any one some me some sample how to put the code. i check the sample from pushwoosh but they are using

Not Body onload=init(); now i am confused....
I am new on android and phonegap and pushwoosh. please please help me.
Please help me.
Thanking you
Masum
Answer: You can do this:
$(function() {
   document.addEventListener("deviceready", init, true);
});

pushwoosh init(); give me error


Solving the system $px+qy+rz=(p^2+q^2+r^2)\cos\theta$, $ax+by+cz=0$, $\sqrt{x^2+y^2+z^2}=\sqrt{p^2+q^2+r^2},ap+bq+cr=0$ for $x$, $y$, $z$

Question: $$\begin{align}
px+qy+rz &=(p^2+q^2+r^2)\cos\theta \\[4pt]
ax+by+cz &=0 \\[4pt]
\sqrt{x^2+y^2+z^2} &=\sqrt{p^2+q^2+r^2}
\end{align}$$
$$ap+bq+cr=0$$
How would one express the solution $(x,y,z)$ in terms of real constants $a,b,c,p,q,r$ and $\theta$?
What I have so far:
If I choose z to be a free parameter, then
$$
\begin{bmatrix} p & q \\ a & b \end{bmatrix}
\begin{bmatrix} x   \\ y \end{bmatrix}=\begin{bmatrix} (p^2+q^2+r^2)cos(\theta)-rz   \\ -cz \end{bmatrix}
$$
and
$$
\begin{bmatrix} x   \\ y \end{bmatrix}=\begin{bmatrix} b((p^2+q^2+r^2)cos(\theta)-rz) +cqz  \\ -a((p^2+q^2+r^2)cos(\theta)-rz)-cpz \end{bmatrix}1/(bp-aq)
$$
so
$$\begin{bmatrix} x   \\ y \\ z\end{bmatrix}=\begin{bmatrix} b((p^2+q^2+r^2)cos(\theta)-rz) +cqz  \\ -a((p^2+q^2+r^2)cos(\theta)-rz)-cpz \\ z(bp-aq)\end{bmatrix}1/(bp-aq)$$
Then, the rest is a straightforward polynomial in z
$\sqrt{x^2+y^2+z^2}=\sqrt{p^2+q^2+r^2}=\sqrt{(b((p^2+q^2+r^2)cos(\theta)-rz) +cqz)^2/(bp-aq)^2+(-a((p^2+q^2+r^2)cos(\theta)-rz) -cpz)^2/(bp-aq)^2+z^2}$
Comment: The system is homogeneous so it's enough to solve it for $\|(p,q,r)\|=\|(a,b,c)\|=\|(x,y,z)\|=1$. Then you need to find a vector orthogonal to a given vector, having a given angle with another vector.
Comment: If you want $(a,b,c)$ and $(p,q,r)$ to be orthogonal, you should put that in the statement of the problem.  That makes it much easier!  Then the plane through the origin perpendicular to $(a,b,c)$ contains the point $(p,q,r)$. Rotate $(p,q,r)$ about axis $(a,b,c)$ through angle $\theta$; the result is $(x,y,z)$.  There are two drections you could rotate; so there are usually two answers.
Comment: What progress have you made? What have you tried?
Comment: As you say, the last equation is a straightforward polynomial in $z$, specifically a quadratic. So you could solve for $z$, plug the expression into your equations for $x,y$ and get two solutions in terms of the constants. Is the problem that this method is tedious/results in ugly expressions?
Comment: @TonyMathew precisely. I'm having a hard time doing it by hand, and all of the online calculators I've tried have given up on it
Comment: @TonyMathew my intuition is that the column vector (x,y,z) can be expressed as a 3x3 rotation matrix times the column vector (p,q,r). Thus, the final expression is possibly not so ugly
Comment: Re-phrased ... given vectors $(a,b,c)$ and $(p,q,r)$, and angle $\theta$, find vector $(x,y,z)$ that is: perpendicular to $(a,b,c)$ with angle $\theta$  between $(p,q,r)$ and $(x,y,z)$.  Whether this exists will be determined by the angle between $(a,b,c)$ and $(p,q,r)$.
Comment: Rotate in $3$-space to reduce to the case $(a,b,c) = (R,0,0), (p,q,r) = (0,R,0)$, solve that case explicitly $(x,y,z) = (0,R\cos\theta,\pm R\sin\theta)$ then rotate back.
Comment: @TonyMathew The third equation tells me that (x,y,z) has magnitude √(p^2+q^2+r^2). I can modify the first two equations into a 2x2 matrix multiplied by a 2x1 column vector = another 2x1 column vector. I can achieve this by letting one of the variables x,y, or z be a free parameter and expressing the other two variables in terms of the free parameter. Solving the 2x2 matrix equation would tell me the correct direction of my desired (x,y,z) vector, and the third quation would tell me the magnitude of my desired vector. Proceeding with this idea hasn't worked out for me, though
Comment: The line in space containing my desired vector would be expressed in terms of a free parameter. I could let z be the free parameter, for instance. After taking the 2x2 matrix's inverse and solving for the line containing (x,y,z), I could then intersect this line with a sphere of radius √(p^2+q^2+r^2) centered at the origin and the two solutions would be the possible solutions (x,y,z).
Comment: @GEdgar (a,b,c) and (p,q,r) are orthogonal. And yes; I originally formulated this problem as a geometry problem involving these vectors
Comment: @GEdgar is there an existing formula that I can use to come up with a 3x3 rotation matrix in terms of $p,q,r,a,b,c $ and $\theta$? My idea is that each of the 2 possible 3x3 rotation matrices would correspond to one of the 2 solutions (rotating in one direction versus the opposite direction)
Answer: When the algebra becomes messy, my method is to repeatedly define groups of constants as new constants. In your problem, you only care about $x,y,z$: you don't need to worry about the interactions of the remaining constants until the end where you express the final solution in terms of them. So for example, you could define common constant expressions in your final equation as such
$$d=\sqrt{(b(d^2 cos(\theta)-rz) +cqz)^2/e +(-a(d^2 cos(\theta)-rz) -cpz)^2/e+z^2} \\
d = ||(p,q,r)|| = \sqrt{p^2+q^2+r^2}, \quad e = (bp-aq)^2 $$
But this is still ugly, so if you square both sides, expand the $b()$ and $a()$ then define some more, you get this relatively cleaner equation.
$$f_1 = (f_2 z + f_3)^2 +(f_4 z + f_5)^2 + e z^2 \\
f_1 = d^2e, \quad f_2 = cq - br, \quad f_3 = bd^2 cos(\theta), \quad f_4 = a r -cp, \quad f_5 = -a d^2 cos(\theta)$$
Hopefully the $f$ equation is now clean enough for you to solve for $z$ in terms of $f$'s and $e$. Then you could substitute for $z$ in your $x,y$ equations, then substitute the $f$'s, then $d,e$. I agree that the final solution will still be ugly, but maybe it won't be as hard for you to get there now.

Alternative thoughts in case they lead to a simpler solution approach:
Interpreting the algebraic system of equations as vector constraints, you want to solve for $\vec{X}$ given $\vec{P}, \vec{A}, \theta$ in the following.
$$\vec{P} \cdot \vec{X} = ||P||^2 \cos \theta \\
\vec{A} \cdot \vec{X} = 0 \\
||X|| = ||P||$$
Geometrically, you want to find a vector with same magnitude as $\vec{P}$ but forming an angle of $\theta$ with it and is also perpendicular to $\vec{A}$. So in line with your comment, you would want to find something like,
$$\vec{X} = M \vec{P}$$
where $M$ is a rotation matrix that rotates by $\theta$ in a rotational plane containing $\vec{A}$ such that the resulting vector is in the plane normal to $\vec{A}$.
Comment: Also, would it be the case that one solution corresponds to an M that rotates by theta, while the other solution corresponds to an M that rotates by negative theta?
Comment: I'll use exactly those substitutions and get my 2 solutions. After I do so, can I use the resulting solutions to then derive the rotation matrix M in terms of all of the constants? My guess is I can, but it's not immediately obvious to me how I'd come up with the rotation matrix, whether it be with or without first having my 2 solutions
Comment: I'm aware that a general 3x3 rotation matrix can be expressed in terms of yaw, pitch and roll. Is there not a way to express a general rotation matrix in terms of the components of the starting vector, the components of a vector along the axis of rotation orthogonal to the starting vector, and the angle of rotation? It seems to me that such a formula ought to exist, and if it exists then I could make all of this much easier by using the formula
Answer: Can someone tell me if the following solution is correct
$$
\begin{bmatrix} cos(\theta) & -csin(\theta)/d & bsin(\theta)/d \\\ csin(\theta)/d & cos(\theta) & -asin(\theta)/d  \\\ -bsin(\theta)/d & asin(\theta)/d & cos(\theta)\end{bmatrix}
\begin{bmatrix} p  \\\ q \\\ r\end{bmatrix}=\begin{bmatrix} x\\y\\z\end{bmatrix}
$$
where $d=\sqrt{a^2+b^2+c^2}$


How do I figure out whether rhythms have beats with 2/3-1/3 splits or 3/4-1/4 splits?

Question: I am trying to transcribe this song for piano. This is my progress so far (ignore the 8vb, I am planning to switch the left- and right-hand parts).
I am having trouble figuring out whether the rhythms in which I currently have sixteenth-note-triplets with one eighth note and one sixteenth note are correct, or whether they should actually be a dotted sixteenth note followed by a thirty-second note.
Better put, is this version more accurate?
I realize this is a minor difference but the difference between a 2/3 - 1/3 split and 3/4 - 1/4 split in rhythms has always been a bit difficult for me.
Answer: These are definitely triplet subdivisions, not duple 32nds. With experience, you can tell the difference even at fast tempos like this.
If I was doing this transcription, however, I would take a very different approach. I would either write in swing 8ths, 4/4 at q=206, or I would keep the meter the same and make a note up at the top indicating "swing 16ths", and then not write a single triplet or 32nd note.
This style of rhythm is right out of jazz music, and the matching notation is rarely explicit about the triplet subdivision that is implied in swing rhythms. You would only write an explicit triplet if you had a note starting on the second of three subdivisions.
Swing 8ths:

Swing 16ths:

One additional tip about your transcription -- the two consecutive dotted 8ths you have in bar 2 would not usually be considered correct. Often it's debatable, but in this case, the second note does actually have a swing placement, and so showing the distinct 16th is important. (If you listen closely, those two notes are NOT the same length!)
Comment: Thank you! I did not realize that the two dotted eighths weren't the same length. It does sound more like the original when I change the second to a swing placement. How do you hear these things? The difference seems so difficult to figure out by ear ...
Answer: I have got the same issue some times ago and after obsessively seeking an answer I realized human brain is not able to distinguish between those (in 110 bpm) :D
But the common literature uses the 2/3 1/3 split. however it is literally indistinguishable but it is more common to use it.
so don't get obsessed over it, you're transcription is absolutely fine.
Source : I played and listened to music obsessively since I was 11 :D
[for those who are voting down and or not, please read the comment section]
Comment: I've had extensive solfège lessons, and can distinguish between triplets and dotted eighths with sixteenth. Assuming I am - as a human - in possession of a human brain, this seems to contradict your first paragraph.
Comment: Really? you can distinguish them in tempo of 110? If that's so it's amazing, I will seriously reconsider it and practice on it.thanks for sharing
Comment: The difference between a sixteenth note and a triplet is one twelfth of a beat.  At 25bpm, that's a fifth of a second--if you're not hearing that difference, I think you may have set something up wrong in guitar pro.
Comment: @BruceFields I hear it at guitar pro at 25 bpm.but in 110 bpm it's about 0.05 second. it takes 0.003 seconds for sound to travel from 1 m of me. so it remains 0.047 seconds.human blink time response is 0.1 second! I have no idea how can someone say that they can hear the difference at 110 bpm.
Comment: The absolute time it takes for sound to travel 1m isn't really relevant here - the experienced ear is still very sensitive to small differences in *relative* timing between sounds. When trying to sequence a drum pattern and get exactly the right feel, you get used to moving beats by just a few milliseconds one way or another - from memory, moving a beat by just 10 or 15 ms (that's 0.01 to 0.015 s) can easily make a noticeable difference. 0.05 second is 50ms - definitely an audible difference in many situations.
Comment: But I wrote them parallel in guitar pro and even in a tempo of 25 and with precise playing of CPU I could barely hear it
Comment: I left my initial comment before the addition of "in 110 BPM", but I am still convinced it is possible with enough training. Listening obsessively to music since you were eleven is a different kind of training than regular solfège lessons since the age of 5.
Comment: I did some extensive research and yea it is possible to hear. theoretically brain is able to distinguish about 20 ms intervals depending on person.it's amazing. thanks all for participating in the discussion.


Abelianization of $\mathbb{Z}_2*\mathbb{Z}_3$

Question: Intuitively it has to be
$$\text{Ab}(\mathbb{Z}_2*\mathbb{Z}_3)=\mathbb{Z}_2\times\mathbb{Z}_3$$
here is my approach on how to prove it
$$\mathbb{Z}_2=P(a\mid a^2),\mathbb{Z}_3=P(b\mid b^3)\Rightarrow \mathbb{Z}_2*\mathbb{Z}_3=P(a,b\mid a^2,b^3)$$
then
$$\text{Ab}(\mathbb{Z}_2*\mathbb{Z}_3)=P(a,b\mid 2a,3b)=\mathbb{Z}\langle a,b\rangle/\langle 2a,3b\rangle=\mathbb{Z}\langle a\rangle/\langle 2a\rangle\times\mathbb{Z}\langle b\rangle/\langle 3a\rangle$$
which gives the wanted result, although I don't why that last equality holds.
Comment: The last equality holds since the quotient of a product of two groups by the product of two normal subgroups is the product of the quotients: $(G1\times G_2)/(H_1\times H_2)=(G_1/H_1)\times (G_2/H_2)$, if $H_i$ is a normal subgroup of $G_i$.
Comment: Let $p_i\colon G_i\rightarrow G_i/H_i$ be the quotient map, for $i=1,2$. Let $p\colon G_1\times G_2\rightarrow (G_1/H_1)\times(G_2/H_2)$ be the morphism defined by $p(x_1,x_2)=(p_1(x_1),p_2(x_2))$. Since $p_1$ and $p_2$ are surjective, $p$ is. The kernel of $p$ is $H_1\times H_2$. Therefore, $p$ induces the above isomorphism.
Comment: An idea on how would the proof go?
Comment: you could also think in terms of presentations........
Answer: The last step of your proof follows from the fact that for groups $G_1$ and $G_2$ and normal subgroups $N_1 \subseteq G_1$ and $N_2 \subseteq G_2$ we have that $N_1 \times N_2 \subseteq G_1 \times G_2$ is a normal subgroup with $(G_1 \times G_2)/(N_1 \times N_2) \cong (G_1 / N_1) \times (G_2 / N_2)$.
To see the isomorphism notice that the group epimorphism
$$
\tilde{\varphi} \colon G_1 \times G_2 \to (G_1/N_1) \times (G_2/N_2),
\quad
(g_1,g_2) \mapsto ([g_1],[g_2])
$$
has kernel $N_1 \times N_2$ (which is therefore normal), and thus factors through a group isomorphism
$$
\varphi \colon
(G_1 \times G_2)/(N_1 \times N_2) \to (G_1/N_1) \times (G_2/N_2)
 \quad
[(g_1, g_2)] \to ([g_1],[g_2])
$$

I think that $\operatorname{Ab}(\mathbb{Z}/2 * \mathbb{Z}/3) \cong \mathbb{Z}/2 \oplus \mathbb{Z}/3$ can also nicely be seen by using the universal properties of the appearing objects, leading to a more general result:
If $A_1$ and $A_2$ are abelian groups then $\operatorname{Ab}(A_1 * A_2)$ together with the two maps $i_1 \to \operatorname{Ab}(A_1 * A_2)$, $a_1 \mapsto [a_1]$ and $i_2 \colon A_2 \to \operatorname{Ab}(A_1 * A_2)$, $a_2 \mapsto [a_2]$ satisfies the universal property of the direct sum, i.e. the coproduct in the category of abelian groups:
Given any abelian group $B$ and group homomorphisms $f_1 \colon A_1 \to B$ and $f_2 \colon A_2 \to B$ there exists, by the universal property of the free product, a unique group homorphism $\tilde{g} \colon A_1 * A_2 \to B$ with $\tilde{g} \circ j_1 = f_1$ and $\tilde{g} \circ j_2 = f_2$, where $j_1 \colon A_1 \to A_1 * A_2$ and $j_2 \colon A_2 \to A_1 * A_2$ denote the inclusions into the free product.
Because $B$ is abelian $\tilde{g}$ factors through a unique group homomorphism $g \colon \operatorname{Ab}(A_1 * A_2) \to B$ by the universal property of the abelization. $g$ is the unique group homomorphism $h \colon \operatorname{Ab}(A_1 * A_2) \to B$ with $h \circ i_1 = f_1$ and $h \circ i_2 = f_2$.
This shows that $\operatorname{Ab}(A_1 * A_2)$ together with $i_1$ and $i_2$ satisfies the universal property of the direct sum. As the direct sum is unique up to unique isomorphism there exists a unique isomorphism $\varphi \colon \operatorname{Ab}(A_1 * A_2) \to A_1 \oplus A_2$ with $\varphi \circ i_1 = \iota_1$ and $\varphi \circ i_2 = \iota_2$, where $\iota_1 \colon A_1 \to A_1 \oplus A_2$, $a_1 \mapsto (a_1,0)$ and $\iota_2 \colon A_2 \to A_1 \oplus A_2$, $a_2 \mapsto (0,a_2)$. More explicitely, $\varphi([a_1 a_2]) = (a_1, a_2)$ for all $a_1 \in A_1$, $a_2 \in A_2$.

PS: This tells us that the functor $\operatorname{Ab} \colon \mathbf{Grp} \to \mathbf{Ab}$ is somehow compatible with coproducts, which can probably be formulated in a fancier and more category theoretic way.
Answer: This is most easily proved by abstract nonsense.
There's a forgetful functor $U : \mathbf{Ab} \rightarrow \mathbf{Grp}$. It has a left adjoint $F : \mathbf{Grp} \rightarrow \mathbf{Ab},$ the abelianization functor. Since left-adjoints commute with colimits, we have: $$F(G \sqcup H) = F(G) \sqcup F(H)$$
But an abelian group is just a $\mathbb{Z}$-module. Hence $\mathbf{Ab}$ has biproducts. So:
$$F(G \sqcup H) = F(G) \times F(H)$$


An inductive limit of amenable groups is amenable

Question: It is a Theorem that an inductive Limit of amenable Groups is amenable.
Could someone sketch me a proof of this, or give me a reference? I couldn't find one.
Thanks in advance.
Edit: I wanted it for a directed Limit over a directed poset, not just a totally ordered one.
Comment: The proof is straightforward using the characterization by fixed points.
Answer: This is Theorem 3.4 in A Survey of Amenability Theory for Direct-Limit Groups. If you are interested in arbitrary colimits, see also Theorem 3.3 (3).
Comment: great thanks. and sorry that I used the terminology "inductive Limit" instead of "directed colimit" (as you would prefer, but I use "inductive Limit" only because it is very common).
Comment: Btw I see now that the case presented there is too special.. I have thus edited the question


Getting 'bool(false)' output before normal page HTML

Question: I've seen this happen once or twice before, but can't remember where or why.
Basically, in one of my page's HTML output, the first line of HTML is returned as 'bool(false)' - On that particular page, I have a function in hook_init() that logs in a user using user_login_finalize(). Here's the HTML from the
page:bool(false)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">
<html lang="en" dir="ltr" version="HTML+RDFa 1.1"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
...

On the page as displayed, I get a blank line above my theme's header with this bool(false) appearing.
On refreshes, that goes away (basically, it only happens when I log in a user programmatically using user_login_finalize()).
Answer: It seems that the problem went away if I commented out the user_module_invoke() call inside user_login_finalize().
Obviously, I didn't want to maintain a patch for that, nor did I want to take out that behavior, as I may want to use hook_user_login() sometime. So, I basically copied user_login_finalize() into my own private function, removed the user_module_invoke() call, and am now using the private function for my particular need. Seems to be working fine!
Comment: In this way, you are curing the effects, not the cause. As `user_login_finalize()` doesn't normally create any problem, there must be a third-party module that is the cause of the problem; probably it's a module that implements `hook_user_login()` in the wrong way.


How to compute the pseudoinverse of a rank deficient transform of an SPD matrix in terms of the inverse of the SPD matrix?

Question: Say we have a symmetric positive definite matrix $A\in\mathbb{R}^{n\times n}$ of which we know the inverse $A^{-1}$. We also have a rank deficient matrix $P\in\mathbb{R}^{n\times n}$, and we consider the singular array $A' := P^TAP$. Now, we are interested in the pseudoinverse $A'^+$. Ideally, I would not want to have to compute the pseudoinverse from scratch, but rather use the fact that we know $A^{-1}$. A naive attempt is to distribute the pseudoinverse assuming $(AB)^+ = B^+A^+$ irrespective of $A$ and $B$. By doing so, we get $P^+A^{-1}(P^T)^+$. However, I realized later that the pseudoinverse does not generally distribute, so that $P^+A^{-1}(P^T)^+$ is actually not equal to $A'^+$. So my question is the following, does there exist a way to compute $A'^+$ which makes use of $A^{-1}$?
Answer: The beginning of an attempt: Since $A$ is PSD, we can decompose it as $A = B^T B$, $B$ being invertible. Then $P^T A P = P^T B^T B P = (BP)^T BP$.
Now this satisfies one of the sufficient conditions (let's take $C = (BP)^T$), so
$$
\big[(BP)^T BP\big]^+ = \big[C C^T\big]^+ = (C^+)^T C^+
$$
Will update further as I think about it. This might be the best we can do however.
Edit: By this question, we can maybe compute $(BP)^+$, tbd.


Show that this matrix is positive definite

Question: Consider the set $\{(x,t)\in\mathbb R^n\times\mathbb R\mid t>\|x\|\}$ ad the matrices:
$$
A=(t^2-x^Tx)I+2xx^T,\quad B=-2tx,\quad C=t^2+x^Tx.
$$
Clearly $C\succ 0$ (it is a positive scalar). I need to show that $A-BC^{-1}B^T\succ 0$.
My attempt at a solution has been to substitute the values for $A$, $B$ and $C$ and massage the expression to obtain:
$$
A-BC^{-1}B^T=\underbrace{(t^2-\|x\|^2)}_{>0}\left(I-\frac{2}{t^2+\|x\|^2}xx^T\right).
$$
However it does not look to me like $I-\frac{2}{t^2+\|x\|^2}xx^T$ is positive definite... $I$ certainly is, but $-\frac{2}{t^2+\|x\|^2}xx^T$ is a rank 1 matrix with the eigenvalues $\{-\frac{2}{t^2+\|x\|^2},0\}$ so it is negative semidefinite.
Comment: Have you tried to write down what happens if you check positive semidefinite using the definition?
Answer: We can complete the proof by using the definition of positive definite, as per max_zorn's suggestion. Consider $y\in\mathbb R^n,y\ne 0$. We have:
$$
y^T\left(I-\frac{2}{t^2+\|x\|^2}xx^T\right)y=\frac{t^2\|y\|^2+\|x\|^2\|y\|^2-2\|x^Ty\|^2}{t^2+\|x\|^2}\ge \frac{t^2\|y\|^2+\|x\|^2\|y\|^2-2\|x\|^2\|y\|^2}{t^2+\|x\|^2}>0
$$
where the first inequality is due to Cauchy-Schwarz inequality.


Sampling / Importance Resampling Poisson Weights

Question: Another question from Introducing Monte Carlo Methods with R by Robert and Casella.
Exercise 3.6 basically says the following.  Suppose $f$ and $g$ are densities.  Draw a random sample $X_1, \ldots, X_n \sim g$, then draw $(w_i \mid X_i) \sim Poisson( (f(X_i)/g(X_i) )$ for $i = 1, 2, \ldots, n$.  Also define $X^*_i \mid w_i$ as iid draws from the categorical distribution $(X^*_i \mid w_i) \sim Categorical(\frac{w_1}{\sum_j w_j}, \ldots, \frac{w_n}{\sum_j w_j})$ for all $i$.
Based on the fact (which I've managed to show) that
$$ E_g\Big(w_i h(X_i)\Big)= E_f\Big(h(X_i)\Big),$$
we're supposed to "deduce that this sampling mechanism is marginally distributed from $f$".  In other words, $X^{*}_{i} \sim f$.
I'm stuck.  What I've tried is (pretend there is an $i$ subscript everywhere):
$$
\begin{aligned}
\pi(x^*) &= \int_{-\infty}^{\infty} \sum_{w=0}^{\infty} \pi(x^* , w, x) dx\\
 &= \int_{-\infty}^{\infty} \sum_{w=0}^{\infty} \pi(x)\pi(w \mid x)\pi(x^* \mid w , x) dx \\
&= \int_{-\infty}^{\infty} \sum_{w=0}^{\infty} g(x)\frac{\exp\Big(-\frac{f(x)}{g(x)}\Big) \Big(\frac{f(x)}{g(x)}\Big)^w}{w!}  \frac{w}{\sum_j w_j} dx
\end{aligned}
$$
The sum is zero for $w=0$, so we change the bounds on the sum.  After some manipulation, we get
$$
\begin{aligned}
\pi(x^*) &= \int_{-\infty}^{\infty} \sum_{w=1}^{\infty} f(x)\frac{\exp\Big(-\frac{f(x)}{g(x)}\Big) \Big(\frac{f(x)}{g(x)}\Big)^{(w-1)}}{(w-1)!}  \frac{1}{\sum_j w_j} dx \\
&= \int_{-\infty}^{\infty}  \frac{f(x)}{\sum_j w_j}  \sum_{w=1}^{\infty} \frac{\exp\Big(-\frac{f(x)}{g(x)}\Big) \Big(\frac{f(x)}{g(x)}\Big)^{(w-1)}}{(w-1)!}dx \\
&= \int_{-\infty}^{\infty}  \frac{f(x)}{\sum_j w_j}dx
\end{aligned}
$$
which seems wrong to me.  But I can't tell where I'm going wrong.  Any help would be appreciated!
Comment: Given that this question is about one exercise you want help with, I would suggest you add the `self-study` tag.
Answer: Thank you for the question and sorry for being vague! The way the exercise is set is slightly different though:

Exercise 3.6. Given an importance sample $(X_i,f(X_i)/g(X_i))$, show that if
  $\omega_i$ has a Poisson distribution
  $\omega_i\sim\mathcal{P}(f(X_i)/g(X_i))$, the estimator $$
  \frac{1}{n}\sum_{i=1}^n \omega_i h(x_i) $$ is unbiased. Deduce that
  the sample derived by this sampling mechanism is marginally
  distributed from $f$.

The first part of the question is about
$$\mathbb{E}_g\Big(w_i h(X_i)\Big)= \mathbb{E}_f\Big(h(X_i)\Big)$$ as you gather. The second and vaguer part means that, if one takes the sample
$$(\underbrace{X_1,\ldots,X_1}_\text{$\omega_1$ times},\ldots,\underbrace{X_n,\ldots,X_n}_\text{$\omega_n$ times})$$
then it behaves like a sample from $f$. Almost because
$$\sum_{i=1}^n \omega_i \ne n$$ for most realisations,


I am confused about double trigger trombone notes

Question: For bass trombone, I'm new with two triggers, and I was confused about the positions between low E and pedal Bb, and the notes below pedal Bb. Are they the same as with one trigger, or are there alternative positions?
Answer: The first trigger is pretty standard, it adds in enough tubing to lower the pitch by a perfect 4th, the equivalent of extending the slide from 1st to 6th position.  You get a trombone 'in B♭/F'.
The second trigger is less standard.  It may be additive to the first, adding a relatively short extra length of tubing.  So you get an instrument 'in B♭/F/E♭'.    Or it may be independent, typically adding rather less extra tubing than the F trigger, enough to put the instrument 'in G♭'. Overall you get an instrument 'in B♭/F/G♭/D'.
The 'additive' second trigger gives a lighter instrument.  The 'independent' one allows some extra low notes.
Look at the choice of double--trigger bass trombone here:
https://www.musicarts.com/double-trigger-bass-trombones
But don't get frightened!  It doesn't give you three new instruments to learn!  You still read the same music, basically play the same positions.  It's just that in the extreme low range you get some additional options regarding where to put the slide/use the triggers when filling in the range down to pedal B♭, and maybe the choice of playing a few notes down from B♭ as 'normal' rather than 'pedal' notes.
To answer your direct question, no, positions for low E down to pedal B♭ won't be the same as with just one trigger.  Just as you learned some 'long' positions for use with the single trigger, you'll be learning some even 'longer' ones for use with both.   But don't worry.  There's only a few notes down there.  Each one (or most of them) can be played with one trigger and the slide THERE, or both and the slide THERE.  Learn where THERE is for each instance.  It's not hard.
(And it's like every note on the trombone, really.  The right place for the slide is where THAT note is in tune.  Not necessarily where you put a chalk mark labelled '5th position' :-)
Answer: If you have just one trigger it takes the trombone down a fourth to F.
If you have two triggers the first one does exactly the same (down a fourth) so you still have all those positions. Plus you have all the positions the second trigger adds.
You'd play the notes below low B-flat down to G-flat with no trigger, so those positions stay the same.
Comment: Sort of.  With the slide in 1st position, the single trigger takes you down a  perfect 4th.   With the slide in 4th position, it takes you down rather less, which is why we have to use 'long' positions with the trigger.


Calculus use formal definition of limit to verify the indicated limit

Question: I want to verify the following limit using the definition of a limit:
$$\lim_{x \to 1} \sqrt{x} = 1$$
I know that:
$$0<∣x-1∣<\delta
\qquad\text{and}\qquad
∣\sqrt{x}-1∣<\varepsilon,$$
but then I do not have a clue on how to move on.
Comment: Hint : $$\sqrt{x}-1=\frac{x-1}{\sqrt{x}+1}$$
Comment: Are you sure that $|\sqrt{x}-1| < \varepsilon$?  Or is this the inequality that you are trying to prove holds?  Do you understand the *definition* of a limit?  Or does your confusion lie elsewhere?
Comment: I am starting to understand most of it, however I do not understand how √−1 can become (x−1/(√x+1), how is the math done here?
Comment: @JavaProgrammer The third binomial formula shows $$(\sqrt{x}-1)(\sqrt{x}+1)=(\sqrt{x})^2-1=x-1$$ Divide by $\sqrt{x}+1$ to get my equation
Comment: https://math.stackexchange.com/questions/450410/epsilon-delta-proof-that-lim-x-to-1-sqrtx-1?rq=1
Answer: Since $x-1=\sqrt x^2-1^2=\bigl(\sqrt x+1\bigr)\bigl(\sqrt x-1\bigr)$, and since $\sqrt x+1>1$ when $x>0$, if you take any $\varepsilon>0$ and if you choose $\delta>0$ such that $\delta\leqslant\varepsilon$ and that $\delta\leqslant1$, then$$|x-1|<\delta\iff\bigl(\sqrt x+1\bigr)\bigl\lvert\sqrt x-1\bigr\rvert<\delta\implies\bigl\lvert\sqrt x-1\bigr\rvert<\delta\leqslant\varepsilon.$$
Answer: $∣\sqrt{x}-1∣<\varepsilon$ means $\sqrt{x}-1<\varepsilon\land \sqrt{x}-1>-\varepsilon$
That is, for $0<\varepsilon\leq 1$
$\sqrt x < \varepsilon+1$ or $x < \varepsilon^2+2\varepsilon+1$ and
$\sqrt x > 1 -\varepsilon$ or $0<\varepsilon\leq 1 \land x>1-2\varepsilon+\varepsilon^2$
Thus we have $1-2\varepsilon+\varepsilon^2<x < \varepsilon^2+2\varepsilon+1$
which can be written as
$\varepsilon^2-2\varepsilon<x-1 < \varepsilon^2+2\varepsilon$
so taking $\delta=|\varepsilon^2-2\varepsilon|$
we are sure that if $|x-1|<\delta$ then $|\sqrt x -1| < \varepsilon$
For instance if $\varepsilon=0.001$ taking $\delta=|10^{-6}- 2 \times 10^{-3}|\approx 0.002$
if $|x-1|<0.002$ let's say $x=0.999$ then $|\sqrt x-1|\approx 0.0005<\varepsilon$


How can i get my query execution time in logging

Question: I want to know query execution time so i follow this answer
   <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="persistenceYous" />
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="persistence" />
      <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />

   </bean>

 <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generate_statistics" value="true" />
</bean>

but i got this error
Caused by: org.springframework.beans.NotWritablePropertyException:
Invalid property 'generate_statistics' of bean class [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter]:
Bean property 'generate_statistics' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?

Answer: Have you tried to write the property into the persistence.xml instead? (This is only a guess)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                       http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit ...>
    ...
    <properties>
        ...
        <property name="hibernate.generate_statistics" value="true" />
    </properties>
    ...
</persistence-unit>

without persistence.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
   ...
   <property name="jpaVendorAdapter" .../>
   <property name="jpaPropertyMap">
      <map>
        <entry key="hibernate.generate_statistics" value="true"/>
      </map>
   </property>
</bean>

Comment: Thats up to you - a seperate file would spread the information about different places/files, but if this are a lot of properties, then this is often better to have them in different files instead of in one.
Comment: I don't use a `persistence.xml` , i have to ?
Comment: I use directly ``
Comment: persistence.xml is only one way to set the generic properties, but I would give it a try
Comment: @Youssef: I added an example of how to set the properites without persistence.xml
Comment: thanks it work now but would be better if i use a separate file ?


Como pegar uma resposta que está no header da requisição

Question: Estou fazendo um site que contem um fórum e preciso pegar a quantidade de tópicos e usuários cadastrados e com isso em meu back-end eu envio essas quantidades pelo header. Estou usando no meu back-end Cors, Express, Knex, Nodemailer, SQLite3.
async listAll(request, response){
    const { page = 1 } = request.query;
    const [count_topics] = await connection('topics')
    .count();
    const [count_users] = await connection('users')
    .count();
    const topics = await connection('topics')
    .join('users', 'users.id_user', '=', 'topics.user_id')
    .orderBy('id_topic', 'desc')
    .limit(3)
    .offset((page - 1) * 3)
    .select(['topics.id_topic', 'topics.title', 'topics.description', 'topics.date_topic', 'users.user']);
    const recent_topics = await connection('topics')
    .join('users', 'users.id_user', '=', 'topics.user_id')
    .orderBy('id_topic', 'desc')
    .limit(7)
    .offset((page - 1) * 7)
    .select(['topics.id_topic', 'topics.title', 'topics.date_topic', 'users.user']);
    response.header('X-Total-Count-Topics', count_topics['count(*)']); //aqui estou enviando a quantidade de tópicos pelo header
    response.header('X-Total-Count-Users', count_users['count(*)']); //aqui estou enviando a quantidade de usuarios cadastrados pelo header
    const send = {topics, recent_topics};
    return response.json(send);
}

E essas informações estão no cabeçalho conforme eu inseri.

Aqui está meu front-end feito em React onde eu tento pegar as informações que estão no header. Estou usando no meu front-end Axios, html-react-parser, react-router-dom, react-scripts, sweetalert2.
const [topics, setTopics] = useState([]);
const [recentTopics, setRecentTopics] = useState([]);
const [totalTopics, setTotalTopics] = useState(0);
const [totalUsers, setTotalUsers] = useState(0);
async function loadTopics() {
    const response = await api.get('/topics');
    setTopics(response.data.topics);
    setRecentTopics(response.data.recent_topics);
    setTotalTopics(response.headers['X-Total-Count-Topics']); //eu tentei pegar desse jeito mas aparece undefined
    setTotalUsers(response.headers['X-Total-Count-Users']); //eu tentei pegar desse jeito mas aparece undefined
}
useEffect(() => {
    loadTopics();
}, []);

Quando quando eu uso o que armazenei na state basicamente não aparece a quantidade de usuários e tópicos que está no cabeçalho, já coloquei um console.log() e ele aparece undefined.

Queria saber como é que eu pego esses dados que enviei para meu header para eu poder dar continuação em meu projeto.
Comment: Irei dar uma olhada mais tarde, mas você não pode passar essa informação no json do backend e recuperar ela no front? se puder e não souber como fazer é só falar que tento fazer um exemplo simples em código e ti mostro
Comment: da um console.log(response.headers) e console.log(response.data) e vê oque aparece se não estiver essas informações lá você esta tentando acessar da maneira errada, e fala oque esta aparecendo em Preview e Response
Answer: Quanto aos headers deixa assim:
setTotalTopics(response.headers['x-total-count-topics']);
setTotalUsers(response.headers['x-total-count-users']);

Quanto aos outros dados leia meu comentário e post, precisamos de mais informações.
Answer: Tenha em mente que para receber os headers ja deve ter a response, e ler eles como chaves no array, logo eles estarão lower case, ficaria assim:
response.headers['x-total-count-topics'] //4
response.headers['x-total-count-users'] //2

para ficar de melhor entendimento, basta usar o
console.log(response.headers['x-total-count-topics'])
console.log(response.headers['x-total-count-users'])

Na documentação abaixo está explicito que é necessario acessar os header com lower case
https://axios-http.com/docs/res_schema


There is an island and 20 houses at the beach around the island, each house with 20 wrestlers.

Question: There is an island and 20 houses at the beach around the island, each house with 20 wrestlers. Each wrestler fights with all wrestlers from other houses. There is no two wrestlers with the same power and the stronger wrestler always win. We say that house $A$ is stronger than house $B$ if there is $k$ fights in which fighters from house $A$ wins. What is a maximum $k$ if we know that each house is stronger than the neighboring house in the direction of the clock movement?
I was trying to solve this was but in the end I gave up and I read an official solution. I was very unsatisfied how it was solved, because they never say how they find this $k_{\max}$, just proved it is ok. Perhaps someone will have a different aproach here.
Here is an offical solution: http://natjecanja.math.hr/wp-content/uploads/2015/02/2012_izborno-rjesenja.pdf
Appeared:

Serbia and Montenegro preparation test for IMO $2006$;
III International Festival of Young Mathematicians Sozopol $2012$;
Croatia TST for IMO $2015$;
Swiss TST for IMO $2018$.
Comment: It looks like a nice generalization of the concept of non-transitive dice - https://en.wikipedia.org/wiki/Nontransitive_dice
Comment: I suppose you meant "We say that house $A$ is stronger than house $B$ if there are $k$ fights in which fighters from house $A$ win against fighters from house $B$". Is that correct?
Comment: If $k\leq 200$ then it is possible for $A$ to be stronger than $B$ and at the same time $B$ to be stronger than $A$. This means that for any of those lower values of $k$, we can create the clockwise arrangement by simply having every house be stronger than both of its neighbors. Therefore the maximum $k$ is greater than $200$. If $k=400$ then "stronger than" is transitive and it is certainly impossible.
Answer: Too long for a comment.
I don't understand why you are unsatisfied with the official solution. I am for a quarter of a century in math competitions and may assure you that this is a typical solution of (such) a competition problem. It is short, simple and clear. Also it is correct. I provide its English translation for not easy reading Slavic languages people.

The required number is $k = 290$. Let's first show that $k>290$ is impossible. In every house
  we rank the wrestlers with respect to their strength (from $1$ to $20$) and choose a wrestler who is tenth by strength in each house. Let the weakest among the chosen wrestlers live in the house $A$. Then in
  every other house $B$ (and, in particular, in the house neighbor to house $A$) there are at least $10$ wrestlers
  (from 1st to 10th strength rank) who beat at least $11$ wrestlers (from 10th to 20th strength rank)
  from $A$. So the number of fights in which the wrestlers from $A$ beat wrestlers from its neighbor house  is at most $20\cdot 20 – 10\cdot 11 = 290$, which is a contradiction with the assumption that house $A$ is stronger than its neighbor.
An example that shows that for $k = 290$ the cyclic house strength order is possible can be constructed as
  follows. Rank all $400$ wrestlers from the weakest to the strongest, and we mark
  $210$ weaker (for $1$ to $210$) and $190$ stronger wrestlers (from $211$ to $400$). For each $i = 1, \dots, 20$, let's
  in the house $A_i$ live $i$ weaker and $20-i$ and stronger wrestlers. More precisely, in $A_1$ live wrestlers with ranks $1$ and from $211$ to $229$, in $A_2$ live wrestlers with ranks $2$, $3$ and form $230$ to $247$ etc.
Let us show that the house $A_i$ is stronger than the house $A_{i-1}$ for each $i = 2,\dots 20$. All the weaker wrestlers from $A_i$ beat the weaker wrestlers from $A_{i-1}$, and all the stronger wrestlers from $A_i$ beat all wrestlers from $A_{i-1}$. The number the fights in which the wrestlers from the house $A_i$ win is $i(i-1) + (20-i)20 = i^2-21i + 400$. This number is the smallest when $i = 10$ or $i = 11$ and then it is exactly 290. In addition, $19$  stronger wrestlers from the house $A_1$ beat all the wrestlers from the house $A_{20}$, so there were $20\cdot 19 = 380>290$ victories and the house $A_1$ is stronger than the house $A_{20}$, which proves the claim.
Comment: @JohnWatson I do agree with you, this expectation of coming up with solutions by "divine inspiration" is one of the things that turned me off math contests in school in favour of physics. But this one's not that bad. I started looking at 3 houses, 3 wrestlers each, and that gave me the idea of how to construct the example which shows some $k$ works. I think you could get to 290 then by seeing how far you can push that construction. For me it turned out trickier to prove that 291 can't be done some other way - now that I read this solution, I'm embarrassed by the simplicity of that part.
Comment: Well there is not explained how did they get this 290. They just prove that 290 is OK but there is no methodological way to find this number. So, my question is how would someone find this 290.
Comment: @JohnWatson I also don't see a clear way to this number. I guess that both participants and jury of IMO selection have a common belief that the first should be sufficiently smart to find lower and upper bounds which are good up to coincidence. :-)
Comment: Even when you were writing this comment I have encountered the same problem with an [other contest math bounty question](https://math.stackexchange.com/questions/2474654/find-the-least-of-the-lambda-such-this-inequality-hold), about which OP have told  "I have heard my country's there are no people who solved this problem". :-) Let's wait what other MSE members will say.


A collection/Data Structure which prevents deletion and allows insertion and read only functionality

Question: I want your help for creating a data structure/ Collection which supports read and insert functionality and prevents deletion/removal of records.
One way i could think of is , to create a customized collection ( like myHashMap ) and override all the delete/remove methods and thus prevent removal/deletion of records? But this approach will not work if the Object is having removal method as Final.
Please suggest any better way ..!!!!
Comment: Prefer composition over inheritance. Create a class that `implements Map` and _wraps_ a fully mutable `Map`. Then just delegate the calls you allow and not the ones you do not. Incidentally, this is exactly how `Collections.unmodifiableMap` works.
Answer: You can create your own arraylist by overriding the methods like remove() with unsupported operation exception. If you want you can also declare arraylist like this.
ArrayList<String> myList = new ArrayList<String>() {

    @Override
    public boolean remove(String str) {
      //If you want, you can throw Unsupported operation exception also.
      return false;
    }
  };

There may be some other good approaches, you can check answers from others also.
Comment: Thanks. But as I mentioned in the question I thought the same thing. But , what if the remove method is marked as Final !!! Let's say I want to use HashMap and delete method is marked as final .. in that case this approach will fail.
I wanted to know if there is any better approach.
Comment: This is only for list type structure. If you want, you can create your map by extending the AbstractMap or HashMap and throw the exception. You can see the code for HashMap. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/HashMap.java
Answer: You can create your Map wrapper and provide only the methods you want to :
class MyHashMap<K, V>  {

    Map<K, V> map;

    public MyHashMap(Map<K, V> map) {
        this.map = map;
    }

    public V put(K key, V value) {
        return map.put(key, value);
    }

    public V get(K key) {
        return map.get(key);
    }

    // other methods you want
}

example:
MyHashMap<String, String> myMap = new MyHashMap<>(new HashMap<>());


Polynom irreducibility over $\mathbb Z_5$

Question: So, I have polynom over $\mathbb Z_5$: $x^8 - x^7 + 2x^6 + x^5 + 2x^4 + 2x^2 +3x +1$  and I have to find his irreducibile factors. How to do that? I can find his roots by replacing $x$ with $[1]_5, [2]_5, \dots $ and so on. What step is the next one?
Answer: Because $\mathbb{Z}_5$ is a field, an element $r \in \mathbb{Z}_5$ is a root of your polynomial $p$ if and only if $x-r$ is a factor of $p$.  So one way to attack this problem is to test each element of $\mathbb{Z}_5$ one at a time to see if it is a root; if it is, use polynomial long division (or synthetic division -- both algorithms work over $\mathbb{Z}_5$ exactly the same way that they do over $\mathbb{R}$) to write $p$ in the form $(x-r)q$, and then iterate the procedure by testing for the roots of $q$.  Eventually you will get down to a polynomial that has no roots; at that point the process terminates.
Comment: You should add after "this process terminates": **and the real work begins**.
Comment: Exactly how does it depend on fact that $\mathbb Z_5$ is a field?
Comment: @DarkArchon The fact that $Z_5$ is a field implies that it has no $0$ divisors.
Comment: You misuderstood me. How does the fact that $r$ is root of polynomial if and only if $x−r$ is a factor of $p$ depends on a fact that $\mathbb Z_5$ is a field?
Comment: @MarcvanLeeuwen -- Yes indeed, but in this case it just so happens that after factoring out all linear factors, all that is left is an irreducible quadratic.  So there isn't very much "real work" to do.
Comment: @DarkArchon, I should clarify:  Even if $R$ is not a field, it is still true that $r$ is a root of polynomial $p$ if and only if $x-r$ is a factor of $p$.  This is because the Euclidean algorithm works over any ring, as long as the divisor is monic.  In this case, the relevance of the statement that $\mathbb{Z}_5$ is a field lies in the fact that if it were not a field, we would not have unique factorization, and therefore the process outlined above produces (at best) *one* representation of the polynomial as a product of irreducible factors; potentially there could be others.
Comment: For example, working over $\mathbb{Z}_{12}$, applying this process to the polynomial $x^2-1$ could lead to the factorization $(x-1)(x-11)$, completely missing the fact that $x-5$ and $x-7$ are *also* irreducible factors.
Answer: You could start finding all roots in $\Bbb F_5$, which give degree $1$ (irreducible) factors. Don't forget to try again after Euclidean division by $X-a$ after finding a root $a$, since it might be a multiple root. After than it depends on what degree is left. If it is $3$ or less you are done, because such polynomials cannot be reducible without having a root; otherwise you must also consider the possibility of a decomposition without linear factors. If the remaining degree is at most$~5$ it might be worth while to look for roots in $\Bbb F_{25}\setminus\Bbb F_5$ in order to locate degree $2$ irreducible factors. If there is no easy way out, there is [Berlekamp's algorithm][1], which I described in [this answer][2].
It turns out you are extremely lucky here, with a total of $6$ linear factors, leaving a polynomial of degree$~2$ without roots, which is obviously irreducible. Ask for a more interesting example next time!


Markov chain periodicity

Question: Can a Markov chain have 5 states, one open and one
closed class and all the states be periodic (e.g. period 2)?
I tried the following: https://www.dropbox.com/s/v818oqlizaci23m/Untitled.png?dl=0
but I have doubts for the transient state. If it will move from the left part to the right side, then it will never come back, meaning that the class on the left is not periodic. Is this a possible MC at all?
Answer: The chain you drew is a correct example of what you were trying to do. In the second paragraph of the question, you seem to be working with a wrong idea of periodicity. Periodicity in the context of Markov chains does not refer to periodicity of the occupation probabilities of the states as a function of time (which is, as you rightly point out, not given due to the "leakage" from the open to the closed class). It requires not that the process always return to the same state after the period, only that if it does return, this can only occur after the period or a multiple thereof, which is the case in your example.
Answer: Assume we have the following image.

Firstly, yes, it can represent a graph of a Markov Chain.
We have the 2 communicating classes $A = \{1,2,3\}$ and $B=\{4,5\}$. All states in $A$ are transitive, while all states in $B$ are positive recurrent.
Also, it is true that all the states that belong to the same class have the same period. Clearly, the period of the class $A$ is $d_A = 2$ and the period of class $B$ is $d_B=2$. It is totally accidental that the two classes have the same period.

Markov chain periodicity


How to disable one specific translation page?

Question: How can I disable only one page in English on a Drupal 7 site, without disabling the Danish page?
I'm using Multilingual - Internationalization module.
Comment: Can't you just create a Danish version and not create an English version?
Comment: Ahh just figured it out myself, just went into the menu item, and disabled the node translation for that menu item, and the page only shows up on the danish site. But thanks anyway.
Comment: No problem, if you could summarise that in an answer that would be great!
Answer: Since translations in D7 are new nodes, you can simply Unpublish the English node, while keeping the Danish one Published.


Redirect to login page when click the tab

Question: I'm very new in ASP.Net Core.
Let say I have three tabs such as Home, contact and about.
The user can only access contact and about page if they are login. Otherwise, they cannot access the page. My question is, if the user is not login yet, how to redirect to the login page if they click the Contact or about tab?
Comment: When you click on the tab, is it a normal GET request to those action methods ? If yes you can check it there and redirect the user using the standard pattern.
Comment: You could decorate your controller or action with the `Authorize` attribute. https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple
Answer: Before you go into the answer, it might be to your benefit to read through the great documentation available at the official Microsoft Docs.
As a simple solution, I would suggest you add authorization by using the AuthorizeAttribute.
If your project is using MVC
public class HomeController : Controller
{
    public ActionResult Index()
    {
    }

    [Authorize]
    public ActionResult About()
    {
    }

    [Authorize]
    public ActionResult Contact()
    {
    }
}

Alternatively, if your project is using RazorPages
[Authorize]
public class AboutModel : PageModel
{
    ...
}

Comment: If you want to go further in-depth with authorization for RazorPages you can see my other answer for a similar question here https://stackoverflow.com/a/46881927/3645638


store json object to azure table storage entity using azure data factory pipeline

Question: I've created one azure data factory pipeline. By which, I need to store my JSON file content as string from my blob storage JSON file to azure table storage entity.
I tried with copy activity where the source is my blob storage JSON file and destination is my azure table storage's table where I need to store that.
Finally, I need the content of my JSON file to an entity of table storage as below.
Answer: You can copy data from a blob storage JSON file to Azure table by having the source and the sink in the copy activity.
In the mapping tab of the copy activity, you can define the mapping between the attributes of the JSON file and the table as shown below :
Comment: But in above situation, I can not store 'data' json with all data(id, email...) in single column. As you defined above, which will map to different column of an entity.
Comment: That is correct Manish. You can map an attribute to a column in the table. If you wish to store the entire JSON response in a field, you can have a web activity to get the JSON response and store it in a blob file and then copy it using a copy activity with the required mapping.
Comment: i have done it, but still the array column does not land into the storage table :(


In survival analysis, when should we use fully parametric models over semi-parametric ones?

Question: This question is the counterpoint of the other question In survival analysis, why do we use semi-parametric models (Cox proportional hazards) instead of fully parametric models?
Indeed, it clearly demonstrates the advantages of Cox Proportional Hazards regression over fully parametric ones, without assumption on the distribution of the survival time.
Still, there are some recent R packages (SmoothHazard(2017) for instance, function shr with method="Weib") which makes it possible to easily fit fully parametric models.
I happen to have had the opportunity to perform both on a 50k dataset, with very similar results.
What benefits are expected from a fully parametric survival model? What additional analyzes would it allow?
Answer: This has been studied in detail for many years and there is a large literature.  I really like spline hazard models.  The simplest answer to your question is this:

If you want to estimate covariate effects, especially in the absence of time-dependent covariates, then semiparametric models such as the Cox proportional hazards model are usually preferred because they are fast, robust, and Y-transformation invariant
Flexible parametric models are a little more efficient for estimating absolute quantities such as survival curves
Parametric models provide a formula that makes prediction easier
If you can integrate the hazard function analytically when time-dependent covariates are present, parametric models provide faster prediction and more intuition
Parametric models can extrapolate (but beware) to yield survival estimates beyond the last follow-up time, and to estimate expected (mean) survival time

In summary I'd say the main reason to like parametric survival models is not efficiency, but rather ease of interpretation and of obtaining predictions for future observations.
See this paper for example.
Comment: Great answer thanks. I've been wondering about the spline hazard model, the `SmoothHazard` package's `shr` vignette says that it can use a "linear combination of M-splines", which would thus be semi-parametric but makes no assumption on the hazard functional form. The paper you linked is about RCS, does it make such assumption ?
Answer: When you know the actual functional form of the hazard function, the fully parametric survival model is far more efficient than the Cox model. Statistical efficiency is like power. A good way to think of it is the width of the confidence interval for your final estimate of the log-hazard ratios: a tight CI is the result of an efficient analysis (assuming you have an unbiased estimator).
Exponential and Weibull survival models are indeed popular examples of "known" hazard functions (constant and linear in time respectively). But you could have any old baseline hazard function $\lambda(t)$, and calculate the expected survival at any time for any combination of covariates given a parameter estimate $\theta$ as:
$$S(\theta, t) = \exp(\Lambda(t)\exp(\theta \mathbf{X}))$$
where $\Lambda(t)$ is the cumulative hazard. An iterative EM-type solver would lead to maximum likelihood estimates of $\theta$.
It is a neat fact that, assuming a constant hazard, the relatively efficiency of the Cox model to the Weibull model to the Exponential fully parametric survival model is 3:2:1. That is, when the data are actually exponential, it will take 9 times as many observations under a Cox model to produce a confidence interval for the effect estimate, $\theta$ with an equal expected half-width as that of the exponential survival model. You must use what you know when you know it, but never assume wrongly.
Comment: @DanChaltiel it's a paradox if ever there was one. Prior research or heuristic models could be used to support the idea. For instance, emission of radioactive isotopes have independent interarrival times. Some diagnostics like plots of studentized residuals vs. event time could be used to see if the (fully parametric) model is appropriate. Estimating the hazard with a kernal smoother speaks to fharrel's answer though I suspect the flexibility/generalizatbility tradeoff leads to results asymptotically consistent with Cox models at their most flexible.
Comment: Great answer thanks. But how could someone *know* the hazard function's functional form?
Comment: In calculations I did a long time ago the efficiency of parametric models is not nearly as great as @AdamO found, when estimating survival probabilities.  In terms of estimating hazard ratios, the Cox model is exactly as efficient as the simple exponential model.
Comment: Example: if you look at confidence intervals for the empirical cumulative distribution function without censoring, they are about the same width as you get from estimating 3-4 parameters of a specific parametric distribution.
Comment: @FrankHarrell: probably not surprisingly, I think the relative efficiency of the Cox PH vs a parametric model for survival probabilities is highly sensitive to both the distribution of the censoring and which quantile you are estimating. As a really extreme case, suppose you have some data that is right censored and the last inspection time is beyond the last event time. Then tail of the semi-parametric model is non-identifiable, while the parameteric model (for better or worse) is!
Comment: Yes but I was referring to the time interval that is well supported by the data, for both nonparametric and parametric approaches.
Answer: I've spent a lot of time working with the general case of interval censoring, i.e., when the event time may be known exactly, right or left censored or only known up to an interval. For example, suppose a part is inspected and passed at $T_1$ and then inspected again at $T_2$ and failed. Then all we know is that it failed in the interval $(T_1, T_2]$.
In the interval censored case, while we can use bootstrap + asymptotic normality to make inference about the regression coefficients, this is not the case for the baseline survival curve itself. Thus, if one wants to make inference about actual survival times and not just hazard ratios, one needs to use the fully parametric model. As such, the semi-parametric model is often used more to check model fit rather than for full inference in regards to survival times.
Of course, this is not the case for right censored data. I would guess that the confidence intervals for the survival estimates are a bit tighter for a fully parametric model, although I have not tested that. In fact, see @AdamO's answer for more on that.
As another point, the AFT model does not have a semi-parametric model (in the sense of a Kaplan-Meier-like baseline distribution), even for right censored or uncensored data. Or more specifically, the model is very difficult to optimize. The reason for this is that you can think of the AFT model as rescaling the times, compared to the proportional hazards or odds models, which rescale the survival probabilities. The issue with this is that in a semi-parametric model, the only way in which event or censoring times affects the likelihood is the relative rank. Small enough movements of the event times will not change the ranks at all (assuming no ties in the data), meaning the derivatives are all zero without ties. And when there are ties, the derivatives are unbounded! Not a very fun optimization problem. Given that the AFT model is more resilient to missing covariates and more interpretable, there's a strong argument to use AFT, even though there is no semi-parametric model.
One more reason to favor parametric models over semi-parametric is that they can be easier to generalize. For example, if one wants to perform a Bayesian analysis, it's much easier with a parametric model. Or if one wants to build a cure-rate model, this is non-identifiable for a semi-parametric model, but is identifiable for a parametric model.


Delaying form submission via Javascript doesn't work in IE

Question: I have a form built for creating an instance of a custom entity. Upon submitting the form, I have a jquery script completing some actions on the page that need to execute before the form submits, so I attempt to stop the default event, perform those actions, and then resume the event as follows:
$('#submit').on('click', function(event){
    if (valid === true) {
        valid = false;
        return;
    }
    event.preventDefault();
    valid = true;
    //do some stuff
    $(this).trigger('click');
});

This works perfectly in Chrome, but unsurprisingly does not work in IE11. Through console logging I see that the re-click is fired, but the return line  simply does nothing, so the button click does not submit the form at all. I have tried some alternatives to $(this).trigger('click'); explained in a stackoverflow thread, but nothing is getting it to work.
The reason I'm creating a Drupal-specific thread about it is that I also tried  to skip re-firing entirely and just do a form submission like this:
$('#submit').on('click', function(event){
    event.preventDefault();
    //do some stuff
    $('form[data-drupal-selector="my-form-id"]').submit();
});

But this, for whatever reason, clears all of the data in any field collection items contained within the form.
Is there any feasible way to do what I'm trying to accomplish in Drupal that works in all modern browsers?
Comment: `if (valid === true) {  valid = false;` I don't get this part of your code. Why are you making valid = false when it's true?
Comment: @NoSssweat I left out a line above the function where valid is preset to false. When false it stops the default event and executes the form actions and fires itself again, and the "valid" flag makes it know not to do all that a second time and just continue with submission.
Answer: Try doing something like:
 $("form").submit( function () {
   //do something
   return true;
 }

Source
Comment: Thanks, this seemed to work. My field collection items retained their contents when I used this.


Find all functions $f∶ \Bbb R \to \Bbb R$ such that, for all $n \in \Bbb N, \left[\frac{{f(x+n) - f(x-n)}}{{2n}} = f'(x)\right]$

Question: There was a similar question in the Putnam ($2010$ A$2$) but I can't wrap my head around this one. I've tried attacking it in some standard ways of eliminating arbitrary functions but it doesn't seem to be an easy manipulation. Also noticed that this is the expression for the average rate change of a differentiable function in the interval $[x-n,x+n]$ but again don't know how I can use that information. Linear and quadratic functions seem to fit the bill but how do you find the other ones or prove that these are the only kinds?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Certainly, functions of the form $f(x) = ax+b$ meet the criteria.  The harder part would be to prove that only functions of the form $f(x) = ax+b$ will work.
Comment: Presumably you mean for all real numbers $x$ and for all integers $n$, ...
Comment: Could you please share more information like your thoughts and ideas behind the DDE so that we can really help you, not just solve the task and the question meets the quality standards for Math.SE.
Comment: @fredgoodman Putting zero for $n$ would give a zero denominator. And negative $n$ would not add anything since the statement is symmetric around $0$ in $n.$ I agree about the for all real $x.$
Answer: Start with $$f'(x) = \frac12 \Big(f(x+1)-f(x-1)\Big).$$
As $f$ is differentiable, it follows that $\frac12 (f(x+1)-f(x-1))$ is differentiable, so $f'$ is differentiable.  Let's differentiate it!
$$\begin{align*}
f''(x) &= \frac12 \Big(f'(x+1)-f'(x-1)\Big) \\
&= \frac12 \left(\frac12\Big(f(x+2)-f(x)\Big) - \frac12\Big(f(x)-f(x-2)\Big)\right) \\
&= \frac14\Big(f(x+2)-2f(x)+f(x-2)\Big).
\end{align*}$$
Once again, we note that since $f$ is differentiable, the expression on the right side of this equation is differentiable, so $f''$ is differentiable.  Differentiating again yields
$$\begin{align*}
f'''(x) &= \frac14\Big(f'(x+2)-2f'(x)+f'(x-2)\Big) \\
 &= \frac14\left(\frac12\Big(f(x+3)-f(x+1)\Big) - \frac22\Big(f(x+1)-f(x-1)\Big) + \frac12\Big(f(x-1)-f(x-3)\Big)\right) \\
&= \frac18\Big(f(x+3)-3f(x+1) + 3f(x-1)-f(x-3)\Big) \\
&= \frac18\Big(\big(f(x+3)-f(x-3)\big) - 3\big(f(x+1)-f(x-1)\big)\Big) \\
&= \frac18(6f'(x)-6f'(x)) = 0.
\end{align*}$$

In particular, this shows that if $f$ is differentiable and $$f'(x) = \frac{f(x+n)-f(x-n)}{2n}$$ for every real $x$ and for $n \in \{1,3\},$ then $f$ is thrice-differentiable and $f'''(x) = 0$.
By integrating (or equivalently, applying the mean value theorem to the derivatives of $f(x)-f(0)-f'(0)x-\frac12f''(0)x^2$), we see that $f(x) = ax^2 + bx + c$.
To finish, it suffices to check that every quadratic function satisfies the given condition for any natural number $n$.
Comment: @4plus4man If $f$ is differentiable, then so is $\frac12 (f(x+1)-f(x-1))$ (and we know what its derivative looks like) .  Inductively, it follows that $f$ is differentiable of every order.
Comment: I guess it also assumes that the function $f$ is at least thrice-differentiable on $\mathbb{R}$, though perhaps this can be weakened to just assuming $f$ is once-differentiable using a density argument.
Answer: Continuing the answer from Brian Moehring, we have $f'''(x) = 0$. Assuming $f(x)$ has a convergent Taylor series at $x$, we have,
$$f(x) = a+bx+cx^2$$
$$f'(x) = b+2cx$$
$$f(x+n)-f(x-n) = b2n + c((x+n)^2-(x-n)^2) = b2n + c(4nx)$$
Hence $\frac{f(x+n)-f(x-n)}{2n} = b+2cx = f'(x)$.
So any function of the form $f(x) = a + bx + cx^2$ will work.
Comment: Note that $f'''(x)=0$ is strictly stronger than having a convergent Taylor series.  As long as the domain is an interval, the mean value theorem (or equivalently, standard integration techniques) suffices to show $f$ is quadratic.


Use Ipython-sql with snowflake and externalbrowser authenticator

Question: in my jupyter notebook I connect to snowflake with an externalbrowser auth like so:
conn = snowflake.connector.connect(
user='<my user>',
authenticator='externalbrowser',
account='<my account>',
warehouse='<the warehouse>')

this opens an external browser to auth and after that works fine with pandas read sql:
pd.read_sql('', conn)

want to use it with ipython sql, but when I try:
%sql snowflake://email@example.com

I get:
snowflake.connector.errors.ProgrammingError) Password is empty

well I don't have one :)
any ideas how to pass this?
Answer: IPython-sql connection strings are SQLAlchemy URL standard, therefore you can do the following:
%load_ext sql
from sqlalchemy import create_engine
from snowflake.sqlalchemy import URL

engine = create_engine(URL(
    account = '<account>',
    user = '<user>',
    database = 'testdb',
    schema = 'public',
    warehouse = '<wh>',
    role='public',
    authenticator='externalbrowser'
))
connection = engine.connect()

This would open the external browser for authentication.
Comment: This is great! You can try `pip install jupysql` as it has more features like visualizing the data and in-memory data. It also has bug fixes that are still missing in `ipython-sql`. Moreover it allows you to set multiple connection engines, and maintain it, so you wouldn't need to hardcode the connection string in your notebook.
Comment: it seems you still need to take the actual url string (output of the URL(...) fumc), but other than that using URL() solves the problem
Comment: **pre op:** pip install ipython-sql
**1st cell:** %load_ext sql
**2nd cell:** %sql snowflake://:@/?authenticator=externalbrowser&warehouse=
**3rd cell:** %sql select current_time (just an example)
Comment: @Ezer K: I have the same question as you. After establishing the connection as suggested by Sergiu, what was the next step to be able to run a query using %sql rather than pd.read_sql?
Comment: @Ezer K: Thanks for this. It is working for me now.


Prove that $n^{31} \equiv n$ mod $77$ for all integers $n$

Question: Question:

Prove that $n^{31} \equiv n$ mod $77$ for all integers $n$

I've read this question: How to prove $n^5 - n$ is divisible by $30$ without reduction But I don't know how to use the same method to prove my example.
Induction seems very long and unnecessary.
I tried to come up with something using:

$n^7 \equiv n \mod{7}$ and
$n^{11} \equiv n \mod{11}$

but I am not sure that's useful.
I am now assuming I have to show that $n^{31} - n$ is a multiple of 7 and 11 and thus a multiple of 77. How do I arrive in this conclusion?
Comment: read https://en.wikipedia.org/wiki/Carmichael_function
Comment: Use the same methods as in the linked diupe.
Comment: See also the "Linked" questions in the sidebar of the dupe for many worked examples.
Answer: Let's work $\pmod {7}$: in this case you have $a^6 \equiv 1$ for all $a \neq 0$. Then
$$n^{31} \equiv (n^5)^{6} \cdot n \equiv 1 \cdot n \equiv n$$
If we work $\pmod {11}$, we have $a^{10} \equiv 1$ for all $a \neq 0$. Then
$$n^{31} \equiv (n^3)^{10} \cdot n \equiv 1 \cdot n \equiv n$$
Comment: Why is $a^{6} \equiv 1 \mod{7}$ valid for all a != 0 ? Doesn't the theorem hold only if a is not divisible by 7 by Fermat's theorem?
Comment: Please strive not to add more dupe answers to dupes of FAQs. We already have hundreds of anowers on this topic.