Where can I find music notes for classical guitar and lute online?

Question:
Possible Duplicate:
Sites with a good selection of sheet music

Occasionally, I search for music notes online, e.g. for pieces by Sor, Dowland, Bach and others. Are there some good resources for musical notes (or tabs)? I am interested in classical guitar and lute compositions.
I have seen this question (What is the legality of online tabulature?) and agree with the shadowy (and often ad-cluttered) ambiance of some of these sites. Are there some legal, maybe even well-organized, too?
Comment: If you're seriously into classical guitar music, then you would have to *buy* actual books! Even then, many of these books are hard to find!
Answer: You need to specifically be searching for '"sheet music" piece name', not musical notes.
Some pieces by Sor and Bach can be found here http://classicalguitar.homeip.net/Sheetmusic.htm
This was the first link from the Google search "sheet music classical guitar"
Answer: Please pay for them and stick with the masters:
Andres Segovia:
http://www.amazon.com/Andres-Segovia-Studies-Guitar-Transcribed/dp/0793504368
Paco DeLucia:
http://www.amazon.com/Scores-Fuente-Caudal-Visual-Spanish/dp/0786675063
Julian Bream: http://www.sheetmusicplus.com/s?q=Julian+Bream
Comment: Paco De Lucia, isn't a classical guitar player.
Answer: What is probably the largest online collection of lute music in the world is at http://gerbode.net/ (and mirrors). There are currently more than 3,000 pieces available (actually, I think it may be closer to 4,000 by now), many in several different arrangements. All of them are available in Fronimo file format, and most of them are also available in TAB, PDF, and MIDI.
You mentioned Dowland. A quick glance shows more than 100 pieces by him alone. There are 588 Fronimo files under his directory, including separated parts for SATB singers.
The collection is entirely free -- both in price and in copyright. All of the pieces are transcriptions by Sarge Gerbode, either from the originals or scans of the originals made available to him by libraries. This collection represents many years of work by him and it has been a labor of love. I'm currently working with Sarge to put a much nicer front end on the collection and we hope to have the up and running by Summer, if not sooner.
Check out the site. You can contact him at firstname.lastname@example.com, or me at email@example.com.
Answer: Have a look at International Music Score Library Project http://imslp.org/
Answer: I answered this for a different question, but it might be useful here:
You can find a lot of music sheets on http://www.ultimate-guitar.com/ Most of them are modern songs, or older music on modern instruments, but I also found a lot of classical guitar and lute pieces there. Some of the files can only be viewed with proprietary software (like Guitar Pro) but there are free ones as well.
If you are interested in even older music which is even harder to find, you can find some medieval music (mostly for lute or for flute) here> http://www.terrasoft.hu/kultura/consort/kotta/


Como publicar uma aplicação python

Question: Boa tarde:
estou querendo desenvolver uma aplicação com python (django) minha preocupação é como vou publicar minha aplicação (será web), por que python é interpretado, mas não posso mandar meu fontes pro servidor.
existe algum forma de resolver esse problema?
Grato:
Paulo
Comment: Em essência não, achei que esta questão já estava superada. Hoje quase todas linguagens podem ser revertidas para o fonte mesmo sem ter os fontes. C, C++, Rust e algumas poucas outras ainda não são fáceis, mas pode reverter com um pouco de esforço e aceitação que não terá tanta qualidade. Mas se ainda acha isso muito importante pode jogar fora tudo o que fez e fazer em alguma dessas linguagens, segura um pouco mais. Alguém falará que tem como, é só uma forma de ofuscar um pouco, não protege nada, se alguém quiser mesmo ver o que você fez ela fará normalmente.
Answer: Você vai mandar seus fontes para o servidor, e não tem nenhum problema com isso.
De fato você está com as preocupações erradas - e, como sua pergutna tem só duas linhas, não consigo entender quais conceitos você ainda precisa ver.
Mas aplicações em Javascript, PHP, Python e Ruby em conjunto devem ser mais de 95% de toda a Web - e em todas elas o código fonte fica no servidor - e qualquer um que possa acessar o servidor com um usuário que tenha acesso aos arquivos pode ler o código fonte.
Um conceito que você talvez não tenha estudado bastante é justamente o de quem tem acesso ao servidor, e mesmo sendo um servidor com vários usuários, há como restringir a leitura dos arquivos apenas ao dono dos mesmos e ao super-usuário.
Mais recentemente, no entanto, se popularizaram os servidores virtuais rivados, ou ainda containers, em que, com o mesmo custo de hospedagem, você é pode ser a única pessoa com acesso ao servidor (e portanto ao código fonte) - é o caso das máqunas funcionando na Amazon, no OpenShift da RedHat, no Heroku, e Digital Ocean, dentre dezenas de outros provedores.
O modelo antigo, muito usado no Brasil para projetos em PHP, em que o cliente ganhava uma conta de usuário em um servidor compartilhado e só tinha acesso via FTP, não serve para publicar projetos em Python, em que o acesso ao shell é, em geral, necessário. Mas mesmo nesses casos o acesso aos arquivos de código fonte é restrito ao títular da conta.
Quanto a como colocar seu projeto em produção, a recomendação é buscar isso na docuemntação dos projetos que está usando, ou do serviço de hospedagem que contratar - uma vez que é um assunto muito amplo, e não tem como abordar numa única resposta de pergunta aqui.

Como publicar uma aplicação python


Factorization of $x^n + y^n$, what sort of coefficients show up?

Question: We know that$$a^2 + b^2 = (a + bi)(a - bi).$$ What are the complete factorizations of $a^3 + b^3$, $a^4 + b^4$, $\ldots$ , $a^k + b^k$, etc.? What sort of coefficients show up?
Comment: Have you learned anything about "the roots of unity"?
Answer: You could always write $a^n+b^n = a^n - c^n$ where $c = \xi_n b$, where $\xi_n = e^{\pi i/n}$ (so that $\xi_n^n = -1$). Then fixing $a$, the roots of $a^n - c^n$ are solutions to $a^n = c^n$ and so there are $n$ solutions for $c$; namely, the numbers in the form of $\zeta_n^k a$ where $0\leq k\leq n-1$ and $\zeta = e^{2\pi i/n}$ so that $\zeta_n^n = 1$. So the original polynomial factors completely over $\Bbb{C}$ as
$$(c - a)(c - \zeta_na)(c - \zeta_n^2a)...(c - \zeta_n^{n-1}a)$$
Such $\zeta_n$ is called an $n^{th}$ root of unity. There are always $n$ $n^{th}$ roots of unity, namely, the distinct powers of $\zeta_n$.
Comment: Isn't your $\zeta_n$ a **primitive** root of unity?
Comment: @YoTengoUnLCD Yes, it is.
Answer: The problem simplifies if you divide through by $a$ and lent $\frac{b}{a} = x$. Once you have the factors of $1+x^n$ it is easy to re-introduce $a$ and $b$.
The pattern in these is easy to see.  For odd $n$,
$$a^3 + b^3 = (a+b) (a+b\mbox{ cis } (\frac{2\pi}{3})) (a+b\mbox{ cis }(\frac{4\pi}{3})) $$
$$a^5 + b^5 = (a+b) (a+b\mbox{ cis } (\frac{2\pi}{5})) (a+b\mbox{ cis }(\frac{4\pi}{5})) (a+b\mbox{ cis } (\frac{6\pi}{5})) (a+b\mbox{ cis }(\frac{8\pi}{5}))$$
and so forth.  For even $n$,
$$a^4 + b^4 =  (a+b\mbox{ cis } (\frac{1\pi}{4})) (a+b\mbox{ cis } (\frac{3\pi}{4})) (a+b\mbox{ cis } (\frac{5\pi}{4})) (a+b\mbox{ cis } (\frac{7\pi}{4}))$$
and so forth.
You can in fact express the full factorization in terms of easy to swallow radicals for $n=2,3,4,5,6,8$.  Also for $n=17$ for example; see Fermat primes.


Proving conditional independence from mutual independence

Question: Suppose I have a Bayesian inference problem where $E$ is the result of a chemistry experiment. The chemistry experiment consists of a controlled sequential digestion of one end of the protein using a specific enzyme that has known statistical properties. The sequence of the protein is unknown at the beginning of the experiment. The data collected is the number of reactions and the times in which they occur. The goal is to infer sequence information using the enzyme.
$P\left(x_{1},\, x_{2},\,\ldots,\, x_{n}|E\right)$ = $\dfrac{P\left(x_{1},\, x_{2},\,\ldots,\, x_{n}\right)P\left(E|x_{1},\, x_{2},\,\ldots,\, x_{n}\right)}{P\left(E\right)}$
Suppose also that the discrete random
variables $X_{1},\, X_{2},\,\ldots,\, X_{n}$ of the posterior are known to be mutually independent a priori. These random variables of the posterior give sequence information (the 20 amino acids) for the first n positions in the protein. This Bayesian inference calculation is performed for all amino acid sequences of length n. The marginal distributions are then taken to infer the unknown sequence.
How do I prove the conditional independence of the posterior random variables given
the evidence:
$P\left(x_{1},\, x_{2},\,\ldots,\, x_{n}|E\right)$ = $P\left(x_{1}|E\right)P\left(x_{2}|E\right)\cdots P\left(x_{n}|E\right)$
.
Comment: What do you mean by 'of the posterior' in 'Suppose also that the random variables $X_1,X_2,\ldots,X_n$ of the posterior are mutually independent'. Do you mean that you are assuming the conclusion? Or do you mean to assume that the random variables $X_1,\ldots,X_n$ are independent? In the latter case, the conclusion is not in general true.
Comment: I revised the question by including how I am using the variables and the evidence (i.e. the event).
Comment: I answered by a counterexample based on the latter interpretation. If that was not intended, you need to clarify the question.
Comment: You need to define what 'these random variables cannot be a part of $E$ in a counter example' means. What does your result $E$ look like? Is it a single number, or do you perhaps have one measurement per each component of $X$?
Answer: If you mean that the assumption is independence of $X_1,\ldots,X_n$ (a priori), the conclusion is not true. For a counter-example, let $X_1,X_2$ be independent Bernoulli random variables:
\begin{equation}
P(X_i=1) = 0.5,~P(X_i=0) = 0.5,~i\in\{1,2\}.
\end{equation}
Let $E$ be the event that $X_1=X_2$. Clearly $X_1$ and $X_2$ are not conditionally independent conditional on $E$.
Comment: I don't know if to be 'part of $E$' means anything. Surely $E$ somehow depends on the $X$s, otherwise the experiment is not informative at all.
Comment: The assumption is that X_1,...,X_n are known to be mutually independent a priori. In the situation I am considering the random variables X_1,...,X_n are not part of E. E is the result of an experiment that counts the number and times of chemical reactions.
Comment: What I mean is that your counter example does not apply to my situation. I do not condition on the X_1,...,X_n random variables.
Comment: What, then, is $P(E\mid x_1,\ldots,x_n)$ in your question? If your $E$ is independent of the $X$s, then the prior is equal to the posterior.
Comment: The E is the result of a experiment on a single protein molecule. The measured quantities are the number of reactions and when the reactions occur. X_1 takes on one of the twenty amino acids at position one in the protein. X_2 does the same thing at position two, and so on until position n is reached.
Comment: Does the number of reactions depend on all $X_1,\ldots,X_n$ or is there a different number of reactions measured for each of these $n$ positions? It might even help if you edited the question to contain your complete model.
Answer: Recall the multiplication rule of probability
$$P(A_{1}\cap ...\cap A_{n})=P(A_{1})P(A_{2}|A_{1})...P(A_{n}|A_{1}\cap...\cap A_{n-1})$$
Well you could extend this for conditional probability so
$$P(A_{1}\cap ...\cap A_{n}| E)=P(A_{1}|E)P(A_{2}|A_{1}\cap E)...P(A_{n}|A_{1}\cap...\cap A_{n-1}\cap E)$$
where since all $A_{i}$'s are mutually independent then the only "valuable" information (i.e. changes the conditional probability) is $E$ so we have
$$P(A_{1}\cap ...\cap A_{n}| E)=P(A_{1}|E)P(A_{2}|E)...P(A_{n}| E)$$
Though this is not really a proof maybe it can give some insight to why this is your proposition is true


