Django: Testing app causes Tastypie error

Question: I am trying to test my Django app via
python manage.py test project

but I get the error message that
django.db.utils.DatabaseError: relation "tastypie_apiaccess" already exists

How is that possible? Never tested before. Is that in relation to the migration files I have stored in the app folder and test uses the migrations to create the sqlite copy of my db?
I am running South as a migration app.
Answer: It can be related to south migrations. If so, you can avoid this by using SOUTH_TESTS_MIGRATE = False, then test runner will use syncdb instead of migrate.


É possível detectar a tecla pressionada em Lua?

Question: Trabalhando em modo terminal, eu tenho controle sobre as coordenadas de tela onde o texto será exibido, no entanto preciso detectar se uma tecla foi pressionada, sem que a mesma ecoe na tela.
Existe alguma função ou biblioteca que me permita detectar isso?
Answer: Diretamente, de forma pronta, até onde eu sei, não. É possível fazer isto em C e expor para Lua acessar. De fato existem alguma bibliotecas que já fizeram isto. Exemplo NTLua.
Achei este outro exemplo mas não sei se ele funciona como você deseja.
Aqui há outra tentativa.
Answer: Sim, é possível, você precisa adicionar  uma linha com o código 'Runtime:addEventListener('key', minha_funcao)'.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: O exemplo apresentado na pergunta é valido apenas para versão do interpretador embutido com [Solar2D Corona SDK](https://docs.coronalabs.com/guide/events/detectEvents/index.html#event-listeners). Aproveite e leia [answer] e faça o nosso [tour].


Is correction for multiple testing necessary when almost all variables show p-values < 0,05?

Question: If you compare patients and controls with respect to many clinical variables, making a large number of statistical tests and finding that only few of the variables are significantly different, whereas most of the variables show no significant difference between patients and controls.
Then it is obvious that the obtained p-values should be corrected for multiple testing.
However, if most of the variables are significantly different and very few are the same for patients and controls, shall we correct? If yes, what kind of correction do you propose?
Answer: Without context I'd say you'd have to correct for multiple testing in both of the described settings. Moreover, you should plan any correction for multiple testing before seeing your results. So irregardless of finding a relatively large amount of 'significant' differences or finding a relatively small amount, you, as the researcher, have to consider in advance whether you aren't 'blowing up' your assumed alpha level by performing a shotgun-blast of hypothesis tests.
When you are doing a lot of hypothesis testing however the most important questions you might ask yourself are: "why am I doing all these anyway?" and "do I need an hypothesis test to see these are different?"
Comment: The last paragraph of this answer is particularly valuable.
Comment: If you do a large number of tests you might want to consider FDR (false discovery rate) as a criterion.
Answer: Yes, it generally is (agreeing with @IWS that you should decide this beforehand). Indeed, the most basic correction, Bonferroni, compares the p-values to $\alpha/q$ where $q$ is the number of multiple tests and $\alpha$ is the nominal level. So p-values between $\alpha$ and $\alpha/q$ would be redeclared as nonsignificant after this multiple testing correction.
Conversely, if none of the p-values is less than $\alpha$, you may as well skip the correction, because multiple testing procedures generally avoid spurious rejections by making rejections more difficult (see e.g. above). So if there are no rejections in the first place even without correction, there won't be any, a fortiori, after a correction.
Comment: All right. Apparently that is not convenient from the app, so I hope I think of it when in front of my PC. If not I appreciate a reminder :-)
Answer: IWS provides the most relevant fact about correcting for multiple comparisons: You should not decide to use a correction based on what you see in your results (e.g. how many of the comparisons are significant when uncorrected), but rather based on what you expect your actual alpha would be for an analysis relative to what alpha you're comfortable with. In general, if you have a couple specific comparisons of interest (a priori, not based on what looks interesting in the data), you're better off testing those separately as contrasts. Then you can compliment that hypothesis testing with a more general description of the patterns in the data provided by post hoc tests, correcting for multiple comparisons.
I want to add that sometimes the question is not about a difference in any particular outcome(s), but rather about a general pattern across a whole set of outcomes. From what you describe, it sounds like that may be the case here. If your research question is something like "Do patients differ from controls on X? How about on Y? And Z?" where you really care about the particulars of X, Y and Z, then comparing patients vs. controls on each of them makes sense (the analysis you've asked about). However, if you research question is more like "Do patients differ from controls? I measured them on X, Y, and Z." where you have a set of variables that you think are relevant to the difference between patients and controls, but each one isn't really interesting on its own, then you may be better off with a multivariate test that tests them all simultaneously. If group (patient vs. control) is your only predictor, then you can run this as a MANOVA, putting all of your outcome variables in at once and looking for differences between groups across all of them. Not only will this be a more direct test to answer your question (if your question is about global differences rather than particular outcomes), it will also generally be more powerful. It also solves your problem of multiple comparisons, of course, since you are able to conduct the whole analysis with one test.


What are the most serve attempts for a single tennis point?

Question: In Tennis, you usually have 2 attempts for a service.
however under certain circumstances there are more serves made fot one single point, for example when the ball touches the net and then enters the correct T area or when an attempt is overruled by the hawk-eye.
What are the most attempts for one single point that have been recorded?
Answer: Here is a video of Serena Williams serving four lets on a single serve.
Comment: What evidence do you have that four lets is the greatest number of attempts?


After removing an item from a Dictionary, how to change the other keys accordingly?

Question: For example, a dictionary contains,
key:   1 2 3 4 5
value: a b c d e

Once you delete the item b, the dictionary would looks like this,
key:   1 3 4 5
value: a c d e

However, I want the key to be like so,
key:   1 2 3 4
value: a c d e

Is there any possible way to do this?
Comment: i think you want a sorted list. a dictionary isn't really for stuff like that.
Comment: I don't know why you need a dictionary. Use a `List` which contains only the values. The keys are just the indexes. So if you remove an item there is one item less, hence one index less. Retrieving the value via index is an O(1) operation; so you have even the same performance as a dictionary.
Comment: A dictionary is a list of pairs of values. What you're asking means not treating them as that. You'll need to create your own collection type.
Comment: How do you plan to manage the adding of new items to the dictionary? If you could describe the root problem more specifically, you will get a better solution. This isn't what a dictionary was built for.
Answer: You want an Array or a List, not a dictionary.
If you want to keep it as a dictionary, you could convert it to a list, then remove the entry, then reconvert it back to a dictionary.
var list = new List<string>();
foreach(var item in dictionary)
{
    list.Add(item.Value);
}
var newDict = new Dictionary<int, string>();
for(int i = 1; i < list.Count + 1; i++)
{
    newDict.Add(i,list[i]);
}

Don't do this though.
Comment: +1 this suggestion is not that bad (see my comment above). However, i'm missing an explanation.
Answer: As others have said, this is not the right approach. However, it is possible. Here's another way:
public static void Test()
{
    var foo = new Dictionary<int, string> { { 1, "a" }, { 2, "b" }, { 3, "c" }, { 4, "d" }, { 5, "e" } };

    RemoveItemByKey(ref foo, 3);
    RemoveItemByValue(ref foo, "a");

    foreach (var kvp in foo)
    {
        Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
    }

    // Output:
    // 1: b
    // 2: d
    // 3: e
}

public static void RemoveItemByValue(ref Dictionary<int, string> dictionary, string valueToRemove)
{
    foreach (var kvp in dictionary.Where(item=>item.Value.Equals(valueToRemove)).ToList())
    {
        RemoveItemByKey(ref dictionary, kvp.Key);
    }
}

public static void RemoveItemByKey(ref Dictionary<int, string> dictionary, int keyToRemove)
{
    if (dictionary.ContainsKey(keyToRemove))
    {
        dictionary.Remove(keyToRemove);

        int startIndex = 1;
        dictionary = dictionary.ToDictionary(keyValuePair => startIndex++, keyValuePair => keyValuePair.Value);
    }
}

Comment: Note, you may also need to implement an 'Add item' property that takes a string value to add, so it gets the correct key. Something like `dictionary.Add(dictionary.Count, newValue)`. But if you could describe your problem better, you'll get a better solution!


Qual é a diferença entre Meter e Progress no HTML5?

Question: Qual é a diferença dessas duas tags html, apenas a aparência(layout,cor) é diferente?
<meter min="0" max="100" value="22"></meter>

<progress value="22" max="100"> </progress>

Qual é a diferença da meter e progress ? sendo que aparentimente elas tem o mesmo propósito e objetivo?
Answer: Apesar de serem parecidas visualmente elas tem diferentes propósitos, vejamos:
<progress>: representa o progresso da realização de uma tarefa, exemplo: upload de um arquivo.
<meter> representa uma medida, por exemplo de uso de disco, relevância do resultado de uma consulta, ou a fração de uma população que votou num candidato em particular.
Fontes: 1, 2
Answer: De acordo com está resposta no SOEn não há muita diferença entre a utilização entre uma ou outra. Basicamente a tag <progress> é usada para exibir o andamento de uma tarefa específica(eg: informar o usuário sobre o andamento do seu pedido ou tarefa, importação de dados, etc), enquanto a tag <meter> tem bom uso por exemplo, em exibir a utilização do disco ou a relevância do resultado de uma consulta.
Veja este gráfico onde exibe a diferença entre elas.


version of Nakayama's lemma for group rings

Question: I have the following rather complicated setting and I would like to know if something that resembles Nakayama's lemma can be proved in this setting, but I can make no progress with it:
Let $G$ be a finite group and let $K$ be a field of characteristic $0$. Assume that $M$ is a module over the polynomial ring $K[X]$, that $M$ is finitely generated as a $K$-module and also that there exists an action of the group $G$ on $M$, so that $M$ becomes a module the group ring $(K[X])[G]$.
I know in addition that the annihilator of $M$ in $K[X]$ is of the form $(X-c)^d$ for some $c \in K$, $d>0$ and that the set of elements in $M$ annihilated by $(X-c)$ is a cyclic $K[G]$-module (also the action of $X$ and $G$ commute). Does it follow that $M$ is cyclic as a $(K[X])[G]$-module?
Comment: So $M$ is not just a $K\left[X\right]$-module, but actually a $K\left[X\right] / \left(X-c\right)^d$-module. Note that $K\left[X\right] / \left(X-c\right)^d$ is a local ring, with its maximal ideal generated by $X-c$. This may help in applying regular Nakayama.
Comment: Is the set of elements in $M$ annihilated by $\left(X-c\right)$ isomorphic (as a $K\left[X\right]\left[G\right]$-module) to $M / \left(X-c\right)M$ ? Or, at least, is there a surjective $K\left[X\right]\left[G\right]$-module homomorphism frm the former to the latter? I suspect so; this would reduce your question to the standard Nakayama lemma.
Comment: @darijgrinberg I can see the obvious isomorphism $M/N \cong (X-c)M$ (where $N$ is the set of elements annihilated by $X-c$), but I don't see how to construct the 'swapped' version $M/(X-c)M \cong N$ you suggest
Comment: OK, I see why $M / \left(X-c\right) M \cong N$ **as $K\left[X\right]$-modules**: Both sides are $K\left[X\right] / \left(X-c\right)$-modules, which is the same as $K$-vector spaces, so it suffices to prove that their dimensions are equal; but this follows from looking at the Jordan normal form of a nilpotent endomorphism (the endomorphism being the action of $X-c$ on $M$). But this isomorphism is not canonical, so it is not clear at all that it will play well with the action of $G$.
Comment: For future discussions, let's agree to simplify our life and substitute $Y$ for $X-c$.
Comment: @darijgrinberg I understand the argument for $M/YM \cong N$. I have also been trying several ideas in the meantime, such as proving recursively that for all $j$ the submodule of $M$ annihilated by $Y^j$ must be $(K[X])[G]$-cyclic, but did not get very far with it.
Answer: Maybe there's a more elegant way to prove this, but one way to do it is to just classify all such modules.  First, we may assume $c=0$.  By Artin-Wedderburn, $K[G]$ is isomorphic to a product $\prod M_{n_i}(D_i)$ of matrix rings over division rings, and then $K[G][X]\cong \prod M_{n_i}(D_i[X])$.   Any $K[G][X]$-module $M$ then splits as a product $\prod M_i$ of modules over each $M_{n_i}(D_i[X])$, and $M$ is cyclic iff each $M_i$ is cyclic.
So, it suffices to prove the following.  Suppose $D$ is a division ring and $M$ is a finitely generated $M_n(D[X])$-module that is annihilated by some power of $X$ such $N=\{a\in M:Xa=0\}$ is a cyclic $M_n(D)$-module.  Then $M$ is cyclic.
To prove this, note first that any finitely generated $D[X]$-module which is annihilated by some power of $X$ is isomorphic to a direct sum of modules of the form $D[X]/(X^i)$.  (There several ways to prove this; some commonly used proofs of this fact over fields (which amounts to Jordan normal form for nilpotent matrices) work just as well over division rings.  Another approach is to show that $D[X]/(X^i)$ is injective as a module over itself using Baer's criterion (the only ideals in $D[X]/(X^i)$ are those generated by powers of $X$) and then use this to repeatedly peel of direct summands of the form $D[X]/(X^i)$ where $i$ is minimal such that $X^i$ annihilates the module.)  By the Morita equivalence of $D[X]$ and $M_n(D[X])$, similarly any finitely generated $M_n(D(X))$-module which is annihilated by some power of $X$ is a direct sum of modules of the form $D^n\otimes_D D[X]/(X^i)$.
So, $M$ is a direct sum of modules of the form $D^n\otimes_D D[X]/(X^i)$, and then $N$ will be a direct sum of copies of $D^n$, one for each summand in $M$.  An $M_n(D)$-module is cyclic iff it is a direct sum of at most $n$ copies of $D^n$, so if $N$ is cyclic, there are at most $n$ summands in $M$.  But then $M$ is a quotient of a direct sum of at most $n$ copies of $D^n\otimes_D D[X]$, and so $M$ is a cyclic $M_n(D[X])$-module.


Markings in Second Waltz by Dimitri Shostakovich

Question: I came across these indications in a piano piece: the Second Waltz by Dimitri Shostakovich.

What do "1.3. x p" and "2. x f" mean?
Answer: That means on the first and third repeats, play piano (quietly), on the second repeat, play forte (loudly).
Comment: Yup, it seems like an attempt a rendering at the piano the different orchestration of the different repeats in the original orchestral version (if I'm not mistaken, solo oboe - first time, full violin section - 1st repeat, solo trombone (but rather smoohtly) - repetition after B part.


Isomorphic affine classical varieties over a non-algebraically closed field. Does the isomorphism preserve polynomials?

Question: $\def\bbA{\mathbb{A}}
\def\spec{\operatorname{Spec}}
\def\sO{\mathcal{O}}
\def\sA{\mathcal{A}}$Let $k$ be a non-algebraically closed field. Let $X=V(I)\subset\bbA^n_k$ be a classical affine variety (where $I\subset k[x_1,\dots,x_n]$ is an ideal), which is naturally a locally ringed space over $\spec k$ when equipped with the sheaf of regular functions. Denote $\sA(X)=k[x_1,\dots,x_n]/I(X)$ to the $k$-algebra of polynomial functions on $X$. Then we have a containment
$$
\tag{1}\label{1}
\sA(X)\subset\Gamma(X,\sO_X)
$$
which in general is not an equality (for instance, consider $k=\mathbb{R}$, $X$ the real affine line and $\frac{1}{1+x^2}\in\Gamma(X,\sO_X)$). Suppose now that we have another classical affine variety $Y=V(J)\subset\bbA^m_k$ and an isomorphism $\varphi:X\to Y$ of locally ringed spaces over $\spec k$. We then get an induced isomorphism $\varphi^*:\Gamma(Y,\sO_Y)\to\Gamma(X,\sO_X)$ of $k$-algebras, given by precomposition by $\varphi$.
I have two questions:

Does it hold $\varphi^*(\sA(Y))\subset\sA(X)$?

If 1 is false in general, can we always find some isomorphism $\psi:X\to Y$ such that $\psi^*(\sA(Y))\subset\sA(X)$?

(Note that if $k$ were algebraically closed, then 1 holds, for \eqref{1} is an equality on this case.)
I am trying to produce a counterexample for 1 given by some automorphism of the real affine. I am thinking on a map of the form
\begin{align*}
\rho:\mathbb{R}&\to\mathbb{R}\\
a&\mapsto\frac{f(a)}{1+a^2},
\end{align*}
where $f(x)\in\mathbb{R}[x]$. However, I don't know if we can find $f$ so that $\rho$ is bijective and $\rho^{-1}$ is given by a quotient of polynomials.

Put in other words, this post is asking: is the $k$-algebra of polynomials functions $\sA(X)\subset\Gamma(X,\sO_X)$ an invariant of $X$ as a classical affine algebraic variety? (I guess this question is relevant in the field of real algebraic geometry, for instance.)
EDIT: E. Wofsey's counterexample implies that the answer is no.
Comment: Why would you want to do this? Doing algebraic geometry with "classical" varieties over non-algebraically-closed fields was something we largely stopped doing for a reason.
Comment: @KReiser Short answer: for fun, what else? xD. Short and more serious answer: I said that such a question might be interesting in the realm of real algebraic geometry. Long answer: After realizing one can construct $F$ [here](https://mathoverflow.net/q/450147/101848) for the schematic varieties with dense rational points, now I am trying to show fully faithfulness of $F$. I can show it in the affine case. In the general case, one takes an classical affine cover and has to glue the schematized affine pieces. To make the gluing possible, I think reduced the problem to what I asked here.
Comment: Do you assume that $I=I(X)$ as well? (So, $I$ is not just an ideal that cuts out $X$ but is the largest such ideal?)  Without that, the natural map $\mathcal{A}(X)\to\Gamma(X,\mathcal{O}_X)$ need not be injective (for instance, $X$ could be empty!).
Comment: @EricWofsey Yes, when I write $\mathcal{A}(X):=k[x_1,\dots,x_n]/I(X)$, with "$I(X)$" I mean the ideal of polynomials that valuate identically zero in all of $X$. Thank you very much for your answer, by the way ^^
Answer: Consider, for instance, $X=\mathbb{A}^1$ and $Y=V(y(1+x^2)-1)\subset\mathbb{A}^2$ over $\mathbb{R}$.  Then there is an isomorphism $\varphi:X\to Y$ given by $\varphi(x)=(x,(1+x^2)^{-1})$ whose inverse is just the first projection.  This does not map $y\in\mathcal{A}(Y)$ to an element of $\mathcal{A}(X)$, and indeed $\mathcal{A}(Y)=\mathbb{R}[x,(1+x^2)^{-1}]$ does not embed into $\mathbb{R}[x]$ at all (since there are no nonconstant units in $\mathbb{R}[x]$).
More generally, given any $X$ and elements $f_1,\dots,f_n\in\Gamma(X,\mathcal{O}_X)$, the graph of $(f_1,\dots,f_n):X\to\mathbb{A}^n$ is a variety $Y$ that is isomorphic to $X$ but which has $f_1,\dots,f_n$ in $\mathcal{A}(Y)$.
Comment: $Y$ is dense in the closed subscheme of $\operatorname{Spec}\mathbb{R}[x,y]$ defined by $y(1+x^2)-1$ (since $Y$ is infinite and that subscheme is an irreducible curve).  So, any polynomial that vanishes on $Y$ must vanish on that whole subscheme and thus be in the ideal generated by $y(1+x^2)-1$.
Comment: In this situation, I know how to show that $I(X)=(0)$ (so that $\mathcal{A}(X)=\mathbb{R}[x]$), but how does one show $I(Y)=(y(1+x^2)-1)$?


Is there an easy way to convert unicode character representation to actual characters in python.

Question: I need to convert "disk \u6253\u5305\u5185\u5BB9" to "disk 打包内容" in python. Is there an easy way to do it
Comment: Show us the hard way and we will show you the easy way.
Answer: There's no need to convert them, they are those characters.  Whether they render nicely depends on your console settings.
They render just fine in Cygwin on my machine:
<code>>>> print u'disk \u6253\u5305\u5185\u5BB9'
disk 打包内容
</code>


What are the universally effective epimorphisms of topological spaces?

Question: An effective epimorphism in a category is a morphism that is the coequaliser of its kernel pair, and a universally effective epimorphism is a morphism $f : X \to Y$ such that, for every pullback diagram of the form below,
$$\require{AMScd}
\begin{CD}
X' @>>> X \\
@V{f'}VV @VV{f}V \\
Y' @>>> Y
\end{CD}$$
the morphism $f' : X' \to Y'$ is an effective epimorphism.
In the case of the category of topological spaces, an effective epimorphism is precisely a quotient map.
Question. What are the universally effective epimorphisms in the category of topological spaces?
Every universally effective epimorphism is an effective epimorphism, but the converse is known to be false. On the other hand, the class of universally effective epimorphisms contains every open surjection and also every proper surjection, so there are lots of examples. And it is not hard to construct a universally effective epimorphism that is neither open nor proper.
What I'm hoping for is some characterisation of the universally effective epimorphisms in the category of topological spaces as "surjective continuous maps that have property $P$", where $P$ is some property that non-surjective maps may have; it would be even better if $P$ is a generalisation of both open and proper. However, I do not think there is any reason to expect such a characterisation.
Answer: A surjective map $f: X \twoheadrightarrow Y$ is universally effective iff any of the following two equivalent properties hold:

For every point $y \in Y$ and every covering $\mathcal{U}$ of $f^{-1}(\{y\})$ by open subsets, there exist finitely many subsets $U_1, \ldots, U_n \in \mathcal{U}$ such that $f(U_1)\cup\cdots\cup f(U_n)$ is neighbourhood of $y$.
For every point $y \in Y$ and every filter $\mathcal{F}$ in $Y$ converging to $y$ there exists a point $x \in f^{-1}(\{y\})$ such that $f^{-1}\mathcal{F}$ converges to $x$.

This is proved in the paper "On topological quotient maps preserved by pullbacks or products" by Day and Kelly.


rhev and number of cpus

Question: I use RHEV-M to manage a cluster which has several RHEV hypervisor nodes. Currently, each node has 2 CPU sockets.
My question is can I add to the RHEV cluster another node which has 4 sockets, and how will scheduling behave when I do that.
All CPUs are AMD and exactly the same.
Answer: Yes. There is no problem to mix such hosts. Scheduling should take this into account and load them according to their resources.
Comment: Is there documentation that shows this? Or is it from your experience?
Comment: @AndrewSchulman Itamar leads the development of RHEV, he knows.
Answer: You can easily mix different hosts with different RAM sizes and CPU counts, as long as the cluster CPU is at the same baseline. The RHEV scheduler is clever enough to distribute VMs across different hosts according to their resources.

rhev and number of cpus


Drush Scripting? Or Batch API?

Question: We have an Ubercart website that handles large volumes of orders daily, processes them and runs other tasks like billing, delivery routing, and future order creation.
Some of these tasks are heavy and sometimes cause PHP to timeout. Is there a better way to run these tasks like through Drush or Batch API?
Speed is not necessarily a priority (although nice), but we want to avoid timeouts, which can sometimes cause issues with billing correctly and scheduling daily orders.
Is Drush script the better option, or Batch API? Are there any tutorials to make better use of both?
Answer: I would not suggest to use the batch API, simply for the fact that batch operations depend from the browser; if for any reason the browser crashes, or it loses the connection with the server, the batch operations will not terminate, or (worse) they will be hanging.
In fact, to avoid PHP timeouts, the batch operations cause the browser to ping the batch page at intervals; that is what happens, whenever JavaScript code is involved, or not (in the later case, Drupal uses the refresh meta tag).
In these cases, Drush is probably a better choice; you can create a custom module that implements specific Drush commands, or simply add a command file in the directory Drush uses for its commands.
Comment: Additional to drush you could actually also use a queue to get multiple items runned at the same time.
Answer: Also you may use custom PHP CLI script.
Here is a simple example for drupal 7:
<code>#!/usr/bin/php
<?php
echo "Ubercart tasks\n===================\n";

$_SERVER['HTTP_HOST']       = 'default';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REMOTE_ADDR']     = '127.0.0.1';
$_SERVER['SERVER_SOFTWARE'] = NULL;
$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['QUERY_STRING']    = '';
$_SERVER['PHP_SELF']        = $_SERVER['REQUEST_URI'] = '/';
$_SERVER['HTTP_USER_AGENT'] = 'console';

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
//-------------------------------------------

// Place your code here
</code>
Comment: The issue here is that you're reinventing the wheel. Drush is the better choice since it will already do this kind of thing and the framework is already in place!
Comment: Is there a reason why? it's about as intensive as installing any other module.
Comment: I don't like to install drush on all servers where I want to do something.
Comment: I was doing it many times and I think this method a little easier.
Answer: I have a D6 Ubercart site that requires significant back-end processing for 'auto-generated digital products'. I handle this via:

Purchase of one of these custom digital products causes a db table entry for 'products that need to be compiled.' In that db entry is a 'status' field.
A BASH script is started from within Drupal that runs in the background. This script is 're-entrant', meaning it is aware of being invoked while running and adds the new work to any existing work yet to be completed.
This BASH script increments the 'status' field in the Drupal database as a custom digital product is created, and finally an email notice is sent to the user with a download link for their completed custom product.

This is a somewhat similar solution to the one proposed by Xio, with the exception that this does not use a PHP CLI script, but BASH scripts invoked by PHP in Drupal to run in the background. Those BASH scripts access the Drupal database and advance the 'status' values of any products it is compiling and sending to customers. Plus, Drupal is able to see these status values and report back to the custmers where in the 'custom creation process' their purchases happen to be at the moment.

Drush Scripting? Or Batch API?


Remove or hide the submit button on search block in Drupal 7

Question: I need to do some custom theming on the search block in Drupal 7.
Specifically, I need to add a class to the submit button that makes it invisible and removes it from the content flow.  So:

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

Becomes...

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

I added element-invisible to the edit-actions div element.  However, I can't figure out how to do this.  What's the best practice for doing this sort of thing?
Answer: One of the standard ways to do this would be to use hook_form_alter() and add the attributes to the actions element directly:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['#attributes']['class'][] = 'element-invisible';
  }
}

Comment: Yeah if I can fully understand the way Drupal loads up it's arrays when dealing with forms I'll have a much happier time with this system.  I love Drupal now, but when I finally figure that aspect of it out, I'll be in theming heaven.
Comment: Yeah it's a tricky one to get your head round at first but it's so powerful it really is worth learning about
Answer: You can also hide it using a php condition like this:
<?php
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
      unset($form['actions']['submit']);
  }
}
?>

Comment: This can cause form submission not to work properly. FAPI checks for the presence of the triggering element before accepting input.


Can I restrict which user can use a given term of taxonomy?

Question: I am using Taxonomy as Category.
For example taxonomy "Categories" have "Internal Coms" as term.
Then I have a view that shows all Internal Coms.
But this term must be used only by some users (or role), because those are institutional communications.
I see that any user that can publish an article can select Internal Coms. as term and then his post will be shown as something that it is not.
How can I handle this situation?
Answer: Taxonomy Term Permissions seems to be created just for this purpose:

This module allows taxonomy administrators the ability to restrict setting individual terms on nodes by user or role.

Alternatively, you could implement mymodule_form_alter(). In it, test something like user_access('use_internals'), and if it returns false, remove forbidden terms from [#options].
Source: https://stackoverflow.com/a/21289211/2389310
Comment: Yes I saw it but it is not maintained any more and has many critical bugs :(
Comment: It claims to be maintained, but I admit it's a long time since I was trying it.
Comment: I just created a new Content Type to use core permissions.


Sql Server, Composite Primary keys and clustered indexes

Question: How does Sql Server handle fill factor on tables with clustered indexes on composite primary keys?
I would assume a key node value would be generated based on the fields that make up the clustered index.  Would this mean that each new row inserted would effectively get inserted to at the end of the index?
Answer:
Would this mean that each new row
  inserted would effectively get
  inserted to at the end of the index?

No, it would be inserted where it belongs in the order of the columns that make up the index. In other words if you PK is zipcode and state (silly example) and you insert 22222, NJ then it will be inserted after 22222, NI and before 22222,NK


Qual a melhor forma de manipular horários usando python 3?

Question: tenho um trabalho da faculdade para fazer, onde precisarei criar um código em python que permita o usuário agendar horários para uso de salas da instituição, porém não sei uma forma funcional de manipulação de horários utilizando python, se puderem ajudar fico muito grato!
Answer: O módulo datetime, que vem por padrão no Python, é um dos melhores que eu já usei pra manipulação de data, hora e intervalos de tempo.
Comment: Muito obrigado, dei uma olhada e realmente creio que possa usá-lo para sanar o problema, vou estudar mais sobre ele.


Android Youtube API - is there an alternative for youtubeActivity

Question: I want to implement youtube api, I noticed that I must have an activity inherited from the youTubeActivity class Is there another way to play YouTube video without having what youTubeactivity? I'd like to run it in a recyclerview if anyone has an example I'd love
Comment: check [this](https://github.com/PierfrancescoSoffritti/android-youtube-player)
Answer: youtube doc
Use YouTubePlayerView inside your recyclerview
Answer: You can use Youtube Fragment
<code>    YouTubePlayerSupportFragment mYouTubePlayerSupportFragment = new YouTubePlayerSupportFragment();
                        mYouTubePlayerSupportFragment.initialize(beanAppConfig.getData().getYoutubeDetail().getDeveloperkey(),
                                new YouTubePlayer.OnInitializedListener() {
                                    @Override
                                    public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                                                        YouTubePlayer youTubePlayer, boolean wasRestored) {

                                        myouTubePlayer = youTubePlayer;
                                        Log.e(TAG, "" + wasRestored);
                                        if (!wasRestored) {
                                            myouTubePlayer.loadVideo(youTubeVideoID);
                                            myouTubePlayer.setPlayerStateChangeListener(LiveActivityYoutube.this);
                                        }
                                    }

                                    @Override
                                    public void onInitializationFailure(YouTubePlayer.Provider provider,
                                                                        YouTubeInitializationResult youTubeInitializationResult) {
                                        Log.e("onInitializationFailure", "");
                                    }
                                });

                        mYouTubePlayerSupportFragment.setRetainInstance(true);

                       loadFragmentOverLay(mYouTubePlayerSupportFragment);
</code>
Load Fragment to FrameLayout
<code>  private void loadFragmentOverLay(Fragment fragment) {
        // load fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(frame_container_live.getId(), fragment);
        transaction.commit();
    }
</code>


What is the difference between an A Record and a DNS Server

Question: When I register a domain with a registrar and want to host it at a hosting company, I usually set the hosting compan's  DNS servers in the interface at the registrar.   But  I now see a hosting company which is asking me to set "A Records" at the registrar  and does not provide DNS servers.
Do these two approaches accomplish the same thing?

(I note this related question, which discusses the architecture but does not explain whether the two approaches are functionally the same.)
Comment: http://www.ietf.org/rfc/rfc1035.txt
Answer: You're getting confused with terminology, which isn't helped by hosting providers using unclear "friendly" language.
An "A Record" is just one type of record which is exists within DNS. It's all a matter of context. See this list:
http://en.wikipedia.org/wiki/List_of_DNS_record_types
Those are all the things that you COULD configure within your DNS server. In other words, you've never been configuring DNS as such - someone else has done that - you're just configuring a field within their servers.
But yes, generally, when you're configuring Y's DNS servers, you're probably setting up an "A Record".
You may have also come across a "CNAME" which lets you point to another DNS name, rather than an IP address.
I hope that make some sense - it's a little hard to explain from scratch. This Wiki page explains more of the fundementals of DNS:
http://en.wikipedia.org/wiki/Domain_Name_System
Comment: easiest way to remember cnames is its basically an alias. so Cname of vpn.yourdomain.com may point to netserver.yourdomain.com which has an A record that gives an IP of 184.108.40.206.
Answer: Two good answers already, although I don't think either of them answer the question particularly clearly.
Do these two approaches accomplish the same thing?
Yes (if you're just talking about getting the website working)
Ultimately, both end up with an A record (as you can tell from the other answers, a type of DNS record) for your website pointing to your host's web server, which results in your website being accessible from your domain name.
Version 1) You configure your domain settings at the registrar to point to your host's DNS servers
This hands control of DNS for the domain to the host; the host's DNS servers will already be set up with all of the records you need (eg, A records) for your domain so you don't need to worry about setting up individual records.  www.yourdomain.com will point to your website, ftp.youdomain.com will probably point to the address for ftp, the mail will already be set up etc.
Version 2) You use your registrars DNS servers, and configure an A record pointing to your host's web server
This leaves control of DNS for the domain with your registrar, you have to set up any DNS records yourself.  They've given you the details for the record to set up the website, but you may also want to set up records for FTP and mail - this is main difference you'll see between the two approaches.
Answer: The registrar's technical service typically consists of running a DNS server that hands out an NS record pointing at your DNS server, which you then configure to give out A records for the names that should be resolvable.
When you are with a provider that offers DNS service as well as hosting, the registrar points at their DNS server (NS), which points at their hosting (A). If your new provider does not provide a DNS server, your options are to get that service separately and have the registrar point their NS there, or to ask the registrar to configure an A record directly, removing the need for a separate DNS server for your domain.
Whether that is a sensible thing to do depends on the registrar as you lose a bit of flexibility for creating subdomains and some registrars charge extra for the service and/or changes to the zone data.


field_image_cache missing from all content types

Question: I've had a strange thing happen to a Drupal 6 site. All images are missing from the site. Looking at the Edit screen for a node shows that the ability to edit and upload an image for any node is missing.
Further checking the content types shows that under 'Manage Field' the 'Image' field [field_image_cache] has be removed for every content type.
As far as i can see all the correct modules are still enabled.
Anyone got any ideas?
Answer: Just thought I would update this one, just in case anyone else has a similar problem.
Turns out that the database was erroring and running out of disk space. Which meant the queries couldn't be completed. This ended up corrupting the database and I had to restore from a backup.
Once the restore completed all images and ability to Edit them returned to the site.
Hope that helps.


Inverse sampling for discrete data

Question: I have to pick a ball from a set of balls. Each ball has a size, so I have a distribution for ball sizes (I assume a number between 0-1).
I want to pick a new ball at each step with the probability associated with its size. I have read about Inverse transform sampling. But I wasn't able to find any numerical example. All I could find were some well known distributions, that are always reversible, however in my example two or more balls can have the same size. I'm not able to understand how to move forward.
Any help is greatly appreciated.
Comment: Welcome to CV! For clarity, is it correct that you have a set of balls, all with known sizes?
Comment: yes the sizes are known.
Answer: Given the sizes of the balls, and that probability of each ball being drawn is a known function of size, you can partition $(0,1)$ appropriately and map a series of random uniform draws to this partition. (You'll also have to make sure these probabilities properly sum to $1$.)
For instance, say you have 3 balls with $p_1 = \frac{1}{2}, p_2 = \frac{1}{3}, p_3 =\frac{1}{6}$. This would give the partitions $(0, \frac{1}{2}), (\frac{1}{2}, \frac{5}{6}), (\frac{5}{6}, 1)$. Generate a few uniform random draws,
<code>>>> np.random.uniform(size = 5)
array([ 0.3214321 ,  0.4209206 ,  0.72415894,  0.84439061,  0.36170096])
</code>
and then map them to the partitions. In this case, the random uniform draws above would give ball $1, 1, 2, 3, 1$.
This first page of this note details this process nicely.
Comment: thanks for the clear answer and reference. just to double check that I got this right: if I have say two balls of size 3, note them $3_1$ and $3_2$ which have the equal probabilities of $p_{3_1}=p_{3_2}$ I should consider them as two different values now. right?
Comment: Yes that's right: They should each be represented by a separate partition, but there's no reason they can't have equal probability.

Inverse sampling for discrete data


Operators from $\ell^\infty$ into $c_0$

Question: I have the following question related to $\ell^\infty(\mathbb{N}).$ How can I construct a bounded, linear operator from $\ell^\infty(\mathbb{N})$ into $c_0(\mathbb{N})$ which is non-compact?
It is clear that $\ell^\infty$ is a Grothendieck space with Dunford-Pettis property, hence any operator from $\ell^\infty$ into a separable Banach space must be strictly singular. But I do not know any example above which is non-compact.
Comment: From  problem VII.3 in Diestel's *Sequences and Series in Banach Spaces*: The bounded linear operators from $\ell_\infty$ to $c_0$ correspond to the weak$^*$ null sequences in $\ell_\infty^*$ and a bounded operator $T$ from $\ell_\infty$ to $c_0$ is compact iff the sequence $(T^*e_i^*)$ is norm null in $\ell_\infty^*$.
Answer: A bounded operator $T:\ell_\infty\rightarrow c_0$ has the form $Tx=(x_n^*(x))$ for some weak$^*$ null sequence $(x_n^*)$ in $\ell_\infty^*$.  A set $K\subset c_0$ is relatively compact if and only if there is a $x\in c_0$ such that $|k_n|\le |x_n|$ for all $k\in K$ and all $n\ge1$.  From these two facts, it follows that $T(B({\ell_\infty}))$ is relatively compact if and only if the representing sequence $(x_n^*)$ is norm-null.
So, you need only find a sequence in $\ell_\infty^*$ that is weak$^*$ null, but not norm null.
Such a sequence exists in $\ell_\infty^*$ since: 1) weak$^*$ convergent sequences in $\ell_\infty^*$ are weakly convergent ($\ell_\infty^*$ has the Grothendieck property), and  2) $\ell_\infty^*$ does not have the Schur property (weakly convergent sequences are norm convergent).
(There may be a less roundabout way of showing the the result of the preceding paragraph.)
Comment: What is a null sequence?
Comment: @NateEldredge Sorry, a sequence that converges to the zero vector.
Comment: I expected a direct example but now I understand why this is not immediate. Thank  you!

Operators from $\ell^\infty$ into $c_0$


Can't get ShouldDecompile configuration in DelegateDecompiler to work

Question: I'm trying to get an auto decompile configuration for DelegateDecompiler to work, as shown here: http://daveaglick.com/posts/computed-properties-and-entity-framework
But it doesn't work :(
Not sure what I'm doing wrong.
Here's the class that has a computed value.
public class Person
{
    public int Id { get; set; }
    public string First { get; set; }
    public string Last { get; set; }

    [NotMapped]
    [Computed]
    public string Full { get { return First + " " + Last; } }
}

This is the configuration.
public class DelegateDecompilerConfiguration : DefaultConfiguration
{
    public override bool ShouldDecompile(MemberInfo memberInfo)
    {
        // Automatically decompile all NotMapped members
        return base.ShouldDecompile(memberInfo) || memberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0;
    }
}

I also tried removing the [NotMapped] and then changed typeof(NotMappedAttribute) to typeof(ComputedAttribute) in the above configuration.
Then I register it like so
DelegateDecompiler.Configuration.Configure(new DelegateDecompilerConfiguration());

In Startup.cs. I also tried putting it directly into my action.
public ActionResult Test()
{
    DelegateDecompiler.Configuration.Configure(new DelegateDecompilerConfiguration());

    var ctx = new ApplicationDbContext();
    var result = ctx.People.Where(x => x.Full.Contains("foo bar")).ToList();

    return View();
}

Neither work :(
If I put .Decompile() on the query then it works as expected. So the DelegateDecompiler is working, but not the configuration.
Answer: As you discovered in your GitHub issue, you always have to call .Decompile() within your LINQ query. The extra configuration just eliminates the need to decorate all of your computed properties with the Computed attribute, instead relying on the Entity Framework NotMapped attribute.
Answer: As Dave says it requires Decompile()
So you don't have to remember to call it you can create a mapper extension that wraps what you are doing.
public static class MapperExtensions
{
    ///
    /// Creates a list from automapper projection. Also wraps delegate decompiler to supprt Computed Domain properties
    ///
    /// <typeparam name="TDestination"></typeparam>
    /// <param name="projectionExpression"></param>
    /// <returns></returns>
    public static List<TDestination>
        ToList<TDestination>(this IProjectionExpression projectionExpression)
    {
        return projectionExpression.To<TDestination>().Decompile().ToList();
    }
}


How might I update this code

Question:    <object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
        <param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/>
        <param value="high" name="quality"/>
        <param value="#FFFFFF" name="bgcolor"/>
        <param value="opaque" name="wmode"/>
        <embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/>
    </object>

I am having to insert this legacy markup into a new site that I'm building. Problem is its using an <embed> tag.
Would I just do away with the <embed> and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.
Answer: You can nest object elements to display alternatives. The W3C explains it here. I copied a snippet below:

One significant consequence of the OBJECT element's design is that it offers a mechanism for specifying alternate object renderings; each embedded OBJECT declaration may specify alternate content types. If a user agent cannot render the outermost OBJECT, it tries to render the contents, which may be another OBJECT element, etc.
In the following example, we embed several OBJECT declarations to illustrate how alternate renderings work. A user agent will attempt to render the first OBJECT element it can, in the following order: (1) an Earth applet written in the Python language, (2) an MPEG animation of the Earth, (3) a GIF image of the Earth, (4) alternate text.

<OBJECT title="The Earth as seen from space"
    classid="http://www.observer.mars/TheEarth.py">

    <OBJECT data="TheEarth.mpeg" type="application/mpeg">

      <OBJECT data="TheEarth.gif" type="image/gif">

       The Earth as seen from space.
     </OBJECT>
   </OBJECT>
</OBJECT>

Answer: I recommend that you use swfobject which is a cross platform, open source library to display flash on your pages.
http://code.google.com/p/swfobject/
There are a variety of ways to load the flash and the alternative (non-flash) content. For example the following code could replace your code:

Alternative content

Answer: I use function AC_FL_RunContent for embedding flash objects - it's good because it supports all browsers and is recommended by Adobe.
More is here:
They also suggest using <object> tag instead of <embed>
Answer: Basically, you should keep embed, because it is a fallback for some old browsers. It might hurt validation of page, but as long as you know why it is there, it is OK.
At least that's the way Adobe officially recommends: Macromedia Flash OBJECT and EMBED tag syntax
You are right to want to do code for XXIth century, but we have to deal with browser from previous millennium... :-)
Comment: Yeah, but what browser would that be you want to deal with by using the "embed" tag? As far as I know, even IE 6 can play flash movies in an "object" tag without "embed" quite fine. And that is probably one of the worst browsers one has to deal with nowadays ...
Answer: I found this code on the web (from a usability site) which caters for IE and others, and I use it on my flash pages (I've changed it to your code):

<object type="application/x-shockwave-flash" data="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" width="75" height="25">

  <param name="loop" value="false">
  <param name="menu" value="false">
  <param name="quality" value="high">
</object>

How might I update this code


Google Domains and GCP accounts

Question: I recently transferred a domain from Yahoo to Google.  I have an environment set up on Google Cloud Platform and (perhaps naïvely) thought I could manage the domain there.  the instructions I found, turns out were for Google Domains (which apparently is a separate system), and I cannot log into GD using the credentials I use for GCP.  So, 2 questions:

can I transfer my domain from Google Domains to GCP so I can manage it there?
if not, then how do I log into the Admin Console on GD using the same account that I use for GCP?

I've contacted GD tech support and they are completely useless, so I'm hoping someone here can set me straight
TIA
Comment: AFAIK it is not currently possible to transfer a domain _in_ to Cloud Domains. I'd guess this will eventually be added before it goes GA. As for Google Domains, how did you manage to transfer the domain there without being able to log in to it?!
Comment: Yeah man. `domains.google` is where you will find your recently transferred domain. Just log right in with your gmail account. Your gmail account is the owner account for this domain.
Comment: my gmail account is apparent not a "Workspace" account.  so it's odd because the account owns the domain but cannot manage it.  I'm working through it with Support (which leaves much to be desired)
Answer: Regarding your first question, currently in GCP you can purchase your own domain using Cloud Domains and you can export/migrate it to a different registrar, but it is not possible (at this moment) to import a domain as described here:

Note: Cloud Domains does not currently support incoming transfers or
import of domains. You can make outgoing transfers to Google Domains
or other registrars directly in Cloud Domains.

Nevertheless, you can delegate the control of your domain to Cloud DNS (or any other DNS provider like GoDaddy) which is also offered in GCP, for that you need to create a new zone in your project for your domain, and you will receive some instructions and nameserver (NS) records. Then you need to replace/update your NS records in your registrar (Google Domains in this case) for those provided by Cloud DNS and wait some time until the propagation is finished, here is the official guide about this, but you can find some useful guides on the Internet for your particular use case. This way you can manage your domain from the GCP Console but take into consideration that this is only a delegation, the registrar will still be Google Domains, if by any reason you update your NS records in Google Domains (pointing to a different DNS provider), any change in Cloud DNS will not be effective anymore.
Comment: I just realised you only answered the first question, so I'm re-opening this in hopes of getting an answer to the second question
Comment: For the second question, as it is unrelated to the DNS issue it is better to handle it directly with the Google Domains support team.
Comment: makes sense.  I've reclosed the issue.  thanks for the well thought answer
Comment: You can now import Google Domains into Google Cloud. https://cloud.google.com/domains/docs/import-domains

Google Domains and GCP accounts


Follow Link in Microsoft Word Index

Question: Using Microsoft Word 2007. I create a document with both a Table of Contents and an Index. I Save as PDF.
Inside the PDF, if I click on a page number in the TOC, it goes to that page. How do I get Word to do the same thing for page numbers in the index?
Thanks.
Update: It appears that TOC adds page numbers as internal Hyperlinks. Is there a way to get the Index to do the same thing?
Answer: Press ctrl before you click on table of content item.
Comment: Sorry I wasn't clear. It works fine for a page number in the TOC. But you can't click on a page number in the Index. Is there any way to get it to work that way in the Index as well?
Comment: Sorry for misunderstanding... It seems that my option doesn't work with indexes. What you could do is to: 1) add bookmark for the word within the text 2) add link to the page number in index referring to appropriate bookmark. That could be done with VBA, I hope quite easily (but I didn't try it). You could also ask you question on [SuperUser](http://www.superuser.com).
Comment: It appears that the TOC adds page numbers as internal hyperlinks. Curious that the Index does not do that also.

Follow Link in Microsoft Word Index


Sync Windows Server shares with OneDrive

Question: Recently one of my costumers bought office 365 and now we have a slew of space online we would like to fill, so we would like to sync some main folders from WS2012 to it so it's always accessible and up to day.
What's the best way? I've tried onedrive but with no luck, is there any open source software you guys recommend? Preferably like a service that syncs any changes made
Answer: You don't specify what Office 365 subscription/license this customer has, but if it includes Sharepoint Online, Microsoft has a free mihration tool that can migrate shared folders to Sharepoint Online Document Libraries. It needs to be manually run, but you can probably figure out how to automate it.
https://docs.microsoft.com/en-us/sharepointmigration/introducing-the-sharepoint-migration-tool


Can app use android security mechanism (pin code, pattern, password...)?

Question: Screen lock have some good security mechanism. (like pin, password, pattern...)
My AP would like to have a similar security mechanism.
Is it possible to invoke screen lock security mechanism?
(so my AP just need to know the result and does not need to handle security by itself)
Answer: I found a way to do that, for someone reference
<code>//put below source code in where you want to launch password UI
km = (KeyguardManager) getSystemService(context.KEYGUARD_SERVICE);
if(km.isKeyguardSecure()) {
    Intent i = km.createConfirmDeviceCredentialIntent(null, null);
    activity.startActivityForResult(i, 1234);
}

// call back when password is correct
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1234) {
        if (resultCode == RESULT_OK) {
            //do something you want when pass the security
        }
    }
}
</code>


