Show $\mathbb E[e^{4W_t-8t}(W_t-4t)^4]=3t^2$ without Girsanov

Question: I would like to know  if it is possible to prove the identity $\mathbb E[e^{4W_t-8t}(W_t-4t)^4]=3t^2$ without the use of a measure change and Girsanov Theorem? I only know the solution by using the exponential martingale for the first term and then simplify terms under the new measure.
Comment: If $W_t$ is meant to be a Gaussian random variate with mean $0$ and variance $\sigma^2 = t$ then the naive integral indeed comes out to $3\sigma^4 = 3t^2$.  But in doing that integral, I find I have to do a change of variables, which if you wish to be rigorous, is much like a measure change.
Answer: Since $W_t$ is a normal random variable with mean $0$ and variance $t$, we have
$$ \mathbb{E}[e^{4W_t-8t}(W_t-4t)^4]=\frac{1}{\sqrt{2\pi t}}\int_{-\infty}^{\infty}(x-4t)^4e^{4x-8t-\frac{x^2}{2t}}\;dx$$
$$ =\frac{1}{\sqrt{2\pi t}}\int_{-\infty}^{\infty}(x-4t)^4e^{-\frac{1}{2t}(x-4t)^2}\;dx=\frac{1}{\sqrt{2\pi t}}\int_{-\infty}^{\infty}u^4e^{-\frac{u^2}{2t}}\;du$$
$$=\frac{t^2}{\sqrt{2\pi}}\int_{-\infty}^{\infty}y^4e^{-\frac{y^2}{2}}\;dy=3t^2$$
using the fact that the fourth moment of a standard normal random variable is $3$.
Answer: For arbitrary real $a$,
$$\int_{-\infty}^{\infty} \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{x^2}{2\sigma^2}}e^{4x-2a\sigma^2}(x-a\sigma^2)^4 \, dx = e^{(8-2a)\sigma^2}\sigma^4 \left( (a-4)^4\sigma^4 + 6(a-4)^2 \sigma^2 + 3\right)
$$
The relation you want to prove is the special case of $a=4$.


Como desabilitar a sugestão de senhas salvas no browser via HTML

Question: Tenho aqui a seguinte situação:
Criei um formulário em HTML para alterar a senha do usuário caso ele se esqueça dela.

O problema é que ao tentar digitar a senha o browser expõe as opções de senhas já salvas, no entanto como essa não se trata de uma tela de login não é interessante que isso seja exibido para o usuário.

O código HTML que estou usando é o seguinte:
<form id="form" action="@Url.Action("ResetPassword", "Login")" method="post">

@ViewBag.UserId - @ViewBag.Identifier

            <input class="password-mask"
                   type="password"
                   autocomplete="off"
                   id="NewPassword"
                   maxlength="16"
                   name="NewPassword"
                   required
                   onchange="VerifyInput('NewPassword', 'newPassword-text'); this.setCustomValidity('');"
                   oninvalid="this.setCustomValidity('Por favor, preencha este campo.')"
                   onkeyup="CalculeStrength('NewPassword', 'strengt-bar', 'strengt-label')"
                   title=" " />
            Nova senha

            Força da senha.

            <input class="password-mask"
                   type="password"
                   autocomplete="off"
                   id="ConfirmPassword"
                   maxlength="16"
                   name="ConfirmPassword"
                   required
                   onchange="VerifyInput('ConfirmPassword', 'confirmPassword-text'); this.setCustomValidity('');"
                   oninvalid="this.setCustomValidity('Por favor, preencha este campo.')"
                   title=" " />
            Confirmar senha

            <input id="submit" name="submit" role="button" type="submit" class="btn btn-irenic float-right" tabindex="0" value="SALVAR" onclick="ClickWait('form');" />

    </form>

Como posso fazer para que essa lista de senhas salvas não seja exibida?
Por que o browser interpreta essa como sendo uma tela de login?
Comment: Isso certamente não resolveria, pois ai eu estaria jogando essa responsabilidade para o usuário. A raiz do problema é que o browser está entendendo este form como se fosse um form de Login, mas não é.
Comment: O que ele está fazendo é perguntado se quer utilizar senhas salvas para os CPFs e CNPJs que foram armazenados no navegador, que em algum momento foram utilizados para fazer login.
Comment: Qual navegador aparece isso?
Comment: O navegador é o firefox.
Comment: Se puder, teste isso, e me comente o resultado: https://pt.stackoverflow.com/a/10879/70
Answer: Isto é um recurso nativo do navegador e não há como desabilitar via código.
Veja o que diz a documentação do MDN:

O atributo autocomplete e campos de login
Navegadores modernos implementam gerenciamento de senhas integrado:
  quando o usuário preenche um usuário e senha para um site, o navegador
  se oferece para lembrar dos dados para o usuário. Quando o usuário
  visita o site novamente, o navegador preenche os campos de login
  automaticamente conforme os valores salvos por ele..
Os navegadores também permitem ao usuário selecionar uma senha mestra
  para que os dados salvos sejam criptografados.
Mesmo sem uma senha mestra, o gerenciamento de senhas dentro do
  navegador é geralmente vista como um ganho de segurança. Como os
  usuários não precisam se lembrar das senhas que o navegador salva para
  eles, eles podem escolher senhas mais fortes do que geralmente
  escolheriam.
Por esta razão, muitos navegadores modernos não suportam
  autocomplete="off" para campos de login.

se um site utiliza autocomplete="off" para um form, e o formulário inclui campos de usuário e senha, então o navegador ainda
  assim se oferece para salvar os dados de login, e se o usuário
  aceitar, o navegador vai preencher estes dados automaticamente na
  próxima vez que o usuário visita a página.
se um site utiliza autocomplete="off" para campos input de usuário e senha, então o navegador ainda assim se oferece para salvar
  os dados de login, e se o usuário aceitar, o navegador vai preencher
  estes dados automaticamente na próxima vez que o usuário visitar a
  página.

Este comportamento existe no Firefox (desde a versão 38), Google
  Chrome (desde a versão 34), e Internet Explorer (desde a versão 11).

Concluindo, uma das formas é apagar as senhas memorizadas no Firefox (por exemplo) é clicando com o botão direito do mouse sobre a página e escolher no menu "Ver informações da página":

Na aba "Segurança", clicar em "Ver senhas salvas":

Em seguida clica em "Remover tudo":
Comment: No Chrome digite `chrome://settings/` no navegador, clique em avançado, e veja quadro `Senhas e formulários` https://i.stack.imgur.com/pgMN4.png
Comment: Muito bom, levando em consideração essa informação vou verificar se existe algum meio de contornar essa situação via código. Caso eu consiga volto aqui.


How do the following videos work

Question: This video is a version of Rick Astley's Never gonna give you up,

except all notes are C.

What does one change in the original compositions to make all notes in a song to be of the same pitch? Do they take relative notes, because I've only heard of relative keys, Eg: A minor being relative to C major.
And if all the notes are the same, wouldn't the song pretty much be a continuous and monotonous pitch? How do such microtonal variations (as seen in the video) arise?
Comment: I downvoted because I can't see how this question is useful here. But I have answered it anyway because the answers are pretty clear.
Comment: @noorav instrument it is played on (timbre), duration, volume, attack, decay, vibrato, sustain, other effects like distortion, reverb, etc.
Comment: *Rick*, not "Nick"
Comment: I don't understand what you mean. To make all the notes in a composition be C, you just take every single note, keep all the properties of the note except the pitch and write it as a C. But in the video it is just shifted with some kind of software...
Comment: What other properties does a note have apart from its pitch?
Comment: The list of note properties that I've seen most often is fourfold: pitch, loudness, timbre, and duration/timing.
Answer: I think it's important to note that not ALL of the notes are C. They have stabilized the bass and vocals on one pitch. The accompanying instruments are shifted as well, but not to C - they keep their relative position to the original notes.
You can hear the synths and strings hitting a variety of notes other than C.
Comment: Maybe I couldn't bear to listen to enough of it to hear this, but it sounded to me like it was all at C. But it would make sense if they just shifted the everything so all the vocal melody notes were C and then the other chords are changed relative to that.
Comment: It's especially noticeable if you listen to the strings on the chorus.
Answer: They just used pitch shifting software to literally make every pitch a C.
In terms of "wouldn't the song pretty much be a continuous and monotonous pitch?", I'm not sure what you're hearing, but it is a continuous and monotonous pitch.

How do such microtonal variations (as seen [sic] in the video) arise?

The pitch shifting software requires a short moment of music to detect the original pitch before it can shift it. So you're hearing maybe 1/10 of a second of the original pitch before it is quickly shifted to C. If you listen to his singing, you can hear how the pitch detection is much faster and all his vocal notes are just C.
Comment: Are you thinking they used something like melodyne?
Comment: @topomorto Probably.
Comment: It may be worth explaining how melodyne could be used to do this kind of thing - it's "not your father's" pitch shifter!

How do the following videos work


Adding a second SSL for a second domain on a server - second domain is still using the first SSL Cert

Question: I need to add an ssl cert to a second domain on my server (AWS Amazon Linux)
I thought I enabled SNI correctly?  although probably not...
domain1 already has a functioning SSL cert.
First attempt I was getting stuck in a redirect loop.
Second (current) attempt it now gives me a 403/Forbidden on the /users/login/ directory.
httpd -v
Server version: Apache/2.2.29 (Unix)

base httpd.conf:
    ...
    LoadModule ssl_module modules/mod_ssl.so
Listen 80
NameVirtualHost *:80
Listen 443
NameVirtualHost *:443
...

domain1.conf:
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl

SSLPassPhraseDialog  builtin

SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

SSLMutex default

SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin

SSLCryptoDevice builtin

<VirtualHost *:443>

   ServerAdmin firstname.lastname@example.com
   ServerName domain1.com

   SSLEngine On
   SSLProtocol all -SSLv2

   SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

   SSLCertificateFile /var/www/domain1.com/apache_includes/secure/domain1.com.crt
   SSLCertificateKeyFile /var/www/domain1.com/apache_includes/secure/domain1.com.key
   SSLCertificateChainFile /var/www/domain1.com/apache_includes/secure/gd_bundle.crt

   ProxyPreserveHost On

   RequestHeader set X-Forwarded-Protocol https
   ProxyPass / http://127.0.0.1/

   SetEnvIf User-Agent ".*MSIE.*" \
    nokeepalive ssl-unclean-shutdown \
    downgrade-1.0 force-response-1.0

</VirtualHost>

domain2.conf:
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl

SSLPassPhraseDialog  builtin

SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

SSLMutex default

SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin

SSLCryptoDevice builtin

<VirtualHost *:443>

   ServerAdmin email@example.com

   ServerName domain2.com
   ServerAlias www.domain2.com #prob don't need this....

   SSLEngine On
   SSLStrictSNIVHostCheck on
   SSLProtocol all -SSLv2

   SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

   SSLCertificateFile /var/www/domain2.com/apache_includes/secure/domain2.crt
   SSLCertificateKeyFile /var/www/domain2.com/apache_includes/secure/domain2.key
   SSLCertificateChainFile /var/www/domain2.com/apache_includes/secure/bundle.crt

   ProxyPreserveHost On

   RequestHeader set X-Forwarded-Protocol https
   ProxyPass / http://127.0.0.1/

   SetEnvIf User-Agent ".*MSIE.*" \
    nokeepalive ssl-unclean-shutdown \
    downgrade-1.0 force-response-1.0