Com quais arquivos deve-se usar a tag  com BootStrap?

Question: Estou estudando sobre o Twitter Bootstrap e tenho uma dúvida: com quais arquivos deve-se usar a tag <link>? São todos os arquivos ou apenas alguns arquivos específicos?
Answer: Você pode incluir apenas o bootstrap.min.css, o bootstrap-theme.min.css é opcional, para caso queira aproveitar alguns estilos de um tema padrão ou para caso queira editar ele e criar um tema customizado.
OBS: Caso você instale via bower ou clone o repositório, você tem a opção de usar LESS e incluir apenas os arquivos referentes aos modulos que esteja usando.
Comment: Muito obrigado @Diego Lopes Lima consegui utilizar o mecanismo.
Answer: Apenas estes devem servir :
<link href="bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="bootstrap-theme.css" rel="stylesheet" type="text/css" />

Com isso você faz referência não só do bootstrap css, assim como o tema que você poderá fazer uma sobrecarga, mas também o arquivo js que permitirá o uso de funções javascript!


Run specific instrumentation test suite with Gradle Managed Devices - Android

Question: So with the release of Android Studio Dolphin & Beta of Electric Eel, I wanted to try the instrumentation tests in gradle. I do however want to exclude some of the tests being run, in order to be able to run specific test suites one at a time.
So here is what I configured so far:
android {
  testOptions {
    managedDevices {
      devices {
        pixel2api30 (com.android.build.api.dsl.ManagedVirtualDevice) {
          device = "Pixel 2"
          apiLevel = 30
          systemImageSource = "aosp-atd"
        }
      }
    }
  }
}

I know I can run my entire suite using
./gradlew device-nameBuildVariantAndroidTest

In my case that would be
./gradlew pixel2api30gaeDebugAndroidTest

gaeDebug being my build variant. This command is being run in my project root.
If I want to run the tests in the tests/large folder for example

How would I go about doing that? Thanks.
Comment: Totally unrelated, but how did you set the different icons for different packages?
Comment: @TWiStErRob Atom icons plugin
Answer: For this you could use 2 different approaches:

Create and run test suites.

For example, for each of these folders, create a TestSuite and define Test classes. For example:
@RunWith(Suite.class)
@Suite.SuiteClasses({
    ExampleLargeTest.class,
    ExampleTwoLargeTest.class,
    ExampleThreeLargeTest.class
})
public class LargeTestsSuite {
}

This suite can be run using following command
./gradlew pixel2api30gaeDebugAndroidTest - Pandroid.testInstrumentationRunnerArguments.class=path.to.your.suite.class

Use Test Categories

Annotate your Test classes like this:
@Category("Large")
public class ExampleLargeTest { ... }

And then you could execute the following command for running all tests with same category:
    ./gradlew pixel2api30gaeDebugAndroidTest -PtestCategory=Large

Hopefully one of these two approaches will suite you.


Facebook Linter - Page Admin URI

Question: Facebook's Linter used to give me the admin uri when I was logged in with an admin account. Also, it would show what the like button would look like on the page which would have another link to the admin page. Were these features taken away with the new Facebook changes?
How can I find the amin uri of website pages that are liked without the lint feature?
Answer: What is the og:type of page? This is true only for real-life types, page with og:type article does not have its own "voice".

Facebook Linter - Page Admin URI


Como mapear uma atributo image pelo Fluent API?

Question: Gostaria de saber como faço para mapear um atributo do tipo image do SqlServer pelo Fluent API.
No meu banco eu tenho a seguinte tabela:
CREATE TABLE [dbo].[ProdutoFotoERP](
    [ProdutoFotoID] [int] NOT NULL,
    [ProdutoID] [int] NOT NULL,
    [Foto] [image] NULL,
 CONSTRAINT [PK_ProdutosFotoERP] PRIMARY KEY CLUSTERED
(
    [ProdutoFotoID] ASC
))

E criei minha entidade da seguinte forma:
public class ProdutoFotoERP
{
    public int ProdutoFotoID { get; set; }
    public int ProdutoID { get; set; }
    public byte[] Foto { get; set; }

    public virtual ProdutoERP ProdutoERP { get; set; }
}