skmaps sdktools integration

Question: I am integrating skobbler maps in my project. I were looking at the SDKTools. Is it necessary to integrate SDKTools to have navigation feature in the app. If yes, I were integrating it using Xcode 6.1 but it shows me error duplicate symbols for arm64 and also
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_SKTNavigationUtils", referenced from:
      objc-class-ref in MapsViewController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I am following this link: http://developer.skobbler.com/getting-started/iosTools
Please help me as I am stuck. Spend two whole days only for integration
Comment: are you integrating SDKTools via cocoapods or grabbing it from the demo project?
Comment: Grabbing it from Demo Project...I am following "How to" for SDK Tools given on getting started guides of Skobbler
Answer: It is not necessary to integrate SDKTools to have navigation feature in the application, just the SDK is enough.
Also based on the steps from the website, skmaps developers created a demo app using the SDKTools for navigation. You can find it at the following link:
http://www1.skobbler.com/iphonebuilds/20150107/SDKToolsIntegrationDemo.zip
The "duplicate symbols for arm64 " error can be caused by these reasons:

Declaring constants with the same name as we have in the SDKTools
(will be fixed in the next release).
The same file is added in the project twice.

skmaps sdktools integration


Is there a closed form or a better solution?

Question: This is another integral in the book "irresistible integral"
I can find that:
$$\int_0^\infty \frac{1}{\left( x^4 +2ax^2+1 \right)^{m+1}} \, \text{d}x =\frac{{{\left( -1 \right)}^m}\sqrt{2}\pi }{4\left( m! \right)}\left. \left( \frac{\text{d}^m}{\text{d}x^m} \sqrt{x}\sqrt{a+\sqrt{x}} \right) \right|_{x=1}$$
Do we have a better closed form? or better solution?
My working:
Let $$I(b)=\int_0^\infty \frac{1}{x^4+2ax^2+b}\,\text{d}x$$
then $$I^{(m)}(b)=m!(-1)^m\int_0^\infty \frac{1}{(x^4+2ax^2+b)^{m+1}} \, \text{d}x$$
Also $$I(b)=\int_0^\infty \frac{1}{(x^2+\alpha)(x^2+\beta)}\,\text{d}x$$
where $$\alpha=a+\sqrt{a^2-b}>0,\ \ \beta=a-\sqrt{a^2-b}>0$$
$$I(b)=\frac{1}{\beta-\alpha}\int_0^\infty \left(\frac{1}{x^2+\alpha}-\frac{1}{x^2+\beta}\right)$$
$$=\frac{\pi}{2(\beta-\alpha)}\left(\frac{1}{\sqrt{\alpha}}-\frac{1}{\sqrt{\beta}}\right)$$
$$=\frac{\pi}{4\sqrt{a^2-b}}\frac{\sqrt{2}\sqrt{a-\sqrt{b}}}{\sqrt{b}} = \frac{\sqrt{2}\pi}{4\sqrt{b}\sqrt{a+\sqrt{b}}}$$
Which follows that $$\int_0^\infty \frac{1}{( x^4+2ax^2+1 )^{m+1}}\text{d}x =\frac{(-1)^m\sqrt{2}\pi }{4m!} \left. \left( \frac{\text{d}^m}{\text{d}x^m}\sqrt{x}\sqrt{a+\sqrt{x}} \right) \right|_{x=1}$$
Answer: For every $a\gt-1$, consider
$$
I_m(a)=\int_0^\infty \frac{\mathrm dx}{\left(x^4+2ax^2+1\right)^{m+1}},$$
then, for every $|t|$ small enough,
$$
\sum_{m=0}^{+\infty}I_m(a)t^m=\frac{\pi}{2\sqrt2\sqrt{1-t}\sqrt{a+\sqrt{1-t}}}.
$$
To deduce a closed form formula for each $I_m(a)$ from this expression does not seem obvious. However, one sees readily that the radius of convergence of the series in the LHS is $1-a^2$ if $-1\lt a\leqslant0$ and $1$ if $a\geqslant0$. Thus, when $m\to\infty$, $m^{-1}\log I_m(a)\to-\log(1-a^2)$ if $-1\lt a\leqslant0$ and $m^{-1}\log I_m(a)\to0$ if $a\geqslant0$.