</VirtualHost>

Answer: In Apache 2.2 The NameVirtualHost directive must match the <VirtualHost> blocks (so use <VirtualHost *:443> for both blocks)
The ServerName and ServerAlias directives inside the <VirtualHost> block are used to select which block to serve based on the incoming request.
Comment: I did change the line   to , but had no change in result.


How to check view is visible in scrollView centre and perform action

Question: For example, I have created a scrollView contained LazyVStack for displaying the label.Example UI
How can I check if the cell is visible in ScrollView centre and perform some action to the cell.
Text (Name 9) in scrollView centre
For example, user is scrolling, when Name 9 label is visible to scrollView centre, the label font size change to 30.
Code Update:
Update code
Answer: In scroll view SwiftUI. You could check if the center by triggering .onAppear of the item inside scroll view(It seems a cheat but it's true).
ScrollView(.vertical, showsIndicators: false) {
            LazyVStack {
                ForEach(listContents) { item in
                     SomeView(item)
                    .onAppear {
                        if (item.index == kCenterPosition) {
                           // DoSomething With Center Scroll List Apear
                        }
                    }
                }
            }
        }

You also auto trigger to center scroll view by the way:
ScrollViewReader { proxy in
  List { ...
  }
  .onApear {
    proxy.scrollTo(listContents[someValue], anchor: .center)
  }
}

Comment: Thank for answering, kCenterPosition is represent for ?
Comment: it's a valuable example of the position you want to move, It could be the center of an array index item
Answer: if you want to know if the given element is visible or in the center of the scrollview you will need to wrap each element inside a scroll with a GeometryReader of its own. I've taken your code snipped and given the functionality you are asking for, also added comments in the code itself for clearance
    @State var model = [
        "name 1", "name 2", "name 3", "name 4",
        "name 5", "name 6", "name 7", "name 8",
        "name 9", "name 10", "name 11", "name 12",
        "name 13", "name 14", "name 15", "name 16",
        "name 17", "name 18", "name 19", "name 20",
        "name 21", "name 22", "name 23", "name 24"
    ]

    @State var middleName: String = ""

    var body: some View {
        GeometryReader { proxy in
            ScrollView {
                LazyVStack {
                    ForEach (self.model, id: \.self) { name in
                        // wrap inner view in geometry reader so you can get its coordinates relative to the scrollView
                        GeometryReader { inner in
                            Text(name)
                                .font(.system(size: name == middleName ? 30 : 18))
                                .frame(maxWidth: .infinity, maxHeight: .infinity)
                                .onChange(of: inner.frame(in: .global).midY) { y in // you can use midY, minY or maxY depending on your case
                                    let threshold: CGFloat = 20 // adjust this to the precision of "middle" to your liking
                                    let screenMid = proxy.size.height / 2 // you can get the middle point of any view if you have outter geometry reader like in this snippet
                                    if y > screenMid - threshold && y < screenMid + threshold {
                                        // do something, you can update @State properties
                                        // to reflect changes when this view gets in the middle
                                        print("is in middle: \(name)")
                                        middleName = name
                                    }
                                }
                        }
                        .frame(height: 100)
                    }
                }
            }
        }
    }

if you just want to know about which elements are visible you would just need to update the math in .onChange(of:) method and have @State properties fitting your own case. For experimenting and figuring out the exact values it is possible to have Text variables printing those GeometryProxy content.
Answer: GeometryReader { geometry in
ScrollView {
   // ur 9th cell
.font(.system(size: self.isInMiddleOfScreen(geometry) ? 30 : 10))
  }
}

private func isInMiddleOfScreen(_ geometry: GeometryProxy) -> Bool {
if geometry.frame(in: .global).maxY <= UIScreen.main.bounds.height {
return true
}
return false
}

Comment: Thank for you reply, I have tried the code but all cell font size updated to 30. I have updated my code, what did i do wrong?


Como chamar o método de uma classe dentro de outra(bluej)

Question: Eis aqui o que tenho feito
public void valorConta(){
    int i=0;
    float totalConta=0;
    for(i=0;i<listaligacoes.length;i++){
    totalConta+=(listaligacoes[i].calcularDuracao()*listaligacoes[i].getvalor());
}
}

Tenho uma variavel listaligacao do Tipo Ligacao(classe) gostaria de nela, chamar os metodos calcular duracao e valor, para setar o valor da conta nesta classe atual.
Uso o bluej.
Comment: Só pra deixar mais claro, eu sou iniciante, tem muito termo que não entendo ainda.
Answer: Use static...
public static void valorConta(){
    int i=0;
    float totalConta=0;
    for(i=0;i<listaligacoes.length;i++){
       totalConta+=(listaligacoes[i].calcularDuracao()*listaligacoes[i].getvalor());
    }
}

Pra chamar em outra classe é simples
NomeDaClasseQueTemOMetodo.valorConta();
Lembrando que dessa forma listaligacoes precisa ser uma variavel static, ou você pode receber ela como Parametro, e da forma ali de cima você nao retorna nada... Se quiser retornar totalConta troca void por int
Comment: O problema é que se esse vetor `listaligacoes` não for estático isso não irá funcionar. Seria melhor você citar isso. Pois se esse vetor pertencer ao objeto, ou precisar pertencer ao objeto... essa solução não funcionará.
Comment: Essa função `valorConta` poderia receber essa lista no parâmetro.
Comment: Eu pensei nesse problema tbm.,.. Mas acho que foge um pouco da Pergunta do cara, mas... Vou colocar ali na resposta então
Comment: Sim.. foge um pouco mesmo. Faltou ela detalhar melhor a pergunta.


Formula for the Boundary of an intersection

Question: I'm wondering if there's a formula for $\partial(A\cap B)$. This isn't homework, just wondering.
Comment: Problems arise because in general $\overline{A\cap B}\ne \overline A\cap \overline B$
Comment: This question is likely to be closed for lack of context.  Can you describe the sort of problems that started you wondering about this?
Answer: For what it is worth.
$\partial A \cup \partial B = \partial (A\cup B) \cup \partial
(A\cap B) \cup (\partial A \cap \partial B)$
Answer: There is one indeed, but it's a bit clunky unless $\partial{A} \cap \partial{B}=\varnothing$ and $A$ and $B$ are closed. The case for abritrary open sets in an arbitrary space appears here.
A similar identity holds for the boundary of a Cartesian product, whose striking similarity to a product rule is discussed here.


What are "#" properties?

Question: While reading the Ajax framework documentation I came across mention of the #ajax property. I know from poking through the code that there are others of these properties with hash signs in front of them. What does the hash sign signify? What are these properties all about?
Comment: Hopefully it's ok for me to want to add "pound sign" somewhere here on this page (since that's a search term I was using to try figure this out, when "hash" wasn't getting me too helpful results).
Answer: This is to do with render arrays in general, it's not just specific to AJAX or the form API (although the form API uses render arrays exclusively for building up it's content).
Put simply, array keys in a render array without a # in front of the name are seen as children of the render array, and are subsequently rendered themselves (recursively).
Those with a # in front of them are seen as meta data/variables for the render array to use as necessary, and are not themselves rendered.
The render array docs (linked to above) actually put this nice and succinctly:

A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type).

