jQuery date picker to select only month and year?

Question: I want to use jQuery date picker to select month and year only?. I tried it using date format, it working but show dates too. I am trying a way to select month and year only
Answer: try
<code>$('.date-picker').datepicker( {
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'MM yy',
    onClose: function(dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
});
</code>
Answer: To the best of my knowledge, that's not possible. It's a date picker, you can't omit date from the output.
Your best bet would be to:
1) grab the month and year using date format
2) use two separate drop down lists, one for month and one for year


What is the autocovariance function of a deterministic process $X_t = cos(\omega_0 t + \phi)$

Question: If $X_t = cos(\omega_0 t + \phi)$ where the constant $\omega_0 \in (0, \pi)$ and $\phi$ is a random variable with a uniform distribution on $(0, 2\pi)$ but is fixed for a single realisation of the process then how do I calculate the autocovariance function?
The book I am reading just states that $\gamma(k) = \frac{1}{2} cos(\omega_0 k)$ so it must be obvious but I can't see it. The book doesn't say but I also suspect in the definition of $X_t$, $t$ is defined only for integer values, i.e. $t = 0, 1, 2, 3, \dots$
Comment: Random variable is $\phi$ so its pdf =$1/(2\pi)$ now use definition of autocorrelation: expected values of $X_t X_{t+\tau}$
Answer: $X_t = cos(\omega_0 t + \phi)$ and R.V. is $\phi$ with uniform distribution so its probability density function $p_\phi=\frac 1{2\pi}$
Now note that autocorrelation function is:
$\begin{align}R_{X}(\tau)=&E[X_tX_{t+\tau}]\\=& \int_0^{2\pi}X_t X_{t+\tau}p_\phi d\phi\\=&\frac 1{2\pi}\int_0^{2\pi}\cos(\omega_0 t + \phi)\cos(\omega_0 (t+\tau) + \phi)d\phi\\=&\frac 1{4\pi}\int_0^{2\pi}\cos (\omega_0 t + \phi-\omega_0 (t+\tau) - \phi)-\cos (2\omega_0 t+\omega_0\tau+\phi)d\phi\\=&\frac 1{4\pi}\int_0^{2\pi}\cos(\omega_0\tau)d\phi=\frac 12\cos(\omega_0\tau)\end{align}$


Frullani integral $\int_0^\infty \frac{\text{csch}(x)-\frac1x}{x} {\rm d}x$

Question:
$$
\int_0^\infty \frac{\text{csch}(x)-\frac1x}{x} {\rm d}x.
$$

This integral was from a recent contest like two weeks ago and I still can't crack it. Well, to be exact it was in the form of
$$
\int_0^\infty \frac{2}{x^2} \left( \frac{x}{e^x - e^{-x}} - \frac12 \right) {\rm d}x.
$$
The hint was to turn it into Frullani integral, but nothing i've tried worked out, by-parts leaves you with something that doesn't converge and I can't find a way to turn the numerator into $f(ax)-f(bx)$. I noted that it can also be written in the form
$$\int_0^\infty \frac{\text{csch}(\frac1x) - x}{x} {\rm d}x.$$
Comment: Do you interest alternative way?
Comment: The result below lead  to think that $a=2,b=1$
Comment: It's a local contest https://www.facebook.com/utarNMC/
Comment: yeah of course, anything that works
Comment: Can't we contour it?
Answer: Define the function $F$ for $x>0$ by:
\begin{align}F(x)=\text{cotanh}\left(\frac{x}{2}\right)-\frac{2}{x}\end{align}
Observe that,
\begin{align}\lim_{x\rightarrow 0}  F(x)&=0\\
\lim_{x\rightarrow \infty}  F(x)&=1\\
F(x)-F(2x)&=\frac{1}{\sinh x}-\frac{1}{x}
\end{align}
On can use Frullani's theorem:
\begin{align}\int_0^\infty \frac{\text{csch}(x)-\frac1x}{x} {\rm d}x&=\int_0^\infty \frac{F(x)-F(2x)}{x}\,dx\\
&=\left(F(0)-F(\infty)\right)\ln\left(\frac{2}{1}\right)\\
&=\boxed{-\ln 2}
\end{align}
Comment: (+1) The only answer of the posted that actually uses Frullani.  You might be interested in [THIS](https://math.stackexchange.com/questions/3746297/an-extended-frullani-integral), which extends the commonly seen version of Frullani,  and [THIS](https://math.stackexchange.com/questions/3180443/integral-int-0-infty-frac-sin-sqrtqx-sin-sqrtpxxdx/3667127#3667127), which converts the original integral to a Frullani integral.
Answer: One way is using the expansion of $\operatorname{csch}x$, that is
$$\operatorname{csch}x=\dfrac{1}{x}+\sum_{n=1}^{\infty}\dfrac{2(-1)^nx}{n^2\pi^2+x^2}$$
then
$$\int_{0}^{\infty}\dfrac{\operatorname{csch}x-\frac1x}{x}\ dx=\sum_{n=1}^{\infty}\int_{0}^{\infty}2(-1)^n\dfrac{1}{n^2\pi^2+x^2}\ dx=\sum_{n=1}^{\infty}\dfrac{2(-1)^n}{n\pi}\arctan\dfrac{x}{n\pi}\Big|_{0}^{\infty}=\color{blue}{\sum_{n=1}^{\infty}\dfrac{(-1)^n}{n}}=\color{blue}{\ln\dfrac12}$$
Comment: This doesn't use a Frullani integral, which was the thrust of the question.


How can I evaluate $\frac{d}{dx}\int_\limits{x}^{x^2}{\frac{\sin t}{t}\,dt}$?

Question: Well I've heard of Leibniz integral rule but don't quite understand it. Other than that I've no idea for how this can be solved given that $\mbox{sinc}(x)$ is an improper integral.
Also, I've used Wolfram Alpha and it states that the solution is $2x\mbox{sinc}(x^2)-\mbox{sinc}(x)$ but I've no idea how it computed the answer?
Comment: Note that the variable used for integration should be different from the variable in the bounds; eg $\frac{d}{dx}\int_x^{x^2}\frac{\sin t}{t}\;dt$.
Comment: Use the fundamental theorem of calculus.
Comment: @stewbasic corrected it.
Answer: Hint. You probably know the Fundamental Theorem of Calculus:
if $f$ is a continuous function in $[x_0, x]$ then
$$\frac{d}{dx}\int_\limits{x_0}^{x}f(t) dt=f(x).$$
Moreover, note that
$$\frac{d}{dx}\int_\limits{x}^{x^2}{\frac{\sin t}t\,dt}=
\frac{d}{dx}\int_\limits{1}^{x^2}{\frac{\sin t}t\,dt}-\frac{d}{dx}\int_\limits{1}^{x}{\frac{\sin t}t\,dt}.$$
Now be careful with the first derivative.
Comment: In this case the function $\sin t/t$ can be extended continuously at 0 with the value $1$. So it is continuous on $\mathbb{R}$ and you can break the integral whereever you want.
Comment: It is the chain rule. Let $F(x)=\int_\limits{x_0}^{x}f(t) dt$, then you are deriving $F(x^2)$.
Comment: can we break the limits $x$ to $x^2$ into $x$ to $a$ and $a$ to $x^2$ for any value of $a$ instead of 1(the one you used) and the result will be same?
Comment: One more question- in the first integral, why we have to multiply the result  of second integral by $\frac{d}{dx}x^2$? Appears like some type of chain rule.
Comment: Many many thankx Robert


Seg fault for writing to CR0

Question: I'm trying to write to CR0 in Linux, but I keep getting a segmentation fault. This for assembly of i386 or x86_64. Is there anyway of getting around this?
Bellow is part of the code that sets the segfault.
<code>mov eax,0xffffffff      ;system call number (sys_write)
mov cr0,eax
</code>
Comment: What are you trying to do? From the comment, it seems you are trying to perform a system call but `0xffffffff` is definitely not the number for `sys_write`.
Comment: I wrote to eax 0xfffffff because you can't do mem to mem operations. You need at least one register. Even though cr0 is a register, I only used eax as a means of being safe. Basically I want to turn off protection mode from user space. However from I have recently learned, cpu's these days are fairly advanced and places code in protected segments that doesn't allow it to mess with certain registers if that segment does not have that privilege 0.
Comment: Setting CR0 to all-ones would disable cache, disable the x87 FPU, and do other weird stuff.  See https://en.wikipedia.org/wiki/Control_register#CR0.  If you were actually in kernel mode like the original tags on this question indicated, it wouldn't fault directly, but user-space probably would soon after.
Answer: CR0 is a protected register.  It cannot be modified in a userspace linux application.

Seg fault for writing to CR0


Measure a process CPU and RAM usage

Question: I've found various ways to track down CPU's and RAM's usage from within a process, in C#. I'd like to obtain those infos for an external program (like providing its PID).
Is there anything in the .NET framework that can help me?
Thanks
Comment: you mean, like passing a PID as argument?
Comment: check this http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-c
You can also use WMI( windows management instrumentation) for memeory usage . Check Win32_process class http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx
Also you can go for performance counters (you code require admin privileges )
Look into WMI.
Answer: you can use process class
Answer: Use Performance Monitor, and add counters for specific processes.
If you need to analyse the results, you can have them written to a performance log.
Comment: I need this for logging purposes, so I need to get the data in a format i can write, store and analyze.
Comment: You can save to a performance log from performance monitor: http://technet.microsoft.com/en-us/library/cc721865.aspx
Answer: You could host a PowerShell RunSpace and call stuff in there - it's got a lot more native stuff dealing with this type of thing.
Answer: You can pass an instance into a System.Diagnostics.PerformanceCounter constructor - this should allow you to specify the process instance you want to monitor

Measure a process CPU and RAM usage


Laravel - Como salvar escolha de checkbox em listagem de itens?

Question: Em um sistema de gerenciamento de contato, tenho umas listagem de itens os quais tem um checkbox cada um(estilo gmail) para que eu possa seleciona-los e utilizar alguma ação relacionada aos selecionados. Qual a melhor forma de salvar esses itens selecionados a cada página acessada?
Um dos Controllers que lista os itens:
$request = DB::table('contatos')
            ->select('*')
            ->paginate(15);

        return view('list')
            ->with('request', $request);

E a View:

        <input type="checkbox" id="seleciona_todos" />
        Nome
        E-mail

    @foreach($r as $p)

        <input type="checkbox" value="{{ $p->id }}" />
        {{ $p->nome }}
        {{ $p->email }}

    @endforeach

    {!! $r->appends(Input::except('page'))->links(); !!}

- Tem paginação
- Utilizo o Laravel
- Terá outras contas de usuários admin mexendo ao mesmo tempo
Já pensei em fazer um ajax para um arquivo php que grava e exclui itens de um array em uma sessão ou até mesmo utilizar uma tabela no banco de dados para gravar os itens selecionados atualmente(porém terá outros usuários mexendo no momento e acho q isso não ia dar certo).
Qual o melhor jeito de resolver isso?
Comment: Se vc quer ver as modificações em real-time pusher e Laravel echo
Comment: vc pode fazer assim no seu input: ``e capturar o array:  $dataForm = $request->all();

dd($dataForm['selecionados']), o `dd()`  deve retornar um `var_dump` do laravel.
Answer: Acredito não haver problemas em utilizar o banco de dados e ajax mesmo que tendo outros usuários mexendo no momento. Se esse for o problema você pode utilizar DB::transaction() no método que executa a ação de excluir os itens.
Por exemplo:
DB::transaction(function(){

  // ação de deletar, inserir e etc

});

caso ocorra algum erro nesta ação o sistema não efetuará a mudança no banco de dados.


Multiple if statements efficiency

Question: Let's say I have boolean show and difficult method public boolean isArraySorted( ).
I want to know how if statement works, and if checking order means anything. Basicly what I want to is if( !show && isArraySorted( ) ) is faster than if( isArraySorted( ) && !show ).
As far as I know statements are checked one after another until one fails, right ? So keeping this in mind if( !show && isArraySorted( ) ) should be faster ( at least slightly ). Please, correct me if I'm wrong.
Comment: The more **boldface** you use in your writing, the harder it is to read, just FWIW.
Comment: Logical operator short circuiting is happening with `&&`. And yes, the order matters. Therefore, you also see thousands of examples such that `if (objVariable != null && objVariable.doSomething() )`.
Comment: Hint for the net time: why don't you implement two methods that log to the console that they've been called and return a boolean value. Then call them two combinations of such an expression and see what's being logged. Protip: use a debugger and step into those methods, don't struggle writing console statements. Further: your question is not limited to `if` statements, the same applies for `bool result = a || b;`. Finally: for or-statements if the lefthandside is true, there's no need to evaluate the righthandside.
Answer:
Basicly what I want to is if( !show && isArraySorted( ) ) is faster than if( isArraySorted( ) && !show ).

Let's leave speed off to the side. if( !show && isArraySorted( ) ) won't call isArraySorted if show is true, and will if it's false. (Because you're using !show, otherwise it would be the other way around.)