Why is my function call that should be scheduled by setTimeout executed immediately?

Question: Here's my issue. I have this function to test proxy servers.
function crawl() {
    var oldstatus = document.getElementById('status').innerHTML;
    document.getElementById('status').innerHTML = oldstatus + "Crawler Started...
";
    var url = document.getElementById('url').value;
    var proxys = document.getElementById('proxys').value.replace(/\n/g,',');

    var proxys = proxys.split(",");

    for (proxy in proxys) {
        var proxytimeout = proxy*10000;
        setTimeout(doRequest(url,proxys[proxy]), proxytimeout);
    }
}

I want the 'doRequest()' function to be called in roughly 10 second intervals but even with the setTimeout() the functions are called immediately.
Any ideas are welcome, thanks.
PS: Even if I put an arbitrary value for 'proxytimout' it has no effect.
Answer: As you give the function to the setTimeout in that form, the function is executed instead of passed to the setTimeout. You have three alternatives to make it work:
Give first the function, then the timeout and the parameters as the last arguments:
setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

Or just write a string that will be evaluated:
setTimeout('doRequest('+url+','+proxys[proxy]+')', proxytimeout);

Third style is to pass an anonymous function that calls the function. Note that in this case, you have to do it in a closure to prevent the values from changing in the loop, so it gets a bit tricky:
(function(u, p, t) {
    setTimeout(function() { doRequest(u, p); }, t);
})(url, proxys[proxy], proxytimeout);