The # keys are the 'hints' that the above paragraph is talking about, the non-# keys are the nested data.
I'd thoroughly recommend giving that page a read, it does a good job of de-mystifying the whole render array thing, and provides code examples.
There's also another small explanation/code example on the Theming the page docs which might be useful.
Render arrays are used all over the place in Drupal (forms, themes, general markup, etc.) so knowing a good bit about them will help a lot with future Drupal development.
Comment: Well put beat me to it.
Answer: The form API uses a # in front of all the properties, to make a distinction between properties, and child elements. In the following code, $form['choice_wrapper']['choice'] is a child element, while $form['choice_wrapper']['#tree'] is a property.
  // Add a wrapper for the choices and more button.
  $form['choice_wrapper'] = array(
    '#tree' => FALSE,
    '#weight' => -4,
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // Container for just the poll choices.
  $form['choice_wrapper']['choice'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#theme' => 'poll_choices',
  );

All those properties are listed in the Form API reference. There are many properties, but they are all about rendering, validation, and submission.
The reason to use a prefix for properties is to able to quick filter out the properties from the child elements, which is useful when they need to be rendered, for example with drupal_render(), which contains the following code.
  // Get the children of the element, sorted by weight.
  $children = element_children($elements, TRUE);

  // Initialize this element's #children, unless a #pre_render callback already
  // preset #children.
  if (!isset($elements['#children'])) {
    $elements['#children'] = '';
  }
  // Call the element's #theme function if it is set. Then any children of the
  // element have to be rendered there.
  if (isset($elements['#theme'])) {
    $elements['#children'] = theme($elements['#theme'], $elements);
  }
  // If #theme was not set and the element has children, render them now.
  // This is the same process as drupal_render_children() but is inlined
  // for speed.
  if ($elements['#children'] == '') {
    foreach ($children as $key) {
      $elements['#children'] .= drupal_render($elements[$key]);
    }
  }

If you look at element_children(), you will notice the code to filter out properties is the following one.
  // Filter out properties from the element, leaving only children.
  $children = array();
  $sortable = FALSE;
  foreach ($elements as $key => $value) {
    if ($key === '' || $key[0] !== '#') {
      $children[$key] = $value;
      if (is_array($value) && isset($value['#weight'])) {
        $sortable = TRUE;
      }
    }
  }

What are "#" properties?


Passing a pointer to a multidimensional enum array

Question: I am still trying to get my head around using pointers to arrays and while making a simple game I have encountered the following issue:
in a header file, I have an enum defined as:
typedef enum {UNDEF, YELLOW, RED} State;
then, in my main function, I have two multidimensional arrays as:
State particle_exists[WIDTH][LENGTH];
State temp_particle_exists[WIDTH][LENGTH];

I am trying to pass a pointer to these arrays, like so:
clear_grid(&particle_exists[WIDTH][LENGTH]);

with clear_grid() defined as:
void clear_grid(State *particle_exists[WIDTH][LENGTH])
{
 // code that clears this array (sets it all to UNDEF basically )
{

this however, gives me the error:
main.c:57:16: warning: passing argument 1 of 'clear_grid' from incompatible pointer type [-Wincompatible-pointer-types]
     clear_grid(&particle_exists[WIDTH][LENGTH]);
                ^
In file included from main.c:18:0:
printer.h:24:6: note: expected 'State * (*)[6] {aka enum <anonymous> * (*)[6]}' but argument is of type 'State * {aka enum <anonymous> *}'
 void clear_grid(State *particle_exists[WIDTH][LENGTH]);
      ^~~~~~~~~~

I have tried looking for answers but none that I could find worked in my case. So is what I'm doing logical, and if yes, how can I fix this issue?
Comment: `clear_grid(&particle_exists[WIDTH][LENGTH]);`  -> `clear_grid(&particle_exists);`. But I imagine that you don't really want to pass a pointer
Comment: @EugeneSh. I tried that as well, that gave me the following error: `main.c:57:16: warning: passing argument 1 of 'clear_grid' from incompatible pointer type [-Wincompatible-pointer-types]
     clear_grid(&particle_exists);
                ^
In file included from main.c:18:0:
printer.h:24:6: note: expected 'State * (*)[6] {aka enum  * (*)[6]}' but argument is of type 'State (*)[7][6] {aka enum  (*)[7][6]}'
 void clear_grid(State *particle_exists[WIDTH][LENGTH]);`
Answer: The name of the array is particle_exists. It is not particle_exists[WIDTH][LENGTH].
So when you want to refer to the array in an expression, you use its name, particle_exists, not particle_exists[WIDTH][LENGTH].
The declaration State particle_exists[WIDTH][LENGTH]; declares an object named particle_exists and says it has WIDTH rows, each of which has LENGTH elements, each of which has type State. The declaration describes the array named particle_exists.
In an expression, particle_exists refers to the array, and particle_exists[i][j] refers to element j of row i. So particle_exists[WIDTH][LENGTH] attempts to refer to element LENGTH of row WIDTH. However, there is no such element, because the elements are indexed from 0 to LENGTH−1, inclusive, and the rows are indexed from 0 to WIDTH−1 inclusive. WIDTH and LENGTH are outside those bounds.
The code clear_grid(&particle_exists[WIDTH][LENGTH]) attempts to pass the address of an element that does not exist. If it did exist, the element would have type State, so its address would have type State *.
The code clear_grid(&particle_exists) would pass the address of the array, and there is a way to make that work. However, it is more common in C to use ``clear_grid(particle_exists). When an array is used in this way, it will be automatically converted to a pointer to its first element. Its first element is a row of LENGTHelements. So the type of a pointer to the first row will beState (*)[LENGTH]`.
void clear_grid(State *particle_exists[WIDTH][LENGTH]) declares clear_grid to have a parameter that is an array of WIDTH rows of LENGTH elements in which each element is a pointer to State. That is not what you want with anything discussed above. [WIDTH] and [LENGTH] grammatically bind to particle_exists before *, so you would be declaring the parameter to be a (two-dimensional) array whose elements are pointers. To declare a pointer to a two-dimensional array, you would use void clear_grid(State (*particle_exists)[WIDTH][LENGTH]). That would work if you passed &particle_exists.
However, as mentioned above, it is more common to pass a pointer to the first row. With this, use void clear_grid(State particle_exists[WIDTH][LENGTH]). This nominally declares the parameter to be a two-dimensional array. However, parameters declared as arrays are automatically adjusted to be pointers, so this declaration is the same as void clear_grid(State (*particle_exists)[LENGTH]). You can also use that.
Then clear_grid(particle_exists) will pass a pointer to the first row, which is an array of LENGTH elements of type State, and clear_grid will accept a parameter that is a pointer to an array of LENGTH elements of type State.
Inside clear_grid, you can use the parameter with subscripts in the same way you would use a two-dimensional array. particle_exists[i][j] will refer to element j of row i.
Comment: thank you, I was stuck on this all evening. `void clear_grid(State (*particle_exists)[WIDTH][LENGTH])` did solve my issue. And I guess I'm using an older book or something because it keeps hammering on that passing a pointer to an array is faster than passing the array itself, I did not know about the automatic pointer conversion you describe.


Solving a recurrence equation with multiple recursive steps

Question: I'm looking at some algorithms, and I'm trying to ascertain how multiple recursive steps are treated when forming the equation.
So exhibit A:

It is obvious to me that the recurrence equation here is: T(n) = c + 2T(n/2) which which in big O notation simplifies to O(n)
However here, we have something similar going on as well and I get the recurrence equation T(n) = n + 2T(n/2) since we have two recursive calls not unlike the first one, which in big O notation simplifies to O(n), however that is not the case here. Any input as to how to get the correct recurrence equation in this second one over here?
Any input as to how to go about solving this would be brilliant.
Comment: It's late and I'm probably reading it wrong, but did you accidentally post the same code snippet twice?
Comment: Both of the functions you have posted are the same, was that your intention?
Comment: No but you guys are right! I'm sorry about that I just fixed it. Didn't notice that myself.
Answer: You might be interested in the Master Theorem:
http://en.wikipedia.org/wiki/Master_theorem
The recurrence equation T(n) = n + 2T(n/2) is Theta(n log n), which can be derived using the theorem. To do it manually, you can also assume n = 2^k and do:
T(n) = 2T(n/2) + n
     = 2(2T(n/4) + n/2) + n
     = (2^2)T(n/(2^2)) + 2n
     = (2^2)(2T(n/(2^3)) + n/(2^2)) + 2n
     = (2^3)T(n/(2^3)) + 3n
     = ...
     = (2^k)T(n/(2^k)) + kn
     = nT(1) + n log2 n
     = Theta(n log n)

Comment: Stuart do you mind taking a look at the question again? I've updated it with the fixed image link


Erro: There are no primary or candidate keys in the referenced table

Question: Estou tentando criar uma nova tabela em um DB existente, porém, aparece a seguinte mensagem:

There are no primary or candidate keys in the referenced table
  'parceria_conta_corrente_ao' that match the referencing column list in
  the foreign key 'R_795'.

Esta tabela já existe no banco e possui dados:

Estou tentando criar a seguinte tabela:
CREATE TABLE parceria_item_resgate_rateio_aux
(
    id_parceria_item_resgate_rateio_aux int  NOT NULL IDENTITY,
    dt_conta_corrente    DATETIME  NOT NULL ,
    id_periodo           BIGINT  NOT NULL ,
    id_ao                bigint  NOT NULL ,
    id_gr_cliente        int  NOT NULL ,
    id_cliente           BIGINT  NOT NULL ,
    data_importacao_cli_gr_cli DATETIME  NOT NULL ,
    hp2                  varchar(50)  NOT NULL ,
    hp2_filho            varchar(50)  NOT NULL ,
    valor_nc             decimal(18,2)  NULL ,
    datetime_inclusion   datetime  NOT NULL ,
    status               int  NULL ,
    CONSTRAINT XPKparceria_item_resgate_ PRIMARY KEY  CLUSTERED
        (id_parceria_item_resgate_rateio_aux ASC,
        dt_conta_corrente ASC,
        id_periodo ASC,
        id_ao ASC,
        id_gr_cliente ASC,
        id_cliente ASC,
        data_importacao_cli_gr_cli ASC,
        hp2 ASC),
    CONSTRAINT R_795 FOREIGN KEY(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
        REFERENCES parceria_conta_corrente_ao(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)
go

Onde está o erro?
Answer: Esta relação de colunas da tabela parceria_conta_corrente_ao
dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2

Não é uma chave primária de parceria_conta_corrente_ao.
Aliás, o que você está fazendo pode ser considerado como uma má prática, pois você está tentando amarrar uma série de colunas sem um bom motivo pra isso.
Procure usar apenas uma coluna para definir uma chave primária (e, consequentemente, uma chave estrangeira), pois a causa do problema, num sentido mais amplo, é uma falha de design do seu banco de dados.
Comment: Obrigado pela dica :)


Orthogonal Set of Vectors

Question: I am trying to find values for a and b for the following set of vectors:
$$\left(\left[\begin{matrix} 1\\2\\3\end{matrix}\right],\left[\begin{matrix} 4\\1\\-2\end{matrix}\right], \left[\begin{matrix} a\\b\\3\end{matrix}\right]\right) = 0$$
I know the idea is that, if I take the dot product of all the column vectors in the above vector space, I should end up with zero. But I am not sure how to get started solving for a and b, such that the below set of vectors is orthogonal. A hint as to how to get started?
Comment: The dot product is an operation that is applied to *two* vectors, not three. You mean, *every pairwise dot product* equal to $0$?
Comment: Sorry, you are right. I should have said take the dot product of all pairs of vectors.
Answer: In order for $(1,2,3)^t$ to be orthogonal to $(a,b,3)^t$, we must have
$$a + 2b + 9 = 0.$$
In order for $(4,1,-2)^t$ to be orthogonal to $(a,b,3)^t$, we must have
$$4a + b - 6 = 0.$$
$(1,2,3)^t$ and $(4,1,-2)^t$ are orthogonal, regardless of the values of $a$ and $b$.
So what you need to do is solve the $2\times 2$ system of linear equations
$$\begin{array}{rccccl}
a & + & 2b & = & -9\\
4a & + & b & = & 6.
\end{array}$$
Do you know how to solve systems of linear equations? (Gaussian-Jordan elimination, for instance?)
Comment: Yes, I know how to solve with Gauss-Jordan. I think I can figure it out now. Thanks.
Comment: Solving the above system I found the following: $\left[\begin{matrix}1&0&3\\0&1&-6\end{matrix}\right]$ . I made sure to check each pairewise dot product, where $a=3$ and $b=-6$, and it does check out. Thanks for the tip.

Orthogonal Set of Vectors


Why $-2Ric=\mathcal{L}_vg$?

Question: $\varphi_t$ is a one-parameter group of diffeomorphisms generated by a vector field $V$ on $M$,
$$
g_{ij}=\varphi_t^*g_{ij}(x,0) ~~~
\frac{\partial g_{ij}}{\partial t}=-2R_{ij}
$$
How to show that $-2Ric=\mathcal{L}_vg$ ? The $\mathcal{L}_vg$ is Lie derivative
I only have a little knowledge of Riemannian geometry and PDE.But I must read some paper about Ricci flow .What should do? What book I should read before read Ricci flow? Thanks for any helping .
Answer: You already have it! I assume $v$ in your Lie derivative is the vector field tangent to the orbits of $\phi_t$. If that is the case then $v=\partial/\partial_t$ and the Lie derivative of $g_{ab}$ is just $\partial_t g_{ab}$.
I do not know about Ricci flow in particular, but I suggest you get a good grounding in differential and Riemannian geometry first. For a general introduction to differential geometry I would look at Tu's Introduction to Manifolds or Lee's Smooth manifolds. For Riemannian geometry therea re good books by John Lee again or Do Carmo.
Comment: How compute $\mathcal{L}_vg_{ij}=g_{ij}\nabla_jV^k+g_{jk}\nabla_iV^k$?
Comment: I think it should be $\mathcal{L}_vg_{ij}=g_{ij}\nabla_jV^k+g_{jk}\nabla_iV^k+V^k\frac{\partial g_{ij}}{\partial x^k}$, but the it is above one on the book.

Why $-2Ric=\mathcal{L}_vg$?


Does anyone know a free compiler for Delphi?

Question: I want to learn Delphi, does anyone know of a good free program that would let me write code with Delphi?
I want to learn as many languages as I can, I already kinda know C#, some LUA, some VB and Java, but I want to know more. For the sake of knowing I guess.
Comment: Only Delphi let you program in Delphi
If you want something free try Free Pascal.
Comment: Well, I might be too late but Borland has released older Delphi versions (<= D7) for free download. Now, getting to them in this time and age is a whole different story.
Answer: You can use Lazarus FreePascal.


Deleting rows where all elements are missing value from list-R

Question: Let I have a list(list1) which consists data frames(df1, df2, ..dfn) where each data frame has different number of columns.
Let list1[[1]]:
df1:

indx  v1  v2
1     23  45
2     NA  34
3     NA  NA
4     NA  NA
5     56  NA

and
df2:

indx  v9  v6
1     5   15
2     11  78
3     16  NA
4     NA  NA
5     NA  8

I want to delete rows where all elemetns of rows(except the indx row) are NA.
So the ouput should be(list2)
list2[[1]]:
df1:

indx  v1  v2
1     23  45
2     NA  34
5     56  NA

and
df2:

indx  v9  v6
1     5   15
2     11  78
3     16  NA
5     NA  8

How can I do this using R? I will be very glad fotr any help. Thanks a lot.
Answer: We can loop over the list with lapply, get the rowSums on the logical matrix (!is.na(x[-1])), convert to logical vector by checking the elements are not equal to 0 and use that to subset the rows.
lapply(list1, function(x) x[!!rowSums(!is.na(x[-1])),])
#$df1
#  indx v1 v2
#1    1 23 45
#2    2 NA 34
#5    5 56 NA

#$df2
#  indx v9 v6
#1    1  5 15
#2    2 11 78
#3    3 16 NA
#5    5 NA  8


Celery BROKER_URL with vhosts not properly recognized

Question: I have a problem connecting to a RabbitMQ vhost via BROKER_URL. My vhost name is navarro which rabbitmqctl shows:
 $ rabbitmqctl list_vhosts
 /
 navarro
 $

However, with
BROKER_URL = 'amqp://guest:guest@localhost:5672/navarro'

I get error: [Errno 104] Connection reset by peer and "access to vhost '/' refused for user 'guest'" in my logfile (guest is only configured for my vhost, note it is not the auth issue but the vhost issue that is the problem).
If I use
BROKER_URL = 'amqp://guest:guest@localhost:5672//navarro'

I get
"access to vhost '/navarro' refused for user 'guest'"

which makes sense since there is no vhost /navarro. But how do I connect to the actual host navarro?
Writing this I got the idea to allow the user guest also on '/', will let you know whether it helps.
Well it helps because the tasks ends up in the '/' vhost and not in the navarro one. However, starting Celery with the app connects to the correct queue. I thought both locations are defined by the same setting.
Answer: Not enough rep to comment, so leaving an answer.
Are you sure that the user guest has permissions on the vhost? What did you do to make sure he does?
You could run:

rabbitmqctl set_permissions -p navarro guest ".*" ".*" ".*"

Your first way of getting to the vhost is the correct one (only one /).


What is the most efficient way for a control to determine if it's rendering in a Web form or a master page?

Question: I have a control that can be placed in a Web form (.aspx) or a Master Page (.master).  I want it to function differently depending on which one it's in.
My first thought is to climb the control tree back to the root and see if I cross over a MasterPage control.  If so, then it would have to be in the Master Page.
But, this seems inefficient.  Is there a better way?
Answer: I am not sure if there is a more efficient way, but if you are climbing up the hierarchy, do so through NamingContainer. You will skip plenty of unnecessary hops by using that.
Unless is a control that will appear lots of time on the page, going through the NamingContainer will be more than enough :)
Answer: First check if the page has a master page at all. Then go through the control tree to look for a content place holder:
<code>public static bool IsInMaster(Control control) {
    if (control.Page.Master == null) return false;
    while (control != null) {
        if (control is ContentPlaceHolder) return false;
        control = control.Parent;
    }
    return true;
}
</code>


ListView Fragment

Question: A lista é carregada no Fragment com a seleção do ítem de menu da ActionBar. Contudo, quando eu clico numa tab diferente da que tem o Fragment com a lista, e retorno para a tab com a lista, a lista que estava anteriormente não é destruída. Ou seja, é feita uma nova requisição a API, retornam os dados normalmente e eles são adicionados a lista que já estava lá.
Como corrigir isto?
Meu Fragment:
public class Fragment1 extends ListFragment {
    List<Notice> result = new ArrayList<Notice>();
    NoticeAdapter adpt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.list_notice, container, false);
        ListView lView = (ListView) view.findViewById(android.R.id.list);

        JsonArrayRequest jReq = new JsonArrayRequest("http://192.168.1.101:3000/notices",
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        for (int i = 0; i < response.length(); i++) {
                                try {
                                    Notice notice = new Notice();
                                notice.setId(response.getJSONObject(i).getInt("id"));
                                notice.setPicture(response.getJSONObject(i).getString("picture"));
                                    notice.setPublicationTime(response.getJSONObject(i).getString("publication_time"));
                                notice.setReducedDescription(response.getJSONObject(i).getString("reduced_description"));
                                notice.setReference(response.getJSONObject(i).getString("reference"));
                                notice.setTitle(response.getJSONObject(i).getString("title"));
                                result.add(notice);
                            } catch (JSONException e) {
                                Toast.makeText(getActivity(), "Falha com a conexão de internet", Toast.LENGTH_LONG).show();
                            }
                        }
                        adpt.setItemList(result);
                        adpt.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
          Volley.newRequestQueue(getActivity().getApplicationContext()).add(jReq);
        adpt = new NoticeAdapter(result, this.getActivity());
        lView.setAdapter(adpt);

        return view;
    }
}

E Adapter:
public class NoticeAdapter extends BaseAdapter {

private List<Notice> itemList;
private LayoutInflater inflater;

public NoticeAdapter(List<Notice> itemList, Context ctx) {
    this.itemList = itemList;
    inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    if (itemList != null)
        return itemList.size();
    return 0;
}

public Notice getItem(int position) {
    if (itemList != null)
        return itemList.get(position);
    return null;
}

public long getItemId(int position) {
    if (itemList != null)
        return itemList.get(position).hashCode();
    return 0;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;

    if(view == null) {
        view = inflater.inflate(R.layout.item_layout, null);
        holder = new ViewHolder();
        view.setTag(holder);

        holder.tvId = (TextView) view.findViewById(R.id.title);
        holder.tvDesc = (TextView) view.findViewById(R.id.description);
        holder.tvPtime = (TextView) view.findViewById(R.id.publication_time);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    holder.tvId.setText(itemList.get(position).getTitle());
    holder.tvDesc.setText(itemList.get(position).getReducedDescription());
    holder.tvPtime.setText(itemList.get(position).getPublicationTime());

    return view;
}

private static class ViewHolder {
    TextView tvId;
    TextView tvDesc;
    TextView tvPtime;
}

public List<Notice> getItemList() {
    return itemList;
}

public void setItemList(List<Notice> itemList) {
    this.itemList = itemList;
}

}

Answer: Um dos tópicos mais importantes que devemos entender quando se utilizam Fragments é o seu ciclo de vida.
O método onCreateView() é chamado sempre que o Fragment necessita de ser apresentado na tela.
Como você tem o preenchimento da lista nesse método, sempre que muda de tab o método é chamado e a sua lista recebe novos itens.
Esse código tem de ser mudado para um método que seja chamado apenas um vez. O melhor candidato é o onCreate()
Altere o seu código para:
public class Fragment1 extends ListFragment {
    List<Notice> result = new ArrayList<Notice>();
    NoticeAdapter adpt;
    Context context;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        //Obtém e guarda o context para uso futuro
        context = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Defina aqui o seu request
        JsonArrayRequest jReq = new JsonArrayRequest("http://192.168.1.101:3000/notices",
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        for (int i = 0; i < response.length(); i++) {
                                try {
                                    Notice notice = new Notice();
                                notice.setId(response.getJSONObject(i).getInt("id"));
                                notice.setPicture(response.getJSONObject(i).getString("picture"));
                                    notice.setPublicationTime(response.getJSONObject(i).getString("publication_time"));
                                notice.setReducedDescription(response.getJSONObject(i).getString("reduced_description"));
                                notice.setReference(response.getJSONObject(i).getString("reference"));
                                notice.setTitle(response.getJSONObject(i).getString("title"));
                                result.add(notice);
                            } catch (JSONException e) {
                                Toast.makeText(context, "Falha com a conexão de internet", Toast.LENGTH_LONG).show();
                            }
                        }
                        adpt.setItemList(result);
                        adpt.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
           });
        adpt = new NoticeAdapter(result, context);
        Volley.newRequestQueue(context.getApplicationContext()).add(jReq);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.list_notice, container, false);
        ListView lView = (ListView) view.findViewById(android.R.id.list);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setListAdapter(adpt);
    }
}

Edit
Esta solução só funciona se em vez de replace você usar hide/show para alternar entre Fragments.
Outra solução será declarar um construtor para a classe Fragment1 e colocar lá o código que faz a requisição.
Má ideia, há alturas em que o Android necessita de criar novas instâncias utilizando para isso o construtor default
Outra solução será testar se a lista result está vazia e só fazer a requisição nesse caso:
public class Fragment1 extends ListFragment {
    List<Notice> result = new ArrayList<Notice>();
    NoticeAdapter adpt;
    Context context;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        //Obtém e guarda o context para uso futuro
        context = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Defina aqui o seu request
        JsonArrayRequest jReq = new JsonArrayRequest("http://192.168.1.101:3000/notices",
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        for (int i = 0; i < response.length(); i++) {
                                try {
                                    Notice notice = new Notice();
                                notice.setId(response.getJSONObject(i).getInt("id"));
                                notice.setPicture(response.getJSONObject(i).getString("picture"));
                                    notice.setPublicationTime(response.getJSONObject(i).getString("publication_time"));
                                notice.setReducedDescription(response.getJSONObject(i).getString("reduced_description"));
                                notice.setReference(response.getJSONObject(i).getString("reference"));
                                notice.setTitle(response.getJSONObject(i).getString("title"));
                                result.add(notice);
                            } catch (JSONException e) {
                                Toast.makeText(context, "Falha com a conexão de internet", Toast.LENGTH_LONG).show();
                            }
                        }
                        adpt.setItemList(result);
                        adpt.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
           });
        adpt = new NoticeAdapter(result, context);
        setListAdapter(adpt);

        //Se result é está vazia faz a requisição
        if(result.isEmpty){
            Volley.newRequestQueue(context.getApplicationContext())
                  .add(jReq);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.list_notice, container, false);
        ListView lView = (ListView) view.findViewById(android.R.id.list);
        return view;
    }
}

ListView Fragment


Extracting repeated measures standardised difference from studies for meta-analyses (unknown correlation between measures)

Question: I am conducting a meta-analysis and trying to extract standardised differences from a study using pre-post (or repeated measures) design. I am given the Mean, SD, and Sample Size for the pre- and post-test scores (in terms of the metafor package, I have the m1i, m2i, sd1i, and sd2i).
The repeated measures standardised difference takes into account the correlation between the measures (e.g. see a brief description of the method in a previous post here). However, I do not have this information and recommended not to guess it. Are there any ways I can find the repeated measures standardised difference without knowing the correlation between the measures?
(a simple guide on how to do that in R would be sufficient, but feel free to add any mathematical details)
Many thanks!
Answer: Without a value for the correlation or some way of imputing it you cannot compute the standard error of the mean differences. You could always impute a range of values over the plausible range and see how much it affects the analysis but if your advisors are against any form of imputation that is ruled out.
If these are randomised trials then you could just analyse the post scores as the effect of controlling for pre scores should just be to increase precision.


If dim($W$), $|S|$ are equal and finite, then the elements of $S$ are not linearly independent.

Question: Given that $V$ is a vector space, $S \subseteq V$ is a subset, and $W \leq V$ is the subspace spanned by the elements of $S$, I'm asked to prove or disprove the statement in the title. I'm simply looking for verification/critique of what I've written below:
This statement is false. Without loss of generality, assume that $S$ has size $n\geq1$. That is, $S=\{s_1,s_2,\cdots,s_n\}$. Because $W$ is spanned by the elements of $S$, we have that $s_1,\cdots,s_n\in W$, and every element of $W$ is a linear combination of $s_1,\cdots,s_n$. The dimension of $W$ is given by the size of a basis for $W$. A basis for $W$ is given by linearly independent elements of $W$ that span $W$. Because every vector in $W$ is a linear combination of $s_1,\cdots s_n$, dim$(W)\leq n$. This implies that, if dim$(W)=|S|=n$, then $s_1,\cdots,s_n$ must be linearly independent, as they are all basis vectors for $W$.
Comment: Your argument is right, but I think you could be more precise in "if $dim(W)=n$, then $s_1,..., s_n$ must be linearly independent".
Comment: @RafaelHolanda Thanks, I added a small clarification at the end.
Answer: Since you want to prove that the statement is false, it suffices to find a counterexample. Just take $W = \{0\}$ and $S = \emptyset$. Then $|S| = \dim(W) = 0$ but the elements of $S$ are linearly independent...
Comment: If you ever have a doubt about what is spanned by the empty set, you should remember the definition of the vector space spanned by $X$: it is the smallest subvector space of $V$ containing $X$. With $X=\emptyset$, this becomes "the smallest subvector space", in other words $\{0\}$
Comment: Does this work? I'm not sure if $W$ is spanned by the elements of $S$ here, since $S$ is empty. Is 0 a linear combination of, well, nothing? If so, this is great.
Comment: It does work. See [Empty sum](https://en.m.wikipedia.org/wiki/Empty_sum).


Drupal in sub directory, still not clear

Question: My drupal project is in directory /var/www/MY_ORGANIZATION/MY_PROJECT/current, and apache2 is configured to point the web subdirectory of the above location. When I access the site, it is of course under http://www.myorganization.it/. Now I need to move it to http://www.myorganization.it/myproject, both for organization policies and to allow it to be more easily reached through a reverse proxy. I searched around and I found a couple of interesting links, like this and this and a few more. Inspired by them, I tried to move the contents of web/ to web/myproject, but when I accessed http://www.myorganization.it/myproject I got blank page. The error in the logs is crystal clear:
Failed opening required '/var/www/MY_ORGANIZATION/MY_PROJECT/current/web/myproject/../vendor/autoload.php'

So I put back the installation in web/ and renamed it to myproject, changed apache configuration to point /var/www/MY_ORGANIZATION/MY_PROJECT/current, and that worked like a charm. But I am not sure this is an advisable configuration, since, well, since all Drupal installations I saw were in a web directory. Also, from my research I had understood that Drupal installation can be moved to arbitrary subdirectories, but I didn't find any official documentation. It would appear that I should at least configure a path for vendor.
So, the concluding question is, would you recommend simply renaming web to myproject, or should I do it another way?
EDIT: a symlink from myproject to web seems an elegant solution, it works fine in apache (dev environment), while I'm getting errors with nginx+php-fpm (staging environment); still, it may be the way to go.
Comment: To clarify the error message you're seeing in the log: this is coming from PHP rather than Apache. When `index.php` is run it (indirectly) looks for a file with the _relative_ path `../vendor/autoload.php`. If the contents of `web` are moved, this relative path to `../vendor` stops being correct.
Answer: Apache can handle this. You can leave the Drupal code where it is.
Have a look at the Apache documentation for Mapping URLs to Filesystem Locations. In particular, the differences between DocumentRoot and Alias.
In the absence of any other information, Apache looks for files/scripts in the document root. For a Drupal site located at https://www.myorganization.it/, it's enough to point DocumentRoot at the web directory. Apache will find index.php there.
But myproject isn't a directory in the filesystem. So you need to explicitly tell Apache about it, that any URL starting /myproject refers to the web directory. You can do that with the Alias directive:
Alias "/myproject" "/var/www/MY_ORGANIZATION/MY_PROJECT/current/web"
You'll also want to point DocumentRoot somewhere else to stop Drupal being visible at the root too (an empty directory will do).
Comment: Yes, I know, but then all the links to static files will be wrong, and I'd have to set `file_public_base_url` to change that; it seems easier to me to just put everything in a separated directory, from my research it appears to be a supported configuration, but it's not clear to me what is the recommended way to do it.


Equivalent formulation of a regression (subtracting something from a dep var or controlling for it)

Question: From my Stata experiment, the following two approaches give the same coefficient and standard errors for X.
(1) regressing Y1-Y2 on X and Y2.

(2) regressing Y1 on X and Y2.

That is,
(1) gen Ydiff = Y1-Y2
    reg Ydiff X Y2

(2) reg Y1    X Y2

Is this generally true? Why would that be the case?
Comment: Hint: there's also a simple obvious relationship between the coefficient estimates for $Y_2$.
Comment: @whuber Can I safely generalize that  #1 and #2 produce the same coefficient and standard errors for X?
Comment: @whuber  Hi, I would like to revisit the question. Could you explain more?
Answer: Yes, this is generally true.
Given data $(x_i, y_{1i}, y_{2i}),$ the second model supposes
$$y_{1i} = \beta_0 + \beta_1 x_i + \beta_2 y_{2i} + \varepsilon_i$$
for fixed unknown $\beta_j$ (which are estimated by reg).  The first model supposes
$$y_{1i} - y_{2i} = \alpha_0 + \alpha_1 x_i + \alpha_2 y_{2i} + \delta_i.\tag{**}$$
By subtracting $y_{2i}$ from both sides of the first model you obtain the equivalent model
$$y_{1i}-y_{2i} = \beta_0 + \beta_1 x_i + (\beta_2-1) y_{2i} + \varepsilon_i.\tag{*}$$
Comparing this term-by-term to the first model shows $(*)$ and $(**)$ are the same but merely use different notation with
$$\alpha_0 = \beta_0,\ \alpha_1=\beta_1,\ \alpha_2 = \beta_2 - 1,\ \text{ and }\delta_i=\varepsilon_i.$$
Consequently the model estimates will have the same relationships; in particular, $\hat\alpha_0 = \hat\beta_0$ (the estimated intercept) and $\hat\alpha_1=\hat\beta_1$ (the estimated slopes) must be equal whenever the estimates are unique (which is the case when the $x_i$ are not constant). (You will also notice that $\hat\alpha_2 = \hat\beta_2 - 1.$)
Furthermore, the residuals will be the same and will have the same meanings, so the software will report that the root mean squared errors are the same. That causes all the standard errors of the parameter estimates to be the same in the two models.
However, the software will likely report a different $R^2,$ because that depends also on the variance of the responses and there's no assurance the variance of the $y_{1i}$ (in the second model) will equal the variance of the $y_{1i}-y_{2i}$ (in the second model).
Comment: Thank you so much!
Answer: This is definitely not true in general.
The obvious case where this is true is when the Y2 is all zeros, then your equations are equal to each other.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = x
y2 = x - x

# coef for x is 1 in both cases

And the obvious case where this is not true, set Y1 == Y2 (both non-zero) then in the first case, your dependent variable is all 0s, therefore the coefficient for X has to be 0, but in the second case, it won't be all 0s.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = x
y2 = x

# coef for x is
#   eq(1): 0
#   eq(2): 0.5

Comment: I am sorry I missed a critical thing in my question. (1) is regressing Y1-Y2 on X and Y2. Not just on X. Then I suppose (1) and (2) give the same coef and s.e. for X?


calendar View in android 3.0

Question: I am trying to bring in the default Calendar's view into my app and i found its possible using this
 CalendarView calander = new CalendarView(this);
        setContentView(calander);

This shows the calendar in month mode. Is it possible to make the CalendarView show the calendar in hourly mode?
Answer: I think you will need to write a custom implementation for that?

calendar View in android 3.0


Classification when training data contains probability

Question: I am trying to use basic classification algorithms in Python using sklearn. Unfortunately my dependent variable in training data are probabilities of whether it will rain or not. I know how to do this if my dependent variable is "rain" or "sunny". But now it is a probability. Can I use sklearn classification algorithms for this problem or should I use regression? Please advise.
Comment: After googling a bit, I realized that I could convert the [0,1] probability into a normally distributed variable using log (1 / (1 - x)) transformation and then run the regressions. I am still unsure how to solve this as a classification problem.
Comment: If you have the base counts the probabilities came from (the denominator of the prob calculation), you can easily alter data to use classification algorithms.
Comment: Otherwise you could try what you suggest, but Beta regression is developed specifically for this type of problem.
Answer: I do not see any chance to model a continuous output between [0,1] as a classification problem.
Use regression with P('Sunny') as the target variable.


SQL ajuda a unir 2 selects

Question: tenho 2 selects abaixo, como posso unir em apenas 1 select?
Eu preciso pegar tudo que vendeu num determinado período (BETWEEN) por item só que ao mesmo tempo eu tenho que pegar o que tinha de estoque do item até a data inicial.
para separar se é entrada ou saída é a opção d.tipo
Exemplo:
Produto     Estoque             qtd vendida
XPTO         100                     50

Select 1:
SELECT DISTINCT d.cat_id prod, p.id, p.nome id_prod,
SUM( d.qtd ) AS qtd_prod, SUM( d.valor_total ) AS total_prod
FROM lc_controle c
INNER JOIN lc_detalhe d ON d.controle_id = c.id
INNER JOIN `lc_cat` p ON p.id = d.cat_id
WHERE d.tipo = '0'
and c.dtConcat BETWEEN '$dtinicial' AND '$dtfinal'
and c.exportado = 'Sim'
GROUP BY d.cat_id
ORDER BY qtd_prod DESC

Select 2:
SELECT DISTINCT d.cat_id prod, p.id, p.nome id_prod,
SUM( d.qtd ) AS qtd_estoque
FROM lc_controle c
INNER JOIN lc_detalhe d ON d.controle_id = c.id
INNER JOIN `lc_cat` p ON p.id = d.cat_id
WHERE d.tipo = '0'
and c.dtConcat < '$dtinicial'
and c.exportado = 'Sim'
GROUP BY d.cat_id
ORDER BY qtd_estoque DESC

Answer: Penso que dessa forma irá conseguir ter os resultados que pretende:
SELECT      DISTINCT TMP.*
FROM        (
                SELECT      DISTINCT d.cat_id   AS prod
                        ,   p.id
                        ,   p.nome              AS id_prod
                        ,   SUM(d.qtd)          AS qtd_prod
                        ,   SUM(d.valor_total)  AS total_prod
                        ,   SUM(0)              AS qtd_estoque
                FROM        lc_controle c
                INNER JOIN  lc_detalhe  d ON d.controle_id  = c.id
                INNER JOIN  lc_cat      p ON p.id           = d.cat_id
                WHERE       d.tipo      = '0'
                        AND c.dtConcat  BETWEEN '$dtinicial' AND '$dtfinal'
                        AND c.exportado = 'Sim'
                GROUP BY    d.cat_id
                UNION
                SELECT      DISTINCT d.cat_id   AS prod
                        ,   p.id
                        ,   p.nome              AS id_prod
                        ,   SUM(0)              AS qtd_prod
                        ,   SUM(0)              AS total_prod
                        ,   SUM(d.qtd)          AS qtd_estoque
                FROM        lc_controle c
                INNER JOIN  lc_detalhe  d ON d.controle_id  = c.id
                INNER JOIN  lc_cat      p ON p.id           = d.cat_id
                WHERE       d.tipo      = '0'
                        AND c.dtConcat  < '$dtinicial'
                        AND c.exportado = 'Sim'
                GROUP BY    d.cat_id
            ) TMP
ORDER BY    TMP.qtd_prod DESC

Em princípio o DISTINCT estará a mais no SELECT principal, visto que o UNION valida duplicados, mas de qualquer forma, mal não faz!

Edit
Coloquei o SUM também nas colunas que estão com valor "0", caso contrário iria provocar problemas na consulta porque são valores numéricos e não estão agrupados.
Comment: João, obrigado pela ajuda...mas a segunda parte ele não está somando as quantidades e está trazendo todos os itens e não apenas os itens que tem movimento da primeira parte...to mexendo aqui mas não consegui resolver...
Comment: O _SUM_ não está a ser feito no 2º _SELECT_? Estranho... se executar cada consulta individualmente, que resultados tem?
Comment: Se rodo apenas a primeira parte o resultado é o mesmo com a segunda, o problema está na segunda parte, somei manualmente as qtd da primeira parte e está trazendo as quantidades corretas...tenho um item que ele mostra na primeira parte e tive saída no período informado de 426 unidades e entrada até a data inicial que fica na segunda parte de 600 unidades e ele mostra zero
Comment: Atenção que na 2ª consulta ele vai somar **apenas** as quantidades anteriores à data inicial! Não sei se está a ter isso em conta.
Comment: sim é isso mesmo que preciso, esse item que te falei a entrada dele foi antes da data inicial por isso ele deveria ter somado
Comment: Tem a certeza que o _SELECT_ que colocou na sua questão devolvia dados? Usando os _INNER JOIN_ a tabela _lc_controle_ tem que ter obrigatoriamente registos na _lc_detalhe_ e essa na _lc_cat_. Confirme pf a informação
Comment: Devolvia sim as informações só que separadas, tinha uma consulta para entradas e outras para saidas, preciso unificar justamente para ter as 2 informações no mesmo relatorio, sendo assim: o usuario escolhe a data inicial e data final para consulta o relatorio traz todos os itens que tiveram movimentação nesse periodo da seguinte maneira: Nome do produto quantidade vendida quantidade entrada e valor total da venda
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/81063/discussion-between-joao-martins-and-robert).
Answer: Voce vai ter que usar um Union Select, e para isso os dois select tem que ter a mesma quantidade e os mesmos nomes de campos de retorno;
 Select prod, id_prod, qtd_prod, total_prod from ((
      SELECT DISTINCT d.cat_id prod, p.id, p.nome id_prod,
      SUM( d.qtd ) AS qtd_prod, SUM( d.valor_total ) AS total_prod
      FROM lc_controle c
      INNER JOIN lc_detalhe d ON d.controle_id = c.id
      INNER JOIN `lc_cat` p ON p.id = d.cat_id
      WHERE d.tipo = '0'
    ) as t1
    union select (
      SELECT DISTINCT d.cat_id prod, p.id, p.nome id_prod,
      SUM( d.qtd ) AS qtd_estoque, 0 as total_prod
      FROM lc_controle c
      INNER JOIN lc_detalhe d ON d.controle_id = c.id
      INNER JOIN `lc_cat` p ON p.id = d.cat_id
      WHERE d.tipo = '0'
      and c.dtConcat < '$dtinicial'
      and c.exportado = 'Sim'
      GROUP BY d.cat_id
      ORDER BY qtd_estoque DESC
    ) as t2
) as t3

referencia : mysql
Comment: deu erro, pq vc tirou a data inicial e final no BETWEEN, não sei muito de select......#1064 - Você tem um erro de sintaxe no seu SQL próximo a 'union select (
      SELECT DISTINCT d.cat_id prod, p.id, p.nome id_prod,
   ' na linha 9
Comment: fiz as pressas aqui, mas adaptando as suas necessidades deve resolver.

SQL ajuda a unir 2 selects


Using string from a file in a function

Question: I have this function in c++
<code>double f_x(double y , string sfy )
{
  return sfy;
}
</code>

I want to read the string sfy from a file and pass it to the f_x function.
sfy contains something like y or cos(y) or exp(y).
when I pass y and sfy to the f_x, I want f_x calculates sfy and return it.

I can do number 1 and 3 but the problem is that the type of f_x is double and sfy is string, so I get error.
I can not change the type of f_x to anything else it should be double or float.
How can I overcome this problem namely what should I do in order to f_x returns sfy as double.
Comment: Do you mean that you would have a call like f_x(3.14, "cos(y)") and you would actually like it to return the cosine of y?
Comment: yes i do.
i will use this function to solve an integro-differential equation.
this function is a minimal example of my real function.
if fact sfy contains a very large expression in temrs of several variables.
Answer: Something like this, perhaps:
<code>#include <map>
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>

std::map<std::string, double(*)(double)> m;

double f_x(double y , std::string sfy )
{
    if (m.find(sfy) == m.end()) throw "Invalid operation.";
    return m[sfy](y);
}

int main()
{
    m["exp"] = std::exp;
    m["cos"] = std::cos;
    m["sin"] = std::sin;

    std::ifstream file("test.txt");
    std::string op;
    std::getline(file, op);

    std::cout << f_x(42.0, op);
}
</code>
Comment: In that case you need a parser of some sort. Perhaps you should look for some existing tools that would do that (flex, lex, etc...).
Comment: You could start at wikipedia entry for "parsing". [This book](http://www.amazon.com/Programming-Principles-Practice-Using-C/dp/0321543726) is a great resource for learning input handling. It teaches it by making a calculator.
Comment: Thanks.
There are some problems with this code.
1-in real situation sfy(the string) contains a very large expression in terms of several variables, but i think your code is suitable when there is one variable and one expression.
2-Because there are several variables in sfy so it is necessary that i put cos or sin or exp in test.txt with their arguments.
here in below is a small expression of what i have in sfy
Comment: -1. E^(s-t+t1-t2) Cos[1.88346 t-1.88346 t2] Cos[1.88346 t1-1.88346 t2] Sin[1.88346 s-1.88346 t] Sin[1.88346 s-1.88346 t1]
Comment: as you see there are 4 variables s,t1,t2 and t
Comment: OTOH, extracting arguments from file isn't that hard. Perhaps you should update the question with an example expression and explain how would you want to parse it.
Comment: I don't know anything about "parse". Is there a tutorial about it?

Using string from a file in a function


XAML+TextBox: Referencing text from resource file included in assembly

Question: I know how to use an image from my assembly resources in XAML for the Image element:
<Image Source="pack://application:,,,/MyImage.png" />

But, how can I do it for the Text attribute of a TextBox?  Something similar to:
<TextBox Text="pack://application:,,,/MyTextFile.txt" />

Answer: Here is my current solution, but requires some code-behind:
Uri licenseUri = new Uri("pack://application:,,,/MyTextFile.txt", UriKind.Absolute);
StreamResourceInfo info = Application.GetResourceStream(licenseUri);

StreamReader reader = new StreamReader(info.Stream);
_textBox.Text = reader.ReadToEnd();


Windows C: drive size

Question: Our C: drive on some of our Windows servers is only 8GB, is there anyway to dynamically update this? Its all locally attached storage.
Thanks
John
Answer: You need a partition resize tool. Examples include PartitionMagic, or the excellent gparted. The latter is a linux boot disc: boot, resize, sorted! Its also free, just remember to make a full backup just in case something goes wrong.
edit: as mentioned, Dynamic disks are a different matter for most resizing tools. If you want to resize a dynamic volume, you use the diskpart utility provided by Microsoft. This comes with Win2003. Please note that you cannot resize a dynamic volume if it was originally on a basic disk and was later upgraded to dynamic. Back everything up regardless before starting.
Comment: I am mostly a Windows guy, but have found gparted to be easy and reliable.  I have used it on some of our W2000 servers where the OS partition is tiny.
Comment: yep, things can go wrong. In such a case I'd create a brand new partition and restore from the backup I made before resizing. If you're a l33t hax0r, you could follow these steps: http://fugitivethought.com/blog.php?action=view&blog_id=77 Impressive knowledge that chap has!
Comment: gParted is the best.
Comment: Is this easy enough to do with Raid configurations?
Comment: Yes, it will work with RAID configurations, assuming it is hardware RAID.  It might be possible with software RAID, but it would probably be much harder to perform than with hardware RAID.
Comment: If you see my answer below, you'll likely run into problems when trying to use gparted with Server 2003 and dynamic disks.
Comment: +1 on Backup first.  It is unlikely that something will go wrong, but you don't want to be "that guy" when you screw up the OS partition on an important production server.
Comment: Gparted is great, but has a hidden limitation. When resizing an NTFS partition from small (say, 30G) to large (say, 300G), you are likely to get a "disk read error" due to changes in the geometry stored in the Windows boot/partition scheme. For more information, search on the terms "ntfs partition resize disk read error"
Answer: There are a number of products which can do this. One Open Source solution is Gparted, which is a bootable Linux based application which can perform non-destructive re-partitioning. Always take a backup before such operations, just to be safe.
Answer: If your disk is bigger than 8Gb you can use software like Partition Magic, or Acronis  to extend the partition. However if your physical disk is only 8Gb, then your going to need to look at getting a new disk and using something like Acronis to image the old drive and move it to the new one.
Answer: You're going to run into some issues if you are trying to resize a dynamic disk.  There are some tools out there that will allow you to convert the dynamic disk to a basic disk to resize it, but I'd be pretty leery of trying it.  take a look here:  http://www.partition-tool.com/easeus-partition-manager/copy-dynamic-volume.htm
Answer: I recently used Acronis Disk Director Suite for that, works like a charm.
Answer: Windows 2000 introduce a new feature called dynamic disk.
It allows, amongst other things, to dynamically resize a partition. You can even extend your partition on another disk.
This article provides some usefull informations.
Comment: One thing to bear in mind is that many disk recovery tools will not work with dynamic disks.

Windows C: drive size


fixture 'pylon_config_missing_usageplan' not found while running pytest-bdd

Question:     @scenario('../features/config.feature', 'Loading a valid config')
def test_config():
    pass

@given("I have provided a valid pylon config",target_fixture="pylon_config")
def pylon_config():
    input_data = {

        }
    return input_data

@when("The configuration is loaded")
def excute_pylon_config(pylon_config):
    createFilterPattern(pylon_config)

@then("It should be enriched with the expected FilterPatterns")
def no_error_message(pylon_config):
    test_data1= {

            }

    test_data_2 = {

    }
    result = pylon_config

@scenario('../features/config.feature', 'Missing usagePlan section')
def test_missing_usageplan():
    pass

@given("I have provided a pylon config with a missing key",target_fixture="pylon_config_missing_usageplan")
def pylon_config_missing_usageplan():
    input_data = {
            'metricFilters': {
                'defaults': {
                    'xyz': []
                }
            }
        }
    return input_data

@when("The configuration is loaded")
def excute_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
    try:
        createFilterPattern(pylon_config_missing_usageplan)
    except KeyError:
        pass

@then("I should receive an exception")
def error_message_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
    print(pylon_config_missing_usageplan)

I have written multiple test case with specifying target_fixture in both @given scenario.
While running the test case it's throwing an error with
fixture 'pylon_config_missing_usageplan' not found
available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pylon_config, pytestbdd_given_I have provided a pylon config with a missing key, pytestbdd_given_I have provided a valid pylon config, pytestbdd_given_trace, pytestbdd_then_I should receive an exception, pytestbdd_then_It should be enriched with the expected FilterPatterns, pytestbdd_then_trace, pytestbdd_when_The configuration is loaded, pytestbdd_when_trace, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
use 'pytest --fixtures [testpath]' for help on them.
Can anyone help me over here?
Answer: The issue is, that the step When The configuration is loaded has two different implementations in code:
@when("The configuration is loaded")
def excute_pylon_config(pylon_config):
    createFilterPattern(pylon_config)

@when("The configuration is loaded")
def excute_pylon_config_missing_usageplan(pylon_config_missing_usageplan):
    try:
        createFilterPattern(pylon_config_missing_usageplan)
    except KeyError:
        pass

The function excute_pylon_config_missing_usageplan overrides the step implementation of excute_pylon_config and therefore if you try to load the pylon config in scenario Loading a valid config, pytest-bdd actually tries to execute the function excute_pylon_config_missing_usageplan, which is expecting the fixture pylon_config_missing_usageplan (which is not available in this scenario ...)
Solutions

Have two distinct steps for loading a valid/invalid config, e.g. When The configuration is loaded and When The invalid configuration is loaded (I would recommend this approach, since it is simpler and easier to read than solution 2)
Add a variable to the step for loading the configuration which contains the type of the configuration

Example of variable in configuration loading step:
@when(parsers.parse("The {config_type} configuration is loaded"))
def excute_pylon_config(request, config_type):
    if config_type == 'valid':
        # Retrieve fixture dynamically by name
        pylon_config = request.getfixturevalue('pylon_config')
        createFilterPattern(pylon_config)
    else:
        # Retrieve fixture dynamically by name
        pylon_config_missing_usageplan = request.getfixturevalue('pylon_config_missing_usageplan')
        try:
            createFilterPattern(pylon_config_missing_usageplan)
        except KeyError:
            pass


How to process an http request with a controller?

Question: I try to write a custom Restful API to send contents between two drupal site. The present code work except the datas are in a weird format with @ in the json.
My resquest is:
<code>$serializer = \Drupal::service('serializer'); $data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);

$response = \Drupal::httpClient()
        ->post("http://site1.test/api_test/send_content", [
          'headers' => [
            'Content-type' => 'application/json',
          ],
          'json' => $data,
        ]);`
</code>
The function which process my request:
<code>public function createNewContent(Request $request) {

   if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {

     $data = json_decode( $request->getContent() );

     \Drupal::logger('test_rest_api')->notice($data);
   }

   $response['data'] = 'Query well received';
   $response['method'] = 'POST';

   return new JsonResponse( $response );
}
</code>
The problem is, after the json_decode my datas let a big string and look like:

@"nid":[{"value":5197],"uuid":[@"value":"8310f782-06ce-4fb8-957d-ec7feecc8929"],"vid":[@"value":63527],"langcode":[@"value":"en"],"type":[@"target_id":"page","target_type":"node_type","target_uuid":"189f826c-e516-4a22-8d4d-f3a2f418aea9"],"revision_timestamp":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"revision_uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"revision_log":[],"status":[@"value":true],"title":[@"value":"Test"],"uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"created":[@"value":"2017-12-19T21:07:57+00:00","format":"Y-m-d\TH:i:sP"],"changed":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"promote":[@"value":true],"sticky":[@"value":false],"default_langcode":[@"value":true],"revision_translation_affected":[@"value":true],"moderation_state":[],"content_translation_source":[@"value":"und"],"content_translation_outdated":[@"value":false],"metatag":@"value":{"title":"Test","og_site_name":"Test","shortlink":"http://site1.test/en/node/5197/sendContent","canonical_url":"http://site1.test/en/node/5197/sendContent","og_type":"article","og_url":"http://site1.test/en/node/5197/sendContent","image_src":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_title":"Test","og_description":"This
  is a
  test","og_image":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_updated_time":"2017-12-19T16:08:36-05:00","article_published_time":"2017-12-19T16:07:57-05:00","article_modified_time":"2017-12-19T16:08:36-05:00"},"path":[@"alias":"/test","pid":16287,"langcode":"en"],"rh_action":[@"value":"bundle_default"],"rh_redirect":[],"rh_redirect_response":[@"value":301],"publish_on":[],"unpublish_on":[],"menu_link":[],"body":[@"value":"\u003Cp\u003EThis
  is a test\u003C/p\u003E","format":"full_html","summary":""]}

I precise the @ are already present before the json_decode. I don't know where I could have made a mistake.
I suppose I can clean it easily but I'm more interested to understand what is this format and how can I convert it properly and quickly.
Answer: Ok, my problem was the serialization. To recover my node object in my function of POST, I should deserialize the json with the function:
<code> $data = \GuzzleHttp\json_decode( $request->getContent(), TRUE);
 $serializer = \Drupal::service('serializer');
 $node = $serializer->deserialize($data, \Drupal\node\Entity\Node::class, 'json');

 $new_node = Node::create(array(
   'type' => $node->bundle(),
   'title' => $node->title,
   'langcode' => $node->language()->getId(),
   'uid' => '1',
   'status' => 1,
   'body' => $node->get('body'),
 ));

 $new_node->save();
</code>
Now, I can manipulate my node like I want in my other website.


Steps to find Kernel of $T - \lambda I$ where $T$ is a linear operator?

Question: Let $K(t,s)= st$ for $s, t \in [0,1]$. Define the operator $T$ on $C[0,1]$ by
$$
(Tf)(t) = \int_0^1 K(t,s)f(s)ds \,\,\,\,\,(\forall \,f \in C[0,1]).
$$

a) For any $\lambda$, describe the Null space(= Kernel) of $T - \lambda I$.

  b) Find all values of $\lambda$ such that the equation
  $$
(T-\lambda I)f=g
$$
  has a unique solution for every $g \in C[0,1]$.

Also, can you explain what is the interpretation of $g$'s that satisfy the above equality?
Comment: Note that $(Tf)(t) = \left(\int_0^1 sf(s) ds\right) t$ is just a linear function in $t$.
Comment: $T$ is a compact self adjoint operator and its only non-zero eigen value is $\frac  1 3$. Hence $\frac  1 3$ is the only possible value of $\lambda $. The kernel is $\{f: \int_0^{1} tf(t)dt=0\}$.
Comment: @Kabo Murphy: Can you please show me how you would write $T- \lambda I$?
Answer: If $(T-\lambda I)f=0$, you have
$$\tag1
\lambda f(t)=\int_0^1 st f(s)\,ds=t\int_0^1 sf(s)\,ds.
$$
So, if $\lambda=0$ then $\ker T$ consists of all those $f$ with $\int_0^1 sf(s)\,ds=0$. When $\lambda\ne0$: if $(1)$ holds for $\lambda\ne0$, we have
$$\tag2
f(t)=\phi_\lambda(f)\,t,
$$
where $$\tag3\phi_\lambda(f)=\frac1\lambda\,\int_0^1 sf(s)\,ds.$$ Then
$$\tag4
\phi_\lambda(f)=\frac1\lambda\,\int_0^1 sf(s)\,ds=\frac1\lambda\int_0^1 s\,\phi_\lambda(f)\,s\,ds=\frac1{3\lambda}\,\phi_\lambda(f).
$$
For $f$ to be an eigenvector we need $f\ne0$, which forces $\phi_\lambda(f)\ne0$. Then $3\lambda=1$, and so $\lambda=\tfrac13$ is the only possible nonzero eigenvalue. In summary, $\ker(T-\lambda I)=\{0\}$ when $\lambda\not\in\{0,\tfrac13\}$, and
$$
\ker(T-\tfrac13\,I)=\{\alpha g:\ \alpha\in\mathbb R\}
$$
where $g(t)=t$.
For the second part, if the equation $(T-\lambda I)f=g$ has a unique solution for all $g\in C[0,1]$, this means that $T-\lambda I$ is invertible. Because $T$ is compact (or, instead of using a more general result, we could just notice that $T$ is rank-one), its spectrum consists only of eigenvalues, and so the equation $(T-\lambda I)f=g$ has a unique solution for all $g$ precisely when $\lambda\not\in\{0,\tfrac13\}$.


Will SQL update a record if the new values are the same?

Question: Will SQL update a record if there is no change to the record?
For examople, is it more efficient to replace
UPDATE TABLE myTable
Set Col1 = ISNULL(Col1,'')
...
Set Col100 = ISNULL(Col30,'')

with
UPDATE TABLE myTable
Set Col1 = ISNULL(Col1,'')
...
Set Col100 = ISNULL(Col30,'')
WHERE
Col1 IS NULL OR
...
Col30 IS NULL

Comment: Yes. T-SQL doesn't attempt to figure out whether or not column values have changed. If you specify a row to be updated in an `UPDATE` statement, it **will** be updated - whether needed or not. If it's not needed in the first place - then **don't** put that into your SQL statement
Comment: Yes, it will update the table.  More efficient is a different question.  Note that triggers will not be fired if an update is not performed, e.g. in your second example.  That could be good or bad depending on your intent.
Answer: Yes, it will attempt overwrite.
Comment: I don't think any database would optimize away the updates.  It would prevent on update triggers from being fired.
Answer: You have to control it manually, in the where clause you can put all the fields if they are differ the new values, and where the id of your table is equals to your parameter, you will ensure that only modified records will be updated.
    UPDATE table
    SET field1 = @field1,
                 field2 = @field2
    WHERE field1 != @field1 AND
          field2 != @field2 AND
          id = @id


Zeros of a complex function on the unit circle

Question: I need a closed form for the zeros of $$f(z):=\frac{z^{2(1+\omega)}-z^{2\omega}}{i}-e^{-\frac{\pi}{2\sqrt{3}}} $$ where $z$ lies on the unit circle $|z|=1$ and $\omega$ is a cube root of unity.
We know that the cube roots of unity satisfy $$1+\omega+\omega^2=0\ \ \ \text{and}\ \ \ \omega^3=1$$
Now we have
$$\frac{z^{2(1+\omega)}-z^{2\omega}}{i}-e^{-\frac{\pi}{2\sqrt{3}}}=0$$
So $$e^{\frac{\pi}{2\sqrt{3}}}z^{2\omega}\left(\frac{z^2-1}{i}\right)-1=0$$
Any help would be highly appreciated. Thanks!
Comment: Define $z^{2\omega}$.
Comment: $1+\omega = - \omega^2 = -\frac{1}{\omega}$ and $i = e^{i\frac{\pi}{2}} = -e^{-i\frac{\pi}{2}}$. Maybe these substitutions could be useful?
Comment: @geetha290krm Since $z$ lies on the unit circle and $2\omega=-1+\sqrt{3} i$ so we define $$z^{2\omega}=e^{i t (-1+\sqrt{3} i)}=e^{-it-\sqrt{3} t}$$
Comment: @TonyMathew Thanks a lot for the idea. I tried but cannot come to an answer. I request you for help.
Comment: You can rearrange into $z^{2\omega+2}-z^{2\omega}=ie^{-\frac\pi{2\sqrt 3}}$ and substitute $u=z^{2\omega}$ to get $u^{1+1\frac1\omega}-u= ie^{-\frac\pi{2\sqrt 3}}$. See [here](https://mathoverflow.net/questions/418392/series-solution-for-general-trinomial) for series solution for general trinomial.
Comment: @TymaGaidash Thank you for the wonderful idea. I would really appreciate if you write an answer and give a closed form for zeros. I will with utmost respect accept your answer.
Answer: Numerically, $z=\sqrt[6]{-1}$ is the only $|z|=1$ solution to $$z^{1+ i\sqrt 3}-z^{-1+ i\sqrt 3}=ie^{-\frac\pi{2\sqrt 3}}$$
Now substituting $z=\pm\sqrt w$ and use Lagrange reversion for the other equation:
$$\begin{align}z^{1- i\sqrt 3}-z^{-1- i\sqrt 3}=ie^{-\frac\pi{2\sqrt 3}}\iff z^2=i e^{-\frac\pi{2\sqrt3}}z^{2\sqrt[3]{-1}}+1\iff w= (\pm 1)^{2\sqrt[3]{-1}}i e^{-\frac\pi{2\sqrt3}}w^\sqrt[3]{-1}+1\implies z=\pm 1\pm\frac12\sum_{n=1}^\infty\frac{\left(i(\pm 1)^{2\sqrt[3]{-1}}e^{-\frac\pi{2\sqrt3}}\right)^n}{n!}\left.\frac{d^{n-1}}{dw^{n-1}}w^{\sqrt[3]{-1}n-\frac12}\right|_1\end{align}$$
to finally use the Fox Wright function, a special case of Fox H:
$$\bbox[5pt,border: 1px solid blue]{\begin{align}z=\pm1\pm\frac12\sum_{n=1}^\infty\frac{\left(\pm i e^{-\frac{\{1,7\}\pi}{2\sqrt 3}}\right)^n}{n!}\frac{\Gamma\left(\frac12+\sqrt[3]{-1}n\right)}{\Gamma\left(\frac32+(-1)^\frac23n\right)}=\pm1\pm\frac12\,_1\Psi_1\left(^{\left(\frac12,\sqrt[3]{-1}\right)}_{\left(\frac32,(-1)^\frac23\right)};\pm i e^{-\frac{\{1,7\}\pi}{2\sqrt 3}} \right)\end{align}}$$
where one solution takes $+,1$ and the other takes $-,7$. Both roots match Wolfram Alpha's. This calculates $z+1$ more precisely for $z$ being the root taking $-,7$ as it's real part is almost $-1$.
Comment: $+1$ and Thank you for the wonderful answer. I would request a closed form of the zeros.
Comment: The Fox Wright function is not classically defined as having complex parameters, but if you consider an extension, then it could work
Answer: $$\omega^3=1\implies\omega\in\{1,-\frac{1}{2}+\frac{1}{2}i\sqrt{3},-\frac{1}{2}-\frac{1}{2}i\sqrt{3}\}$$
$$|z|=1$$
$\ $
$$\frac{z^{2(1+\omega)}-z^{2\omega}}{i}-e^{-\frac{\pi}{2\sqrt{3}}}=0\tag{1}$$
We see, equation (1) is an algebraic equation over $\mathbb{C}$ of more than one algebraically independent monomials ($z^{2(1+\omega)},z^{2\omega}$). The main theorem in [Ritt 1925] cannot help in these cases: We cannot read an elementary inverse function directly from the equation because we don't know how to rearrange the equation for $z$ by applying only finite numbers of elementary functions (operations) we can read from the equation. We have to guess $z$ therefore.
[Ritt 1925] Ritt, J. F.: Elementary functions and their inverses. Trans. Amer. Math. Soc. 27 (1925) (1) 68-90
1) Solutions in terms of Elementary functions
1a) $\omega=1$
$$\frac{z^4-z^2}{i}-e^{-\frac{\pi}{2\sqrt{3}}}=0$$
We see, this equation is a $\mathbb{C}$-algebraic equation of $z$.
$$z\in\left\{\frac{1}{2}\sqrt{2+2\sqrt{1+4e^{-\frac{\pi}{2\sqrt{3}}}i}},-\frac{1}{2}\sqrt{2+2\sqrt{1+4e^{-\frac{\pi}{2\sqrt{3}}}i}},\frac{1}{2}\sqrt{2-2\sqrt{1+4e^{-\frac{\pi}{2\sqrt{3}}}i}},-\frac{1}{2}\sqrt{2-2\sqrt{1+4e^{-\frac{\pi}{2\sqrt{3}}}i}}\right\}$$
There is no $z$ with $|z|=1$.
1b) $z=\sqrt[6]{-1}$
Tyma Gaidash wrote in his answer, numerically, $z=\sqrt[6]{-1}$ is a solution.
$$z=\sqrt[6]{-1}\implies z\in\left\{-i,i,-\frac{1}{2}\sqrt{2+2i\sqrt{3}},\frac{1}{2}\sqrt{2+2i\sqrt{3}},-\frac{1}{2}\sqrt{2-2i\sqrt{3}},\frac{1}{2}\sqrt{2-2i\sqrt{3}}\right\}$$
Numerically, we find that
$$z=\frac{1}{2}\sqrt{2+2i\sqrt{3}}$$
is a solution of the equation for
$$\omega=-\frac{1}{2}+\frac{1}{2}i\sqrt{3}$$
with $|z|=1$.
2) Solutions in terms of nonelementary functions
$$\frac{z^{2(1+\omega)}-z^{2\omega}}{i}-e^{-\frac{\pi}{2\sqrt{3}}}=0\tag{1}$$
We see, equation (1) is a trinomial equation with complex exponents.
$$z^{2(1+\omega)}-z^{2\omega}-ie^{-\frac{\pi}{2\sqrt{3}}}=0$$
$$-\frac{1}{i}e^{\frac{\pi}{2\sqrt{3}}}z^{2\omega}+\frac{1}{i}e^{\frac{\pi}{2\sqrt{3}}}z^{2(1+\omega)}-1=0$$
$z\to e^{-\frac{1}{2}\frac{\pi}{2\sqrt{3}\omega}}(-xi)^\frac{1}{2\omega}$:
$$x-e^{\frac{\pi}{\omega}i}e^{-\frac{\pi}{2\sqrt{3}\omega}}i^\frac{1}{\omega}x^{\frac{1}{\omega}+1}-1=0$$
Now the equation is in the form of equation 8.1 of [Belkic 2019]. Solutions in terms of Bell polynomials, Pochhammer symbols or confluent Fox-Wright Function $\ _1\Psi_1$ can be obtained therefore.
Szabó, P. G.: On the roots of the trinomial equation. Centr. Eur. J. Operat. Res. 18 (2010) (1) 97-104
Belkić, D.: All the trinomial roots, their powers and logarithms from the Lambert series, Bell polynomials and Fox–Wright function: illustration for genome multiplicity in survival of irradiated cells. J. Math. Chem. 57 (2019) 59-106