As far as I know statements are checked one after another until one fails, right ?

Sort of, yes. The logical operators (&& and ||) are short-circuited. That means that they evaluate their left-hand operand and, if that operand is enough that they know their result, they don't evaluate the right-hand operand. So for &&, if the left-hand is false, there's no need to evaluate the right-hand. For ||, if the left-hand is true, there's no need to evaluate the right-hand.
Comment: thanks, that's what I wanted to know!

Multiple if statements efficiency


Problemas com datas no R

Question: Estou novamente com problemas de datas no R. Tenho o dataset abaixo e gostaria de calcular a diferença de datas entre as revisões. Acontece que não estou conseguindo, às vezes retorna alguns valores que não sei de onde vem, às vezes o dataset aparece vazio. Será que alguém pode me ajudar?
structure(list(CPF = c(4.71e+13, 4.71e+13, 222146826, 10491445890,
40557199816, 10799846821, 5702868838, 47011947868, 8.77e+13,
3.9e+11, 2511422050, 45250618049, 26690683087, 50286986949, 83178880020,
460414003, 52466078015, 2.31e+12, 10702601004, 18057438053),
    PLACA = c("GJD-6942", "GJD-6942", "EVI-7442", "FSI-2944",
    "FHY-4766", "FGK-0375", "EAA-3772", "FLE-1840", "EYH-8581",
    "IVX2436", "IQL1145", "IIR3216", "INX8756", "ITI6522", "IRR7035",
    "ISA8749", "IQB5774", "IUS4704", "ITL2283", "IOG3399"), COD_REV = c(563558L,
    563559L, 563562L, 563567L, 563745L, 563961L, 564074L, 564184L,
    564185L, 20313L, 20333L, 20338L, 20623L, 20627L, 20631L,
    21107L, 21118L, 21121L, 21275L, 21284L), DATA = c("07/02/2018 15:32",
    "07/02/2018 15:32", "07/02/2018 15:33", "07/02/2018 15:35",
    "07/02/2018 16:56", "08/02/2018 08:21", "08/02/2018 09:26",
    "08/02/2018 10:32", "08/02/2018 10:34", "11/04/2016 20:20",
    "11/04/2016 20:55", "11/04/2016 21:05", "13/04/2016 20:41",
    "13/04/2016 20:47", "13/04/2016 20:55", "16/04/2016 15:11",
    "16/04/2016 15:39", "16/04/2016 15:45", "18/04/2016 20:57",
    "18/04/2016 21:04"), KM_ATUAL = c(46250L, 46250L, 75425L,
    70632L, 78257L, 176305L, 293761L, 54996L, 175200L, 32925L,
    73251L, 151000L, 144500L, 57700L, 158000L, 52000L, 97200L,
    47350L, 108000L, 129324L), KM_MEDIA = c(15000L, 15000L, 14000L,
    23000L, 18500L, 35000L, 30L, 13000L, 32000L, 80L, 60L, 60L,
    40L, 80L, 100L, 60L, 60L, 200L, 60L, 60L), TIPO_MEDIA = c("anl",
    "anl", "anl", "anl", "anl", "anl", "dia", "dia", "anl", "NI",
    "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI"
    ), KM_MED_DIA = c("41,0958904", "41,0958904", "38,3561644",
    "63,0136986", "50,6849315", "95,890411", "30", "13000", "87,6712329",
    "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI",
    "NI"), ESTILO_DIR = c("etd", "etd", "cdd", "etd", "cdd",
    "etd", "cdd", "cdd", "etd", "NI", "NI", "NI", "NI", "NI",
    "NI", "NI", "NI", "NI", "NI", "NI"), CAMBIO = c("atc", "atc",
    "mnl", "atc", "mnl", "mnl", "mnl", "mnl", "atc", "NI", "NI",
    "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI", "NI"), LOJA = c(9L,
    9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 144L, 144L, 144L, 144L, 144L,
    144L, 144L, 144L, 144L, 144L, 144L)), .Names = c("CPF", "PLACA",
"COD_REV", "DATA", "KM_ATUAL", "KM_MEDIA", "TIPO_MEDIA", "KM_MED_DIA",
"ESTILO_DIR", "CAMBIO", "LOJA"), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))

Código usado:
# Carregando os pacotes
library(tidyverse)
library(taRifx)
library(lubridate)

# Carregando os datasets
revisao <- read_csv2("rev_seg.csv")
colnames(revisao)
#revisao$DATA <- dmy_hms(revisao$DATA)

dif_km <-
  revisao %>%
  select(CPF, PLACA, COD_REV, DATA, KM_ATUAL, KM_MEDIA, TIPO_MEDIA, KM_MED_DIA) %>%
  arrange(DATA) %>%
  mutate(KM_MED_DIA = as.numeric(KM_MED_DIA), CPF = as.character(CPF)) %>%
  filter(KM_MED_DIA != "NULL") %>%

  group_by(CPF,PLACA) %>%
  mutate(ORDEM_REV = row_number()) %>%
  filter(n() > 1) %>%
  mutate(DIF_KM = KM_ATUAL - lag(KM_ATUAL)) %>%
  mutate(DIF_DATA_DIAS = difftime(DATA, lag(DATA) , units = c("days"))) %>%
  mutate(DIF_DATA_MIN = DIF_DATA_DIAS * 1440) %>%
  mutate(KM_RODADA_ESPERADA = KM_MED_DIA * DIF_DATA_DIAS) %>%
  na.omit() %>%
  filter(ORDEM_REV > 1)