The second format is a bit hacky, but works nevertheless if the arguments are scalar values (strings, ints etc). The third format is a bit unclear, so in this case the first option will obviously work best for you.
Comment: Correct me if I'm wrong, but since this is happening inside a loop, the second method you've given won't work. The value of `proxy` will change because there's no closure created.
Comment: @nickf: I was about to say that.  Also, the third option violates `eval is evil`.
Comment: @nickf, you're true, I overlooked that point. I've updated my answer.
Comment: Thanks that's a huge help, this is an incredible community!
Comment: the setTimeout(doRequest, proxytimeout, url, proxys[proxy]) won't work in IE, right?
Answer: This line here is the problem:
setTimeout(doRequest(url,proxys[proxy]), proxytimeout);

Writing doRequest() is actually calling the function. What you want is to pass the function itself:
setTimeout(doRequest, proxytime, url, proxys[proxy]);

Answer: You're misunderstanding the setTimeout function.
The setTimeout function takes a function and executes it later.
By writing setTimeout(doRequest(url,proxys[proxy]), proxytimeout), you're _calling the doRequest function (immediately), and passing the result (assuming that it returns another function) to setTimeout.
You need to pass doRequest's parameters to setTimeout, like this:
setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

This will pass setTimeout the doRequest function itself (without calling it first), and will also pass it the parameters to give to doRequest when it finally calls it.