A princípio minha classe de configuração está assim:
public class ProdutoFotoERPConfiguration : EntityTypeConfiguration<ProdutoFotoERP>
{
    public ProdutoFotoERPConfiguration()
    {
        ToTable("ProdutoFotoERP");

        HasKey(c => c.ProdutoFotoID);
        Property(c => c.ProdutoFotoID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

Comment: Infelizmente é um sistema legado e estou fazendo melhorias nele, se eu pudesse, nem imagem gravaria no banco de dados, somente o path de onde ela se encontra.
Comment: Cara, o tipo `image` tá depreciado e vai ser removido nas próximas versões do SQL Server. Se você está começando o sistema agora, é melhor usar `varbinary(max)`.
Comment: Conseguiu resolver?
Comment: @jbueno acabei de testar e funcionou perfeitamente, muito obrigado
Answer: A única coisa que você precisa fazer é o usar o método HasColumnType.
Note que os tipos text, ntext e image estão obsoletos e serão removidos nas próximas versões do SQL Server.
public class ProdutoFotoERPConfiguration : EntityTypeConfiguration<ProdutoFotoERP>
{
    public ProdutoFotoERPConfiguration()
    {
        ToTable("ProdutoFotoERP");

        HasKey(c => c.ProdutoFotoID);
        Property(c => c.ProdutoFotoID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(p => p.Foto).HasColumnName("Foto").HasColumnType("image");
    }
}

Comment: Agora uma duvida, minha entidade seria um tipo byte[] mesmo? Caso seja, quando fosse salvar no banco de dados ele entenderia isso normalmente e salvaria corretamente?
Comment: Acho que sim, mas isso é outra questão, né.
Comment: Essa era minha principal dúvida
Comment: Acabei de ver, e é isso aí mesmo, você quer salvar um array de bytes. Tá certinho
Comment: Vlw, vou testar aqui e te digo


The digits 3, 4. 5, and 6 are used to form a four digit code. No repeated digits are allowed. How many codes are possible?

Question: I'm not exactly sure how to solve this specific problem, but I think I would need to come up with 2 or more equations then solve them together... can't come up with equations though. Can I get some help?
Comment: This is a straightforward application of the [rule of product](https://en.wikipedia.org/wiki/Rule_of_product).  Alternately phrased (*though I insist that you should learn the answer via rule of product first*), this is a straightforward application of one of the many uses of [permutations](https://en.wikipedia.org/wiki/Permutation).  Pick what the first digit in the code is.  You have four options.  Pick what the second digit in the code is.  Since you can't have repeated digits, you have only three options.  Continue and then multiply the number of options for each step to get the count.
Comment: Since all 4 digits are used in the code, the answer is just $4!$
Answer: No equations are needed. Let's construct the number of codes:
We have $4$ numbers at our disposal. Let's take a number and make it our first digit. There are $\color{blue}{4}$ ways to choose this first number.
Now we choose our second digit. We can't repeat numbers, so we have $3$ numbers left and therefore  $\color{blue}{3}$ ways to choose the second number.
Then we choose our third digit. We can't repeat numbers, so we have $2$ numbers left and therefore  $\color{blue}{2}$ ways to choose the second number.
And now we only have one number left, and so we have $\color{blue}{1}$ way to choose the last number.
So in total we have $\color{blue}{4 \times 3 \times 2 \times 1 = 24}$ ways$^{[1]}$ to create such a code.
In general, the number of ways that we can order $n$ objects (such that no object can be used twice) is $$n \times (n-1) \times (n-2) \times \cdots \times 1 = \color{blue}{n!}$$

$[1]$ We multiply because if there are $a$ ways to do stage 1 and $b$ ways to do stage 2, the number of ways that stage 1 and 2 can be done is $a \times b$. Likewise, for the $4$ stages we have here, we multiply the the possibility of each stage, giving $4 \times 3 \times 2 \times 1$. This is known as the rule of product.
Comment: Would it be possible to apply the permutation formula? $n!/(n-r)!$
Comment: @MatinNawabi Absolutely! In terms of permutations (with $_nP_r = \frac{n!}{(n-r)!}$), we want to order $r=4$ elements from a set of $n=4$ elements, which means we need $_4P_4 = \frac{4!}{(4-4)!} = \frac{4!}{0!} = 4!$ .
Comment: Thank you for the help!
Answer: Since there are no repeats, you can think of the first digit having $4$ possibilities. And because you've used that digit already, the next one has $3$ possibilities. And this continues all the way to the end. So your answer is $4\cdot3\cdot2\cdot1$ (the $1$ is there for visuals. You can exclude it and have the same product) which is just $4!$
Answer: First, we draw four boxes.  In the first box, there are 4 possible numbers.  In the second box, there are only 3 choices since numbers cannot be repeated.  Repeating this process, we have $4\times3\times2\times1=24$.


Show that the equation $z^3+3xyz^2-5x^2y^2z+14=0$ has an implicit solution $z(x,y)$ for $z\approx2$ and $(x,y)\approx(1,-1)$.

Question: I recognize that this is an implicit function theorem problem, but I'm not sure exactly how to approach it. I can say that because $\frac{\partial f}{\partial z}(1,-1,2)=3(2)^2+6(1)(-1)(2)-5(1)^2(-1)^2=-5\neq0$, $f=z^3+3xyz^2-5x^2y^2z+14$ can be written in the form $z=g(x,y)$ near the point $(1,-1,2)$, but I'm not sure how this helps.
I also need to determine a locally valid approximation of $z(x,y)$. Any assistance with this is greatly appreciated.
Answer: Let $$f(x,y,z)=z^3+3xyz^2-5x^2y^2z+14$$
then we have $ f(1,-1,2)=0$ and $\displaystyle \frac{\partial f}{\partial z}(1,-1,2)=-5\neq0$ So we can apply the Implicit function theorem which garanty the existence of $W\subset \mathbb{R}^2$ neighbour of $(1,-1)$ and $V \subset \mathbb{R}$ neighbour of $2$ and a function $g:W\subset \mathbb{R}^2 \rightarrow V \subset \mathbb{R}$ such that
$$ f(x,y,g(x,y))=0 \quad \forall (x,y)\in W$$
And to determine a local approximation you can use Euler method when the partial derivative of $g$ on $W$ are given by
$$ \partial_xg(x,y)= - \frac{\partial_xf(x,y,g(x,y))}{\partial_zf(x,y,g(x,y))} $$
$$ \partial_yg(x,y)= - \frac{\partial_yf(x,y,g(x,y))}{\partial_zf(x,y,g(x,y))} $$
Comment: Thank you for the clarification on how to utilize the implicit function theorem. Could you elaborate on how Euler's method is applied here? I don't understand the setup.


Front and backend public files not found

Question: I'm trying to display some image in my front and my backend, a simple image, not a media, but I'm always receiving a 404.
For example, I'm trying to display the icon from my paragraph, to i'm extracting the URL, but when I call it, I have a 404. Where does this error come from ?
Answer: Got it, for some reason, the permission of web/site/default was this (change to 755)

drwxrwx--- 4 vagrant vagrant 4096 juil.  2 15:45 default


Why tag value can't be compared with a same string?

Question: import lxml.html
strings = """
 xyz

xyz
 xyz
"""
root=lxml.html.document_fromstring(strings)
for e in root.iter() :
    print(e.tag)

To print all elements tag value.
html
body
p
<cyfunction Comment at 0x7f6819bb11b8>
br
br

The comment in html string here is ,the tag value of it is <cyfunction Comment at 0x7f6819bb11b8>,i want to compare 's tag value with <cyfunction Comment at 0x7f6819bb11b8>.
import lxml.html
strings = """
 xyz

xyz
 xyz
"""
root=lxml.html.document_fromstring(strings)
for e in root.iter() :
    print(e.tag)
    print(e.tag ==  "<cyfunction Comment at 0x7f6819bb11b8>")

The result is aas below:
html
False
body
False
p
False
<cyfunction Comment at 0x7f6819bb11b8>
False
br
False
br
False

Why is not as below:
html
False
body
False
p
False
<cyfunction Comment at 0x7f6819bb11b8>
True
br
False
br
False

For , the tag value is <cyfunction Comment at 0x7f6819bb11b8>,why <cyfunction Comment at 0x7f6819bb11b8> != <cyfunction Comment at 0x7f6819bb11b8>?
What a joke?
Comment: `0x7f6819bb11b8` is a memory address. It changes every time you run the program. What is the problem that you are trying to solve?
Answer: Not sure if this will satisfy your requirements but you can get the function name and then compare that is it a function Comment
Below is an example of how to do it.
>>> for e in root.iter() :
...     try:
...         e.tag.__name__
...     except:
...         pass
...
>>> 'Comment'

You can match strings as if its a function and it is a function named commnet.
I don't think function objects can be compared in this way although you can compare them using their attributes but can't compare a whole object with other


randomly choose value between two numpy arrays

Question: I have two numpy arrays:
left = np.array([2, 7])
right = np.array([4, 7])
right_p1 = right + 1

What I want to do is
rand = np.zeros(left.shape[0])
for i in range(left.shape[0]):
  rand[i] = np.random.randint(left[i], right_p1[i])

Is there a way I could do this without using a for loop?
Answer: You could try with:
   extremes = zip(left, right_p1)
   rand = map(lambda x: np.random.randint(x[0], x[1]), extremes)

This way you will end up with a map object. If you need to save memory, you can keep it that way, otherwise you can get the full np.array passing through a list conversion, like this:
rand = np.array(list(map(lambda x: np.random.randint(x[0], x[1]), extremes)))


Bad GPU performance when compiling with -G parameter with nvcc compiler

Question: I am doing some tests and I realized that using the -G parameter when compiling is giving me a bad performance than without it.
I have checked the documentation in Nvidia:
--device-debug (-G)
    Generate debug information for device code.

But it is not helping me to know the reason why is giving me such bad performance.
Where is it generating this debug information and when? and what could be the cause of this bad performance?
Comment: I don't know details on nvcc, but typically turning on debug information disables a pile of compiler optimizations to make the generated code better match the source.
Answer: Using the -G switch disables most compiler optimizations that nvcc might do in device code.  The resulting code will often run slower than code that is not compiled with -G, for this reason.
This is pretty easy to see by running your executable in each case through cuobjdump -sass myexecutable and looking at the generated device code.  You'll see generally less device code in the non -G case, and you can see the differences in specific optimizations as well.
One of the reasons for this is that highly optimized device code may eliminate actual lines of source code and actual source code variables.  This can make it very difficult to debug code.  Therefore to enable debugging, most optimizations are disabled with -G.
Also note that with Thrust, using the -G switch may result in unpredictable behavior.  Newer versions of thrust should behave better, but there may still be unexpected issues when compiling thrust code with -G.


'Microsoft.ACE.OLEDB.12.0' 64x Sql Server and 86x Office?

Question: The error:

OLE DB provider 'Microsoft.ACE.OLEDB.12.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.

And the answers I'm seeing is a conflict between 64 bit Sql Server and 32 bit Office.  Is there a way to run an openrowset on Excel into Sql Server?
insert into dbo.FiscalCalendar
select * from
openrowset('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;Database=C:\Users\uname\Desktop\fy11.xlsx;',
'Select * from [Sheet1]')

Answer: ...the key is to install the 64-bit Access engine using the /passive flag:
c:>AccessDatabaseEngine_64 /passive
Comment: I didn't know what the passive flag would do until I encountered an issue installing the 64 bit driver when Office 32 bit was installed. Without the passive flag, it fails to install.
Answer: Looks like Microsoft hasn't come up with a solution on this yet.
check Microsoft feedback form of products
They have some workarounds like using SSIS
Answer: You have to install the Microsoft Access Database Engine 2010 Redistributable 64-bit first, which you can download from here.
Assume that your Excel file is: E:\Sample.xls and your Excel sheet name is: Sheet1
Run the following to get the data from Excel file:
SELECT * FROM OPENDATASOURCE( 'Microsoft.ACE.OLEDB.12.0', 'Data Source="E:\Sample.xls";
Extended properties=Excel 8.0')...Sheet1$

The above query is running on Windows Server 2008 64-bit with SQL Server 2005 64-bit and SQL Server 2008 R2 64-bit installed.
The key is to specify the 64-bit provider 'Microsoft.ACE.OLEDB.12.0' instead of 32-bit only Jet engine.
Answer: I've run into this same exact issue and the only thing I could ever do were an SSIS data source component where you can consume it as part of a workflow
Answer: I installed the Microsoft Access Database Engine 2010 Redistributable 64-bit with no success. I am running W7 64bit, Office 2010 and SQL 2008 R2.
The import/Export wizard prepares the package, but when I choose to save the package, and execute it, it executes just fine. It is when I open the package on a MS VS 2008 that it gave me the error.
Installing the Access Database Engine 2010 did not solve the problem. I tried the 2007 and it worked.
Go figures.
Comment: For me it only work win Access Engine 2016 https://www.microsoft.com/en-us/download/details.aspx?id=54920
Answer: Situation: MS Office 2010 (x86/32bit) on a Windows 7 (x64/64bit) with SQL Server 2014 (x64/64bit) installed
Our solution:

Stop SQL Server if running and close any opened MS Office programs
Download MS Access Database Engine 2010 Redistributable as x64/64-bit version: https://www.microsoft.com/de-de/download/details.aspx?id=13255
Open windows command shell (Start-Execute-"cmd") with administrator rights and execute downloaded setup file as follows:
AccessDatabaseEngine_X64.exe /passive
Start regedit and go to the following key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPath. Rename the value mso.dll into mso.dll.rename
We also needed to grant full rights to everyone for the folder, where the XLSX files were stored we wanted to import (don't do this on multi-user machines or on shared folders).
Open windows system control. Go to administrative tools, services and open the properties of MS SQL Server service. Under "Log On" select  "local system account". Save and restart MS SQL Server.
Open SQL Server Management Studio, connect to your MS SQL Server instance and run the following T-SQL statement:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

Check with following T-SQL statement:
SELECT * FROM OPENROWSET( 'Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;HDR=YES;Database=C:\YourFolder\File.xlsx', 'SELECT * FROM [Sheet1$]');


Multiple svn projects in a folder

Question: I believe the most common way to setup a project in SVN is host/svn/projectA/trunk . However if there are multiple projects that are related, can we have them under one common parent folder, or do they have to be under the svn root?
i.e.
host/svn/projectA/trunk

host/svn/projectB/trunk

host/svn/projectC/trunk

or
host/svn/parentFolder/projectA/trunk

host/svn/parentFolder/projectB/trunk

host/svn/parentFolder/projectC/trunk

Answer: You can setup Subversion any darn way you please. The various directories in Subversion have no meaning to Subversion itself. The meaning is put on it by you. For example, I know many people who don't use trunk, but put a main under their branches directory. This way, everything is a branch which can make things easier to talk about and document.
The standard way (and it's only a standard because most people do it this way) is one of two methods:
/trunk/proj1
/trunk/proj2
/branches/1.2/proj1
/branches/1.2/proj2
/tags/1.2/proj1
/tags/1.2/proj2

Vs.
/proj1/trunk
/proj2/trunk
/proj1/branches/1.2
/proj2/branches/1.2
/proj1/tags/1.2
/proj2/tags/1.2

Sometimes you see it like this:
/trunk/proj1
/trunk/proj2
/branches/proj1/1.2
/branches/proj2/1.2
/tags/proj1/1.2
/tags/proj2/1.2

How should you do it? I would say it all depends how interrelated the projects are. If the projects are all under the same versioning and release schedule, I'd put trunk, branches, and tags at the beginning of the URL. If the projects are not related at all, I would put the project first, and then have each project with a separate branch, tags, and trunk.
The advantage of the second way is that you don't have a confusion which branch or tag goes with which project. It increases the namespace of your tags and branches because each has its own area under each project.
The disadvantage is that you have to create three new directories every time you create a project, and if you are doing a common release, you'll end up making separate tags for each one.
Oh, one more disadvantage: If you use svn:externals on a project (something that I usually don't recommend except under some very specific circumstances, and you use relative URLs, you'll mess up your system doing it the second way.
We have a special Ivy project that's an external for all of our packages. The Ivy package is a way to integrate Ivy into our existing projects without too much difficulty. We have the tags, trunk, and branches directories on the front of our URL. On the root of the project, you put property:
$ svn ps svn:externals ../ivy.dir ivy.dir .

Here's our layout:
/branches/1.2/ivy.dir
/branches/1.2/project
/trunk/ivy.dir
/trunk/project
/tags/1.2/ivy.dir
/tags/1.2/project

The ../ivy.dir means go up one directory, then down to the ivy.dir project. When I branch the project (and the Ivy project), the svn:externals won't have to be edited because it'll point to the same branch. When I tag, I also do the ivy.dir project at the same time. Again, the URL for the svn:externals doesn't change because they're pointing to the same tag.
So, you can setup Subversion any way you want. Using the standard means that when new developers come in, they know where things are and don't have to be trained. Less confusion. The big difference is how related are the projects to each other. If they are all branched, tagged, and released together, use a common set of branches, tags, and trunk directories. If not, you might be better off giving each project their own set of branches, tags, and truck directories.
Answer: The way we have ours setup is in your first example
host/svn/
..
Project A
..
project B
..
Project c
..
etc
It has been working fine for me and I have been using this method for 6+ months.
Comment: Im sure it could, you could create a General folder name, and within that just checkout the project(s) you would like within that folder. I haven't tried it personally though but in theory it sounds do able, Sorry I do not have experience with this route.
Comment: Can it be setup using the 2nd approach as well?

Multiple svn projects in a folder


Prove via induction $H_k(n) = \sum\limits_{j=1}^n H_{k-1}(j)$ where $k>1$

Question: First yes this question is related to the problem I posted before here. But I want to try proving this via induction this time.
Let $H_k(n)$ be the number of vectors $x_1,\dots,x_k$ for which each $x_i$ is a positive integer satisfying $1\leq x_i\leq n$ and $x_1\leq x_2 \leq \dots \leq x_k$. Prove
\begin{equation*}
\begin{aligned}
H_1(n) & = n & \\ \\
H_k(n) & = \sum\limits_{j=1}^n H_{k-1}(j) & k>1
\end{aligned}
\end{equation*}
So the proof is the same for $i=1,2$ which I will provide below. From the previous post,
Let $(x_1,\dots,x_k)$ be a vector such that $x_i\geq 0$ and $x_i\in \mathbb{Z}$ and $1\leq x_i\leq n$.
When $i=1$, then the vector is of length 1. Since $x_1$ is an integer between (and including) 1 and $n$, there are $n$ different choices of integers. Hence $H_1(n)=n$.
When $i=2$, then the vector is of length 2. Since $x_1$ is an integer between (and including) 1 and $n$, we have $n$ options. Now for $x_2$. We know $x_1\leq x_2$. This implies whatever $x_1$ equals $x_2$ has $n-x_1+1$ options (because $x_1$ can be the same as $x_2$). Hence
$$
H_2(n)
= \sum\limits_{x_1\in\{1,2,\dots,n\}} (n-x_1+1)
= 1+2+\dots+n
= \dfrac{n(n+1)}{2}
$$
Now here is the different part. Assume that the sum is true for $i=k$. i.e.
$$ H_k(n) = \sum\limits_{j=1}^n H_{k-1}(j)$$
We want to show that
$$ H_{k+1}(n) = \sum\limits_{j=1}^n H_{k}(j)$$
So here is what I got so far
$$ \sum\limits_{j=1}^n H_{k}(j) = \sum\limits_{j=1}^n \sum\limits_{\ell=1}^j H_{k-1}(\ell)$$
I know I can repeat this continuously until I get $H_1(\alpha)$ where $\alpha$ is some positive integer. But that doesn't get me anywhere.
I have also tried doing the following:
\begin{equation*}
\begin{aligned}
\sum\limits_{j=1}^n H_{k}(j) & = H_k(1) + H_k(2) + H_k(3) +\dots+H_k(n) \\
& = \sum\limits_{j=1}^1 H_{k-1}(j) + \sum\limits_{j=1}^2 H_{k-1}(j) + \sum\limits_{j=1}^3 H_k(j) + \dots + \sum\limits_{j=1}^n H_{k-1}(n) \\
& = nH_{k-1}(1) + (n-1)H_{k-1}(2) + (n-2)H_{k-1}(3) + \dots +H_{k-1}(n)
\end{aligned}
\end{equation*}
Again I can repeat this step again with the equation for $H_{k-1}(n)$ but I feel like I am going on a never ending battle. Any suggestions.
Comment: Let $\mathcal H_n$ be the set of $n$-vectors $(x_1,\cdots,x_n)$ you're counting. Notice that $x_n$ can actually be any value between $1$ and $n$ and that once you fix $x_n=k$, all other $n-1$ numbers $x_1,\cdots,x_{n-1}$ can only take the values between $1,\cdots,k$. Can you continue from here?
Comment: @Alessandro ... So how would that translate to the equations? And which string of equations that I have above would you use?
Answer: I would have done induction on $n$: First, it's easy to see that $H_k(1)=1$ for every $k$, so that $H_k(1)=\sum_{j=1}^1H_{k-1}(1)$, for $k>1$.
Let $\mathcal H_k(n)$ be the set as of tuples $(x_1,\cdots,x_k)$ as in the question. You want to break $\mathcal H_k(n)$ into two subsets of which you can apply induction. In this case, you break the set into $x_k<n$ and $x_k=n$, because then you can reduce $n$, because if $x_k=n$, then you're only $k-1$ variables $x_1,\cdots,x_{k-1}$, so the number of tuples $(x_1,\cdots,x_{k-1},n)$ is just $H_{k-1}(n)$. Next, if $x_k<n$, then all other variables must be $<n$ and so we're counting $H_k(n-1)$ and you can apply induction and conclude that $$H_k(n)=H_{k-1}(n)+H_k(n-1)=\sum_{j=1}^nH_{j-1}(n)$$


Destructure ES6 in React props

Question: I want to destructure my props two levels down. I know you can do it like this:
const MyComponent = ({ aPropOneLevelDown: { anotherPropButTwoLevelsDown } }) => { ... }

I know this will work, but the issue is when aPropOneLevelDown is not defined yet. Then I get the error message: Uncaught TypeError: Cannot read property 'anotherPropButTwoLevelsDown' of undefined
What can I do to keep the advantage of destructuring?
Comment: assign `defaultProps`  to the component https://reactjs.org/docs/react-without-es6.html#declaring-default-props
Answer: Use default props
Like this
const MyComponent = ({aPropOneLevelDown: { anotherPropButTwoLevelsDown } = {}}) => {}

Or this
const MyComponent = ({aPropOneLevelDown: { anotherPropButTwoLevelsDown }}) => {}

MyComponent.defaultProps = {
    aPropOneLevelDown: {}
}

Destructure ES6 in React props


a Function with several periods

Question: A periodic function is given by $ f(x+nT)=f(x) $, with 'n' an integer and T the period.
My question is if we can define a non-constant function with several periods; by that, I mean
$ f(x+T_{i})=f(x) $ with $ i=1,2,3,4,\dots $ a set of different numbers.
For example, a function that satisfies $ f(x+2)=f(x) $, as well as $ f(x+5.6)=f(x) $ and  $ f(x+ \sqrt 2) =f(x) $, but $ f(x) $ is NOT a constant.
Answer: There are the elliptic functions, which are functions that have two (in general) complex periods. It is a deep theorem of the theory of elliptic functions that the ratio of these two periods is necessarily not real. This was proven by C.G.J. Jacobi in 1835, who also showed that there cannot be a single-valued function of one variable that has more than two periods.
Comment: See [this](http://books.google.com/books?hl=en&id=N2pX-wMEIb4C&pg=PA17) as well.
Answer: If we work with functions from the real line to itself, we have several cases. Since the set of periods of a function is a subgroup of the additive group of the real, it is either dense in $\Bbb R$ (for the usual topology) or discrete (of the form $a\Bbb Z$ for some $a\in\Bbb R$.
If $G$ is a subgroup of $\Bbb R$, then the characteristic function of $G$ is $g$-periodic for each $g\in G$.
The group of the periods of a continuous function is either $\Bbb R$ (constant functions) or discrete.
Comment: OK, discrete, and what?
Answer: Dirichlet function is not a constant and has both 2 and 5.6 as its periods. But there is no smallest period.
Comment: @Aniket it has no smallest period but has other periods.
Comment: Dirichlet function is a periodic function with no definite period.
Comment: What do you mean by "it has no smallest period"?

a Function with several periods


How can I change the 'active' class in main menu to something else?

Question: I'd like to change the class in the main menu from 'active' to say 'current'.  How can this be accomplished?
Answer: Assuming you are using Drupal 7.
You can overide theme_links in your own theme.
find the line:
$class[] = 'active';
make it
$class[] = 'current';
check API:
http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_links/7
by the way, I would suggest you not to change 'active', instead you can just add additional class for it.  As many contributed modules use the default 'active' class. Such as SuperFish, Menu Block


probability function of a function of random variables

Question: For any random variable that is a function of other random variables, e.g. $Z = g(X_1,X_2,X_3) = 5X_1 + (X_2X_3)^2$, is there a general formula/method to find $f_Z(z)$ given one knows $X_1,X_2,X_3$ are all independent and one also knows $f_{X_1}(x_1),f_{X_2}(x_2),f_{X_3}(x_3)$?
I know the existence of convolution i.e. to find $f_Z(z)$ when $Z=X_1+X_2+...+X_n$ but apart from convolution I know no other formula/method to find the probability function of a function of random variables.
Comment: In principle, Yes. Consider the Jacobian formula. However, computing an explicit formula might not be easy, in general.
Comment: @AdityaGhosh Does *Jacobian formula* refer to *the change of variable technique*?
Comment: Yes. It is the change of variable technique, for functions of several variables.
Comment: @AdityaGhosh Okey, nice. And it can be used to find $f_Z(z)$ for any linear combination of $X_1, X_2, ... , X_n$ as long as we know $f_{X_1}(x_1) , f_{X_2}(x_2), ... , f_{X_n}(x_n)$, right?
Comment: Yes, in principle. But as I said earlier, the Integrals may be hard to compute and it is possible that there is no explicit closed-form expression.
Comment: @AdityaGhosh I looked it up. I think you miss understood my question. My question is not in regards to a vector $Z$, but rather what $f_Z(z)$ would be given $Z=g(X_1,X_2,...,X_n)$ i.e. $Z$ is **one** random variable (not a vector of random variables) and $Z$ is a function of a bunch of other random variables. *the change of variable technique* can be used to find $f_{Z_1,Z_2,...,Z_n}$ when each $Z_i$ is a linear combination of  $X_1,X_2,...,X_n$ i.e. we go from a joint distribution to another joint distribution only the variables are different. Please correct me if I have misunderstood.
Answer: If $Z=g(X_i)$, then general formula would be:
$$
f_Z(z) = \int \delta\left(g(x_i)-z\right)f_{X_i}(x_i)dx_i,
$$
where $\delta(x)$ is Kronecker delta function and $f_{X_i}(x_i)$ is probability density function of vector $x_i$.
If $X_i$ has independent components, then joint pdf is a product of pdfs: $f_{X_i}(x_i)=f_{X_1}(x_1)f_{X_2}(x_2)\ldots f_{X_n}(x_n)$.
Finally, if it's possible to express one of the components $X_i$ from the function $g$, you can contract one of the integral and delta function:
$$
f_{Z}(z) = \int\limits_{-\infty}^\infty\int\limits_{-\infty}^\infty\int\limits_{-\infty}^\infty
\delta\left(5x_1+(x_2x_3)^2-z\right)f_{X_1}(x_1)f_{X_2}(x_2)f_{X_3}(x_3)dx_1dx_2dx_3=\\
\int\limits_{-\infty}^\infty\int\limits_{-\infty}^\infty
\frac15f_{X_1}\left(\frac{z-(x_2x_3)^2}5\right)f_{X_2}(x_2)f_{X_3}(x_3)dx_2dx_3,
$$
Answer: This is a good question. I'd say the most general purpose technique is to find the CDF and then differentiate. I.e., calculate:
$$F_Z(z) = \int_{(x_1,\dots,x_n):g(x_1,\dots,x_n) \leq z} f_{X_1,\dots,X_n}(x_1,\dots,x_n) \ dx_1\cdots \ dx_n$$
and then
$$f_Z(z) = \frac{d}{dz}F_Z(z).$$
I think this will work in your particular example as long as you can determine the region of $(x_1,x_2,x_3)$ where $5x_1+(x_2x_3)^2 \leq z$. However, one can certainly come up with functions $g$ for which this won't be possible.


In football, a player is to be cautioned if he 'shows a lack of respect for the game': what does this mean?

Question: Although the Laws of the Game say a player must be cautioned if he's guilty of unsporting behaviour, a direct definition of what constitutes "unsporting behaviour" is never provided (apart from a very brief and rather generic description given in the Glossary, which merely states that "unsporting behaviour" is any 'Unfair action/behaviour').
Instead, the Laws explain this concept by giving a (non-exhaustive) list of examples, among which this can be found (Law 12.3):

Cautions for unsporting behaviour
There are different circumstances when a player must be cautioned for
  unsporting behaviour including if a player:
[...]
• shows a lack of respect for the game

I've always been curious as to what showing a lack of respect for the game can possibly mean: what's an example of behaviour that can warrant a yellow card for showing a lack of respect for the game that doesn't also belong to any other categories of misconduct? (Including the red card offences as well, so offensive/insulting/abusive actions or words are out of questions since they're already sending-off offences.)
Answer: It's impossible to give an exhaustive answer here, but here are some of examples of behaviour where a referee may elect to caution a player for unsporting behaviour for shows a lack of respect for the game:

using provocative, derisory or inflammatory (but not offensive, insulting or abusive) language or gestures against another person,
smoking or otherwise consuming intoxicating substances on the field of play,
uses a mobile phone on the field of play, during the match,
"relieving themselves" outside the field of play, without using a restroom (if a player exposed themselves while doing this or did this on the field of play, they would probably be sent-off for offensive, insulting, abusive gesture),
using an unsporting gesture to humiliate the opponents when there is no footballing reason to do so (e.g. rounding the goalkeeper, stopping the ball on the goal line, and then heading it in off the ground.

As you've noticed, the Law isn't prescriptive in this area, so cautioning for any of these offences heavily depends upon the opinion of the referee, the context, the temperature of the match, etc.


What is an endomorphism?

Question: This question is really basic, but I have essentially no background on algebra so I really do not know basic things. On page 4 of these notes, the author defines $\text{End}S$ to be the set of all endomorphisms of a given finite-dimensional vector space $S$. What is the definition of an endomorphism?
Comment: An endomorphism is a linear transformation $S \to S$.  An isomorphism between $S$ and $V$ is a bijective linear map $S \to V$.
Comment: A homomorphism from the structure to itself. "Homomorphism" means "function that respects the structure". In the case of vector spaces, it means "linear transformation." So the endomorphisms of $S$ are the linear transformations $T\colon S\to S$. The *isomorphisms* are the invertible homomorphisms (in this case, invertible linear transformations). An endomorphism that is an isomorphism is usually called an "automorphism".
Comment: @Randall why not make it an anwer
Comment: @KennyLau because it's probably going to just get closed or deleted.
Comment: Thank you guys! I know the question is really basic, but a search on the internet and you find a bunch of things and it is really difficult to know what is the appropriate definition for you.
Comment: Did you mean to ask about "isomorphisms" at the end of your question, or was that meant to be "endomorphism"? Because that was a pretty sudden change of subject.
Comment: @ArturoMagidin ops! My mistake! Corrected now! Thanks!
Answer: An endomorphism is a homomorphism $\varphi : A \to A$ with $A$ being an mathematical structure. So its a mapping from a structure to itself with respect to the structure ("not losing it through the mapping").
To be more precise and for example: In terms of $(A, \circ), (B, \ast)$ being groups or monoids with $\varphi : A \to B$:

$\varphi(1_A) = 1_B$ for any $1_A, 1_B$ being neutral elements in $A$ and $B$
$\varphi(a \circ_A b) = \varphi(a) \ast_B \varphi(b)$ for all $a \in A$ and $b \in B$

What is an endomorphism?


how to validate parameter value in ruby on rails?

Question: example contrived for this question. what is the best way to validate values of parameters passed in ruby on rails. I want to make sure the value of property parameter is one of the allowed values ( auto , home, boat). also what is the best way to validate id is a valid numeric value.
Module Lib
 class Service
  include HTTParty
  base_uri "https://www.quotescomare.com"

  class << self

    def QuoteSearch (property, id)
     begin
       response = HTTParty.get(url/property/id)
       if response.successful?
         filter_json(response)
       else
         raise 'invalid response'
       end
     end
   end
  end
 end
end

Answer: Regarding the allowed values, you can create a simple constant with the valid values, like this:
PERMITTED_PROPERTIES = %w(auto home boat).freeze

And then you can check if the property is one of them:
PERMITTED_PROPERTIES.include?(property)

About the check to see if the id is numeric, you can do this:
id.is_a? Numeric

Comment: This way you will have to convert it to a number to pass it as a parameter in the QuoteSearch method. You can do it with `.to_i`, just mind that it will convert `nil` to 0, I am not sure if this is a problem to you. You can also filter the valid parameters using Rails built int strong parameters: https://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
Comment: I found two gems that may help you with that: `https://github.com/alfa-jpn/params_sanitizer` and `https://github.com/rgrove/sanitize`. The first one is not being maintained, though.
Comment: thank you. if id is passed as a query string. do I have to convert it to a number first? is there any inbuilt sanitizing built in so that nothing harmful is passed?
Comment: thanks. I looked at that too, but i didn't see how to check for data type of params and how we can sanitize values from a ajax request. let me know if you have any more thoughts on how to sanitize the values?


How many people need to be screened if the disease has an R0 of 2, and starts with 1 infection in 1000?

Question: I need to calculate how many people I would need to screen to catch a disease in its early stages. If the disease has an R0 of 2, and starts with 1 infection in 1000, and I screen one person in every 1000 - how many people will the disease have reached by the time I screen an infected individual?
How can I do this on excel?
Comment: What's R0? In what context does this question arise?
Comment: It seems as if there's some information required that isn't here, but this may simply be my own ignorance. (Further, is this screening 'perfect' in the sense of no false positives and no false negatives?)
Answer: You really should provide more information otherwise only the people in your field know what you are actually asking. Since you only specified $R_{0}$ and $f(0)$ I assume your growth model is a logistic, which is: $$ f(t)=\frac{1}{1+e^{-R_{0}t+log(\frac{1}{f(0)}-1)}}$$ The probability of sampling 1000 individual in which >1 infected individual is found at time t is $$P=1-(1-f(t))^{1000}$$. Or:
$$t=\frac{1}{R_{0}}[log(\frac{1}{f(0)}-1)-log(\frac{1}{1-(1-P)^{\frac{1}{S}}}-1)]$$
where $S$ is sample size (1000).
Excel code:
<code>=1/B2*(LN(1/C2-1)-LN(1/(1-(1-A2)^(1/D2))-1))
</code>
if $P$ is in A2 cell, $R_{0}$ in B2, $f(0)$ in C2 and sample size $S$ in D2
Comment: Since you seem to know what "$R_0$" refers to, would you mind enlightening us?
Comment: Sure, this question is regarding the logistic growth model, used mainly in ecology, microbiology and medical research. The model is better illustrated in a form of differential equation: $\frac{df(t)}{dt}=r f(t)(1-\frac{f(t)}{K})$, $r$ is often called intrinsic growth rate and $K$ called carrying capacity, $f(t)$ is the population size/number of animal/bacterial/new product sold at time $t$. $f'(0)$ is the grown rate at zero time also labeled as $R_0$, or I hope that's what the OP means. It couldn't be $r$ for sure.


What algorithm to use for fitting several different lines

Question: I have a unique problem I'm not sure how to approach.
I have some data. The data was generated by a function that's basically $k$ different lines ($k$ may or may not be given).
Example:
However, since the data is noisy or poorly measured, it doesn't look exactly like $k$ lines when I see it, and it's certainly not labelled. In-fact what I see is this:

My goal is to label each point in this data and assign it to a different line. For instance, in this case, I would like something akin to this:

So this is a variant of clustering problem, where I know for certain that the shape of the cluster has to be almost a straight line.
I tried using k-means and had terrible results, I tried using mixture of Gaussians and saw significant improvement but nothing to write home about.
I am open to new suggestions, I'm unsure what to do.
download link for data sample - https://easyupload.io/deumkr
the column time received is the x-axis, the column tcptimestamp is the y-axis
Comment: The appropriate model would be a *linear spline* model, or *piecewise regression*. If I understand you correctly, the breakpoints (i.e., the x values where the slopes change) are not given, correct? Then they would need to be detected. There are tools that can do so. Can you edit your post to include (some of) your data?
Comment: the breakpoints are not given. The problem is exactly how to detect them. Once they are detected, it's a simple matter to find the straight lines (its not strictly speaking linear regression, since i have a constraint i have not mentioned, but safe to say the problem is solved once I find the breakpoints). What do you mean by including the data? as in a download link to the data file?
Comment: Yes, a download link to a csv file would work fine. Or simply paste them into the post.
Comment: @StephanKolassa done.
Comment: If you take the derivative of the data, it should be very easy to cluster.
Answer: Here is what the segmented package for R finds if we ask it to find a single break point:

R code:
foo <- read.table("noisy data.csv",header=TRUE,sep=",",dec=".")
library(segmented)

# model without breaks as a starting point
model.0 <- lm(TcpTimeStamp~Time.received,data=foo)

# model with one break
model.1 <- segmented(model.0,npsi=1)
plot(model.1,lwd=2,col="red")
with(foo,points(Time.received,TcpTimeStamp,pch=19,cex=0.8,col="grey"))

You can control the number of breaks to be detected by changing the npsi parameter to segmented(), or alternatively specify a vector of initial break locations with the psi parameter. Depending on your needs, you can change pick a number of breaks that makes sense visually, or base the decision on adjusted $R^2$ or AIC or similar, or even use cross-validation.
Take a look at the help page with ?segmented (or read the documentation at the CRAN page linked above) for more parameters and pointers to literature for the algorithm used.
There are a number of short tutorials online that may be useful, e.g., here. You can also google for "linear spline", "breakpoint detection", "piecewise linear regression" or similar search terms.


Access public function from private function in JavaScript

Question: I have recently started with OOP in JavaScript. And, I am allover confused with these things. I know JavaScript is entirely different from Java. But this is causing problem.
What I am trying to implement:
function myClass() {
    //Declare private variable
    var privateVar = '';

    //To act as constructor
    privateFunction('Hello');

    //Getter
    this.publicFunctionGet = function() {
        return privateVar;
    }
    //Setter
    this.publicFunctionSet = function(x) {
        privateVar = x;
    }
    function privateFunction(x) {
        this.publicFunctionSet(x);
    }
}

//Create object of myClass
var me = new myClass();
alert(me.publicFunctionGet());

This is throwing an error, which says:

Uncaught TypeError: undefined is not a function

For
function privateFunction(x) {
    this.publicFunctionSet(x);
}

What should I do? How to implement this part.? have I misunderstood something about JavaScript classes.?
Answer: Look at this answer.
You wrap the public functions in an object literal and return it. You can thus call the private functions in the object literal functions.
Answer: You should read about hoisting and differences between declaring function and function expression.
Your code does not work because js knows that there is declared var publicFunctionSet (function expression) but it is not a function when privateFunction(x) is being declared.
PS. @Akash Pradhan answer will solve your problem, but I guess you still should check the background and undestand why it is not working the way you tried :)


How to charge a user to post a job listing in D7?

Question: I have a job board and want to charge recruiters for each time they post a job listing. I will be using paypal and would not mind using the Commerce module in Drupal 7. I'm comfortable building Rules, even very complex ones. What is the best way to let job recruiters and businesses manage purchasing credits to be granted permission to create a job posting content type?
Comment: On a side note, I don't think node-access is an appropriate tag for this post, but maybe I'm missing something.
Answer: You can use a combination of Commerce userpoints and Commerce Node Checkout. This will allow them to purchase credits to be applied to publishing nodes.
Answer: Commerce Credits gives the developer many different granular options to configure paying per content basis


Can $\sum_{\ell=1}^{k-1} \binom{k}{\ell} \frac{x^{\ell}y^{k-\ell}}{\ell} $ be written more simply?

Question:
Question: Can the expression $$\sum_{\ell=1}^{k-1} \binom{k}{\ell} \frac{x^{\ell}y^{k-\ell}}{\ell} $$ be written as a polynomial in or other elementary function of $(x+y)$,$x$,$y$ with a fixed number of terms for all $k\ge 2$? (I.e. in a way such that the number of terms does not increase with $k$, but is constant irrespective of the value of $k$.)

As a warning, I'm fairly certain that the answer is no, but I have no idea how one could even hypothetically prove that it's impossible. Is it easier to prove that it's impossible to do so in terms of polynomials or rational functions?
I know that for $k \ge 3$ one can write
$$\sum_{\ell=1}^{k-1} \binom{k}{\ell} \frac{x^{\ell}y^{k-\ell}}{\ell} = (x+y)^k - x^k - y^k -\sum_{\ell=2}^{k-1} \binom{k}{\ell}\frac{\ell -1}{\ell}x^{\ell}y^{k-\ell} $$
but that obviously doesn't give a solution or even simplify the solution, since that has $(k-2)+3 = k+1$ terms, and thus the number of terms also goes to infinity with $k$, just like for the original expression.
Motivation: I was trying to write a bivariate power series related to the exponential integral function as a single summation instead of a double summation. While $\sum_{k=1}^{\infty} \frac{x^k}{k \cdot k!}$ can be written in terms of an antiderivative for  $\frac{e^x}{x}$, because of the unsolvability of the above problem it seems there is no way to write the "bivariate analogue" $$\sum_{k=1}^{\infty} \frac{1}{k!} \sum_{\ell=1}^{k-1} \frac{1}{\ell}\binom{k}{\ell}x^{\ell}y^{k-\ell} $$
simply, i.e. it does not seem to simplify to a single summation power series, not even to something that could be written in terms of
$$\sum_{k=1}^{\infty} \frac{1}{k!}(x+y)^k $$
(which itself can be written in terms of an antiderivative for $\frac{e^{z}}{z}$, defining $z=x+y$).
EDIT: This question corresponds well to my username (i.e. it is a really stupid question), because I just realized that if one re-indexes the above power series by setting $k=p+q$, $\ell=p$ (and so $k-\ell=q$), then the bivariate power series is really easy to write in terms of the univariate:
$$\sum_{p=1}^{\infty}\sum_{q=1}^{\infty} \frac{1}{(p+q)!} \frac{1}{p} \binom{p+q}{p} x^p y^q = \sum_{p=1}^{\infty} \frac{x^p}{p \cdot p!} \sum_{q=1}^{\infty} \frac{y^q}{q!} = (e^y - 1) \sum_{k=1}^{\infty} \frac{x^k}{k \cdot k!}\,. $$
(The key observation is that the $(p+q)!$'s cancel, $\binom{p+q}{p}=\frac{(p+q)!}{p!q!}$ after all, and then after that it's possible to separate everything between the $p$'s and $q$'s.)
Answer: Just playing around,
I get this:
$\begin{array}\\
f_k(x, y)
&=\sum_{j=1}^{k-1} \binom{k}{j} \frac{x^{j}y^{k-j}}{j}\\
&=y^k\sum_{j=1}^{k-1} \binom{k}{j} \frac{(x/y)^{j}}{j}\\
&=y^kg_k(x/y)\\
g_k(x)
&=\sum_{j=1}^{k-1} \binom{k}{j} \frac{x^{j}}{j}\\
g_k'(x)
&=\sum_{j=1}^{k-1} \binom{k}{j} x^{j-1}\\
&=\dfrac1{x}\sum_{j=1}^{k-1} \binom{k}{j} x^{j}\\
&=\dfrac1{x}((1+x)^k-1-x^k)\\
\end{array}
$
But integrating this last gives,
according to Wolfy,
a hypergeometric function,
so this is not much help.
Answer: Let $ k $ be a positive integer, we have :
\begin{aligned}\sum_{\ell=1}^{k}{\binom{k}{\ell}\frac{x^{\ell}y^{k-\ell}}{\ell}}&=\int_{0}^{x}{\sum_{\ell=1}^{k}{\binom{k}{\ell}t^{\ell-1}y^{k-\ell}}\,\mathrm{d}t}\\ &=\int_{0}^{x}{\frac{\left(y+t\right)^{k}-y^{k}}{t}\,\mathrm{d}t}\\ &=\sum_{j=0}^{k-1}{y^{j}\int_{0}^{x}{\left(y+t\right)^{k-1-j}\,\mathrm{d}t}}\\ &=\sum_{j=0}^{k-1}{\frac{y^{j}\left(y+x\right)^{k-j}}{k-j}}\\ \sum_{\ell=1}^{k}{\binom{k}{\ell}\frac{x^{\ell}y^{k-\ell}}{\ell}}&=\sum_{\ell=1}^{k}{\frac{y^{k-\ell}\left(y+x\right)^{\ell}}{\ell}}\end{aligned}
I don't see how we can do further simplifications.


Examples for using mixed models in physics & engineering

Question: Could you highlight useful examples when it makes sense to use mixed models in physics / engineering?
I still wonder when I should use a mixed model and when not.
Comment: This is really to broad for this site, can you try to narrow it down?
Comment: Would something like [*Spatial generalized linear mixed models of electric power outages due to hurricanes and ice storms*](https://www.sciencedirect.com/science/article/abs/pii/S0951832007001305) (2008) qualify? What you are asking is pretty open-ended.
Comment: Definitely, sorry for that. So far, I'm mostly or only reading examples of medical or psychological applications and I would like to know whether these models are also used for devices, machines and so on. Or actually rather how.
Answer: As I see it, there is no reason why these models cannot be used in these domains. My feeling is that there is a degree of techniques falling in and out of fashion. Often students will learn the techniques of their lecturers, mentors and colleagues, and I suspect in recent years LMM have gained traction in certain disciplines but not yet in others.
Here are a few examples of their applications to engineering and physics, along with one of my own applications in business.

Productivity estimation of bulldozers using GLMM here they are modelling productivity of bulldozers, including different properties of the bulldozer and the operator. They consider soil type as a random effect.

In my own work I have used LMM to estimate the time it takes workers to complete some process. Very roughly speaking: We want to know whether some change in the process (treatment) leads to a reduction in time to complete the process. A huge source of variability is the worker themselves, some are naturally a lot faster than others, therefore the specific worker is a random effect.

Here is an example in engineering. An Analysis of defective products in auto parts factories with generalized linear mixed models   I was not able to load a copy of the paper. However from reading the abstract I can imagine how they might be useful here. The data was collected from 12 machines and so you could imagine it might make sense to have machine as a random effect. You would have to read the article to be sure what they do though.

Spatiotemporal dynamics of NO2 concentration with linear mixed models: A Bangladesh case study
Published in the journal of physics and chemistry of the earth.
I highlight this as the journal name specifically mentions physics and chemistry.

Update following Ben's comment. I am not sure I can give a good answer for when to use them. For most of the examples above I tried to explain how they might be used there, because I think a good way to learn is to see examples and then as you become familiar with the examples, you will start to see how your potential use cases match examples you have seen before. I am not sure whether you have done many tutorials/hands on examples using these models, but I think working through a few of these would really help you to see how and why they are useful. I would recommend this tutorial, and note also the 'What' section gives an explanation of why you might want to use them. There is also this answer. To quote from the current top answer

"I believe that a multilevel model makes sense when there is reason to believe that observations are not necessarily independent of one another. Whatever "cluster" accounts for this non-independence can be modeled."

In my use case my observations are the times it takes workers to complete some task. The times are not independent, and times from the same worker are likely to be similar (some workers are fast, some are slow). To account for this I group the times by the worker. The overall point of this was to determine whether some treatment had led to a speed-up.
Comment: Hi @Ben I have tried to cover your additional questions.
Comment: Thanks a lot! Could you also add some more general advices when to use it or not (if doable related to physics/engineering)? I will accept your answer then. If not, I'll do that as well but wanna' leave it open for other input. May I ask what exactly you are doing in your job?


msg.mentions.users.first(), does not run

Question: i am a new JS/Discord.js dev making a bot, but msg.mentions.users.first() is not working, nothing runs after this.
Code -
<code>   var mentioner = msg.mentions.users.first();

        let mentiosner = msg.guild.members.cache.get(mentioner.id);

        console.log(mentiosner.nickname)

        let rand = Math.random(1,deaths.length)
        let floor =  Math.floor(rand * deaths.length)
        console.log(deaths[floor])
        console.log(rand)

        let death = new discord.MessageEmbed
        death.title = "**death'd**"
        death.description = `${mentiosner.displayName} ${deaths[floor]}`
       msg.channel.send(death)

</code>
Answer:
I'm not sure what the problem is but maybe this will help you:
https://discordjs.guide/creating-your-bot/commands-with-user-input.html#mentions\
Hope I could help ;)
ShadowLp174


Change Format of Facebook "end_time"

Question: Can anyone suggest a function to convert this: "2012-01-27T08:00:00+0000" to "Jan 27"?
Comment: EDIT: Found out that it is possible to output the right format by simply appending date_format=
Answer: This can be done by using two functions strtotime and date.
Strtotime : http://php.net/manual/en/function.strtotime.php to convert the time to Unix timestamp
Date : to format specific date/time.
date('M d', strtotime('2012-01-27T08:00:00+0000'));
where M = Month and d = date
Comment: Awesome, you can change the format of date if you want for date using different formats in date function :)
Answer: This is what I do with my paypal code which is about the same as here
function convertTime($time) {
    $time = urldecode($time);
    list($hour, $minute, $junk) = explode(':',$time);
    list($second, $month, $day, $year) = explode(' ',$junk);
    $day = explode(',',$day);
    $day = $day[0];

    $montharr = array('Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6,'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12);
    $timestamp = mktime($hour, $minute, $second, $montharr[$month], $day+1, $year);

    return $timestamp;
}

Then you can change timestamp to what you want using the php date function
<?PHP
    date('F j', convertTime($end_time));

?>

I understand that there is a strtotime() function but this gives me a bit more control over things.
Comment: thanks mate, I went with Aby's solution since it suits my needs a bit better. However, I like your solution! Cheers!

Change Format of Facebook "end_time"


To check if $f_x$ and $f$ are bounded for $f(x,y)=\frac{x^2y}{x^2+y^2}$

Question: Let $$f(x,y)=\frac{x^2y}{x^2+y^2}$$ for$(x,y) \ne(0,0)$
I want to check if $f_x$ and $f$ are bounded
I calculated $f_x=\frac{2xy^3}{(x^2+y^2)^2}$
To check if its bounded below or above,do I have to calculate limits?
If so,at which points?
Comment: I am an amateur at this, so I don't know what $f_x$ is. Could somebody please tell me?
Comment: Its partial derivative of $f$ wrt $x$
Comment: I assume that *wrt* means "with respect to", and now it makes sense. Thanks :)
Answer: You can view $f(x,x)=\frac{x^3}{2x^2}=\frac{1}{2}x$, hence it is unbounded, if $f\colon\mathbb{R}^2\setminus\{0\}\to\mathbb{R}$
Edit: Your $f_x$ is correct. You can show that it is bounded by calculating the maximum and minimum.


Fractional differential operator

Question: We consider the operator  $$\eqalign{
  & T: = \left(I - {{{\partial ^2}} \over {\partial {x^2}}}\right):H_0^1(0,L) \cap {H^2}(0,L) \to {L^2}(0,L)  \cr
  &  \cr}
$$
i'm wondering, is this true  :   $$ (Tu,u) = ({T^{1/2}}u,{T^{1/2}}u)$$ ?
Is there an explicit formula of  $ {T^{1/2}} $  ?
Thank you.
Comment: There do exist ways to define fractional differentials. But they are not unique, you could often define them in many different ways.
Comment: Is the formula that i wrote true ?
Comment: Is it a integral scalar product or what is it? That probably depends on how we try to define $T^{1/2}$
Answer: It is true since $T$ is symmetric and has positive eigenvalues. In fact, it is easy to check
$$ (Tu,v)=(u,Tv), \forall u,v\in H_0^1(0,L)\cap H^2(0,L) $$
which means that $T$ is symmetric. Since $\sin(\frac{n\pi x}{L})\}_{n=1}^\infty$ is dense in $H_0^1(0,L)\cap H^2(0,L)$ and
$$ T\sin(\frac{n\pi x}{L})=(1+\frac{n^2\pi^2}{L^2})\sin(\frac{n\pi x}{L}), n=1,2,\cdots, $$
namely $T$ has positive eigenvalues $1+\frac{n^2\pi^2}{L^2}$ with the corresponding eigenfunctions $\sin(\frac{n\pi x}{L})$, $n=1,2,\cdots$.
For $u\in H_0^1(0,L)\cap H^2(0,L)$, let
$$ u=\sum_{n=1}^\infty u_n \sin(\frac{n\pi x}{L}). $$
Clearly
$$ Tu(x)=\sum_{n=1}^\infty u_n (1+\frac{n^2\pi^2}{L^2})\sin(\frac{n\pi x}{L}). $$
Define
$$ (T^{\frac12}u)(x)=\sum_{n=1}^\infty u_n\sqrt{1+\frac{n^2\pi^2}{L^2}}\sin(\frac{n\pi x}{L}).$$
It is easy to check that
$$ (T^{\frac12}u, T^{\frac12}u)=(Tu,u).$$
Comment: Yes this is a classical construction, but this is just one branch (probably the most natural one to pick though). But you could pick different branches and get the same result.
Comment: @mathreadler, what do you mean one branch?
Comment: You could pick $-u_n\sqrt{1+\frac{n^2\pi^2}{L^2}}$ for any of the Fourier coefficients. Or you could even shuffle them around pairwise.
Comment: @mathreadler, essentially they are the same.
Comment: @mathreadler : This is the unique positive square root.
Comment: Yes, but it's not the only solution to the equation which we are solving. Multiplying with $-x$ twice gives the same result as $x$ twice. There is no extra condition for $T^{1/2}$ other than applying twice should give the $I-D^2$ result.
Comment: @mathreadler : This is the unique positive square root. For this root, the equation in the post definitely holds, and this is the unique positive operator for which it holds. I have made no other claims regarding this operator.
Answer: Another way which is useful if you need discrete approximations and if you accept using complex numbers is
$$\cases{D^2 = \frac{1}{k} [1,0,-2,0,1]\\I = [0,0,1,0,0]}$$
If we now consider $$I-iD = [0,0,1,0,0] - i[0,1,0,-1,0]$$
Now performing the self-convolution $(I-iD)*(I-iD)$ the complex numbers will give us a real part which is $[-1,0,3,0,-1]$, which is correct for $k=1$, but we need to expand to use complex numbers and throw the imaginary part away.
$$(I-D)^2 = \mathcal{Re}((I-iD)*(I-iD))$$
Comment: Actually the discretization is mostly for illustration. Wait is (T,S) defined as $\int_{-\infty}^{\infty} T(t)S(t)^*dt$, $*$ meaning complex conjugate? Then we won't have to do real part either I think.

Fractional differential operator


How to show a loading page in between pages while loading?

Question: I am using React with React-Router-Dom. For some pages, I am using the loader as part of the route so I have the data when the page is loaded. The problem is that this data may take awhile to load from the api, and until it is loaded, the user gets no confirmation that their click did anything. Here are some situations when this happens:

When navigating to the next page where data needs to be loaded, the user clicks a button that is supposed to take them to that page. Instead of instantly taking them to the page, nothing changes, but the requests are made, then the page loads once that data is ready. This means that after the user clicks the button to take them to the page, they are stuck looking at the current page until it is fully loaded.
When navigating using a URL, lets say to /dashboard. The user is taken to the page, but the page is completely blank until the page is fully loaded. The user is stuck looking at a white page for about 500ms to 1sec (depending on API speed and their internet speeds).

Both of these situations are not ideal and would like a solution. Here is what the code looks like:
//index.ts
import ReactDOM from "react-dom/client";
import {
    createBrowserRouter,
    RouterProvider,
} from "react-router-dom";

const router = createBrowserRouter([
    {
        path: "/dashboard",
        element: <Dashboard />,
        loader: async () => {
            const data = await getData()
            return data
        }
    }
])

ReactDOM.createRoot(document.getElementByID("root")).render(
    <RouterProvider router={router} />
)

//dashboard.tsx
import { useLoaderData } from 'react-router-dom';
export default function Dashboard() {
    const data = useLoaderData();
    console.log(data);
    return (

{data.name}

    )
}

How do I navigate instantly and show a loader until the data from useLoaderData is available?
I have already tried going into the index.html and adding a loader inside the

but this didn't work due to the page being overwritten with a white screen while the data was loading. I also tried putting a loader outside the div and removing it on page load using useEffect, but having to do this on every single page is troublesome.
I also tried deferring the data like in the react router guide but it didn't work for me as the getData functions await the fetch in an async function from my api. Here is what getData looks like:
export async function getData() {
    const response = await fetch(`${backendURL}/getData`)
    const data = await response.json()
    return data;

I know the problem is that page loading is being blocked by the async await, but I have no idea how to fix it.
Comment: I suggesting to add global state isLoading, before requests set it as true, after getting response set it as false, in jsx render conditionaly by this state your loader
Comment: is using global states good practice?
Answer: This might be what you're looking for: https://beta.reactrouter.com/en/dev/guides/deferred
Another solution would be at the Root level:
<Suspense> relies on a promise being thrown, which the <Outlet> doesn't do while the route's loader is still running.
Instead, you can use useNavigation to access the current navigation state and show a loading component:
   export default function Root() {
      const notes = useLoaderData();
      const { state } = useNavigation();

      return (
        <>
          {state === 'loading' && (
            <progress
              style={{
                position: 'absolute',
                top: '0',
                left: '0',
                width: '100vw',
              }}
            />
          )}

            {/* same code as before */}

        </>
      );
    }

Edit (for refresh)
try your routes like this
    <Route
      path="/dashboard"
      element={
        <Suspense fallback={<YourLoaderComp />}>
          <Dashboard />
        </Suspense>
      }
      loader={withSuspense(dashboardLoader)}
    />

and the withSuspense file
export function withSuspense(fn) {
  return function (...args) {
    let status = 'pending';
    let response;

    const suspender = fn(...args).then(
      (res) => {
        status = 'success';
        response = res;
      },
      (err) => {
        status = 'error';
        response = err;
      }
    );

    return () => {
      switch (status) {
        case 'pending':
          throw suspender;
        case 'error':
          throw response;
        default:
          return response;
      }
    };
  };
}

Comment: @Wamy-Dev edited the answer, try it out
Comment: state doesn't get updated until the page loads. Fetching happens first due to async, then the page loads, which means the state is never "loading". If I console.log(state), the state only shows "idle".
Comment: Okay, so I took another try, and apparently, it is only loading if navigating to another page. So on refresh it doesn't show loading, but only on navigation.
Comment: Is there a way to make this work on refresh? Otherwise this is a great solution!
Answer: I usually use this package:
https://www.npmjs.com/package/react-loading-screen
I don't really know how good practice it is but while I'm fetching stuff from an endpoint or the database, I just call the react-loading screen while not a timeout and it makes wonders.
Hope this help!


How to achieve this tone?

Question: I have been going crazy for months trying to replicate this tone. Any help would be greatly appreciated!

My setup:
Epiphone Les Paul custom top pro
Marshall dsl40cr
Seymour Duncan palladium (distortion)
Eventide timefactor (delay)
Hall of Fame 2 (reverb)
Comment: What about your current tone doesn't sound like the tone you are trying to get? He might have a slight phaser on there.
Comment: Why don't you post a comment on the guy's YouTube channel and ask him?
Answer: I hear a Peavey Vypyr VIP amplifier there, with the Fender Twin modeling selected, and the distortion, delay, and a huge wall of reverb engaged.
$200 American, and that amp can be yours.
Answer: I like that tone as well.
Looking at the YouTube comments for the video (Ryan Leslie) I see he states he used a Digitech RP1000 Guitar Multi-Effects Processor.
I think you'd get real good feedback if you contacted many of the folks who reviewed the RP1000, like this guy,

, and ask them for insight on the settings.
Maybe they'd like that video too and recreate that sound for you and be able to share it ... I don't know if the RP1000 lets users publish sound setup files.
The RP1000 are listed for $399 on Digitech but I see they've been as low as $155 used on Reverb so for $200-ish you could easily try it and resell it should it not fit the bill.
https://digitech.com/en/products/rp1000

How to achieve this tone?


Openness of the Interior

Question: I've been working on some problems in introductory topology, and I wanted
some help on formalizing a proof to a problem that I reached. Given the
set $S$ that contains reals, I want to prove that $\mathring{S}$ is open.
I felt like doing this
via an AFSOC proof around the boundary points of $\mathring{S}.$ Hence,
let's consider the case where $\mathring{S}$ contains at least one of its
boundary points, say $x$. Then For any $\epsilon>0,$ $(x-\epsilon,x+\epsilon)$
is partially contained in $\mathring{S}$ and partially contained in
$$\mathbb{R} \setminus \mathring{S}.$$
Let us fix $\epsilon > 0.$ I can see that if it was the case that
$$(x-\epsilon,x+\epsilon) \cap (\mathbb{R} \setminus S) = \emptyset,$$
We would reach a contradiction because knowing that
$$(x-\epsilon,x+\epsilon) \cap (\mathbb{R} \setminus \mathring{S})$$
$$=(x-\epsilon,x+\epsilon) \cap (\mathbb{R} \setminus (S \setminus
       \partial S))$$
$$\neq \emptyset,$$
This would imply that $x \in \partial S,$ which contradicts the fact that
$x \in \mathring{S}.$ Hence, I need some help working on the case where
$$(x-\epsilon,x+\epsilon) \cap (\mathbb{R} \setminus S) \neq \emptyset.$$
Comment: What is your definition of $\mathring{S}$?
Comment: Echoing Eric Wofsey. What def'n have you been given for Int (S) ? The usual def'n is the union of all open subsets of S, which is of course an open set.
Answer: In a metric space, $x\in \mathring{S}$ if exists $\varepsilon_x > 0$ so that $B(x,\varepsilon_x)\subseteq S$, where $B(c,r)$ is the open ball centered on $c$ with radius $r$.
Note that any point in $y\in B(x,\varepsilon_x)$ also satisfies this property so $y\in\mathring{S}$. Therefore
$$\mathring{S} \subseteq \bigcup_{x\in\mathring{S}} B(x,\varepsilon_x) \subseteq \mathring{S}$$
Wich implies
$$\mathring{S} = \bigcup_{x\in\mathring{S}} B(x,\varepsilon_x)$$
So since $\mathring{S}$ is a union of open sets, it is itself open.

Openness of the Interior


How to calculate effective branching factor?

Question: I would like to calculate the effective branching factor of a tree in order to assess the quality of my heuristic in A* search.
The post here offer a very good explanation of the formula :
N+1=1+B∗+(B∗)^2+⋯+(B∗)^d, presented in the AI: A Modern Approach (by Stuart Russell and Peter Norvig) book. Where, N is the number of nodes searched and the solution depth is
d and "b* is the branching factor that a uniform tree of depth d would have to have in order
to contain N +1 nodes"
I am really puzzled with the example presented in the book. They say:

For example, if A* finds a solution at depth 5 using 52 nodes, then
the effective branching factor is 1.92.

How did they come up with this value? As explained here an approximation to this formula is given by B∗≈N^(1/d).
Using that formula with values in the example from the book I get 2.20 = 52 ^ (1/5), which is a bit far off the value presented in the book as a solution (which btw is not said to be an approximation).
So, my question is how did they come up with the value 1.92? What am I missing?
Answer: The approximation of N+1 = 1+B∗+(B∗)^2+⋯+(B∗)^d by the equation B∗ ≈ N^(1/d) is only accurate for larger values of B∗. The true formula is ((B∗)^(d+1) - 1) / (B∗ - 1) = N+1. When B∗ is not significantly larger than 1, the error of the approximation can be very high.
If you solve for B∗ in the equation 53 = ((B∗)^(d+1) - 1) / (B∗ - 1), for example using Newton's method or another numerical solver, the true value (to 6 s.f.) is B∗ ≈ 1.916729, or B∗ ≈ 1.92 in the textbook.
Comment: @jcampos Absolutely; that's the closed form solution of a [geometric series.](https://en.wikipedia.org/wiki/Geometric_series#Closed-form_formula) So `((B∗)^(d+1) - 1) / (B∗ - 1)` is the partial sum of the geometric series with ratio `B*`. The original formula was `1+B∗+(B∗)^2+⋯+(B∗)^d`.
Comment: Thanks a lot for you answer. Could you please elaborate a bit more on how you do you get to the formula ((B∗)^(d+1) - 1) / (B∗ - 1) = N+1.


Inventory Allocation Generic Inquiry Acumatica

Question: I am trying to create a GI in Acumatica that shows inventory allocations. I already have an inventory allocation details set up in acumatica.

I want to show only certain fields in a GI. I want to show Allocation Type, Allocation Date, and Qty.
When I try to find the table it turns out to be a temp table or filter.
Is there any way to get around this? I am fairly new at creating gi's, but I have an idea of how it works.
Answer: The filter on this page is filled in on entry of the inventory ID, warehouse, location, subitem. Using these DACs in a GI will not work.
You could use some of the IN*Status tables for totals otherwise the INItemPlan table represents the detail in the grid combined with INPlanType for description of allocation type.


uniform location and attribute location - is it the same number series?

Question: Is it OK to make (per-draw-call) uniform and (per-vertex) attribute to share same channel (location = X) explicitly?
Vertex Shader :-
layout(location = 2) in vec3 perVertex_pos;
layout(location = 2) uniform vec3 perInstance_color;
//^ same "location = 2" ... valid?

I am trying to keep location to a low figure as much as possible to fix an error C5102: input semantic attribute "ATTR" has too big of a numeric index.
References :
https://www.khronos.org/opengl/wiki/Layout_Qualifier_(GLSL)
https://www.khronos.org/opengl/wiki/Uniform_(GLSL)/Explicit_Uniform_Location
They explain each type (uniform & attribute) individually, but do not tell whether I can share the index.
Edit: A similar-but-perpendicular question : Are OpenGL indices and locations the same thing for uniforms and vertex attributes?
Comment: [OpenGL 4.6 API Core Profile Specification - 7.3.1 Program Interfaces, page 108](https://www.khronos.org/registry/OpenGL/specs/gl/glspec46.core.pdf#page=124&zoom=100,0,173):
*"Each entry in the active resource list **for an interface** is assigned **a unique unsigned integer index** in the range zero to N − 1, where N is the number of entries in the active resource list.*" - Uniforms and attributes are different types of interfaces.
Answer: Yes, they can share indices. Attribute locations and uniform locations are unrelated.
Comment: May you provide some reference to make me rest in peace, please?
Comment: @javaLover I don't have a reference at hand, but you might be able to verify it by not specifying `location`, and checking the automatically assigned locations with `glGetAttribLocation` and `glGetUniformLocation`.


How can I change form action link?

Question: How can I change form action in drupal 8?
In default, page not change and when my form path is /site/drupal/page, my form action is <form data-drupal-selector="test" action="/site/drupal/page" method="post" id="test" accept-charset="UTF-8">.
But I want change it to other page. How can I do this ?
** Redirect not worked, see this link: Redirect after submit form
Answer: In the form submit handler, you can modify the $form['action'] value.

// Get the routename
$routename = 'My-Route';
  $url = \Drupal\Core\Url::fromRoute($routename);
  // make the redirection
  $form['#action'] = $url->toString();
Comment: Can you paste the form build code? This should work
Comment: Form build code is here : http://drupal.stackexchange.com/questions/232387/redirect-after-submit-form
Comment: You haven't set the #action in that code.
Answer: in the submit form write a redirect
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

//add the below in submit form handler. Use the route name you want to redirect
$response = new RedirectResponse(Url::fromRoute('<front>')->toString());

$response->send();

How can I change form action link?


Limit applied on a function

Question: How do you determine the limit:
$$\frac{e^{-ax} - e^{-bx}}{b-a}$$ as $b$ tends to $a$.
I've tried using L'hospitals by couldn't get the right answer.... Any help would be appreciated
Answer: One way to solve it is to compare the expression with the definition of differentiation. For fixed $x$, define $f(t) = e^{-xt}$, then
$$\frac{e^{-ax} - e^{-bx}}{b - a} = -\frac{f(b) - f(a)}{b - a} \to - f'(a)$$
as $b \to a$.
Clearly, by the chain rule,
$$f'(a) = -xe^{-xa}.$$
Hence the result is $xe^{-xa}$.
Answer: Rewrite $$A=\frac{e^{-ax} -e^{-bx} }{b-a}=e^{-ax}\frac{1-e^{(a-b)x} }{b-a}$$ Now, remember that, for small $y$, $e^y=1+y+\frac {y^2}2+\cdots$.So $$e^{(a-b)x}\approx 1+(a-b)x$$ Then $$A\approx e^{-ax}\frac{1-(1+{(a-b)x}) }{b-a}=-e^{-ax}\frac{{(a-b)x} }{b-a}=x e^{-ax}$$
Comment: There is a typo in the last expression, should it be $1 {\color{red}+} (a - b)x$?
Comment: @Zhanxiong. Thanks for pointing it ! I am almost blind and this happens too often ! Thanks again.
Answer: Consider u=b-a and f(u)=(e^(u-bx) - e^(-bx) ) / u
Limit f(u) when u tends to 0 : using L'hospital : x e^(u x - bx) / 1 = x e^(-bx)
As u tends to 0 , a tends to b , so the limit is   x e^(-ax)

Limit applied on a function


Contradictory results about heteroscedasticity (gvlma / Breusch-Pagan test)

Question: Testing for heteroscedasticity (after OLS regression) using two different tools in R I obtain two contractictory results:
1/ Global Validation of Linear Models Assumptions of the gvlma package :

gvlma::gvlma(BMall_lm)

returns:
Call:
lm(formula = BM ~ TAM_jun + NBD3 + snow_acc, data = d)

Coefficients:
(Intercept)      TAM_jun         NBD3     snow_acc
-618.545     -289.143      -11.785        1.186

ASSESSMENT OF THE LINEAR MODEL ASSUMPTIONS
USING THE GLOBAL TEST ON 4 DEGREES-OF-FREEDOM:
Level of Significance =  0.05

Call:
 gvlma::gvlma(x = BMall_lm)

                      Value   p-value                   Decision
Global Stat        24.7590 5.625e-05 Assumptions NOT satisfied!
Skewness            1.5379 2.149e-01    Assumptions acceptable.
Kurtosis            0.6797 4.097e-01    Assumptions acceptable.
Link Function      22.2932 2.340e-06 Assumptions NOT satisfied!
Heteroscedasticity  0.2482 6.183e-01    Assumptions acceptable.

The conclusion here is that the homoscedasticity assumption is verified
2/ BUT when I use the Breusch-Pagan test in the lmtestpackage I get the reverse :

lmtest::bptest(BMall_lm)

    studentized Breusch-Pagan test

data:  BMall_lm
BP = 25.137, df = 3, p-value = 1.446e-05

Here, the homoscedasticity assumption is not verified
Any help about which one to follow ?
Answer: I would read the thread on whether normality testing is essentially useless (which is very similar to whether you should test for any other model assumption) and consider whether you should even be doing tests for such model assumptions. Various different tests will have more or less power against certain alternatives, so it can easily happen that two tests disagree. So, you could consider reading up on how these two tests differ and whether it is plausible that the particular deviations from assumptions are more plausible than the others in your case.
However, in any case, a failure to reject the null hypothesis does not demonstrate that assumptions are justified. Similarly, a rejection of the null hypothesis does not mean that a meaningful violation of assumptions is present (even if it is a correct rejection).
Usually, one would ideally check on previous similar data whether the assumptions are likely to be approximately fulfilled (looking at some measure of how large deviations - if any - are, instead of just some hypothesis test). You could still do that post-hoc on the data you now have, but this kind of data-driven excercise results in there not being type I error control, confidence intervals not having their nominal coverage and so on - in case this matters to you, which may not be a major consideration for some exploratory investigation. Given the data driven decisions, it will also be important to make this process transparent to those reading your research so that they are aware that analysis decisions were taken after seeing the data.