Comment: Para podermos calcular a diferença de datas entre as revisões precisamos de saber qual das colunas é a coluna das revisões. E, já agora, pode dar um exemplo do código que tentou, por favor?
Comment: Olá Rui,
Então, a coluna das revisões é a COD_REV. A mesma placa pode ter feito muitas revisões. Cada pessoa aponta uma KM_MEDIA quando faz uma revisão. Acontece que este dado é subjetivo. Porém é coletado também a KM_ATUAL do carro de modo que no caso dos clientes que já vieram mais de uma vez, eu gostaria de calcular a diferença de datas entre as revisões, multiplicar pela KM_MED_DIA (que é o que ele disse que anda por dia) e depois comparar isso com a difrença de KM_ATUAL (que é quanto ele andou de fato). Acontece que não estou conseguindo fazer essa diferença entre as datas.
Comment: O código que eu escrevi está embaixo do dataset, é que não sei muito bem oragnizar as informações aqui. Obrigado!
Comment: @DiegoPeliciari, bem-vindo ao StackOverflow! Dê uma olhada em [como melhorar sua pergunta](https://pt.stackoverflow.com/questions/264168/quais-as-principais-fun%C3%A7%C3%B5es-para-se-criar-um-exemplo-m%C3%ADnimo-reproduz%C3%ADvel-em-r) para que possamos ajudar
Comment: @TomásBarcellos eu dei uma olhada lá, mas creio que todos os elementos levantados estão na postagem, como código com tentativa, amostragem de dados e o problema em questão. O que eu poderia melhorar?
Comment: Você uniu muitos problemas na pergunta. Isole apenas o comportamento diferente do esperado. Tem problemas no código fornecido que não tem a ver com a pergunta.
Comment: o comportamento diferente é o da data.não estou conseguindo subtrair as datas..
Comment: @DiegoPeliciari realmente não está claro qual é o seu problema. Você precisa delimitar melhor e fornecer um exemplo reprodutível. Você quer calcular a diferença entre as datas das revisões mas não tem nenhum exemplo de um carro com mais de uma revisão.
Answer: Diego, acredito que o código abaixo faça o que pediu. Acrescentei uma conversão em data que você não estava fazendo mutate(DATA = dmy_hm(DATA)) e também substituindo as vírgulas por pontos mutate(KM_MED_DIA = gsub("\\,","\\.",KM_MED_DIA)). Com a base de dados enviada por você somente um carro aparece mais de uma vez e as duas revisões estão com a mesma data e horário. Fora que seu teste para filtrar os NAs estava incorreto (filter(KM_MED_DIA != "NULL"), para se testar células que tenha NA o correto é utilizar a função is.na(x)
dif_km <-
  revisao %>%
  select(CPF, PLACA, COD_REV, DATA, KM_ATUAL, KM_MEDIA, TIPO_MEDIA, KM_MED_DIA) %>%
  arrange(DATA) %>%
  mutate(KM_MED_DIA = gsub("\\,","\\.",KM_MED_DIA)) %>%
  mutate(KM_MED_DIA = as.numeric(KM_MED_DIA), CPF = as.character(CPF)) %>%
  filter(is.na(KM_MED_DIA)==F) %>%
  group_by(CPF, PLACA) %>%
  mutate(ORDEM_REV = row_number()) %>%
  filter(n()>1) %>%
  mutate(DATA = dmy_hm(DATA)) %>%
  mutate(DIF_KM = KM_ATUAL - lag(KM_ATUAL)) %>%
  mutate(DIF_DATA_DIAS = difftime(DATA, lag(DATA) , units = c("days"))) %>%
  mutate(DIF_DATA_MIN = DIF_DATA_DIAS * 1440) %>%
  mutate(KM_RODADA_ESPERADA = KM_MED_DIA * DIF_DATA_DIAS) %>%
  na.omit() %>%
  filter(ORDEM_REV > 1)

Comment: Flavio, obrigado primeiramente pela ajuda. Mas se você olhar a saída do código, a diferença de datas aparece negativa em alguns casos. Acho que ele não está classificando por data antes de subtrair, por que será?
Comment: Diego, para a base de dados informado por você não tem como ocorrer diferença entre datas negativa, pois somente uma placa se repete. Até fiz algumas alterações na base para ver se ocorre o que você falou, mas não. Se puder passar a base de dados com a qual você está trabalhando seria mais útil.
Comment: Consegui aqui Flavio. O problema é que é necessário converter a data para "data" antes de fazer o arrange.
Obrigado pela ajuda!

Problemas com datas no R


reverse a pointer read from binary file

Question: I'm trying to reverse some pointers that were read from a binary encoded file.
When I try to reverse the pointer 0xfffe0024540 stored in big endian format, I get
0xffffffffe0024540
The pointer is stored in the file in the format:
0000 ff0f 02e0 4045
Answer: The behaviour of right-shifting a negative signed integer is implementation dependent,
as far as I remember. You should replace long by unsigned long or uint64_t.
Comment: Right. I'd gotten languages switched, but sign-extension does indeed seem to be the root issue.
Comment: So, I tried replacing long by uint64_t but it still returns the same result.
Comment: @gary: Can you add a self-contained example demonstrating the problem to your question? Because `0xffffffffe0024540` is just the sign-extension of `0xfffe0024540`, without *any* swapped bytes. So there must be another problem ... (Btw. I tested the code on a Mac and it worked. What platform are you on?)
Comment: I'm running it on linux(OpenSUSE)
Comment: @gary: without an example including the printf's showing the problem it is difficult to help. (But it is late now where I live, so I will probably not respond before tomorrow.)
Comment: @gary: The swap function should be declared as `uint64_t swapPtr(uint64_t value)`. - I have tested your code (on Mac OS X) with a data file containing "00 00 ff 0f 02 e0 40 45"`, and the output was "pointer: 0xff0f02e04045". Perhaps you can show the contents of the pointer before swapping if you get a different result.

reverse a pointer read from binary file


derivative of matrix with respect to vector

Question: I need to calculate the derivative of matrix w.r.t. vector.
< Given Equation >

1)
$\mathbb Y = \mathbb A \mathbb X$

,where
$\mathbb A$: (n$\times$n) matrix
$\mathbb X$: (n$\times$1) vector.

2)
all elements in $\mathbb A$ and $\mathbb X$ are the function of $z_i$, where
$\mathbb Z = [z_1\ z_2\ \cdots\ z_m]^\top$
In other words,
$\mathbb Y(z)=\mathbb A(z) \mathbb X(z)$
< Problem definition >
I want to calculate the following partial derivative: $\frac{\partial \mathbb Y}{\partial \mathbb Z}$, which yields a (n$\times$m) matrix
From the general derivation rule for multiplication, it looks like the rule can be expanded (with some modifications) to the matrix/vector version,
$\frac{\partial \mathbb Y}{\partial \mathbb Z}
=
\frac{\partial (\mathbb A \mathbb X)}{\partial \mathbb Z}
=
\frac{\partial \mathbb A}{\partial \mathbb Z}\mathbb X
+
\mathbb A \frac{\partial \mathbb X}{\partial \mathbb Z}$
However, the above rule is wrong, as you can easily see that the first term's dimension doesn't coincide with (n$\times$m).
I want to calculate the derivation without explicitly calculating all elements in the output $\mathbb Y$.
How can I solve this problem?
Comment: Also, check the dimensions, should $\mathbb{A}$ be $n\times m$?
Comment: This formula should work if you're interested in a partial derivative with respect to a single $z_i$.  It will give you a vector, put those vectors into a matrix and you should be OK.
Comment: What do you mean by $\frac{\partial\mathbb{A}}{\partial\mathbb{Z}}$?  Since $\mathbb{A}$ is a matrix and $\mathbb{Z}$ is a vector, this should be a $3$-tensor, perhaps?
Comment: sorry, I've miswritten the dimensions of $\mathbb A$ and $\mathbb X$: their dimensions should be $n \times n$ and $n \times 1$, for each.
Answer: Your formula should be correct, when interpreted correctly.
Let's first investigate $\frac{\partial\mathbb{A}}{\partial\mathbb{Z}}$.  $\mathbb{A}$ is an $n\times m$ matrix and $\mathbb{Z}$ is a vector with $m$ entries.  This means, to specify a derivative, you need three coordinates: the $(i,j)$ for the entry of $\mathbb{A}$ and $k$ for the choice of variable for the derivative.  Therefore, $\frac{\partial\mathbb{A}}{\partial\mathbb{Z}}$ is really a $3$-tensor, and a $3$-tensor times a vector is a matrix.
Similarly, $\frac{\partial\mathbb{X}}{\partial\mathbb{Z}}$ is a matrix because there are two coordinates, $i$ for the entry of $\mathbb{X}$ and $j$ for the choice of derivative.  Hence, $\mathbb{A}\frac{\partial\mathbb{X}}{\partial\mathbb{Z}}$ is a product of matrices, and is itself a matrix.
If you want to figure out the formula a little more explicitly, if we write $\mathbb{A}=(a_{ij}(z))$ and $\mathbb{X}=(x_k(z))$, then
$$
(\mathbb{Y})_i=(\mathbb{A}\mathbb{X})_i=\sum_j a_{ij}(z)x_j(z).
$$
The partial derivative of this with respect to $z_k$ is
$$
\frac{\partial}{\partial z_k}(\mathbb{Y})_i=\frac{\partial}{\partial z_k}\sum_j a_{ij}(z)x_j(z)=\sum_j\left(\frac{\partial}{\partial z_k}a_{ij}(z)\right)x_j(z)+\sum_ja_{ij}(z)\frac{\partial}{\partial z_k}x_j(z).
$$
We can then combine all of these into a vector by dropping the $i$ to get
$$
\frac{\partial\mathbb{Y}}{\partial z_k}=\frac{\partial\mathbb{A}}{\partial z_k}\mathbb{X}+\mathbb{A}\frac{\partial\mathbb{X}}{\partial z_k}.
$$
This gives you the columns of the Jacobian, so they can then be put all together.
Answer: $
\def\n{\nabla_z}\def\bb{\mathbb}
\def\e{\varepsilon}\def\p{\partial}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\vecc#1{\operatorname{vec}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
\def\gradLR#1#2{\LR{\grad{#1}{#2}}}
$For typing convenience, use the convention wherein lower/upper case letters denote vectors/matrices and rename the problem's variables
$$\{\bb{A,X,Y,X}\} \to \{A,x,y,x\}$$
The gradient calculation with respect to scalar components of $z$ obeys the usual product rule
$$\eqalign{
y &= Ax \\
\c{\grad y{z_k}} &= A\gradLR x{z_k} \;+\; \gradLR A{z_k}x \\
}$$
To convert these component gradients into the desired matrix-valued gradient, multiply by the corresponding vector $\{e_k\}$ from the standard basis for
${\mathbb R}^{m}$ and sum
$$\eqalign{
\grad yz &= {\large\sum_k} \;\c{\gradLR y{z_k}}e_k^T \\
 &= A\gradLR xz
  \;+\; x^T\!\LR{\grad {A^T}{z}} \\
}$$
The final term is ugly because the quantity in parentheses is a third-order tensor, which is difficult to render in matrix notation, but trivial to write using index notation
$$\eqalign{
\grad{y_i}{z_j} &= {\large\sum_k}\;
A_{ik}\gradLR{x_k}{z_j} \;+\; x_k\gradLR{A_{ik}}{z_j} \\
\\
}$$
A common technique to side-step the tensor issue is to
vectorize the $A$ matrix
$$\eqalign{
a &= \vecc A \\
y &= Ax \\
dy &= A\;dx + dA\;x \\
 &= A\;dx \;+\; \LR{x^T\otimes I} da \\
\grad yz &= A\gradLR xz \;+\; \LR{x^T\otimes I}\gradLR az \\
}$$
where $(\otimes)$ denotes the Kronecker product
and $I\in{\bb R}^{n\times n}\,$ is the identity matrix.
This puts everything in terms of familiar vector-by-vector gradients.
Answer: Write $y(z) = A(z)x(z)$. We can approach the computation of the linear map $Dy(z) : \mathbb{R}^m \to \mathbb{R}^n$ using the Frechet derivative. For $v \in \mathbb{R}^m$ small, we have
$$A(z + v) = A(z) + DA(z)v + o(v),$$
$$x(z + v) = x(z) + Dx(z)v + o(v).$$
Therefore
\begin{align}
y(z + v) &= (A(z) + DA(z)v)(x(z) + Dx(z)v) + o(v) \\
&= A(z)x(z) + A(z)Dx(z)v + (DA(z)v)x(z) + o(v).
\end{align}
Thus
$$Dy(z)v = A(z)Dx(z)v + (DA(z)v)x(z).$$
The $j$th column of $Dy(z)$ is therefore
\begin{align}
\frac{\partial y}{\partial z_j}(z) &= Dy(z)e_j \\
&= A(z)Dx(z)e_j + (DA(z)e_j)x(z) \\
&= A(z)\frac{\partial x}{\partial z_j}(z) + \frac{\partial A}{\partial z_j}(z)x(z).
\end{align}
It actually does look identical to the product rule! This is no coincidence since the proof of the above rule was identical to the proof of the product rule.


How do you call Coherence (Elixir) from a test?

Question: My Elixir App is using Coherence for authentication. I am trying to write unit and functional tests for my app, but I don't know how to call the login function from the tests. Searching yielded very little examples on it's usage. Can someone who have done it before shed some light or examples how to do it ?
Comment: Maybe you should share some samples of what you've tried? The question you're asking sounds really simple and so I wonder if I'm missing something.
Answer: The foo function, that is declared in module Bar is called from everywhere as Bar.foo. So, to call login function, one should write the Module.Where.Function.Belongs.To.login(params).
The Coherence project itself provides a Demo pet project, that is in fact the great how to on Coherence usage. It also contains tests that are a very good starting point to write your own tests.
Answer: The other option is to set current_user in the conn.assigns for your test. If conn.assigns[:current_user] is set, the auth plugin will not attempt to authenticate the request.


How to output python graphs from terminal?

Question: I am very new to Python. Just installed it yesterday on Ubuntu 15.04. Now I am trying to output a parabola from the terminal. As far I understand I can not output any drawing on terminal so how can I see the graph?
I did :
sudo apt-get install python-numpy python-scipy python-matplotlib
my code is
import matplotlib.pyplot as plt
import numpy as np

# create 1000 equally spaced points between -10 and 10
x = np.linspace(-10, 10, 1000)

# calculate the y value for each element of the x vector
y = x**2 + 2*x + 2

fig, ax = plt.subplots()
ax.plot(x, y)

it does not show error when i do python parabola.py but no output :(
Answer: You need to add plt.show() at the end of the code, to display the parabola.
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show


How many compositions does the integer $12$ have into three parts none of which is equal to $2$?

Question: I want to find the number of compositions that satisfy the the following conditions:
$x_1 +x_2 +x_3 = 12$ and $x_i \neq 2$

Total $\binom{14}{2}$ compositions (weak)
Number of compositions where one of the parts equals $2$ is $\binom{11}{1}$
Number of compositions where two parts equal $2$ is $\binom{8}{0}$ or $1$
Number of compositions where all three parts equal $2$ is $0$

Hence the total number of such compositions are $\binom{14}{2} -\binom{3}{1} \binom{11}{1} + \binom{3}{2} = 61$
Edit: Somehow I manged to put a "-" there instead of a "+" :)
Answer: From the context, I'll assume the parts are restricted to nonnegative integers.

Using that assumption, the correct count is
$${\small{\binom{14}{2}}}-{\small{\binom{3}{1}\binom{11}{1}}}+{\small{\binom{3}{2}\binom{8}{0}}}=61$$
The subtraction of ${\large{\binom{3}{1}}}{\large{\binom{11}{1}}}$
removes each instance of two $2$'s twice, instead of one time, so they need to be added back.
Answer: I'm counting $61$, assuming nonnegative integers:
<code>n = 0;
N = [0, 1, 3:12];
for x = N,
    for y = N,
        for z = [0, 1, 3:(12-x-y)],
            if (x+y+z==12),
                ++n;
            end
        end
    end
end
n,
</code>
For positive integers (removing the singleton zeroes in the code), the count lowers to $31$.


Customize menu local task links

Question: I am looking for a way to customize 'edit', 'view', 'delete' links.
I use bootstrap theme, but i use bootstrap v4 styles for it. I want to add 'nav-link' class to each link.
And find a way to display somewhere, not just below post title.
I couldnt find a tutorial about it. Where should i look for this? template parts (twig) or themename.theme file?
Answer: For preprocess function you can use HOOK_preprocess_menu_local_tasks(&$variables) {... where HOOK is the name of your active theme.
And for template suggestions you need to enable debugging and see with inspect element, as usual it must be menu-local-tasks.html.twig
Answer: You can customize the local tasks using menu-local-tasks.html.twig and menu-local-task.html.twig. The Stable core theme has samples of these files. You could also try using hook_preprocess_menu(&$vars) in your .theme file. I'm not sure if it processes the local menu items though. I am using it for the main menu.
Answer: You could create your own tpl.php! I think there should be a template file within your bootstrap theme. Copy that file to your subtheme templates folder and edit it the way you want it to look like.
Comment: Sorry forgot to tell that I user drupal 8. which tpl file should I work on it? I can find drupal 8 version of that
Comment: Sorry, I don't have used Drupal 8 yet - shame on me! But I would guess, that the template concept is still working. You could search for page.tpl.php (the whole page) or node.tpl.php (template for nodes).

Search the bootstrap theme folder for a folder called templates, I guess, there you'll find these files!
Comment: Just had a look at bootstrap for Drupal 8. The concept seems to be the same as for Drupal 7 but the tpl.php - files now are the twig files!
Comment: which tpl file should i look for?
Comment: you could have a look at page.html.twig, node.html.twig or the menu-local-task.html.twig / menu-local-tasks.html.twig

Customize menu local task links


What is the difference between a software synth (like Ableton's Operator) & The piano synths they include in Standard

Question: I'm following a tutorial that uses a software synth (Sylenth1 is this case)
I now realize I don't have a software synth at all, because I purchased Standard Edition of Ableton.
Could in theory I get by, using these piano synths?? included?? I would only lose the tweaking abilities of a full synth right?
Answer: I'm not sure what you mean by a "piano synth", but I'll talk about what you don't have when you buy any edition of Ableton Live that is not the full Suite edition and what Sylenth1 is all about.
Most software synthesizers are software recreations or imitations of an analog subtractive synthesizer. The hugely popular Moog Minimoog synthesizer is a classic example of a subtractive synthesizer. Sounds are created by electronic oscillators which make different wave shapes that have different sounds. Those waves are then mixed in different amounts, filtered (the subtractive part), and modulated in different ways, and then amplified in certain ways. The classic ingredients are oscillators, filters, LFOs (low frequency oscillators), mixers, and envelope generators.
Software synths recreate the different components with a combination of sound samples and component modeling (where a small piece of software imitates the function of a real world circuit element) combined with a software interface that imitates the sound and controls of a real-world synthesizer. If you spend the money to by the Suite edition of Ableton Live, then you get their analog subtractive synth virtual instrument that is just called "Analog".
Ableton Operator (also including in the Suite edition of Live) is their software synth version of a real-world FM synthesizer. This type of synthesis is a bit more complicated and the most famous real-world example is probably the Yamaha DX7.
Sylenth1 is a software version of an analog subtractive synthesizer, so it's closer to being like Analog than it is like Operator.
The Intro and Standard editions of Live do not include any software synthesizers, as far as I can tell (see: https://www.ableton.com/en/live/feature-comparison/#software-instruments).
What you do get is Simpler, which is a sample playback instrument. This kind of thing used to be called a "wave table synthesizer" in the late 80s. Simpler just plays back samples, which are little recordings of other instruments or sound files of any kind (it could be crickets chirping, a drill, a rocket, or a harmonica playing). What makes a sampler different from just recording and playing back sound is that it lets you increase and decrease the pitch of the playback automatically as you play different keys on a keyboard or send it different MIDI note messages. So with a sample of just one flute sound, for example, you can play back all the notes you want with a flute sound.
Sampling gets a lot more complicated from there, but that's what Simpler does - it lets you play back samples of other instruments. The included instrument sounds in Live Standard and Intro are samples that Live loads into Simpler. There are some things you can do with Simpler to shape the sample sounds like a real synthesizer, but they are very crude.
If you want to learn about how a full synthesizer or synthesizer virtual instrument works (which I recommend highly if you want to get into music production of any kind), you'll want a real virtual instrument that re-creates a subtractive synthesizer. (Subtractive synths are by far the most popular kind.)
The upgrade to Live Suite is pretty expensive and will give you many other things you may or may not need. Other more affordable options include Sylenth1 (obviously), NI Massive, Arturia's line of virtual synths, several of the u-he products, some of the UVI products, Reveal Spire, and many more.
Comment: @Erik Yes, pretty much all virtual piano instruments are sampled. Pianos create very complicated sounds that are not easily synthesized using other methods. The best virtual pianos have many "layers" of high quality samples that are played back based on complicated algorithms. They often combine modeling and convolution technology to control the balances of the different samples and recreate room reverberation and other elements of a complete piano sound.
Comment: I guess my question is answered, but one more... when I was asking about syth pianos.. I was wondering how the Piano software instruments in Ableton are created.  At first I had guessed they were a synthesizer.. but now you make me think they could be done via sampling..


Bayesian network learning can be derived from learning each conditional distribution separately?

Question: Please helm
I am wondering if we consider a learning the  parameter of a  bayesian network ,with  a training set ,where each training set is a vector of values containing all the random variable ,in the network .,Now can we show that the learning parameter of the network according to the MLE ,can be derived by seperately learning the parameters of each conditional distribution
Comment: I'm assuming the conditions are completely disjoint and the frequency of each condition is known in advance?
Comment: yes probability  of the marginal distributions are known
Answer: Yes, this is explained in the paper Decomposing Parameter Estimation Problems by Refaat et al (2014).


What hook function (is _form_alter correct?) do I use to alter the input submitted by the user into a views exposed filter form?

Question: I'm developing a views exposed filter form for searching for items in given geographic locations.
I want to restrict this to a particular country so that cities with the same name in other countries aren't shown in the View results. For example only London, UK not London, Ontario; Portsmouth UK not Portsmouth New Hampshire, USA.
(Note please don't close this topic as being too local - my question would apply to anyone who wants to do this whatever country they are in.)
The simplest approach I want to consider is suffix the user input with the country. For my example this would be Newcastle becomes Newcastle, UK.  Given that the site is focused on users in particular country, for user experience (UX) usability reasons I do not want the user to have to enter the country name at the end.
I had tried to add a function to do the suffixing by adding it as a callback in the form[#submit] array in _form_alter and implement the function in my custom module. But this did not alter my submitted input as required. Here is my code snippets:
function mymodule_form_alter(&$form, $form_state, $form_id) {

// keep the standard handler
$temp = $form['#submit'][0];

// put my handler in first
$form['#submit'][0] = '_mymodule_custom_handler_submit';

// restore the standard handler to appear in the array after mine
$form['#submit'][2] = $temp;
}

function _mymodule_custom_handler_submit(&$form, &$form_state) {
    $form['field_geofield_distance']['origin']['#value'] .= ", UK";
}

When I try this I find (using  dpm ) that the submitted input is not altered before it gets sent to the View for it to create the results - so I deduce that this code is not running before that, but instead after that.
Can you advise on what I might be doing wrong here?
Also, in the $form['#submit'] array, are the callback functions "chained" together - i.e. in that the first function in the array gets called, it modifies the form submitted input and this is then passed to the next callback. If this were the case I would have expected my code to work.
Is _form_alter the right hook to use for this problem?
Update
Now using debugger (Komodo IDE) connected to my Vagrant VM-based local development environment that's running the site to investigate a solution:

Thanks.
Update 2:
I don't think this form handler approach is going to work, the screenshot below shows a callstack - see bottom right, showing that the views execute display function (presumably the view itself) runs before my code to modify the input
Answer: First if you want to add submit handler as first in form_alter do
//prepend the handler to array
array_unshift($form['#submit'], '_mymodule_custom_handler_submit');

So you dont overwrite any other callback by some other module.
Second, check that the form input elements dont have overriding submit handlers ("
submit action on the buttons")
Third, try to assign the value with form_set_value
$oldValue = $form_state['values']['field_geofield_distance']['origin'];
$value = array('origin' => array('#value' => $oldValue. ', UK')
form_set_value($form['field_geofield_distance'], $value, $form_state);

Syntax above is not correct, but without knowing the structure of the field its impossible to know what kind of array it requires. For example Link module fields can be modified with following.
    // Set first link of the field pointing to google, most likely
    //unsets all the following ones
  $link = array(
    0 => array(
      'title' => 'Google',
      'url' => 'google.com'
    )
  );
  form_set_value($form['field_link'], $link)), $form_state);

Last but not least, use additional form validation callback instead submit handler, that way its sure that the values get passed to all "targeted(see second)" submit handlers.
Long story short. When form is being built, add input validator to it. Validator will get called after user sends the form and there you can modify values before they get submitted to submit handlers.
Summary interpretating view flow
While the view is being built first time it calls the form (which runs through standard drupal hooks like form_alter) and gets the values from it just in case it has some defaults or accepts 0 filters.
After that it runs the queries, renders the form and the result. When finished you get the view including all the elements without user input. Like clean plate (mayby some contextual filters and stuff is applied but thats irrelevant?).
Next when the user sends the form with custom input, drupal (field widgets/handlers) transforms input to values and store them in $form_state and passes them to validators. Here the custom validator can modify the user input values in $form_state and attach them with form_set_value.
If the validation passes correctly $form_state values(modified) get passed to submit handlers. Most likely views will start building itself from them. Heres more exact flow(pdf)
Comment: Thanks again - I've looked at this in more depth now. On first your suggestion: this is the same as my suggestion but is a better approach as mine referred to index positions directly but the outcome is the same - my handler function is first. On your second suggestion, I checked (thank you) and according to dpm there aren't any overriding submit handlers. On your third suggestion, thanks for this but I had to make a few typo corrections (see edit), but even after that I got an error about 'values' undefined index in $form_state.
Comment: I really wish the drupal APIs would display *all* possible values in an array parameter - in my case `$form_state` so that I actually see what `'values'` should be instead. Ho hum, they don't. So, out I wheel my debugger, Komodo IDE to break on the code and step through...
Comment: Your 3rd suggestion would not appear to work as there is not an index 'values' in $form_state array - see the bottom left of my debugger screenshot inspecting the variable - see screenshot in update to my question above or here: http://i.stack.imgur.com/j4QIi.png
Comment: Values get populated by drupal before validation and carry on to submit handlers, they do not exist before that. form_alter can not be used to modify input.
Comment: So where what function/hook should your suggestions go in if it's not _form_alter. My screenshot 2 above (http://i.stack.imgur.com/Tsghg.png ) shows that the submit handlers are called *after* the view is built (see call stack on bottom right) so putting the code in submit handlers would never work, surely?
Comment: I edited the answer with summary of the view flow, because they were too long for to this comments. Btw I need to get some debug stack location tool like yours.
Comment: Thanks for your "Summary interpretating view flow" - it maintains that I should be writing a submit handler to modify the form input. I have already done this: `array_unshift( $form['#submit'], '_cgformutils_custom_handler_submit' );` in `cgformutils_form_alter` and implemented my handler `_cgformutils_custom_handler_submit`: `function _cgformutils_custom_handler_submit(&$form, &$form_state) { $form['field_geofield_distance']['origin']['#value'] .= ", UK"; }` BUT this does not intercept the form-submitted value and append UK before it gets to the view. So, no progress on a solution.
Comment: switch your submit handler to validator.
Comment: OK I will try that and get back to you.
Comment: By the way, my debug stack location tool is Komodo IDE - http://www.activestate.com/komodo-ide/features
Comment: validate handler is not working either. For example, I submit "Durham" into form and my handler appends ",UK" to it so that it is "Durham, UK". BUT this is ignored by the view because I get the same results back for "Durham" even when the handler has changed the value to "Durham, UK". However, if I specifically enter "Durham, UK" myself then this returns the results that I want. So the handlers are being ignored and I need to intercept the form submit somewhere else in the Drupal code with a hook.
Comment: OK, time for an alternative solution: https://drupal.org/project/fapi_validation write a hook and filter. Visit this page for "mymodule_validation_filter_name" to see what I mean. I'll give it a go and report back here...
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10276/discussion-between-user20301-and-therobyouknow)
Answer: There are 2 solutions, depending on what you are trying to do:

For searching in a View of location specific items using geofield: (the specific solution that I was looking for) append ",UK" onto the $location variable in function getSourceValue in geofieldProximityGeocoder.inc in proximity_plugins in views folder of geofield. Notes if interested: This is a hack - it's altering the module code directly, so ideally we'd want to make this override-able in the conventional way - i.e. make the function hook-able so that it can be overridden in a custom module (or theme). I'll try to make a patch for all this. Also written up here: https://drupal.org/node/2070905
Normally, in other exposed filter forms in general, I believe the solution to modify user entered data at the exposed filter would be to use hook_views_query_alter
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
and modify the required input variable (that came from the user) contained in: exposed_raw_input array. Solutions offered by user20301 in their answer regarding handlers may also work, perhaps also for other behaviour that needs to occur when hitting the submit button. But for my solution I with location I needed something else as here I found that the entered location had already been calculated as I could see the long and lat values in the one of the arrays in the $query variable. So that led me to believe that geofield had already been involved and lo and behold it was.
Comment: did you wirte that patch in solution #1? I didn;t see it in that thread. I just need to know what line in geofieldProximityGeocoder.inc to modify. I don;t code but I need this hack to get the thing working in the meantime.
Comment: Sorry, Nigel, no. My advice would be to see if the issue is still occurring. Perhaps since I worked on this, things have improved to not need my hack. Though I guess you are still seeing the issue, is that the case?
Comment: Thanks for getting back to me. Unfortunately, the reason I am asking is because the issue is still not resolved in the module. If I can quickly just hack this module to get this working that would be great. I just don;t know what line number to edit to get what I need. I was hoping you could let me know as I am not a coder.
Comment: (1/4) @NigelWaters the answer to your question is outlined in point 1 of the my answer above. Sounds like you'd like a little expansion on this as to the detail, here goes:
Comment: (2/4) The change is to a file in the geofield module. So you'll need to have this module installed on your site to start with. Inside the geofield module folder, open the following file to edit: views/proximity_plugins/geofieldProximityGeocoder.inc and after line 50: `$location = (isset($views_plugin->value)) ? $views_plugin->value['origin'] : $views_plugin->options['geofield_proximity_geocoder'];` insert line: `$location .= ",UK";` I am assuming that the version of the Geofield module you are using is 7.x-2.0
Comment: (3/4) Note: I don't have the original code to hand where I fixed it, so this is from memory. Give it a go!
Comment: (4/4) Ideally you'd want to move this module to a separate folder, called patched, so that this 'hack' doesn't get overwritten if a new version of Geofield is downloaded. After moving you'd need to tell Drupal that the module is moved =- by doing a `drush rr` - registry rebuild but it sounds like this would be something to consider once you feel comfortable with coding. Just a tip.
Comment: When I add this it makes unfiltered view disappear. Is there a way to make it so it is only added when someone enters text into the exposed proximity filter?
Comment: Here is the code paste of the module. http://pastebin.com/Diwj5deE


Solve for $x$: $3+|x-9|<\frac{2|x-1|}{x}$

Question: I moved one part of the inequality to the other to create the following:
$\frac{2|x-1|}{x}-3-|x-9|>0$
Eventually, I get to a case where I have 2 inequalities after opening 1 of the absolute values, but then get confused on what do I do with the second one. Am I supposed to get 4 inequalities? Isn't there a simpler method which I am missing?
Answer: Unfortunately, there is no easier way than splitting this into different cases. You can restrict yourself to the cases $0 < x \leq 1$, $1 < x < 9$ and $x \geq 9$. However, two of these cases are immediately impossible, so you only end up with one case. Can you finish?


Transformar 3 funções semelhantes em uma só

Question: Em meu projeto, eu possuo funções bem parecidas, com a mesma intenção, porém, como se trata de uma função de troca de classes do DOM (classList.replace), eu acabei fazendo um código muito repetitivo, e gostaria de reduzi-lo para torná-lo reutilizável no futuro. Porém, apesar de várias tentativas com loops como for...if e forEach, eu acabei travando, e por falta de experiência em lógica de programação, pois estudo programação a apenas 6 meses, não consegui.
Eis o código:
handleLeftAnswer() {
    $leftDiv.classList.replace('leftside-div', 'leftside-div-js');
    $centerDiv.classList.replace('centerside-div', 'centerside-div-js-no-display');
    $rightDiv.classList.replace('rightside-div', 'rightside-div-js-no-display');
  }

  handleMidAnswer() {
    $centerDiv.classList.replace('centerside-div', 'centerside-div-js');
    $rightDiv.classList.replace('rightside-div', 'rightside-div-js-no-display');
    $leftDiv.classList.replace('leftside-div', 'leftside-div-js-no-display');
  }

  handleRightAnswer() {
    $rightDiv.classList.replace('rightside-div', 'rightside-div-js');
    $centerDiv.classList.replace('centerside-div', 'centerside-div-js-no-display');
    $leftDiv.classList.replace('leftside-div', 'leftside-div-js-no-display');
  }

O que eu tentei:
handleRightAnswer(rightOne) {
    const options = ['left', 'center', 'right'];

    console.log(rightOne);
    switch (rightOne) {
      case rightOne: 'left'; break;
      case rightOne: 'center'; break;
      case rightOne: 'right'; break;
    }

    for (const option of options) {
      const isThisTheRightAnswer = option === rightOne;
      const element = document.querySelector(`.${option}side-div`);
      console.log(element);
      isThisTheRightAnswer ? element.classList.replace(`${option}side-div`, `${option}side-div-js`)
        : element.classList.replace(`${option}side-div`, `${option}side-div-js-no-display`)
    }
  }

Quais os erros que deram nessa tentativa:

rightOne estava voltando como um mouseEvent
Os três elementos estavam atuando em conjunto e trocando suas classes de uma vez só, ao invés de separadamente.
isThisTheRightAnswer estava retornando como false, e eu não consegui decifrar como fazê-lo para retornar true.

Mais uma vez, me perdoem por minha ignorância e falta de prática, eu realmente gostaria de saber como posso trabalhar mais o meu raciocínio lógico para melhorar o meu código futuramente, e eu, um iniciante em programação, conto com a ajuda de vocês para me auxiliar nisso.
Answer: As partes comuns são:

Sempre faz replace nos três elementos:
O elemento "em destaque" fica com a class "xxx-div-js" e os demais "xxx-js-no-display"

Portanto, precisa passar um parâmetro que determine se é "left", "center" ou "right".
Poderia fazer assim:
handleAnswer(rightOne) {
    var leftSufix = rightOne == "left" ? "" : "-no-display";
    var centerSufix = rightOne == "center" ? "" : "-no-display";
    var rightSufix = rightOne == "right" ? "" : "-no-display";

    $leftDiv.classList.replace('leftside-div', 'leftside-div-js'+leftSufix);
    $centerDiv.classList.replace('centerside-div', 'centerside-div-js'+centerSufix);
    $rightDiv.classList.replace('rightside-div', 'rightside-div-js'+rightSufix);
}

E usar assim por exemplo: handleAnswer('left');
Poderia também no lugar de mudar só o sufix, por todo o nome da class, mas ideia seria a mesma
Outra possibilidade seria mudar todos para "xxx-div-js-no-display", e com um switch mudar só o que que vier no parâmetro "rightOne" para "xxx-div-js", mas isso faria mais sentido se tivesse várias opções, por exemplo umas 10.
Comment: Puts, algo tão simples e eu tava tentando de resolver das maneiras mais complexas que existem. Obrigado mano!


Solve for $x$ in $ \sin x + \sin x \cos x - (\frac{1}{\sqrt{2}} + \frac{1}{2})= 0 $

Question: How can to solve for $x$ in $$ \sin x + \sin x \cos x - \left(\frac{1}{\sqrt{2}} + \frac{1}{2} \right)= 0.$$
My try:
$$ \sin x + \sin x \cos x = \left(\frac{1}{\sqrt{2}} + \frac{1}{2} \right) $$
$$  (\sin x + \sin x \cos x)^2 = (\frac{1}{\sqrt{2}} + \frac{1}{2})^2
$$
$$ \sin^2x + 2\sin^2 x \cos x + \sin^2x \cos^2x - (\frac{1}{\sqrt{2}} + \frac{1}{2})^2 =  0
$$
$$ \sin^2 x( 1 + 2 \cos x + \cos^2 x ) - (\frac{1}{\sqrt{2}} + \frac{1}{2})^2 = 0
$$
$$ (1 - \cos^2x)( 1 + 2 \cos x + \cos^2 x ) - (\frac{1}{\sqrt{2}} + \frac{1}{2})^2 = 0
$$
$$ 1 + 2 \cos x + \cos^2 x - \cos^2 x - 2 \cos^3 x - \cos^4 x- (\frac{1}{\sqrt{2}} + \frac{1}{2})^2 = 0
$$
$$ 1 + 2 \cos x - 2 \cos^3 x - \cos^4x -(\frac{1}{\sqrt{2}} + \frac{1}{2})^2 = 0
$$
thx for all ur help
Comment: Unless you add more details and show your attempts to solve, this will be a closed question soon. I will show you a nice symmetry in the equation, which points out some solutions even befor we solve it completely. $$\sin x \left(1+\cos x\right)=\dfrac{1}{\sqrt{2}}\left(1+\dfrac{1}{\sqrt{2}} \right).$$ As a general strategy you can replace both $\sin x$ and $\cos x$ by $\tan (x/2)$ using double angle formulas.
Comment: No matter which way you try to solve this (tangent half angle substitution, or by immediate squaring as you did), it seems you'll end up with a quartic equation. There are ways to solve those analytically, but they're very difficult.
Comment: Either you use the tangent half angle identities as suggest by Bumblebee or use the substitution $cosx=t$ and you end up with a quartic equation. I beg to ask, where did this question come from and are there any hints/tools as to how a student is supposed to solve this?
Comment: the question is somewhere from physics, which is related to the topic of projectile motion
Comment: from your last equation, $\sin^2x=1-\cos^2x$. finally check your solutions in the original equation
Answer: Using the tangent half-angle substitution, you end with
$$\left(1+\sqrt{2}\right) t^4+2 \left(1+\sqrt{2}\right) t^2-8 t+(1+\sqrt{2})=0$$By inspection (with all these $1$'s and $\sqrt{2}$'s),  $\color{red}{t=(\sqrt{2}-1)}$ is a root.
Factoring, we are left with
$$\left(1+\sqrt{2}\right) t^3+t^2+\left(1+3 \sqrt{2}\right) t-(3+2 \sqrt{2})=0$$ for which $$\Delta=-64 \left(63+44 \sqrt{2}\right) \quad <0$$ Using the hyperbolic method for only one real root which is (!!)
$$\color{red}{t=\frac{1}{3} \left(1-\sqrt{2}+4 \sqrt{3-\sqrt{2}} \sinh \left(\frac{1}{3}
   \sinh ^{-1}\left(\frac{5}{14} \sqrt{\frac{1}{7} \left(173+81
   \sqrt{2}\right)}\right)\right)\right)}$$ I shall not try to find what is this number which is not recognized by inverse symbolic calculators.
To the first root corresponds
$$x_1=2 \tan ^{-1}\left(\sqrt{2}-1\right)=\frac \pi 4+2k\pi$$
and the second is
$$x_2\sim 2\tan ^{-1}(0.778669) \sim 1.323197$$
Answer: You may continue with
$$ 1 + 2 \cos x - 2 \cos^3 x - \cos^4x -(\frac{1}{\sqrt{2}} + \frac{1}{2})^2 = 0
$$
knowing that $ \cos x = \frac1{\sqrt2} $ is a solution from inspection, as commented. So, factorize  the equation as
$$ (\cos x - \frac1{\sqrt2})(\cos^3x +(2+\frac1{\sqrt2})\cos^2x+ (\frac12+\sqrt2)\cos x-1+\frac1{2\sqrt2})=0
$$
where the cubic polynomial has one real root that can be calculated analytically with the Cardano formula.
Answer: One solution, $\pi/4$, is immediately extracted from the form of the given equation, as Bumblebee commented after a few seconds as the question was posted:
$$
\sin x (1+\cos x)=\frac1{\sqrt2}\left(1+\frac1{\sqrt2} \right)\ .
$$
There are two solutions in $[0,2\pi]$, as the following pari/gp-raw plot shows it:
? plot(x=0, 2*Pi, sin(x) + sin(x)*cos(x) - (1/sqrt(2) + 1/2) )

 0.088734 |'''''''_x""x_'''''''''''''''''''''''''''''''''''''''''''''''''|
          ```````x``````x`````````````````````````````````````````````````
          |     x        "_                                              |
          |    x           _                                             |
          |   _             x                                            |
          |                  x                                           |
          |  "                x                                          |
          | _                  x                                         |
          |                     "_                                       |
          |x                      x_                                     |
          _                         xx____                               _
          |                               """"xx                         |
          |                                     "x                      x|
          |                                       "_                     |
          |                                         x                  " |
          |                                          x                _  |
          |                                           x                  |
          |                                            x             "   |
          |                                             "           x    |
          |                                              "_        x     |
          |                                                x      x      |
-2.502948 |................................................."x__x".......|
          0                                                       6.283185
?

Both solutions appear in the interval $[0,\pi/2]$.
To see that the second solution is not a "beautiful solution", i.e. a(n easy) rational multiple of $\pi$, we have to solve explicitly.
Numerically, this is simple. In sage, we have for instance:
? \p 80
   realprecision = 96 significant digits (80 digits displayed)
? c1 = solve(c=0, 0.5, 1 + 2*c - 2*c^3 - c^4 - (1/sqrt(2) + 1/2)^2)
%13 = 0.24507719212504432088553369017245407857420915894751612868529986637012882459682178
? c2 = solve(c=0.5, 1, 1 + 2*c - 2*c^3 - c^4 - (1/sqrt(2) + 1/2)^2)
%14 = 0.70710678118654752440084436210484903928483593768847403658833986899536623923105352
? acos(c1)/Pi
%15 = 0.42118669118081648201964584654917700002378936841121635895529014330812148926140359
? acos(c2)/Pi
%16 = 0.25000000000000000000000000000000000000000000000000000000000000000000000000000000

Here, we have used the equation of degree four from the OP in the unknown $c$, extracted to correspond to $\cos x$. The solution $c_2=1/\sqrt2$ corresponds to $x=\arccos c_2=\pi/4$. But $c_1$ "looks ugly".
To get it explicitly, we can factorize in sage, using the letter $a$ for $\sqrt 2$ and $C$ as unknown (playing the rolw of $\cos x$):
sage: K. = QuadraticField(2)
sage: R.<C> = PolynomialRing(K)
sage: factor(1 + 2*C - 2*C^3 - C^4 - (1/a + 1/2)^2)
(-1) * (C - 1/2*a) * (C^3 + (1/2*a + 2)*C^2 + (a + 1/2)*C + 1/4*a - 1)

The first factor corresponds to the root $c_2=a/2=\sqrt 2/2$.
The second factor has three complex roots, one of them only is real:
sage: (C^3 + (1/2*a + 2)*C^2 + (a + 1/2)*C + 1/4*a - 1).roots(ring=QQbar, multiplicities=False)
[0.2450771921250444?,
 -1.476091986655796? - 0.6774060585198529?*I,
 -1.476091986655796? + 0.6774060585198529?*I]

And the real value above corresponds to the (numerical) one delivered by pari/gp.
Its exact expression is as follows.
Let us introduce:
$$
\begin{aligned}
S &= \frac 1{54}\Big(23 + \sqrt 2 + 3\sqrt{3(13+6\sqrt 2)}\Big)\ ,\\
T &= \frac 1{54}\Big(23 + \sqrt 2 - 3\sqrt{3(13+6\sqrt 2)}\Big)\ ,\\
&\qquad\text{Then the needed unknown root $c_1$ is:} \\
c_1 &= -\frac 16(4+\sqrt 2) + S^{1/3}+ T^{1/3}\ .
\end{aligned}
$$
And the corresponding $x$-solution is obtained by taking arccos of $c_1$.
Let us check this (numerically):
sage: a = sqrt(2); var('C');
sage: pol = (C^3 + (1/2*a + 2)*C^2 + (a + 1/2)*C + 1/4*a - 1)
sage: S = (+3*sqrt(3)*sqrt(6*sqrt(2) + 13) + sqrt(2) + 23)/54
sage: T = (-3*sqrt(3)*sqrt(6*sqrt(2) + 13) + sqrt(2) + 23)/54
sage: c1 = -(4+sqrt(2))/6 + S^(1/3) + T^(1/3)

sage: c1.n(300)
0.245077192125044320885533690172454078574209158947516128685299866370128824596821778908696124

sage: pol.roots(ring=RealField(300), multiplicities=False)
[0.245077192125044320885533690172454078574209158947516128685299866370128824596821778908696122]

sage: x1 = acos(c1)
sage: x1.n(250)
1.3231970148034460170431250253951876668350360601328894523066983942144393866

This corresponds also to the numerical solution given by pari/gp when asked for...
? solve(x=Pi/3, Pi/2, sin(x) + sin(x)*cos(x) - (1/sqrt(2) + 1/2))
%17 = 1.3231970148034460170431250253951876668350360601328894523066983942144393866408301


Modelling both mean and dispersion of count data

Question: I have a model of the following form:
$P(Y \mid X) = \,D(\mu,\sigma^2) ~~\text{where}$
$\mu = f(X) ~~\text{and}~~ \sigma^2=g(X)$
where $y$ is the response vector of count data, $X$ is the predictor matrix, $f()$ and $g()$ are linear inverse link functions (I don't mind what they are), and $D$ is some probability distribution (maybe Poisson with overdispersion).
Does this model have a name? How would you estimate it? Is there a package in R that can do it?
I understand that usually one would use negative binomial or Poisson GLM, but here I have heteroscedasticity that depends on $X$ not in the same way as the expected value of the response (that is $f()$ and $g()$ are not the same).
Thank you for your help!
Comment: seems like a quasi likelihood equation.  you model the "mean function" and the "variance function" - could possibly be a "generalised GARCH" model for discrete data, although im not familiar with software to estimate these.  i look for financial stochastic volatility models as a start, though these are generally based on brownian motion or geometric brownian motion, rather that discrete data.
Comment: Would presumably fit within the framework of [Generalized additive models for location, scale and shape](http://en.wikipedia.org/wiki/GAMLSS), but maybe there's a simpler way, as that seems overly general.
Comment: I'm pretty sure I just reformulated the math to something equivalent, but feel free to revert if I missed something.
Answer: Take a look at 'double generalized linear models'.
e.g.
Smyth, G. K., and Verbyla, A. P. (1999). Double generalized linear models: approximate REML and diagnostics. In Statistical Modelling: Proceedings of the 14th International Workshop on Statistical Modelling, Graz, July 19 – 23, 1999, H. Friedl, A. Berghold, G. Kauermann (eds.). International Workshop on Statistical Modelling, Graz. Pages 66-80.
(http://www.statsci.org/smyth/pubs/iwsm99.ps)


RuntimeError: Working outside of application context. Corey Schafer Flask Tutorial

Question: i'm trying to understand flask. I'm a newbie.
I made progress up to lesson 4. youtube Link
Create templates, static-css, bootstrap connections, ORM classes.
When i open the python terminal and

from flaskblog import db it is ok, no statement like in the vide, then
db.create_all()

this is where my code collapse...
error is exactly as it is:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/erdoganb/Library/Python/3.9/lib/python/site-packages/flask_sqlalchemy/extension.py", line 884, in create_all
    self._call_for_binds(bind_key, "create_all")
  File "/Users/erdoganb/Library/Python/3.9/lib/python/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
    engine = self.engines[key]
  File "/Users/erdoganb/Library/Python/3.9/lib/python/site-packages/flask_sqlalchemy/extension.py", line 636, in engines
    app = current_app._get_current_object()  # type: ignore[attr-defined]
  File "/Users/erdoganb/Library/Python/3.9/lib/python/site-packages/werkzeug/local.py", line 513, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

and tried the add, app.app_context() into my flaskblog.py file.
Can you help me where is my mistake(s)?
Thank you.
and tried the add, app.app_context().push() into my flaskblog.py file. gives me another error
reinstalling some packages, like sqlalchemy
Answer: I've solved my problem.
I've added
app.app_context().push()

then
db.create_all()

solved my problem.
And also, for creating database and initialize, you can just run your code without the codes above, get in directory then open a python terminal (repl) then
from yourapp import *

app.app_context().push()

db.create_all()

Second method is more sensible to me.
Because you better check your database in the beginning and don't touch it later.
Answer: When your app size grows there will be dependency on multiple library. So for this you should start using Factory Pattern to avoid this issue and organize the project
Here is the documentation: https://flask.palletsprojects.com/en/2.2.x/patterns/appfactories/
Comment: thank you i'll check it while my project grows. and kind of solved my problem, i guess its about the "sqlite::///test.db" and you have be in same folder while running the app. somehow it conflicts with some other program, im not sure but it worked for me. thank you for your suggestion.


Windows DHCP not showing the accurate leases

Question: In Windows System Event log, there are DHCP server warnings that IP address range of a scope (10.40.0.0) that available is low.
Windows Event Log

But in the DHCP program, the Address Leases is only showing 4 or 5 leases. Based on the settings it should allow 235 leases in total.
DHCP Address Leases DHCP scope properties

There is only 4 for reservation.

Is it the Windows System Event log warning is inaccurate? Or is it the DHCP program's Address Leases inaccurate? How do I resolve this to see accurate information?
This is in a Windows Server 2012 R2.
Comment: Please check network mask for that DHCP scope.
Comment: Hi @ZoranJankov are you referring to check the Subnet mask? I added a screenshot of the Subnet mask, what should I check in there?
Comment: Hi @Boon Chye Phang! Yes I was referring to the subnet mask. I thought you accidentally put wrong subnet mask, but it is fine. What about your address reservations? Check if you have any. They will count as leased addresses.
Comment: Hi @ZoranJankov, I have checked there is only 4 IPs for reservation. Added the screenshot of it too.
Answer: Is it the Windows System Event log warning is inaccurate?
No the event log is accurate. 27 days ago on October 21 that was the status of the DHCP scope available leases.
Comment: Hi Greg, the screenshots of the DHCP address lease was also taken around the time, that is why I cannot understand why the lease is only a few. Do you have any idea why?


In views, how do I show posts from this calendar day, ten years ago?

Question: I have a view in which I want to display posts that I made on this date 10 years ago. I can get close but not exactly what I want by setting the view's filter  to the following:
"Authored On is between: (offset) -10 year and -10 year +1 day"
My problem is that if it's currently 1pm on Dec. 17, 2019, I want to see all posts from the Dec. 17, 2009, regardless of hour posted. Instead I am seeing posts from Dec. 16, 2009 1pm to Dec. 17, 2009 1pm. I don't care what time the post was authored at, I just want it to show if the calendar day from 10 years ago is the same.
How can I set up my filter to do this?
Answer: Like you did, create two filters for the date range and then use the following values
-10 years midnight
-10 years +1 day midnight

Remember to select
An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

If you want to do this programmatically you can create a date filter and set the actual date values from code for the filter range.
You can create the date filter and set the filter value programmatically like the following
How do I programmatically render a view that has exposed filters?
Comment: Um, that question has no accepted answer. I don't want an exposed filter or a contextual filter. I am looking for a way to do this in the standard (for dummies like me) Views interface under _Filter Criteria_.
Comment: @Tantalus - I have updated the answer with something you can do without code. Can you please check if this works for you?
Comment: I think this is probably right. It's not exactly working in my Drupal install. Today is the 17th and I am still seeing items from the 16th. But, when I use your format in a tiny php file like this `` is outputs exactly the correct time. This leads me to think that maybe my Drupal install or local dev environment is not set up for my correct timezone.
Comment: Well, I checked my timezone settings and everything is set to CST. I have it working now with the following: `-10 year +1 day midnight` to `-10 year +1 day midnight +25 hours`. I tested by creating backdated posts at 12:01am 2009/12/17 and 11:59pm 2009/12/17. I have no idea why this worked and yours didn't. Maybe leap years? I can live with this, and I'll mark your answer as correct. It got me moving in the right direction at least.


REST API: Using a GET Request to match an ID within a File and display the object corresponding to ID

Question: I really need help with a RESTful API project that I am working on. I have done extensive searches and am at a crossroad. This is very new to me and I am not quite understanding everything, so I do apologize if this is an elementary question.
What I am required to do:
I am required to create a "getVehicle" method that will do the following:

getVehicle() will take a given id, and find the vehicle that has the
matching id.
It will iterate the local file line-by-line, check if
the id matches, and if there is a match return the vehicle object.

This is the header:
 @RequestMapping(value = "/getVehicle/{id}", method = RequestMethod.GET)
 public Vehicle getVehicle(@PathVariable("id") int id) throws IOException {

I do know how to do this using purely Java, but this RESTful stuff is throwing me for a loop.
My understanding:
For what I understand is that, when I make my GET request (I use Advance REST Client for this), the ID that I input for {id} will be matched to what is within my text file (called inventory.txt).
I have populated my text file with 6 entries using my POST method, all of which are information about various "vehicles". Therefore, if I make a GET request to url http://localhost808/getVehicle/2, I should get information about the "vehicle" with id 2.
My problem:
However, with what I currently have, my file is not being iterated, so the only "vehicle" that I get is id 0.
What I have so far:
    @RequestMapping(value = "/getVehicle/{id}", method = RequestMethod.GET)
    public Vehicle getVehicle(@PathVariable("id") int id) throws IOException
    {
        //ObjectMapper provides functionality for reading and writing JSON
        ObjectMapper mapper = new ObjectMapper();

        String inventory = FileUtils.readFileToString(new
            File("./inventory.txt"),
                CharEncoding.UTF_8);

        //Deserialize JSON to vehicle object
        Vehicle vehicle = mapper.readValue(inventory, Vehicle.class);

        if (vehicle.getId() == id) {
                return vehicle;
        }

        return null;
    }

My Request:
I am at a lost on how to iterate through my text file to find the id that is being requested.
Figuring out this one thing will drastically clear up my confusing and help me reach the completion of my project
ANY hints, tips, resources, anything that will put me on the path of figuring this out will be GREATLY appreciated. Again, this is very nice to me and I am trying to keep my sanity here.
If I need to clarify anything, please let me know!
I give thanks to anyone and everyone who takes the time to help me out here :D!
Comment: What I don't see is an iteration loop of any kind. I'm assuming `vehicle` return an object, you need to iterate through that using something like `for (v: vehicle) { if statement}`.
Comment: I tried that and I got an error that said: "foreach not applicable to type 'com.example.Vehicle'". I am assuming that I cannot use foreach with my object type??
Comment: Did you give it what type of variable `v` going to be? Sorry, I forgot to add this `for (Vehicle v: vehicle) { System.out.println(v); }`. See if this works.
Comment: Yes, I did that. "vehicle" is underlined, with the error I mentioned previously. Does my package path have something to do with this??
Answer: This question was solved using LineIterator!
My code is here:
@RequestMapping(value = "/getVehicle/{id}", method = RequestMethod.GET)
public Vehicle getVehicle(@PathVariable("id") int id) throws IOException {

    //ObjectMapper provides functionality for reading and writing JSON
    ObjectMapper mapper = new ObjectMapper();

    //Makes inventory.txt an iterable object
    LineIterator inventory = FileUtils.lineIterator(new File("./inventory.txt"),
            CharEncoding.UTF_8);

    //Container for when vehicle is found
    String vehicle = "";

    //iterates through inventory.txt until it reaches the end or finds the vehicle via id
    while(inventory.hasNext()) {
        //Stores each vehicle
        String tempVehicle = inventory.next();
        //Creates a vehicle object for JSON
        Vehicle v = mapper.readValue(tempVehicle, Vehicle.class);

        //checks if id of JSON vehicle object matches the id passed through
        if(v.getId() == id) {
            vehicle = tempVehicle;
        }
    }
    //Returns the found vehicle as a new Objectmapper (still a bit confused about this one)
    return new ObjectMapper().readValue(vehicle, Vehicle.class);
}

Answer: You can't iterate through the inventory because it's a string. You can iterate through vehicle since you're converting the inventory string to Vehicle objects.
Ok So there is a bug I just realised. Vehicle vehicle this is a single object. You need an array.
@RequestMapping(value = "/getVehicle/{id}", method = RequestMethod.GET,
                 produces = MediaType.APPLICATION_JSON_VALUE)
public Vehicle getVehicle(@PathVariable("id") int id) throws IOException {
    //ObjectMapper provides functionality for reading and writing JSON
    ObjectMapper mapper = new ObjectMapper();

    String inventory = FileUtils.readFileToString(new
        File("./inventory.txt"),
            CharEncoding.UTF_8);

    //Deserialize JSON to vehicle object
    List<Vehicle> vehicle = (Vehicle)mapper.readValue(inventory, Vehicle.class);
    // Or
    List<Object> vehicle = mapper.readValue(inventory, Vehicle.class);
    // Recommend the first option, its better to use types, things less likely to go wrong.

    for (Vehicle v: vehicle){
      if (vehicle.getId() == id) {
        return vehicle;
      }
    }

    return null;
}

Comment: I got it solved. A friend suggested using LineInterator instead of what I was doing with String inventory. This way was much better and understandable. Thank you very much for your help!!!
Comment: That was why you always get Object 0 no matter what ID you've passed. It mapped the first one and discarded the rest.
Comment: I tried this and now I get a new error for mapper.readValue(inventory, Vehicle.class). I strongly agree that I need an iterative loop and I know that it has to deal with "vehicle" but I am at a lost on the structure needed for it to iterate through it. I am thinking that I need to populate a List with my vehicle entries, but, again, how do I go about this?
Comment: Error: "  Incompatible types. Required List but 'readValue' was inferred to T: no instance(s) of type variable(s) exist so that Vehicle conforms to List inference variable T has incompatible bounds: equality constraints: Vehicle upper bounds: Object, List  "
Comment: Ok, so it's complaining that you're trying to map values with no type `Object` to a variable with type `Vehicle`. You can either create `List` or cast the `Object` to `Vehicle` type. I'll update the answer. Also, do you have a Git repo that I can take a look at? Its lot easier to fix something with hands-on.


Effect of an impaired finger on playing piano

Question: My right hand index finger has been injured severely. I cannot bend the middle joint of that finger, since the joint is dislocated and not in straight position tilted toward left a bit.
I am wondering how that could affect my ability to play piano.
The finger not being straight actually helps me to play a major triad with fingers 1, 2, and 3 comfortably; whereas this is uncomfortable if I play it with left hand fingers. Also, it is a bit stronger than my left hand index finger even though the middle joint is not bending. But I am not sure if it may naturally fail when a piece gets complicated.
Comment: It's definitely a handicap, but it needn't prevent you from playing well. IIRC, Franz Liszt once played an entire Beethoven piano concerto without using his injured index finger... and people didn't notice.
Comment: A number of people have continued careers as professional pianists after losing the use of complete arm, so don't let a finger injury stop you from finding out what you *can* do!
Comment: Have you healed completely from the injury under the care of a doctor?
Comment: It's gonna be unfortunately permanent. The joint is almost solid :(, maybe further surgery helps, but I cannot think of that right now.
Comment: If you haven't had a doctor look at it, that should definitely be your next step.
Comment: It had been under doctors' eyes for several days, a couple of years ago when the incident happened.
Comment: Did you play piano previous to the injury, or are you considering learning from scratch now? Give it a good try - with a teacher - and if it doesn't work (it probably will work), there are other instruments to play music on that don't necessarily involve using that finger.
Answer: Totally agree with Killian Foth and Alephzero.
These days, even if some techniques are the same as they have always been taught, there is a lot more room for adaptation.
In fact, once you become more advanced, you will start looking for the best fingering to use for a difficult piece. I had a great Aunt who was an excellent harpist and pianist. Her hands were so small that she had to adapt on the piano because she could barely get to an 8th. I can't remember what she said she did but I remember her piano playing and it was great.
Looking for a way to adapt will make you a stronger pianist.
I also suggest finding a teacher who is prepared to work with that impairment.
Answer: If you have control over the finger and can use it to play notes on the piano, you don't have a big problem.  The third finger of my right hand is bent, due to an un-treated childhood injury.  I can stretch an octave 1-3.  You should all have it done!   And there's a fine musical director active on the UK theatre scene whose fingers are all truncated at the first knuckle.  I don't know how the hell he does it, but he's an accomplished pianist.
Answer: First let me express my deep regret for hearing this.
But I am more pessimistic about your piano career. Even if your right middle finger can exert force, if you cannot control it delicately, or if you feel pain when playing, the music content will also be affected. And many pieces designed for "normal" hands will be difficult for you, and the standard repertoire you may play will be extremely restricted. Even if you managed, your playing will not be as natural as other hard-practicing pianists do.
However, have you considered switching your career to that of violin? Violin players mainly use left hand, and your right hand should have no difficulty in holding a bow. And a horn or a flute, I guess, may also require less stringent independency of fingers as pianists do. Since I cannot play any other instrument, this is just my guess.
Anyway, good luck with you. You may still try to find a way to play the piano with such injury, and I will be glad if I was wrong, really.
Comment: It's the right index finger, and only the middle joint of it. The thing is I neither feel pain nor lose control of the finger. As an amateur piano player, I don't see any difference right now. I am thinking if the piece gets complicated my mind would never adapt to the little difference between right and left index fingers.


Does the C++ standard require a binary machine?

Question: I find in the standard:

The representations of integral types shall define values by use of a pure binary numeration system

But my understanding is that this is not a requirement that C++ must be implemented on machines that are based on base 2 in hardware; in other words, this seems to be only a requirement for what the programmer shall see.
Does the C++ standard require a binary CPU, or could a valid C++ implementation be implemented on ternary or decimal machines?

tiny background info: in history, there have already been computers with decimals, ternaries, or computers where a C++byte would be 36 bits long (PDP-10)
Comment: That passage in the standard seems pretty clear to me.  It requires a machine capable of making binary representations of numbers.  In other words, a typical modern digital computer, or at least one that can emulate binary numbers.
Comment: It's hard to see how e.g. bitwise operators would work on a non-binary architecture, unless you have some kind of binary virtual machine in between, in which case the underlying architecture is moot.
Comment: `N3337 3.9.1 Fundamental types` `Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system. [ Example: this International Standard permits 2's complement, 1's complement and signed magnitude representations for integral types. —end example ]` I guess this might come under "as if" though.
Comment: Also `N3337 4.7 Integral conversions` `If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source
integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]`
Answer: Although never directly stated in the standard, there's an "as if" rule that applies to essentially all requirements in the C++ (and C) standard.
In other words, you're allowed to break any rule you want to, as long as you produce the same externally observable effects as if you'd followed the rule as stated. Although not stated in the standards themselves, this rule is explicitly stated in the Rationale for the C standard. As far as I know, there's no matching rationale for the C++ standard, but the two are closely enough related that I see little problem in applying the rule to both.
Comment: I believe there is a foot-note that mentions "as-if" under 1.9.1.
Comment: I don't know about earlier standards, but in C++11 § 1.9/1 this is stated directly: `The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.`


Suggestion for Math Movies

Question: I am interested in Math movies which inspire and motivate. I know about A Beautiful Mind, Good Will Hunting, and Pi. Are there any others someone can suggest?
Comment: [Link](http://www.math.harvard.edu/~knill/mathmovies).
Comment: Try 'Fermat's Room', although I haven't seen it
Comment: just curious, what exactly does 'beautiful mind' inspire and motivate? Battle against mental illnesses?
Comment: [Proof](http://www.imdb.com/title/tt0377107/), [La habitación de Fermat](http://www.imdb.com/title/tt1016301/) and [Flatland](http://www.imdb.com/title/tt0814106/?ref_=fn_al_tt_1).
Comment: Pi is a horrible horrible movie, mathematically speaking. The only good thing in it is the quotes by Saul. The one about Archimedes as well the one about "as soon as you discard scientific rigor you are no longer a mathematician, you're a numerologist."
Comment: Ramanujan??????
Comment: Does it? I'm not sure.
Comment: @Alex no i DIDNT MEANT THAT .yeah you are right
Comment: Does it have to be a film with a story? Are _Powers of Ten_ and _Donald in Mathemagic Land_ (for example) disqualified?
Comment: I can't believe no one's mentioned Story of 1, although it is fairly basic.
Comment: not a math movie, but "prisoner of benda" was the best use of math in pop culture ive ever seen
Comment: @DavidK no not neccesarily i have seen donald in mathland .it is good .i vl try other ones
Comment: @Lucian Thank you for that link. You should post it as a comment since it's more informative than most other answers.
Comment: @AsafKaragila haha yes i think the same . i mentioned it because it contains mathematics
Comment: @AsafKaragila i meant flavour
Comment: The Rites of Love & Math
Comment: Try http://movies.stackexchange.com/
Comment: [_Chaos: A Mathematical Adventure_](http://www.chaos-math.org/) (2010) and [_Dimensions_](http://www.dimensions-math.org/) (2008) by Jos Leys, Étienne Ghys, Aurélien Alvarez, et al. are excellent, [CC BY-NC-ND 3.0](https://creativecommons.org/licenses/by-nc-nd/3.0/deed.en)-licensed (i.e., free) movies about math.
Answer: "Stand and Deliver" is about a math teacher who teaches Advanced Placement Calculus to inner city children.
Twentyone,  en.wikipedia.org/wiki/21_(2008_film), is about a professor and students who use mathematics and planning to win money in Las Vega.
Comment: *Stand and Deliver* is brilliant !
Comment: Stand and Deliver is my favorite math movie. I watched it over and over again when I was little and had no idea what calculus was! My parents say that it's what sparked my love of math.
Comment: @nickalh thanks it was a great movie
Answer: Comment j'ai détesté les maths (How I came to hate maths), elected in France as the best 2014 documentary film. I really enjoyed it. You can see the trailer (with English subtitles) here.
A movie that I haven't seen yet: The Imitation Game, about Alan Turing's life.
See also the Wikipedia page on Films about mathematicians.
Comment: Imitation Game was good but not very accurate.
Answer: I saw 'Donald Duck in Mathemagic Land' many years ago, and I still remember it very fondly.  I recommend it highly!
And it is suitable for all ages!
Comment: A wonderful movie that I saw some 45 years ago and had forgotten! Thanks!
Comment: @Andrew L. That's about when I saw it too!  Definitely a classic!  :-)
Answer: Take a look at Hard Problems. It follows the extremely gifted students who represented the United States in 2006 at the world's toughest math competition—the International Mathematical Olympiad (IMO).
You can probably find the entire movie on Youtube.
Comment: [Beautiful Young Minds](http://en.wikipedia.org/wiki/Beautiful_Young_Minds) was a UK equivalent, also looking at 2006
Answer: Try Numb3rs. http://en.wikipedia.org/wiki/Numbers_%28TV_series%29
Numb3rs (stylized NUMB3RS) is an American crime drama television series that ran on CBS from January 23, 2005, to March 12, 2010. The series was created by Nicolas Falacci and Cheryl Heuton, and follows FBI Special Agent Don Eppes (Rob Morrow) and his brother Charlie Eppes (David Krumholtz) who helps Don solve crimes for the FBI.
Comment: This is mostly pseudomaths.
Comment: @Alizter [citation-needed] since Wikipedia asserts, with citations, that the math in the show is real and at least somewhat relevant to the topic of the episode. (Admittedly it does _seem_ fake sometimes... though to be fair I could say the same about some real math!)
Comment: The episodes are always based on some actual applied-math technique, and always feature an essentially correct heuristic description of the technique, but in most cases the techniques wouldn't actually work so well in practice.  They had real mathematicians consulting on the show, and moreover whenever you see a closeup of someone's hand writing math on a board they used a real mathematician for that instead of the actor's actual hand.
Answer: Try Flatland: The movie. Its about a square who discovers that there are more than 2 dimensions.
Answer: It may not be your traditional math movie,  but the original (NOT THE REMAKE!) of Cheaper by the Dozen is a well done adaptation of the book about an efficiency expert,   and that entire process is highly mathematical/pattern recognition/problem solving.  It inspired me as a child to think in such fashions.
Answer: "The Professor and his Beloved Equation" is a Japanese movie by Takashi Koizumi about the life of a number theorist and the joy of being a mathematician.
Also "An Invisible Sign" could be interesting for you. It is about a math teacher and the role of numbers in her life.
Comment: yes thnaks i will see
Comment: @godonichia Are you searching for documentary movies too?
Comment: sadegh documentaries i have mostly seen but yes if something new is there
Answer: Alex Kasman's Mathematical Fiction website includes an extensive list of movies.
Answer: Try MESH by Beau Janzen and Konrad Polthier.
Answer: Traveling salesman was a pleasant surprise for me.
It's about group of mathematicians who prove P=NP.
Answer: First thing that comes to mind when I hear the question is October Sky.  It's the (slightly dramatized) true story of Homer Hickam and his friends "the Rocket Boys."  They lived in a podunk coal-mining town in West Virginia when Sputnik went up, and when Homer (a high school student at the time) saw the satellite moving across the sky, he was inspired to learn about rocketry.  He and his friends started building little DIY rockets out of steel pipes, at first with almost disastrous results (no one got hurt by their early homemade pipe bombs, but someone could have!) and later with greater and greater success as they learned and refined their techniques.  Homer eventually became a bona fide rocket scientist for NASA.
I'd recommend the movie, and the book it was based on even more so, the actual memoirs of Homer Hickam.  The movie did a good job of staying true to the source material, but it made one really ugly change: stripping away all of the father's redeeming qualities to turn him into a source of dramatic conflict.  A lot of the engineering help that the movie attributes to the teacher and the nerdy friend actually came from Homer's father, who, being a mining foreman, had to know a few things about engineering and physics in order to run the mine and keep his workers safe!
But anyway, it's a true story and it's the sort of story that can inspire kids to learn about math and engineering, exactly the sort of thing you're looking for.
Answer: Moneyball (2011) - Based on the true story of how the Oakland A's manager, Billy Bean, used a statistical approach to finding undervalued players, ultimately allowing him to create a competitive team with a fraction of the budget of teams like the Yankees.
Answer: It must be said, Stand and Deliver is a great mathematics movie - truly inspirational.
I'm not sure about this, but perhaps the film based on Alan Turing, famous cryptographer - The Imitation Game?
An Invisible Sign is also a fairly interesting film.
I suggest looking at Wikipedia's list of movies on mathematicians.
Comment: yes i liked stand and deliver
Answer: Watch the movie $21$ with Kevin Spacey.. here
(If you play poker you will like it very much)
Comment: Kevin's busy at the moment, do you know anyone else who would like to go watch it with me?
Comment: @Nick  Try Anjelina Jolie....
Answer: Although not a movie regarding mathematics, I think Limitless by Bradley Cooper and Robert De Niro could be a good motivator movie. The movie is quite fascinating and entertaining. Just don't get lost in some of the fantasies they throw your way.
Answer: Fermat's Rooms is a good one .They talk about Goldbach Conjecture in beginning ..Four mathematicians who do not know each other are invited by a mysterious host on the pretext of resolving a great enigma. The room in which they find themselves turns out to be a shrinking room that will crush them if they do not discover in time what connects them all and why someone might wish to murder them.
http://www.imdb.com/title/tt1016301/
Answer: I would like to suggest "The Number $23$" starring Jim Carrey. It's not at all about math. It's about the 23 enigma which is only as relevant to mathematics as superstitions surrounding $7, 11$ or $13$. But it's the first time Jim has done a non-comedic role and it's worth a watch.

But to defend myself: $23$ is a number and numbers are dealt under math.
See the Wikipedia page for $23$.
Some of my favorite facts are:

23! is 23 digits long

Twenty-three is the sum of three other, consecutive, prime numbers; 5, 7 and 11. It is the first prime number showing this characteristic.

23 also has the distinction of being one of two integers that cannot be expressed as the sum of fewer than 9 cubes of integers (the other is 239). See Waring's problem.

23 is the concatenation of the base 10 representations of the first two primes (2 and 3) and is itself also prime. It is hence the second Smarandache–Wellin prime in base 10.

The Answer to Life, the Universe and Everything $- 23 =$ The Final Year of Being a Teenager
Comment: Was *The Truman Show* before your time? Because that's the first time I saw Jim Carrey playing a serious role and not doing his usual typecast-as-an-idiotic-goofball routine.
Comment: Awesome film. I completely forgot about this one.
Comment: @MasonWheeler: Ofcourse there's that and then even *The Majestic* and although I haven't seen it, I hear he's quite different in *Eternal Sunshine Of The Spotless Mind* :D I find *The Number 23* to be the most grim. But ofcourse, the Jim we all know and love will never stop playing deranged characters :D

Suggestion for Math Movies