Bugzilla with SSL

Question: I have an install of Bugzilla I'm trying to implement SSL on.
When I go into the parameters screen and edit SSLBASE adding in the full url:

https://foo.com/bugzilla/

the editparams.cgi times out on loading and I have the following error in the apache log

[Tue Mar 30 19:29:39 2010] [error] [client xxx.xx.xx.xx ] (70007)The timeout specified has expired: ap_content_length_filter: apr_bucket_read() failed, referer: http://foo.com/bugzilla/editparams.cgi

On install I also received this error:

WARNING: You need to set the max_allowed_packet parameter in your MySQL
  configuration to at least 3276750. Currently it is set to 3275776.
  You can set this parameter in the [mysqld] section of your MySQL
  configuration file.

How can I force this to work? Editing other parameters (eg urlbase) work fine. The SSL site is setup and direct requests to it eg https://foo.com/bugzilla work correctly.
Any ideas?
Ty
Answer: It seems fairly clear-cut to me.  Have you tried increasing your MySQL setting for max_allowed_packet?
Comment: seems obvious but was certain that I tried arbitrary large values and now it's started working.
Answer: need few change of settings. Goto C:\mysql\bin\my.ini and set the max_allowed_packet setting to 4M. Underneath that, add the following line, mostly max_allowed_packet line not avialble in my.ini file, so add the following lines.
max_allowed_packet = 4M
ft_min_word_len = 2
now the above problem,wont occur