Alternate a BASH variable by Date

Question: What method can one use to alternate a variable which is dependable by time?
For example, this week var = Office, then next week var = Oncall?
The resulting script will be using crontab to output the contents of var depending on which week it was.
Thanks.
Comment: Is it normal that there is 2 variables "var" and "vare1" ?
Answer: You can use date +%W to check what week number of the year it is (starting Monday).
You can alternate between the two with e.g.
if (( $(date +%W) % 2 ))
then
  var=Office
else
  var=Oncall
fi

Comment: so basically this means, if the number of weeks is divisible by 2, then Office, otherwise Oncall (in other words, alternate weeks)? thx.

Alternate a BASH variable by Date


What algorithm might Google Sheets use for a "smooth line chart"? (Not the trend line)

Question: It's not a cubic spline as the line always passes through the data points. It's not a polynomial - I have mapped a 6th order polynomial over seven data points and it is very different. Bard admits to not knowing:"The moving average algorithm that Google Sheets uses to generate smooth line charts is not a simple weighted moving average algorithm.
"A simple weighted moving average algorithm would not go through all of the data points in the series."The moving average algorithm that Google Sheets uses to generate smooth line charts is not a simple weighted moving average algorithm. A simple weighted moving average algorithm would not go through all of the data points in the series."
Here's the type of data I'm working with:

And here's how Sheets interpolates it:
I'm looking for a way to replicate the smoothing programatically in order to interpolate between the data points similarly to Sheets.
Answer: Google Sheet smoothened test data:

It's definitely not cubic spline interpolation.
NB: cubic spline interpolation does go through all the points!

Piecewise quadratic does look quite similar, even if not exactly the same.

Cubic Hermite spline looks even closer (using scipy.interpolate.PchipInterpolator in Python).
Comment: Can you tell me how you did the cubic spline interpolation?
Comment: Using scipy.interpolate.CubicSpline in Python
Comment: Thanks. I am new to Python (although old to C, PHP, Java...!) and haven't explored scipy. Can scipy provide a way to evaluate the curve at intermediate points, like x= 2.2? If so, could you point me to a good reference please?
Comment: Here's a simple example. You can then evaluate cs at any point (for example cs(0.45)).

For documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.CubicSpline.html

`import numpy as np;
from scipy.interpolate import CubicSpline;
x = np.linspace(0, 3, 3);
y = np.sin(x);
cs = CubicSpline(x, y);`
Comment: Thanks, I'm finding Py very accessible and powerful. Any further thoughts on which interpolation Sheets uses to smooth lines?
Comment: You could also try asking on a Google product forum / support (even maybe Excel as they have a very similar option) rather than trying to reverse engineer it.
Answer: It looks like a Catmull-Rom type of interpolant. At each point $P_i$, the slope is taken to be the slope of the line $P_{i-1} P_{i+1}$. Then, for each interval, you the two end-points and the two end-slopes, which you can fit with cubic curve.