Bugzilla with SSL


How to disable database connection while installation script is running in Laravel?

Question: I'm building a custom installation script for a Laravel application but I get a QueryException when I try to execute the script:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'demo_app.users' doesn't exist
This is understandable since the database demo_app is empty until the migrations have been executed by the installation script.
Is there a way I can use to disable the database connection check during the installation process? Some thing like this:
if($appIsNotInstalled){
# disable database connection
}else{
# allow database connection
}
I hope the issue is clear and thanks in advance
Comment: This is because something in your service provider call database. Find this place and bypass, for example, static variable in your script (Installer::isInstalled())
Comment: I thought that much but I wasn't able to locate the call to the database
Comment: If you cannot locate problem - you cannot solve them.
Answer: I might be wrong, but I think an installation script should run composer install first, then php artisan migrate. This way there is no way that your migrations won't run.
Comment: The user should insert the database name and other configurations during the installation process before migrating. That's the issue
Comment: So if I get this right, then the user input values will got into the .env file right? Do the migrations run if you just simply edit the .env file and run the installation process by hand (e.g. composer install then artisan migrate)? Also what kind of script is this? Bash or artisan command, python? Could you give a bit more insight, please.
Comment: It's a PHP script. And you got it right, the values will be saved to the .env file, and the migrations are run using the `Artisan::call()` method. Also, the composer is already installed before the installation script. The user is supposed to upload the app and run the installation script on their server
Comment: If you could insert logs in the script then you could debug on what step it exits. Can the script start running the migrations at all?  Because based on your question it looks like that the database access has been configured fine and there is interaction with the database(e.g. base table not found). I would also check if there are DB seeders that might conflict with the migrations.
Comment: I'll do that and thanks for your time. I appreciate it
Comment: I ended up creating a new laravel project from scratch and the issue is fixed. Thanks


Add Custom Bulk operations to an existing Views

Question: I am creating a custom bulk operation using hook_action_info and I can see that the operation is created successfully. But however, I want to add this to an existing views. I can do this using Views UI with editing the view and editing "Selected bulk operations". So there I can select the custom operation that I have written.
So far doing this works for me but I want to automate this one. So once I enable my module with this custom operation I need to add this custom bulk operation to the existing view's "Selected bulk operations".
Is there any hooks or alters that do this?
Answer: hook_views_default_views_alter() is the sauce you're after
Comment: Drupal is a CMF/CMS, not a food product
Comment: May you expand your answer? In which way should the OP use this hook?
Comment: larowlan, this solved my problem :-)


Possibly wrong result about hyperbolic/parabolic moebius transformations

Question: I found the following result on some lecture notes, but there was no proof... I am not even sure whether it is correct or not... I tried to prove it, but I'm having some troubles:
Let $f$ be a hyperbolic transformation with fixed points $x$ and $y$, and let $g$ be a Moebius transformation mapping $x$ to $y$. Then the following hold:
1) $fgf^{-1}g^{-1}$ is hyperbolic
2) $fgfg^{-1}$ is parabolic
Here is what I tried:
Firstly, I assumed $x=0$ and $y=\infty$ (indeed, the thesis is invantiant by conjugation, since the trace is). Hence, I wrote $f$ and $g$ as
$f(z)=\lambda z$ and $g(z)=\frac{\gamma}{z}+\delta$. Now, an explicit computation gives me:
1) $(fgf^{-1}g^{-1})(z)=...=\lambda^2 z+\lambda\delta(1-\lambda)$
Now I should compute the trace to show that $fgf^{-1}g^{-1}$ is hyperbolic when $f$ is. Is that correct? And how can I do this computation?
2) $(fgfg^{-1})(z)=...=z+\delta(\lambda-1)$
Now, if $\delta(\lambda-1)\neq 0$, clearly the transformation is parabolic, with only fixed point $\infty$. We need to check that $\delta(\lambda-1)= 0$ cannot hold.
If $\gamma=1$ we have $f(z)=z$, which contradicts the hypothesis that f is hyperbolic.
If $\delta=1$, we have $g(z)=\frac{\gamma}{z}$, which is a mobius transformation sending $0$ to $\infty$, and I cannot find an absurd in this. It seems to me that $fgfg^{-1}$ can also be the identity (hence, not parabolic). Does it make sense? Any help?
Answer: Your counterexample to 2) is correct.
Regarding 1), I would not do this using trace calculations, instead I would use the dynamics of the action on $\mathbb{R} \cup \infty$. One of the points $x,y$ is an attracting fixed point for the action of $f$ on $\mathbb{R} \cup \infty$, the other is a repelling fixed point. Let me assume that $x$ is the repelling fixed point for $f$. It follows that $x$ is the attracting fixed point for $f^{-1}$. Since $g(x)=y$ it follows that $y$ is the attracting fixed point for $gf^{-1}g^{-1}$. By composition, $y$ is an attracting fixed point for $fgf^{-1}g^{-1}$. Now complete the proof by using that every Möbius transformation with an attracting fixed point on $\mathbb{R} \cup \infty$ is hyperbolic.


Problema com cookie no PHP

Question: Estou desenvolvendo um sistema em PHP para bares e restaurantes, que ao entrar na página inicial um cookie é settado com o número da mesa, após o cookie ser settado, tem uma condicional abaixo verificando se realmente o cookie foi settado para continuar a operação, porém ele nunca entra de primeira na condição, quando o cookie é settado, preciso dar um refresh na página para ele entrar na condição e só assim continuar a operação. Gostaria de saber porque ele não entra na condição de primeira sem dar refresh. (obs: já tentei usar tanto a função isset quanto empty e não funcionou).
Answer: Olá, de acordo com a documentação oficial:

Uma vez que os cookies foram setados, eles podem ser acessados no próximo carregamento da página através do array $_COOKIE.

Ou seja, o que você tá tentando fazer não vai funcionar mesmo, pois o cookie só é setado quando os cabeçalhos HTTP são enviados.
Para resolver o seu problema, você pode usar uma flag quando verificar se o cookie existe.
<code>$valorCookie = 'seu-valor';
if(!isset($_COOKIE[$_cookieSession])) {
   setcookie($_cookieSession, $valorCookie);
   $firstAccess = true;
}

if($firstAccess) {
   $crypt0 = $valorCookie;
} else {
   $crypt0 = $_COOKIE[$_cookieSession];
}

list($origem, $horai, $mesar0) = explode('#', $crypt0);
</code>
Comment: valeu dms irmão
Comment: Nada, não esquece de marcar a resposta como certa para ajudar os próximos

Problema com cookie no PHP


Continuous migration

Question: I would like to know what is the best way to achieve a continuous migration from external DB (via Migrate).
Basically, there are several migration classes that need to be to repeatedly migrated in an ordered way (the external DB is also updated).
This said, exception management is welcomed/required during the run.
I was trying to find a solution for this but found nothing concrete.
From gathered information some approaches are to use Jenkins/Drush combination, but I wonder if adding Jenkins would be an overkill in my case.
Is there a good way to achieve this via Drush only?
Thanks
Comment: Please avoid questions like "best way" - this is opinion based to the point of loosing usefulness. Also, it's quite impossible to tell if something is overkill in your case, because it's hardly possible to fit your case in enough detail into a Q&A question.
Answer: Set up a script to call drush at regular intervals. There are several drush commands to manage migrations, such as drush migrate-status.

Continuous migration


WNetAddConnection2 returns Error 1200 - Local name is valid

Question: I'm trying to connect a share (let's say \server\folder) to my local device X:
[DllImport("Mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int WNetAddConnection2(
            [In] NetResource lpNetResource,
            string lpPassword,
            string lpUsername,
            int flags
        );

public static bool Connect(string remoteName, string localName, bool persistent) {
            if (!IsLocalPathValid(localName)) return false;
            var r = new NetResource
            {
                dwScope = ResourceScope.RESOURCE_GLOBALNET,
                dwType = ResourceType.RESOURCETYPE_ANY,
                dwDisplayType = ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE,
                dwUsage = ResourceUsage.RESOURCEUSAGE_CONNECTABLE,
                lpRemoteName = remoteName,
                lpLocalName = localName
            };
            return WNetAddConnection2(r, null, null, persistent ? 1 : 0) == 0;
        }

[StructLayout(LayoutKind.Sequential)]
    public class NetResource {
        public ResourceScope dwScope;
        public ResourceType dwType;
        public ResourceDisplayType dwDisplayType;
        public ResourceUsage dwUsage;
        public string lpLocalName;
        public string lpRemoteName;
        public string lpComment;
        public string lpProvider;
    }

When calling
Connect(@"\\server\folder", "X:", true);

the function just returns false - the Error says 1200 (BAD_DEVICE).
The NetResource looks like this:
lpRemoteName = "\\\\server\\folder";
lpProvider = null;
lpLocalName = "X:";
lpComment = null;
dwUsage = Connectable;
dwType = Any;
dwScope = GlobalNet;
dwDisplayType = Share;

I already checked with several snippets (PInvoke) put i can't see any difference. Maybe you can solve this mystery...
EDIT1
Comment: Does the map drive work if you don't give a local name ? i.e., make `localName` an empty string. This may give some clue whether there is any other problem. Error code 1200 means that there is something not right with your "X:\" -- is there any extra space (please see - https://stackoverflow.com/questions/31137879/excel-to-sharepoint-mapnetworkdrive-error)
Comment: Unfortunately not - the Error 1200 persists, even without a local drive specified (empty string). See my Edit1 for further NetResource details. (I had to clear the server name out, sorry.
Answer: [StructLayout(LayoutKind.Sequential)]

That is where the problem started, the attribute does not specify the CharSet property.  The default is CharSet.Ansi, a bewildering choice that requires a trip in a time machine to make sense of, taking you back to 1998.  So the code passes a struct with strings that get translated to 8-bit characters to a function that is explicitly uses the Unicode flavor of the function.  Inevitably the implementation sees garbage.
You can force the marshaling of each individual string member with [MarshalAs].  But it is just simpler and logical to make the character types match.  Fix:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]

Answer: I finally did it.
I solved the issue by adding
[MarshalAs(UnmanagedType.LPWStr)]

Attribute to every string field inside my NetResource class. Unfortunately I don't know why this is solving the issue...
Comment: With 'LPWStr' your specifying that it's a pointer to a null-terminated array of Unicode characters. If you don't specify it explicitly, it may be defaulting to some other value. More details on this here: [Default marshalling for strings](https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshalling-for-strings).


Google Maps Javascript API Issue Drawing Multiple Circles

Question: So I'm trying to draw multiple circles all with different centers and different radius's (radii?) using this code:
var citymap = {
     chicago: {
         loc : "Chicago, IL",
         center: {lat: 40, lng: -70},
         shootings: 140000
     },
     newyork: {
         loc : "New York, NY",
         center: {lat: 40, lng: -70},
         shootings: 80000
     },
     losangeles: {
        loc : "Los Angeles, CA",
        center: {lat: 40, lng: -70},
        shootings: 40000
     },
};

var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 39.14, lng: -98.1},
    zoom: 5
});

for (var city in citymap) {
    var geocoder =  new google.maps.Geocoder();
    geocoder.geocode( { 'address': citymap[city].loc},
          function(results, status) {
              citymap[city].center = {
                  lat : results[0].geometry.location.lat(),
                  lng : results[0].geometry.location.lng()
              }

              // Add the circle for this city to the map.
              var cityCircle = new google.maps.Circle({
                  strokeColor: '#FF0000',
                  strokeOpacity: 0.8,
                  strokeWeight: 2,
                  fillColor: '#FF0000',
                  fillOpacity: 0.5,
                  map: map,
                  center: citymap[city].center,
                  radius: citymap[city].shootings
              });
           });
    }

I feel like this should be working, but all the circles get drawn with the same radii. If I put cityCircle outside of the geocoder function, it then draws the circles with different radii but all on the same spot. Anyone know what the issue is here?
Answer: The geocoder is asynchonous.  When the callback function runs, the loop has completed and city is left at the last value, so all the circles get the radius of the last entry.
One fix is to use function closure:
function createCircleFromGeocode(city) {
  geocoder.geocode({
    'address': citymap[city].loc
  }, function(results, status) {
    citymap[city].center = {
      lat: results[0].geometry.location.lat(),
      lng: results[0].geometry.location.lng()
    }
    // Add the circle for this city to the map.
    var cityCircle = new google.maps.Circle({
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.5,
      map: map,
      center: citymap[city].center,
      radius: citymap[city].shootings
    });
  });
}

proof of concept fiddle
code snippet:

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 39.14,
      lng: -98.1
    },
    zoom: 3
  });

  for (var city in citymap) {
    createCircleFromGeocode(city);
  }
}

function createCircleFromGeocode(city) {
  geocoder.geocode({
    'address': citymap[city].loc
  }, function(results, status) {
    citymap[city].center = {
      lat: results[0].geometry.location.lat(),
      lng: results[0].geometry.location.lng()
    }

    // Add the circle for this city to the map.
    var cityCircle = new google.maps.Circle({
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.5,
      map: map,
      center: citymap[city].center,
      radius: citymap[city].shootings
    });

  });

}
var geocoder = new google.maps.Geocoder();
var citymap = {
  chicago: {
    loc: "Chicago, IL",
    center: {
      lat: 40,
      lng: -70
    },
    shootings: 140000

  },
  newyork: {
    loc: "New York, NY",
    center: {
      lat: 40,
      lng: -80
    },
    shootings: 80000
  },
  losangeles: {
    loc: "Los Angeles, CA",
    center: {
      lat: 40,
      lng: -100
    },
    shootings: 40000
  },

};
var map;

google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}

Comment: Worked like a charm. Thank you for your help!


How to work with numbers of the order 10^100 in C & java?

Question: How to work with numbers of the order 10^100?Like iterating upto a number of that order,getting sum of squares of their digits;then checking if the sum matches the square of a certain number,if yes sum up those numbers and finally display the sum of those numbers.
Comment: Java has a class called `BigInteger`.
Comment: Iterating up to 10^100? Even if iteration is taking 1nSec, it will be 10^91 seconds. about 10^86 years.. Hm.
Comment: You can't iterate to a number that large, you have to use a formula which calculates the result in a reasonable amount of time.
Answer: You can easily handle this kind of task with strings containing the decimal representation of the numbers.
The sum of squares of the digits of a 100 digit number is bounded by 100*9^2 = 8100: you can use int for that.
Comment: It will take longer than the age of the universe to iterate to that number however ;)
Comment: **very much** longer
Comment: @PeterLawrey: It actually depends how the iteration is performed: if large chunks are skipped at a time, it may bring it down to a more manageable timeframe.


Can we interchange one row and one column in a determinant?

Question: Can we swap the ith row and the ith coloumn in a determinant as an elementary operation? What happens when we do interchange them? Does the value of the determinant remain constant or does it change?
Comment: How do we swap row $1$ and column $2$ in $\left[\begin{matrix}1&2\\3&4\end{matrix}\right]$? Seems to me like we run into some definitional problems. Maybe you want to restrict to swapping the $i$-th row and the $i$-th column?
Comment: If one interchanges only one row and column, then the oter columns and rows dont remain t'he same in general, so the value of the determinant is changed.
Answer: Let's take an example as simple as possible:
$\begin{vmatrix}0&1&0 \\ 0&0&1 \\ 1&0&0\end{vmatrix} = 1$
Now, switching the first row with the first column we would get:
$\begin{vmatrix}0&0&1 \\ 1&0&1 \\ 0&0&0\end{vmatrix} = 0$
No, this transformation doesn't preserve the value of the determinant.


Adding new column, based on values of another column pandas

Question: Can anyone help, i'm new to Python so bear with me.
My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.
data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df

Comment: What is your expected output for the sample data?
Comment: sorry that would have been helpful so

    ID   Supplier   Region   Av Price   Eastern Price   Southern Price  Price
    1     EDF         Eastern  400          500                   300                   500
    2     EDF         Southern 200         100                   300                   300

THe idea is to get rid of all the regional prices and just have the actual price if that makes sense.
Answer: IIUC, you can do df.lookup here after adding " Price" to the values of the Region column to match the column names of the Price by region:
m = df.loc[:,df.columns.str.endswith("Price")]
df['actual_Price'] = m.lookup(df.index,df['Region'].add(" Price"))

print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  \
0   1      EDF   Eastern       400            500             300
1   2      EDF  Southern       200            100             300
2   3   NPower   Eastern       600            500             700

   actual_Price
0           500
1           300
2           500

Comment: It appears this has worked but I have a warning

SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Comment: @LMR is your dataframe a reference of any other dataframe or is it the first/source dataframe?
Comment: it was created from taking columns from 2 other dataframes if that makes sense?
Comment: @LMR guess there is some issue there. use `.copy()` when referencing the other dataframes, check [this](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas)
Comment: Thank you @anky that has solved the problem, you have probably jsut saved me a pile of time trying to work it out
Answer: I believe this is what you're looking for:
df["actual_price"] = np.where(df.Region == "Eastern", df["Eastern Price"], df["Southern Price"])

result:
Answer: Use, np.select:
conditions = [df['Region'].eq(reg) for reg in df['Region'].unique()]
choices = [df[f'{reg} Price'] for reg in df['Region'].unique()]
df['actual_price'] = np.select(conditions, choices)

Result:
# print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  actual_price
0   1      EDF   Eastern       400            500             300           500
1   2      EDF  Southern       200            100             300           300
2   3   NPower   Eastern       600            500             700           500


4th order method for solving wave equation

Question: I'm doing a project where I need to code a 4th-order accurate finite difference method for solving a simple wave equation: $u_{tt}-\nabla \cdot (a(x,y)\nabla u) = f(x,y,t)$ in a square domain.  I know the forcing function $f$, my initial conditions $u(x,y,0)$ and $u_t (x,y,0)$, and $a(x,y)$ at each grid point in my domain.  Any advice for stable 4-th order method?
Thanks
Comment: May I ask if you want 4th order in time or in space or in both?
Comment: Both.  Basically, I set the spatial grid size and then calculate the required time step (CFL condition).  Can I used Method of Lines to get fourth-order?  So far, I've been using a 2nd-order accurate method O($h^2$), where $h$ is the grid size (same for both $x$ and $y$ dimensions.
Comment: Sure. Thank you for your clarification.
Comment: The main problem that I'm seeing is that for a fourth-order multi-step finite difference approximation for $u_{tt}$, I need to know the previous two values of the solution $u^{i-2}$ and $u^{i-1}$.  How might I do this if I only know $u_{t}$ and $u_{tt}$ at $t=0$.
Comment: Apologies for being late. I'm at a meeting. I'll get back to you in two hours.
Comment: Seems to long as a comment here. I briefed the ideas as an answer below. Hope they could be helpful for you.
Answer: Spatial discretization for higher order
The explanation in this section takes the 1-D case for instance.
Suppose you have
$$
u''(x)=f(x),
$$
where $f(x)$ could be any given function of $x$, or any $u$-related values (e.g., $f(x)=u_t(x)$, where $t$ is regarded as an auxiliary parameter).
A usual second-order scheme reads
$$
\frac{u_{j+1}-2u_j+u_{j-1}}{h^2}=f_j.
$$
By contrast, a fourth-order scheme could be realized by taking
$$
\frac{u_{j+1}-2u_j+u_{j-1}}{h^2}=\alpha f_{j+1}+\beta f_j+\gamma f_{j-1},
$$
where $\alpha$, $\beta$ and $\gamma$ could be determined by requiring the scheme to be a fourth-order scheme to approximate $u''=f$. You may figure out that
$$
\frac{u_{j+1}-2u_j+u_{j-1}}{h^2}=\frac{f_{j+1}+10f_j+f_{j-1}}{12},
$$
which is known as the fourth-order compact scheme.
This method also applies to the $\left(au'\right)'$ case and the 2-D cases.
In addition, if the boundary condition prescribed to $u$ is the null Dirichlet or the null von Neumann (i.e., $u=0$ or $u'=0$ on the boundary), a more efficient choice would be the spectral method, which could provide you with spectral accuracy.
Time discretization for higher order
For the sake of stability, the second-order Crank-Nicholson usually suffices for most cases. Multistep methods work well for ODEs, but could perform badly for PDEs. In fact, due to the appearance of $\Delta$, a multistep scheme could be unconditionally unstable.
By contrast, the integrating factor method could be helpful. This method requires the spatial discretization at first. Say you have $u_t=\Delta u+f$. A spatial discretization gives you
$$
\frac{\rm d}{{\rm d}t}\mathbf{u}=A\mathbf{u}+\mathbf{f},
$$
where $\mathbf{u}$ is the spatial discretization of $u$, $A$ is a constant matrix, while $\mathbf{f}$ is the spatial discretization of $f$ composed with boundary terms of $u$. Now this equation becomes an ODE, and is equivalent to
$$
\frac{\rm d}{{\rm d}t}\left(e^{-tA}\mathbf{u}\right)=e^{-tA}\mathbf{f}.
$$
As such, the numerical errors with respect to $t$ all come from the quadrature for the integration of the right-hand-side $e^{-tA}\mathbf{f}$. Specifically, if this integration could be carried out precisely, the scheme would then be exact, I repeat, be exact, with respect to time. Further, thanks to the $e^{-tA}$ term, the scheme is always unconditionally stable, as long as all eigenvalues of $A$ are negative (with is of course true for elliptic operators like $\Delta$).
Initial conditions for multistep methods
For multistep methods, more than one initial conditions are expected. Take $u_t=u_{xx}+f$ for instance, where $u|_t=0$ is given.
In this case, Taylor expansion would be helpful:
$$
u^1\approx u({\rm d}t)=u(0)+u_t(0){\rm d}t+\frac{1}{2}u_{tt}(0){\rm d}t^2+\cdots=u^0+\left(u_{xx}(0)+f(0)\right){\rm d}t+\frac{1}{2}u_{tt}(0){\rm d}t^2+\cdots,
$$
where
$$
u_{tt}=u_{xxt}+f_t=\left(u_t\right)_{xx}+f_t=u_{xxxx}+f_{xx}+f_t,
$$
for which
$$
u_{tt}(0)=\left(u^0\right)_{xxxx}+f_{xx}(0)+f_t(0).
$$
Using this trick, you may get $u^1$, $u^2$, ..., $u^k$, as many initial terms as you expect, with arbitrary order of accuracy you want. Plus, since these are just initial terms, there is no need to worry about the stability (stability matters only if it is applied to all time steps iteratively; if only for one or a few steps, it would ruin the result).
Comment: Hey, thanks a lot.  From what you worte above, I think that a fourth-order compact scheme would be the most straightforward for me to implement.  Do you know where I can find more information on this?
Comment: Sure. You may refer to Section 3.6 in [this reference](http://www4.ncsu.edu/~zhilin/TEACHING/MA584/fd_fem_Chap3.pdf).


Loopback 4 - Get subcollection from Firestore

Question: Loopback 4 has a community maintained connector for Firestore here: https://github.com/dyaa/loopback-connector-firestore
How do I get the the subcollection houses from the following collection:

{
  village: {
    id: "yaOh(37Na",
    name: "Greenwich",
    houses: {
      house01: {
        address: "1st Street"
      },
      house02: {
        address: "2nd Street"
      }
    }
  }
}

The following snippet returns only shallow results:

const village = await this.villageRepository.findOne({where: {id: "yaOh(37Na"}});

console.log(village); // returns {id: "yaOh(37Na", name: "Greenwich"}
Answer: On Firestore reading from a collection, only reads the data from that collection and not from collections under it. There is no API that automatically reads data from subcollection too.
You'll have to execute a separate read operation for each subcollection that you want to get data from.
Comment: Reading subcollections are possible with a server-side query. Documentation can be found at the end of the page, here: https://cloud.google.com/firestore/docs/query-data/get-data
Comment: You can get a **list** of subcollections, but you can't read documents from them at the same time you read the village document.


IntelliJ not seeing my golang tests package

Question: I have a directory structure like this.
/home/senthil/greeting]$ tree
.
|-- hello.go
`-- hello_test.go

Hello.go
package greeting

// Hello returns "Hello World - <name>"
func Hello(name string) string {
    return "Hello World - " + name
}

And hello_test.go
package greeting

import (
    "testing"
)

func TestHello(t *testing.T) {
    hello := Hello("Hello")
    expected := "Hello"
    if hello != expected {
        t.Errorf("Expected %s, got %s", expected, hello)
    }
}

I can run the tests with go test -v

But I cannot run the tests directly from my IntelliJ.

What am I missing?
Answer: Okay, I was missing a go.mod file. I had to add a file called go.mod
with the contents.

module greeting

go 1.16

Now, I can exercise the tests from IntelliJ.


How can one determine if a function should have parenthesis around their argument?

Question: I have noticed that there are a select few functions that are acceptable if their argument is not in parenthesis. For example, here are a few functions I noted do not require an arguement:
Trig or hyperbolic functions: $\sin x,\coth x,\cdots$
The factorial function: $x!$ is an acceptable function of $x$
And logarithms, for example: $\log x$
So I was under the impression that all functions must have parenthesis $\sin (x)$ for example, in my mind, would be the correct notation, and so on.
A few functions do actually require parens, like polylogs $\operatorname{Li}_2 x$ is not good.
I can't really differentiate when a function must or doesn't need parenthesis around the argument. Thank you.
Comment: I think it is simply the matter of common sense and convenience in writing functions. For example, $\sin (x)$ will be understood equally well if you write it as $\sin x$, but if you have $\sin(\omega t + \phi)$, I doubt you would write $\sin \omega t + \phi$.
Comment: Well, that is part of it, yes? What about the functions themselves? @Pavel
Comment: @user313351: like what functions?
Comment: Which functions require parens?
Comment: I am not sure that I follow your question. See the answer below.
Answer: In general, reducing complexity of notation is always good. That is, unless it introduces ambiguity into your statement.
As such, I would advise omitting parentheses, unless complexity of the expression dictates a necessity.
For instance, many authors use $ Tx$ to denote $ T(x)$, where $T$ is usually a linear transformation. But sometimes you might have a product like
$$ TxSx=T(x)S(x).$$
The former notation is confusing and not pleasant to read, while the other provides a nice separation that makes the expression clear. As such, use your judgement. In other cases, parentheses are necessary: for instance
$$ T(x+h)\ne Tx +h$$
in general.
Comment: Interesting point, but not an answer. I am saying, if given function $f$ then determine whether or not $f$ requires parens around it's arguement.
Comment: In short: no. Parentheses are merely a grouping symbol- they don't change the meaning of the function (at least not for any function I've seen). In reality, a function is much more abstract than a bunch of letters/symbols on a page.
Answer: When in doubt, use parentheses.
I would codify your observations thus:
Parentheses may be omitted only under these circumstances:

When the function symbol provides its own bracketing. For example, you can write $\sqrt{1 + x}$. Of course when you don't have TeX like we do here, you may have to write something like sqrt(1 + x), even though in this particular case people might understand what you mean if you write sqrt 1 + x.
When the argument is a single variable, constant or literal and:

The function is a logarithm or it is trigonometric or hyperbolic.
When the function symbol is a suffix non-alphanumeric symbol.

Besides the factorial function $n!$, this also covers the arithmetic derivative $n'$, e.g., $14' = 9$.
But this does not cover situations where the argument needs to be expressed in terms of more than one variable, constant or literal and operations or other functions. Like Pavel said in the comments, $\sin \omega t + \phi$ could be very ambiguous, especially to a computer: do you mean sin(omega * t + phi) or sin(omega * t) + phi or even sin(omega) * t + phi?


Definition of "centroid" before the invention of vectors or coordinate system?

Question: It is fairly easy to define the centroid of a finite set of points $v_1,...,v_n$ in $R^n$: $(v_1+...+v_n)/n$ will be it. But how do people define, or calculate the centroid of a set of point $v_1,..,v_n$ in 2D, or even 3D space, before the notion of vector or coordinate system is invented?
Comment: You could say that its the unique point that you can balance a flat object on. This paper might be interesting: http://www.jstor.org/stable/27956057?seq=1#page_scan_tab_contents
Comment: @MaxPayne - How do you define adding $x_i$?
Comment: @ErickWong whoops. I am deleting the comments as they are of no use. Thanks ;)
Comment: One could define the centroid in a vector-free, coordinate-free way by saying it is the unique point that minimizes the sum of squares of the distances to $v_1,\ldots,v_n$.  It's not a very helpful definition for calculation, though.  I also don't see an obvious way to prove that the minimum is unique without Cartesian geometry.
Comment: It's also the center of mass of $n$ bodies with equal mass.
Comment: I'm pretty sure there is some work on centroids in Euclid's Elements.
Comment: @user347489 Is there a good way to define center of mass without coordinates?  I don't know it.
Comment: @Batman Speaking of Euclid, when $n=3$ you can define centroid as the intersection of medians.  Is there a way to generalize this to $n>3$?  I guess drawing a line from each point to the center-of-mass of the other $n-1$ points should work as a recursive definition.  Provided the points are in g.p.
Comment: @MaxPayne Have you read the question or the title? :)
Comment: @ErickWong - if n a power of 3, its straightforward to see that grouping any 3 points and replacing them with their centroid and doing that again and again would work. If you do all choices of groups (where one or two groups are 3 or 4, depending on if n is 1 or 2 mod 3), and do the same argument with all the centroids of those groups, you should be able to get it to work (the proof for n=4 is partitioning into triangles). Or something like that.
Comment: @Batman If you take all the centroids of all choices of groups, won't that be more points than you started with?
Comment: @ErickWong - Yes. The argument isn't precise, but you'd do all powers of 3 which doesn't have that problem. Then, you'd do the 3 or 4's and reduce. Another way is to do triangulations and stuff, which i think is equivalent to what you're proposing.
Answer: The centroid of a set of points points can be defined recursively as follows:

the centroid of a single point is the point itself;
the centroid $G$ of points $P_1,\ldots, P_n$ ($n>1$) is the unique point on the segment joining the centroid $G'$ of $P_2,\ldots, P_n$ with $P_1$ such that: $GG'/GP_1=1/(n-1)$.

Of course one should prove that this definition does not depend on the order of points $P_1,\ldots, P_n$, which can be done (I can provide details if necessary).
This also entails the following useful property:

the centroid $G$ of points $P_1,\ldots, P_n$ and $Q_1,\ldots, Q_m$ is the unique point on the segment joining the centroid $G_n$ of $P_1,\ldots, P_n$ with the centroid $G_m$ of $Q_1,\ldots, Q_n$ such that: $GG_m/GG_n=n/m$.