Enviar valor de uma variável em Javascript para PHP

Question: Tenho procurado muito e feito muitos testes mas não estou conseguindo enviar o valor de uma variável do Javascript para uma variável PHP.
O meu caso é o seguinte: Tenho um portal de imóveis e gostaria de pegar as informações (mais precisamente os dados da imobiliária ou apenas o nome dela) buscadas por uma função Javascript e passar para uma variável no PHP, no caso a variável $title, que é a variável que regula o título que aparecerá em cada página no navegador.
A função JS que pega essas informações é essa:
function getDadosImobiliaria(id) {
$.getJSON('../site/Control/controlUsuario.php', {type: 'selectDadosImob', imobiliariaId: id}, function(data) {
    if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }

    $('#logoAnunciante').attr('src', 'imagensUpload/'+data.logo);
    $('.ruaNumero').html(data.rua+', '+data.numero);
    $('.bairro').html(data.bairro);
    $('.cidadeUf').html(data.cidade+' - '+data.uf);
    $('#fone').html(data.fone);
    $('.showCidade').html(data.cidade);
    $('.showCidade').attr('href', '/imobiliarias/'+data.cidade);
    $('.countTotalImoveis').html(data.count);

    if (data.creci != undefined) {
        $('.creci').html("CRECI: "+data.creci);
    }

});
}

Como posso fazer para passar a variável da imobiliária ou qualquer outra variável para a variável do PHP $title contida em um outro arquivo e assim formar os títulos das páginas do portal de imóveis? Por POST? Ajax?
Desde já agradeço!
Comment: O único objetivo é alterar o título?
Comment: Poste o código da pagina em php também. Pode ajudar a achar a soluçao.
Comment: Mas se for só alterar o title use o famoso... document.title = "titulo"
Comment: Possível duplicata de [Passar variável Javascript para corpo PHP](https://pt.stackoverflow.com/questions/27130/passar-vari%c3%a1vel-javascript-para-corpo-php)
Comment: Andrei, o único objetivo é alterar o título. Ele precisa ser dinâmico para melhorar o SEO das páginas. E o código PHP praticamente não tem, fiz testes apenas com a variável $title recebendo o valor. Como não sou muito da área de programação, não consegui prosseguir. Usei o document.title depois de ver que você sugeriu, mas também não deu certo. Quero apenas conseguir passar essa variável do JS para o PHP. Desde já agradeço!
Comment: A variável `imobiliaria` é o valor que você quer que contenha no ``?
Comment: Mas você quer enviar ao PHP ou pegar via ajax e injetar na  com JS? Sua pergunta esta bem confusa, edite ela e explique o que realmente quer.
Comment: Sim Andrei, a variável imobiliaria é o valor que quero passar pro title.
Comment: Guilherme, eu antes queria ou enviar por PHP, seja do jeito que for (ajax, post e tudo que for possível) ou, por JS mesmo, setar o title com a variável imobiliaria. Eu consegui fazer isso depois de muito testar, mas, infelizmente, setando por JS o título da página, não aparece o título que fiz por JS ao pesquisar no google, ou seja, não é relevante setar por JS o SEO da página. Então terei que fazer por PHP para ter relevância para o google.
Answer: Consegui pegar o valor de outro jeito, direto com o php, e setar no title, depois de muuito tentar também haha. Mas creio eu que a questão que estava procurando, que era passar o valor de uma variável js para php, foi resolvida na resposta acima, onde de fato deu certo, mas, como comentei, na volta para o arquivo JS, a página se atualiza e todas as informações carregadas se esvaem, ficando apenas o title certo. Mas enfim, o principal da questão foi resolvida e assim, encerro a questão aqui. Muito obrigado a todos e espero que a resposta acima dada pelo Andrei ajude muitos com a mesma dúvida. Grande abraço!
Comment: Sim... Foi como eu te falei.. Infelizmente o php é lido antes de você alterar a variavel. Entao, para o SEO, nao iria adiantar muito. =) Abraço
Answer: Depois que olhei melhor o seu código reparei que você estava utilizando o jquery. Existe uma forma de você enviar a variável em js para php da mesma forma que você está utilizando o ajax. Porém, acho mais fácil, nesse caso, você alterar o titulo do documento através do jquery. Pelo que eu entendi do código a variável imobiliaria é a que você quer que esteja no <title>. Então ficaria assim:
 ...

    // Dentro da função mesmo...

    if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }

    $(this).attr("title", imobiliaria); // aqui ele altera o título

...

Provavelmente isso vai dar certo. Se não der, comente aqui que eu dou um jeito
EDIT
"houston we have a problem!"
Em base no que você colocou até agora existe uma variável chamada $titleque está em um arquivo php. O que você quer é lançar um conteúdo resgatado através do arquivo em js e passar esse conteúdo para essa variável, pois supostamente, você resolveria o problema do SEO e alteraria o <title> certo?. Existe uma forma de fazer isso, porém, isso não vai resolver o seu problema, pois o php é interpretado antes do javascript e a unica coisa que você fará é atualizar uma parte do código, mas a página carregada no servidor continua a mesma. Isso é a mesma coisa que o exemplo anterior, só que dando uma volta maior. Veja:
Esse é o código php (resgataVariavel.php)
<?php
    @$title = $_POST['title'];
    echo json_encode($title);
?>

Essa é a index.php:

<title></title>

...

Através do ajax, passei o conteúdo da variável imobiliaria para a variável $title. Porém, no final, o título será alterado pelo javascript com document.title = resultado;.
O que você precisa fazer é pegar esse conteúdo através do php e lançar ele na variável  $title antes do javascipt ser executado.
Entenda, mesmo que essa variável do php $titleestiver dentro da tag <title></title>, e eu usar o javascript para alterá-la, ainda assim não funcionaria, pois o servidor já "leu" o conteúdo antes de ela ser alterada pelo javascript.
UMA SOLUÇÃO QUE PODE FUNCIONAR...
Tente fazer desta forma:
 ... (código anterior)...

if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }

    $.ajax({

        type: 'POST',
        url: 'resgataVariavel.php',
        cache: false,
        data: { 'titulo': imobiliaria },
        success : function(retorno){
            document.write(retorno);
        },
    })

   ...(resto do código)...

Arquivo resgataVariavel.php
<?php
    @$title = $_POST['titulo'];
    echo "<title>".$title."</title>";
?>

Repare que eu coloquei o php para incluir o <title></title>, não sei se vai funcionar para o SEO, pois quem escreve esse arquivo é o javascript. Mas é uma opção. Espero ter ajudado.
Comment: Obrigado Andrei, funcionou da forma como me mostrou. Mas, infelizmente, para o SEO do google, setar o title ou qualquer outra metatag  por javascript não funciona, ao fazer a busca no google, o título que aparece da página não é esse editado por JS. Apenas as páginas que o título são elaboradas por PHP aparecem certo. E eu preciso, muito, fazer com que essa variável passe para uma variável PHP. Agradeço caso consiga me ajudar a fazer isso.
Comment: Ok... vou fazer da forma que vc precisa entao.. calma ae
Comment: @AlessandroBeiersdorf posta a pagina php ou html que tenha esse código. Vai ajudar muito
Comment: Esse última edição que fez também funcionou! Mas.. (sempre tem um mas haha) ao voltar ao arquivo js depois de ir até o arquivo php, as informações da imobiliária que já foram carregadas se esvaem, ficando apenas o título certo, sem nenhuma outra informação na página. Creio que seja a ordem da chamada da função, ou a resposta da chamada no sucess do ajax. Já tentei de tudo para que isso não acontecesse, mas não consegui. Desculpe a demora para responder.
Comment: @AlessandroBeiersdorf , rsrs... é assim mesmo... Mas antes de você corrigir isso. Veja se quando alterou o título, funcionou para o SEO. Entendeu?
Comment: @AlessandroBeiersdorf pois se não funcionar para o SEO, não vai adiantar nada arrumar o código.
Comment: E não esquece que você pode avaliar as respostas ok? Isso da um incentivo.. =)
Comment: Infelizmente não terei como atualizar no ar assim, pois, como mencionei, as informações da página não são carregadas, ficando apenas certo o título. Mas consegui de outro jeito :D


Show that no choice of numbers $a$ and $b$ can make $ax + by = (3,0,0)$

Question:
Show that no choice of numbers $a$ and $b$ can make $ax + by = (3,0,0)$ when $x = (3,-1,0)$ and $y = (0,1,5)$.

The only materials in the chapter talked about are:

Vector Space Operations
Standard Basis
Coordinates of a vector $x$
Components of a vector $x$

I don't think that the vector $v=(3,0,0)$ has a unique linear combination of coordinates with respect to the standard basis with how $x$ and $y$ are defined. I also don't think stating this is "rigorous" enough of an answer. Is there a better (clearer) way I can show that the above statement is true?
How can I show that the statement is true from a geometric point of view?
Comment: $\begin{vmatrix} 3 & 0 & 0 \\ 3 & -1 & 0 \\ 0 & 1 & 5 \end{vmatrix}=-15\ne0$ so they're linearly independent
Comment: can you explain the significance of the determinant $\neq 0$  and being linearly independent?
Comment: See [here](https://en.wikipedia.org/wiki/Invertible_matrix#Properties) and [here](https://en.wikipedia.org/wiki/Linear_independence#Alternative_method_using_determinants) and my answer below
Answer: $ax+by = a(3, -1, 0) + b(0, 1, 5) =(3,0,0)$ gives you the system of equations
$$ 3a = 3 , \, -a+b = 0, \, 5b = 0. $$
Can you go on from here?
Comment: Then $a = \frac{3}{3} = 1$, $b = 1$, but $5(1) = 0$ is false. Then the conclusion is that we can't make $(3,0,0)$ from any given $a$ and $b$?
Comment: Yes, precisely!
Answer: You may not have learned this yet, but
$n$ vectors in $ \mathbb {R} ^{n}$ are linearly independent if and only if
the determinant of the matrix formed by taking the vectors as its columns is non-zero.
In your particular case, that matrix has a form (upper triangular) that makes it very easy to compute
the determinant (simply multiply the diagonal entries):
$\begin{vmatrix} 3 & 3 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & 5 \end{vmatrix}=-15\ne0,$ so they're linearly independent.
Comment: also, the $3\times3$ determinant is the scalar [triple product](https://en.wikipedia.org/wiki/Triple_product) of the vectors in its columns, thus zero iff the vectors are coplanar


Xen USB pass through

Question: Running the Xen (Debian). I want to access the iKey USB dongle from Windows DomU. I have 2 PCI:
lspci:
00:14.0 USB controller: Intel Corporation Lynx Point USB xHCI Host Controller (rev 04)
00:1a.0 USB controller: Intel Corporation Lynx Point USB Enhanced Host Controller #2 (rev 04)
After using Pciback, I am able to Pass the USB to Guest.
DomU.log:
register_real_device: Real physical device 00:14.0 registered successfuly!
register_real_device: Real physical device 00:1a.0 registered successfuly!
In the machine, USB and USB-SS Ports are available. But even after installing Xen drivers, in the DomU, I can see only 1a.0 and Not 14.0. When I start DomU, getting the following error for 14.a:
The kernel doesn't support reset from sysfs for PCI device..
Any tips??
Answer: It may be (and may be not) related to the Xen toolstack in Dom0. I recently experimented with passing a PCI card and a USB controller to HVM DomU, and had completely different experience depending on tools used.

With pure XM/Xend and Xen 4.2, I was able to pass the USB controller only, but unable to bind the PCI card, even together with its parent PCI bridge.
Using XL to create DomU in a XM/Xend environment with Xen 4.2, allowed me to pass both devices (although error messages were displayed almost each time), but the option-ROM was not executed, although the card was then usable by Windows.
Upgrading to pure XL and Xen 4.3, finally helped to recognize the option-ROM, but the card always rebooted the DomU upon keypress.

So you may want to try different Xen versions and toolstacks.
As for the USB controller type, are you sure that both devices are true hosts that can be used to attach peripherals? (I'm not an expert in this, but I noticed that USB infrastructure usually consists of several layers, some of which are supplementary.) Moreover, xHCI may stand for USB 3.0, so are you sure that your Windows version supports USB 3.0, especially in a virtualized environment?

Xen USB pass through


Relationships Between Nodes on Field

Question: I'm trying to work with some information out of our enterprise system to create an employee directory, and I have a question regarding how I can relate nodes together.
I have a content type called Employees, and it has a number of fields, including Employee ID, First Name, Last Name, etc.
I then have a content type called Positions, and it has a number of fields, including Employee ID, Title, etc.
I'm trying to figure out how I can link the Positions and Employee nodes together on the Employee ID field rather than the nid.
Any help would be appreciated. Thanks!
Answer: If you're looking for a relatively simple option, Entity Reference is probably best:

Provides a field type that can reference arbitrary entities:
A generic entity reference field Four widgets: Two implemented on top
  of the Options module (Select and Radios/Checkboxes), Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field) Two formatters: A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.) A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references) Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import

EDIT #1
To set up the view as described in comments:

Create the view for Employee Content Type, and make settings how you desire
Add a Relationship to Entity Reference: Referenced Entity for the entity reference field, Require this relationship

Now you have access to the fields in the referenced (position) content type and can display them in your view.  One thing of note, Title field may not work from Position, so you may have to include a separate field for the Position Title. Otherwise, everything should work as a normal view
Comment: Thanks, Geoff. I can't seem to figure out how to get it to work off the Employee ID field. I can get the reference hooked up, but it references the Node ID, if that makes any sense.
Comment: that does make sense, that's what it's supposed to do. Once you have a relationship between the two, you can access information between them. You won't get a direct relationship between the ID and a node, that causes too many potential issues - the next step is: how do you want to access or relate the data? You tagged your question with Views, but don't give any further information on how you want it displayed in Views
Comment: I would like to build a view that combines information from both content types... for example, I'd like to display a list of people in the organization, and under their name, list their job titles.
Comment: see my edit....
Answer: Try Views Cross Join

Allows to cross join entities in Views. This is an essential tool to
  bring in not related data. For example you want to display two nodes
  in the same row, but there is no reference between them. Then you
  could cross join all nodes. Important all nodes get joined in, so you
  need to limit the result with filters and arguments.

You should also put an index on the fields being joined on the database for performance reasons.

Relationships Between Nodes on Field


Tool for solving complicated system of equations.

Question: $$v_x=\frac{bn_xc+n_yv_zd-n_zv_yd-F_x}{a}$$
$$v_y=\frac{bn_yc+n_zv_xd-n_xv_zd-F_y}{a}$$
$$v_z=\frac{bn_zc+n_xv_yd-n_yv_xd-F_z}{a}$$
Given these equations, is it possible to solve them, also is there a program / online tool that can do it for me?
Solving in this scenario means only having the terms $v_x$, $v_y$ and $v_z$ on the left hand side of the three equations.
Please provide some tool because these equations might change.
Comment: What are the variables?
Comment: The $v$ terms, ex $v_x$.
Answer: I would use SymPy because I am already familiar with Python.  SymPy offers algebraic (symbolic) solutions, too.  You can use Sage, too.  Sage need not be installed as you can use it in your browser.  You can of course solve it manually through Gaussian elimination.
Answer: Yes; you have a system of three linear equations in three variables. Simply apply Gaussian elimination. Explicitly, moving all the constants to one side, you get
$$\begin{pmatrix}
-a&-n_zd&n_yd\\
n_zd&-a&-n_xd\\
n_yd&n_xd&-a
\end{pmatrix}
\begin{pmatrix}
v_x\\v_y\\v_z
\end{pmatrix}
=
\begin{pmatrix}
bn_xc-F_x\\
bn_yc-F_y\\
bn_zc-F_z
\end{pmatrix}.$$
Answer: A very good tool, I recommend you is WIMS that you can find here: http://wims.unice.fr/wims/en_tool~linear~linsolver.en.html Another very good tool is Symbolab that you can download as application for your mobile device: https://www.symbolab.com/mobile.html?OS=Android&redirect=
Comment: I do know about wolfram but it does not accept only letters when solving a system of equations
Comment: @fullnitrous: see my edits. Sorry.


Where is the Visual Studio test playlist schema?

Question: I'm running tests in Visual Studio 2017 from the Test Explorer window using the NUnit Test Adapter. I use a test playlist file which contains the tests I want to run. The contents of that file look like this:
<Playlist Version="1.0">
    <Add Test="MyAssemblyName.MyTestFixture.MyTestMethod()" />
</Playlist>

Is there a schema for these Visual Studio playlist files? If so, where is it? If not, can you provide a list here of valid XML attributes for a Playlist file (other than <Add>)?
Comment: What is your goal? My goal is to define a playlist as a list of test *projects*, instead of as a list of *individual tests*. As I add unit tests to my project, I want them to be automatically added to my playlist. I have not found a way to do that.
Comment: @WallaceKelly look at my answer, I was able to that what you wanted
Answer: I tried to find an XSD too, but I didn't, so I dug on Visual Studio dlls and found this one Microsoft.VisualStudio.TestWindow.Core.dll I used dnSpy to look the C# code, and I found this class PropertyRule in namespace Microsoft.VisualStudio.TestWindow.Internal.Playlists
For the property names all those are valid
PropertyRule.properties = ImmutableArray.Create<ValueTuple<string, TestPropertyType, string>>(new ValueTuple<string, TestPropertyType, string>[]
{
    new ValueTuple<string, TestPropertyType, string>("Solution", TestPropertyType.Solution, string.Empty),
    new ValueTuple<string, TestPropertyType, string>("Project", TestPropertyType.ProjectName, "TestWindow_ProjectName"),
    new ValueTuple<string, TestPropertyType, string>("Namespace", TestPropertyType.NamespaceName, "TestWindow_NamespaceName"),
    new ValueTuple<string, TestPropertyType, string>("Class", TestPropertyType.ClassName, "TestWindow_ClassName"),
    new ValueTuple<string, TestPropertyType, string>("TargetFramework", TestPropertyType.TargetFramework, "TestWindow_TargetFramework"),
    new ValueTuple<string, TestPropertyType, string>("Outcome", TestPropertyType.Outcome, "TestWindow_Outcome"),
    new ValueTuple<string, TestPropertyType, string>("Trait", TestPropertyType.Trait, "TestWindow_Traits"),
    new ValueTuple<string, TestPropertyType, string>("Test", TestPropertyType.FullyQualifiedName, "TestWindow_FullyQualifiedName"),
    new ValueTuple<string, TestPropertyType, string>("TestWithNormalizedFullyQualifiedName", TestPropertyType.NormalizedFullyQualifiedName, "TestWindow_TestGroup"),
    new ValueTuple<string, TestPropertyType, string>("DisplayName", TestPropertyType.DisplayName, "TestWindow_DisplayName")
});

Look the code for the Match attribute
using System;

namespace Microsoft.VisualStudio.TestWindow.Internal.Playlists
{
  [Flags]
  public enum PropertyRuleMatchFlags
  {
    Contains = 0,
    Not = 1,
    Equals = 2,
    Subset = 4
  }
}

Reading the code I was able to edit my playlist XML to ignore some project, so all others are added automatically!


The site has a mix of modules installed manually and via Composer: Can I move all to Composer?

Question: I've inherited a Drupal 8 site where only few modules were installed via Composer; the rest was manually installed.
Is there a way to fix this, and move the manually installed modules to be handled by Composer?
Answer: You can just add the modules to Composer as you would normally: composer require drupal/MODULENAME.
You can then confirm everything is working OK by making a new copy of your site with Composer and verifying that the site loads correctly.
Potential issue:
If you are looking at the list of installed modules to decide what to install, you don't necessarily need to add every module; some may be dependencies of others (for example, with Composer, if you are using Pathauto module, you don't need to install Token explicitly; it will automatically be installed with Pathauto.)  However, it won't hurt anything if you force some dependencies to be installed as well, so this isn't really anything to worry about.


date in spanish webform component coming out in day month year , need month day year

Question: My webform in english shows  the date component as month day year.
but when I translate it to spanish it shows the date as day month year.  How can I modify the format for dates when in different languages?
FOUND THE ANSWER: go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates
Comment: "modify the format for dates when in different languages" Actually, isn't that what is already happening? The date format becomes localized? That would seem to be the correct behavior. Not sure how webform does the formatting of dates though, where exactly do you see this date? Is it a field you've added?
Comment: Great that you found an answer, but please post it as an answer below (and accept it when you can), or this question will remain in an unanswered state.
Comment: it wont let me answer my own question since I dont have enough points!
Comment: I see, I took the liberty of posting the answer for you then. :) Please consider accepting it so we can remove it from the unanswered queue. :) (Yes, this would give me undeserved reputation, but I hope we can agree to call it "drop in a pond")
Answer: Posted on behalf of Diana that can't do it due to reputation limits.
Go to <code>/admin/config/regional/date-time/locale/es/edit</code> and change the date format to month first for the long, short and medium dates.


Which model to use between VAR and VECM for the following problems (conditions)?

Question: I have three variables (monthly for 25 years) including wages (e.g. skilled and unskilled) and food price (P). I am interested to see if there any relationship exist between them, either short or long term and which one has the greater influence on other.
All the variables are non-stationary at levels but stationary at first differences. But when I check the cointegration rank in 'Stata' ('vec rank', for your information, I run this command with the variables in their levels ) then it suggests no cointegration. In that case,
 1. What should I do? Will I go for a VAR model of the first-differenced series?
 2. Why there is no cointegration among the variables?( while I found through
    unit root rest that all the series are stationary after first difference)
3. When I check the cointegration of the first-differenced series then I find the cointegration rank equal to 1. But is it feasible to run a VECM model to first- differenced series?
Comment: Re #3: If the first-differenced series are stationary, then they CAN'T be cointegrated, by definition.
Answer: I would use a VAR in levels if you are only interested in the Impulse Response Functions (IRF) and not specifically in the cointegrating relationship, which seems plausible from your description.
As mentionend in the comments if your first differenced variables are stationary they cannot be cointegrated. Also, don't take every statistical test result at face-value.
You can have a look into the papers below for arguments to estimate a system of integrated (and possibly cointegrated) variables in levels. The classic reference would be the Sims, Stock and Watson paper. Definetly also look into Lütkepohl, he is an authority when it comes to SVARS.

Sims, C. A., Stock, J. H., & Watson, M. W. (1990). Inference in linear time series models with some unit roots. Econometrica: Journal of the Econometric Society, 113-144.
Ashley, R. A., & Verbrugge, R. J. (2009). To difference or not to difference: a Monte Carlo investigation of inference in vector autoregression models. International Journal of Data Analysis Techniques and Strategies, 1(3), 242-274.
Phillips, P. C., & Durlauf, S. N. (1986). Multiple time series regression with integrated processes. The Review of Economic Studies, 53(4), 473-495.
Lütkepohl, H. (2011). Vector autoregressive models. In International Encyclopedia of Statistical Science (pp. 1645-1647). Springer Berlin Heidelberg.
Christiano, L. J., Eichenbaum, M., & Evans, C. (1994). The effects of monetary policy shocks: some evidence from the flow of funds (No. w4699). National Bureau of Economic Research.
Doan, T. A. (1992). RATS: User's manual. Estima.ote


Problema com o relacionamento na Tabela Mãe (Herança) no PostgreSql

Question: Eu tenho a Tabela Mãe Pagamento:
CREATE TABLE pagamento
(
  pagcod serial not null,
  CONSTRAINT pk_pag PRIMARY KEY (pagcod)
)

E as duas tabelas filhas Dinheiro e Cartão de Crédito:
CREATE TABLE dinheiro
(
  desconto numeric(10,2) DEFAULT 0.00,
  juros numeric(10,2) DEFAULT 0.00
)inherits(pagamento);

CREATE TABLE cartao_credito
(
  num_cartao integer NOT NULL,
  datavalidade date NOT NULL,
  senha character varying(256) NOT NULL,
  agencia integer NOT NULL,
  titular character varying(200) NOT NULL
)inherits(pagamento);

Quando eu vou dar o INSERT na tabela DINHEIRO por exemplo o atributo PAGCOD da tabela mãe PAGAMENTO vem automaticamente:
INSERT INTO dinheiro(pagcod, desconto, juros)VALUES (4, 100.00, 12.5);

Dando um SELECT * FROM DINHERIO A PK aparece normalmente:

Assim como dando um SELECT * FROM PAGAMENTO a PK também aparece normalmente:

PROBLEMA: Quando eu vou tentar referencia esta pk de pagamento na tabela PEDIDO:
CREATE TABLE pedido
(
  pedcod serial not null,
  peddata date NOT NULL ,
  ped_num_notafiscal integer NOT NULL,
  pedstatus varchar(20) NOT NULL DEFAULT 'ABERTO',
  ped_funcinario integer NOT NULL,
  ped_cliete integer NOT NULL,
  ped_pagamento integer,
  CONSTRAINT pk_pedido PRIMARY KEY (pedcod),
  CONSTRAINT fk_cliente FOREIGN KEY (ped_cliete)REFERENCES cliente (clicod),
  CONSTRAINT fk_funcionario FOREIGN KEY (ped_funcinario)REFERENCES funcionario (funcod),
  CONSTRAINT fk_pagamento FOREIGN KEY (ped_pagamento)REFERENCES pagamento (pagcod)
);

Aparece o seguinte erro:

Alguém poderia me dar uma luz de como resolver este problema? A PK aparece na tabela PAGAMENTO, porém quando vou tentá-la referenciá-la na tabela PEDIDO dar este erro.
A sintaxe do INSERT do PEDIDO:
INSERT INTO public.pedido(pedcod, peddata, ped_num_notafiscal, pedstatus, ped_funcinario, ped_cliete, ped_pagamento)
    VALUES (7, '02-11-2017', 2323, 1, 1, 1, 4);

Comment: coloca a sintaxe do insert por favor
Comment: Coloquei o insert do pedido, a última coluna que eu tento relacionar ao Pagamento.
Answer: Lendo a documentação: https://www.postgresql.org/docs/current/static/ddl-inherit.html#DDL-INHERIT-CAVEATS
Encontrei que:

Outros tipos de restrições (chave única, chave primária e restrições de chaves estrangeiras) não são herdados.

e

Uma limitação séria do recurso de herança é que os índices (incluindo restrições exclusivas) e as restrições de chave externa aplicam-se apenas a tabelas individuais, e não às suas heranças. Isso é verdade tanto nos lados referenciados como referenciados de uma restrição de chave estrangeira.

Ou seja, esse comportamento é esperado pelo postgresql, você não pode usar herança entre tabelas junto de chaves estrangeiras.
Você pode remover a CONSTRAINT fk_pagamento e talvez fazer essa verificação por trigger.
Reproduzi a situação no SQLFiddle:
Com a CONSTRAINT fk_pagamento (ERRO): http://sqlfiddle.com/#!15/cd38b/2
Sem a CONSTRAINT fk_pagamento: http://sqlfiddle.com/#!15/491475/2
Answer: A restrição faz uma busca apenas nos registros diretamente vinculados a tabela pagamento, algo semelhante a FROM ONLY, e como os registros foram incluídos nas tabelas descendentes (dinheiro e cartao_credito), não existindo então registros exclusivamente adicionados em sua tabela referenciada na chave estrangeira.
Ainda não foi implementada uma integridade que faça a busca nas tabelas herdadas que tenha sido aceita a integridade entre os relacionamentos.


Unable to install iOS app on device. Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653179

Question: I am trying to build an iOS app on a device. I am able to build the project fine, but running into an issue when trying to get the app on device. When attempting to run, I am getting a Unable to install app error message from Xcode and the app is not installed on device. The detailed error message is as shown below:
Details

Unable to install "wordgame"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653179
--
Could not write to the device.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653179
User Info: {
    DVTRadarComponentKey = 261622;
    MobileDeviceErrorCode = "(0xE8000005)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x00000001220d793f DTDKCreateNSErrorFromAMDErrorCode + 220
    1   DTDeviceKitBase                     0x0000000122116124 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x0000000106269b43 DVTInvokeWithStrongOwnership + 71
    3   DTDeviceKitBase                     0x0000000122115e65 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1440
    4   IDEiOSSupportCore                   0x0000000121f86d28 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.292 + 3513
    5   DVTFoundation                       0x00000001063982aa __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x0000000106399ecc __DVTDispatchAsync_block_invoke + 1191
    7   libdispatch.dylib                   0x00007fff70daa6c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff70dab658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff70db0c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff70db15d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff70dbac09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff71005a3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff71004b77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.7 (Build 19H2)
Xcode 12.0.1 (17220)

I am a registered Apple Developer on a paid developer program. I am using the up-to-date version of macOS and Xcode.
I have tried by deleting project derived data, restarting the device, Xcode as well as the Mac. I have created a vanilla project and tried to run it on device with success, but could not do the same with my working project.
What are the steps that I can try to resolve?
Answer: I also had this exact same issue and error code. I was trying to run a newer development version of my app on an older phone that had a much older version of the app.
I found if I deleted the old version of the app from the phone then Xcode could then install the new version when I plugged in.
In between these two events my distribution certificates etc were renewed, not 100% sure if that was related but it worked for me by removing all old versions of the app.
Comment: I just got this issue when updating distribution certs too. Sadly, delete and reinstall hasn't fixed it for me, but it would seem to suggest that signing changes are a factor.
Answer: Deleting the app on device and then re-building fixed the problem for me.
Answer: I have exact the same issue, when I switch branch to a much older repo long time ago, if I happen to run pod install, it will run out dated pods into the repo. And if you switch back to the latest repo, even you have run the pod install, it will just use the same old pod sdk you were using in the older repo. The solution is looking into the error description, uninstall that pod sdk from pod, and then re install that pod. To me, it's mapbox sdk uninstall and re-install, and then I am able to run the app.
Answer: I had the same problem with different targets. One target had a PRODUCT_NAME=AppName and the other target Appname (notice the caps). Whenever I built Appname then AppName and then again Appname, it would show black screen and some error about scenedelegate file not found.
Renaming Appname to AppnameGibberish resolved this error.
Answer: I removed the app on my iPhone then I tried again. It's fixed my issue
Answer: I have recently faced this issue and fixed,
I have followed below steps,
in developer portal, from Certificates, Identifiers & Profiles, I have selected profile option development I have selected my iPhone for installation
after that I have selected profile option distribution I have valid certificate. after that I have download distribution profile and imported in xcode. Now build is installed in my Device.
Answer:
Reboot your Mac
Reboot your iDevice
Start Xcode
Connect iDevice by cable
Open Devices & Simulators, wait for pairing
Build & Run again
Answer: You need to include the file in the target membership. Somehow you remove your target membership from any extension or class. Try this.
Answer: For me, this issue popped up after switching branches. After trying suggestions here and elsewhere, running pod install fixed it for me.
Answer: Just checked my profile provision on xcode. (create a new one). The problem is solve.
Answer: In my case, I inadvertently deleted the @main attribute from my DeviceActivity Extensions, which caused the issue.
Here's the error I've got :

Unable to install "MyApp" Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402652895 User Info: {
DVTErrorCreationDateKey = "2023-07-17 02:06:41 +0000";
IDERunOperationFailingWorker = IDEInstalliPhoneLauncher; }
-- App extensions implemented using the Swift ExtensionKit interfaces require a __swift5_entry section in the bundle executable. This
section must not be present in extensions implemented using the
Objective-C ExtensionKit interfaces. Domain:
com.apple.dt.MobileDeviceErrorDomain Code: -402652895
Answer: In my case, the issue was an internal framework was not being signed. It was embedded but not signed .

Adding the CodeSignOnCopy attribute to the embedded framework in the Apple Watch app target solved it.
Fix Unable to install "CardsBalanceWatch": no code signature found.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620388

Answer: I also face same issue since two days but solved by following steps
You need to just

Add your Apple ID in Xcode -> Preferences -> Accounts if it not added previously.
Check automatically manage signing in "Signing and Capabilities" tab

This solved my issue.
Some Tips

Also Apple has 3 Limitation for testing APP.
Delete old APP with same identifier

I have solved this issue by doing this.


what is if(errno != EEXIST) in c?

Question: what is errno and EEXIST mean?
#include<errno.h>
    if(errno != EEXIST) {
        perror(sha1_dir);
        exit(1);
    }

I can't understand the condition of if statement. is that saying "if errno doesn't exist"?
Comment: You may find this page helpful: https://en.cppreference.com/w/c/error/errno
Comment: It's saying, "if the previous file-access function, which failed, failed for a reason *other* than that the file did not exist, print a relevant error message and exit."  So if the file existed but we couldn't read it because of something like "Permission denied", that's an error.  But if the reason we couldn't read the file was because it wasn't there at all, we're okay, so proceed.  This is a common pattern when reading the file is optional, like a configuration file, or a state file to keep data between runs of a program, but which won't exist the very first time the program is run.
Comment: It is literally saying "if `errno` is not equal to `EEXIST`".
Comment: Right now it means nothing.  `errno` would possibly be set by some function call (it is a variable that should be scoped thread-local).  Check with the function setting `errno` to discover what `EEXIST` means in context of that function.
Comment: What `errno` is depends on the code above that line which you didn't show.
Comment: Sorry, my explanation was almost completely wrong.  I was thinking of ENOENT.  In this case, it's "If the previous file-access function, which failed, failed for a reason other than that the file or directory *did* exist, print a relevant error message and exit."  You might do this after calling `mkdir()`, to create a directory.  If it tried and failed to create the directory, that's probably an error.  But if the directory's already there, the program doesn't have to make it, so proceed.
Comment: so what is errno?
Comment: For a general idea of what EEXIST means, you can check '/usr/include/asm/errno-base.h' and find this: `#define EEXIST          17      /* File exists */`
Comment: `errno` is a sort of a global variable that contains a code indicating why the last system call failed.  `` contains a bunch of constants -- `EPERM`, `ENOENT`, `EEXIST`, etc. -- encoding the failure reasons.  And then `perror()` is a library function which looks at `errno` and prints a human-redable string like "Permission denied" corresponding to the code in `errno`.  See also the comments at [this recent question](https://stackoverflow.com/questions/65940663/why-is-direct-i-o-file-not-being-written-to#comment116593669_65940663).
Comment: @SteveSummit Thank you your answer fulfilled my question
Answer: If you dig into errno.h, you will find EEXIST is a C macro defined in another file.  On my Debian PC, it's in /usr/include/asm-generic/errno-base.h.
#define EEXIST      17  /* File exists */

Run man errno to find the meaning of errno variable:
DESCRIPTION
       The  <errno.h> header file defines the integer variable errno, which is
       set by system calls and some library functions in the event of an error
       to indicate what went wrong.

So the meaning of the code block is to check errno generated by the last function and if it's not "File exists" (file does not exist), print the error message.
Run man perror for more information.  Seriously, you should learn C from some book before asking such a question to stackoverflow.
Comment: [The Definitive C Book Guide and List](https://stackoverflow.com/q/562303/995714)

what is if(errno != EEXIST) in c?


How to hide body field in a view only on certain content types

Question: I have a search result view of different content types, and i want to show the body field (trimmed) on some content types, but show no body on other content types. Since they all share the same body field, I would need to exclude the body field from displaying on the content types that I don't want to see them on.
Right now I am doing this with Views rewrite results and CSS. I add the content type field and exclude, then add the body field. Under rewrite results I rewrite the output of the body field with this:
[body]
I then hide the content type bodies that I don't want to see with CSS:
span.search-body-MY-TYPE1,
span.search-body-MY-TYPE2 {
  display: none;
}

This works "visually", but the class and the trimmed body are still rendered in the HTML. Is there a better way to do this perhaps with a views_pre_render hook?
(I am completely inexperienced with PHP.)
Answer: This can be done really easily with views_conditional module. Once you enable the module, having the content type and body fields already added and excluded from display, do the following steps:

add a views conditional field
set the if condition to the [type] == Indexed Content: Content Type
set is condition to contains
Set the value to the content type name for the body that you want to display
Then in Then output this... Use the [body] replacement pattern

Works like a charm!


template.php breadcrumb function

Question: I'm trying to change the breadcrumb in Drupal to display in Danish through the template.php in my theme, but I cannot change it. I've flushed the cache.
This is what I've put in the template.php.
  function modeindeks_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];

    if (!empty($breadcrumb)) {
      // Provide a navigational heading to give context for breadcrumb links to
      // screen-reader users. Make the heading invisible with .element-invisible.
      $output = '
' . t('Du er her') . '
';

      $output .= '
' . implode(' › ', $breadcrumb) . '
';
      return $output;
     }
    }

Comment: What parts of the breadcrumb are you trying to change?
The breadcrumb links themselves or just the "You are here" text that is the heading of the breadcrumbs?
Answer: Breadcrumb is made up of an array. So to add any element in the breadcrumb you have to give the offset.
So if you want to set t('Du er her') in place of the front page link then you should try this:
$breadcrumb[0] = l(t('Du er her'), 'front');

To know the exact position of element which do you want to add, you can use var_dump($breadcrumb).
I would rewrite the code as follows.
function modeindeks_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    // Instead of front, you can use the URL of your site's front page.
    $breadcrumb[0] = l(t('Du er her'), 'front');

    $output .= '
' . implode(' › ', $breadcrumb) . '
';

    return $output;
  }
}

If you want to add only You are here link then use the below code.
function modeindeks_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '
You are here: ' . implode(' › ', $breadcrumb) . '
';
  }
}

template.php breadcrumb function


Effects of practicing on electronic piano

Question: I want to buy an electronic keyboard for someone that plays piano. I am afraid practicing on an electronic piano may be harmful for her technique. There is not enough space for a mechanical piano or those hybrid pianos.
Is it harmful for the playing technique to practice on an electronic keyboard? In what ways?
Are there ways to go around these problems?
Do you have suggestions about what electronic keyboard may be better so that there is no too much problem practicing on it?
Comment: To help the excellent answers so far,can you please quantify 'not enough space'? The fact that 88 full size keys are going to be necessary means if you can't get an acoustic piano in, you won't get a keyboard in either, width wise. Depth, there won't be a huge difference, so the only factor may be height. If so, a ship's piano could be the answer.
Comment: If this person is a grownup who plays piano, don't.  Musicians do not need people buying instruments for them; but equivalent donations in the form of cash are welcome.
Comment: I think the size of the full keyboard is fine, plus perhaps the stand. I was thinking in saving on the space and weight of the strings (are they called strings?). I thought a vertical piano would have the depth of the keyboard plus the case in which the strings and the mechanism are. Today I saw the Yamaha DGX-640. I think that size might be fine.
Comment: You can play a wide repertoire of keyboard classical music without ever approaching the 88 key limit. A synthesizer with 70-something keys is fine.
Answer: If the person is traditionally trained, which means, he/she started playing on an actual Piano, either a Grand or Upright Piano, it may affect the person's performance.
Here are some points that should be checked when buying an electric piano for a traditionally trained pianist:

As much as can afford, go for the most number of keys. 88 keys is the standard.
Weighted Keyboard or Hammer Action Keyboard.  It simulates the realistic keys like those in piano.
Velocity Sensitivity - the harder you press, the louder it sounds.

All of these at least are very important for someone who starts playing on a real piano and will be playing on an electric keyboard.  Without these can affect their performance, in terms of speed, hand and finger exercises etc.
If the person is not traditionally trained, which means started playing on electric piano that do not have the features mentioned above, it will not affect him/her, but still it is necessary for pianists to be trained traditionally.
Note: "Controller Keyboard" is a good compromise since they are very cheap, but only if the person that will be using it knows how to operate and use it.  It is not a kind of "Plug and Play" keyboard.
Comment: So it comes down, really to "how much do you want to spend?"  Those weighted keyboards cost more than cheapos.  There are even electronic pianos with a full "real" keyboard and hammer mechanics installed, so aside from the fact that the hammers hit a board instead of strings, the action is identical to an acoustic instrument.  But not cheap.
Comment: @Witthoft. I took a look at Yamaha's hybrid pianos NU1 that seem to be what you are saying, the hammer mechanism on an electronic piano, but they are too big for her appartment. I think. Maybe it is better to get a bigger apartment and then get the NU1 directly instead of a smaller and perhaps lower quality piano. I wanted to know if smaller electronic pianos exist with the feel of a mechanical piano.
Answer: I am not recommending this instrument over the many similar instruments available from other manufacturers, but the Korg SP-200:

measures 1328 x 285 x 122 mm
weighs 18.5 kg
has the full 88 keys
strives to imitate the sound and feel of a real piano accurately

Instruments like this are designed to be a professional performance and practice instrument for real pianists, and there are no compromises here that would be harmful to a player using it as their regular practise instrument.
It's up to you whether the price, weight and size are acceptable to you.
To go smaller, lighter or cheaper, there will be compromises:

Instruments with fewer keys mean that some pieces can't be played.
Instruments with smaller keys should not be considered -- they will completely throw
out the player's technique.
Doing without weighted, hammer action keys, means that the response of the keyboard will be different. This is the factor most likely to make a difference to the player's technique. Other mechanisms try to simulate weight with springs - some people find that sufficient.

The effect of this is that a player would practise getting the exact expression they want out of a piece, then perform it on a real piano and find that the sound they're producing doesn't match their expectations. This is likely to be quite a subtle effect, noticeable only by connoisseurs - but it may unsettle the player.
On the practice instrument, the action of the keys might mean that certain phrases are easier - or more difficult - than on a real piano. As an exaggerated example, imagine practising a complex Bach phrase of 16 quavers, on an electric organ with very light action and no velocity sensitivity. After half an hour's practice, you think you've nailed it. It sounds OK. Now move to a piano, and find that gentle movements that were enough to sound a note on the organ, now barely move the piano key. Or find that although you get all the notes out, they vary wildly in volume.
Do note, however, that even real pianos vary in feel, sound and response. My school's upright, my parents' upright and my piano teacher's baby grand all felt and sounded different.
It makes sense to occasionally play a different piano, just to get used to the fact that they vary. After all, concert pianists don't usually bring their own piano with them to venues.
It all depends on the player's aspirations. If they are already an experienced player, they probably know their own needs. If they intend to play on the stage, on real pianos, to fussy audiences, then absolute accuracy might be important to them. If they only ever intend to play at home, then as long as their home instrument makes a pleasant sound, that is surely enough?
Having said all this, I don't feel that even the cheapest plastic organ sold at the market toy stall actively harms a player. I suppose it might if you burned thousands of hours of playing on it into your muscle memory -- but in reality, nobody would do that.
Comment: Good point about trying other pianos. At exam. times, my pupils have a play on each of my three pianos, all quite different (yes, my wife is very understanding !), as the one in the exam. room will inevitably be different in feel, response and sound from the one they normally play.
Comment: OK, I just bought a Korg SP-250. Let's see what she says about it when it arrives. She said she had tried a Casio CDP120CS and was 'ok'. The Korg seems to be nicer, smaller, and lighter than the Casio, so I guess it should be fine. Thanks.
Answer: I'm afraid, that any instrument with decently similar feeling (I think, this means weighted hammer mechanics) does nearly occupy the same space as a piano, even if it is lower (keyboard level + lid + score holder) and can be carried by two not too weak persons (mine has a weight of ca. 70 kg). To care about the touch for me indicates a sort of seriousness difficult to satisfy with less than 88 keys.
Comment: I had the idea that maybe with an electronic keyboard I can save in space and weight a little for not having the strings and the hammer mechanism. I was comparing Yamahas b3 (an upright piano), and the DGX-340 (an electronic one with weighted keys). A little bit is saved.
Comment: You can save in weight, but the floor space is about the same. Electronic pianos save in height, but you can't put the used height to anything. Unless you can put a cabinet right over the keyboard. But that will be in your face when you're playing.
Comment: You might be able to fit it under the stairs or something. And if you went the decent keyboard route (still with weighted keys) you gain a lot of portability.


Spring Session Management with Redis

Question: How do I handle Redis DB down scenario, while using Spring Session with Redis store for session management ? What if Redis DB is down and user tries to access his/her session ?
Comment: Possible duplicate of [How to disable Redis Caching at run time if redis connection failed](https://stackoverflow.com/questions/29003786/how-to-disable-redis-caching-at-run-time-if-redis-connection-failed)
Answer: when redis down, you can store session in you container.
such as apache, Sticky sessions.
Do a filter extends DelegatingFilterProxy , add a switch to control session don't store in redis.
Answer: If Redis is down during startup of your application. Then your application will fail to start.
If Redis goes down once your application is up and running. Then spring tries reconnecting to Redis after specific intervals.
I guess what you're looking for has an answer here.
How to disable Redis Caching at run time if redis connection failed

Spring Session Management with Redis


how to send parameters to trigger in Oracle

Question: The purpose is to send extra information to triggers like current user id from a web application. Since a connection pool is used, and same user id is used for all connections how do I pass the original web user id to trigger?  It is a java based application.
Answer: If you can't touch the application code and the application itself does not pass this information to the database already, you're at an impasse.  The only way to make that information available to back-end code is for the middle tier to pass it in.
Oracle provides a number of ways for applications to pass information from the middle-tier to the back end but the application has to be built to take advantage of them.  The DBMS_APPLICATION_INFO package, for example, has a set_client_info procedure that allows the middle tier to pass in the name of the middle tier user that your back end trigger could query.  You can also use Oracle contexts if you want a more general mechanism.  Either of these approaches, however, realistically require that the Java application be written to pass this information to the back-end when connections are retrieved from the connection pool.
Comment: You can put there whatever you want i.e. the "current user id from a web application"
Comment: thank you , is set_client_info working with when i am using one user name to connect to oracle ?
Answer: You can make use of proxy authentication to identify the users even with a ConnectionPool.
An example:
me@XE> @man proxy

[ P R O X Y A U T H E N T I C A T I O N ]

drop user application_user
drop user end_user

-- let's create the application user which all users
-- need to connect through.
-- This user is meant as the middle-tier-user in a
-- multi-tier setup.
create user application_user identified by application_user

-- create an end-user
create user end_user identified by end_user
quota unlimited on users

grant create session, create table to end_user

-- this is the clause to grant access to end_user.
alter user end_user grant connect through application_user

-- now, we can connect WITHOUT PASSWORD!
@connect application_user[end_user]/application_user

-- this should display "END_USER"
select user from dual

-- this should display "APPLICATION_USER"
column proxy_user format a30
select sys_context('userenv', 'proxy_user') proxy_user from dual

http://blogs.oracle.com/jheadstart/entry/using_proxy_authentication


Statistical criteria (correlation) for aggregating two items together in psychology?

Question: I have a question regarding item aggregation. I have conducted a study where I measured 4 items. Two of these items are conceptually linked together and seem to measure the same dimension, and the other two are also conceptually linked and I would also say they measure a similar dimension.
However, when I check correlation two by two for these items, they are only around 0.4 (in both cases).
I wondered if there existed any articles or references that talked about this issue or gave recommendations on what is an appropriate correlation strength in order to aggregate two items together.
Thank you in advance for your answer !
Comment: You could consider [factor analysis](https://en.wikipedia.org/wiki/Factor_analysis), although I should caution that since you've already explored the data somewhat you are better off taking an [EFA](https://en.wikipedia.org/wiki/Exploratory_factor_analysis) rather than [CFA](https://en.wikipedia.org/wiki/Confirmatory_factor_analysis) approach. You should be careful to avoid [HARKing](https://en.wikipedia.org/wiki/HARKing) and [data dredging](https://en.wikipedia.org/wiki/Data_dredging) at this juncture of your research.
Comment: I am unsure that EDA has no effect on HARKing. Here are a couple of related articles: [Gelman 2013](http://www.stat.columbia.edu/~gelman/research/unpublished/p_hacking.pdf) and [Pu & Kay 2019](https://www.mjskay.com/papers/beliv2018-forking-paths-in-vis.pdf)
Answer: You could look into innumerable sources on scale development, psychometrics, validity (including construct validity) and reliability.  There are websites, books, and articles galore.  You could search for posts on this site.
But no matter what you might find is commonly done, will you feel you have made adequate use of your data (which I presume took some time, effort, and resources to generate and collect) if you combine, by averaging or otherwise, scores that explain only about 1/6 of the variance in each other?  As for the remaining 5/6 of the information, you will essentially be throwing it away.
No matter what your motivation for combining, your results so far tell you that these items are largely measuring different things, supplying different types of information.  Without a strong reason otherwise, you should honor those different "roles" they play by including the items as separate variables in your main analysis.  That is, if you include the items at all.  Perhaps you will determine, from other investigation, that one or more of them is not a sufficiently valid or reliable indicator of any construct relevant to your research.  But then you would be throwing its information away for a sound reason.
Comment: why is this answer downvoted?
Answer: You could consider factor analysis, although I should caution that since you've already explored the data somewhat you are better off taking an EFA rather than CFA approach. You should be careful to avoid HARKing and data dredging at this juncture of your research.
Comment: Hello Galen, this is before carrying out hypotheses tests so HARKing should not be an issue. This is just to know what would be the best way to analyze my data (either the 4 items separately, or by aggregating the items two by two). Since correlations are not that strong I am not sure what I should do. I have also done an exploratory factor analysis and find the two expected factors (though the loadings are only around .6 for each item). I think I still would need references in order to justify any choice I make regarding this.
Comment: @ERMM I am unsure that "*this is before carrying out hypotheses tests so HARKing should not be an issue*" is sufficient. I'll think about it some more. Here are a couple of related articles [Gelman 2013](http://www.stat.columbia.edu/~gelman/research/unpublished/p_hacking.pdf) and [Pu & Kay 2019](https://www.mjskay.com/papers/beliv2018-forking-paths-in-vis.pdf).


Problem about evaluating $\int_0^1 {3x^3 -x^2 +2x -4\over \sqrt {x^2-3x+2} } \; dx $

Question: $$\int_0^1 {3x^3 -x^2 +2x -4\over \sqrt {x^2-3x+2} } \; dx $$
I tried to solve it but I couldn't get the right procedure..
I need help how should I start.
Answer: Let $f:\Bbb R\setminus\{1, 2\}\to \Bbb R$ denote the integrand. We have
$$f(x)=\frac{3x^3-x^2+2x-4}{\sqrt{(x-\frac32)^2-\frac14}}.$$
By substituting $x_{\text{new}}=x_{\text{old}}-\frac32$, we have (looking at indefinite integrals)
$$\int f(x)\,\mathrm dx = \int \frac{3(x+\frac32)^3-(x+\frac32)^2+2(x+\frac32)-4}{\sqrt{x^2-\frac14}} \,\mathrm dx.$$
Now we can use standard trigonometric substitution to deal with the square root in the denominator:
Substitute $u=\operatorname{arcsec}(2x)$. Then $$\sqrt{x^2-\frac14}=\frac{\tan(u)}2$$ and $$x=\frac{\sec u}2$$ so $$\mathrm dx \sim \frac12 \tan(u)\sec(u)\,\mathrm du.$$
Using this in our integral and doing some calculations we see that $$\int f(x) \,\mathrm dx = \frac18\int3 \sec^4(u)+ 25 \sec^3(u)+77\sec^2(u)+55\sec(u)\,\mathrm du.$$
Can you finish from here? (Hint: Use this)
EDIT: For the improper definite integral I got $$-\frac1{16}\cdot\left(202\sqrt 2+ 135 \ln(3-2\sqrt 2)\right).$$
Answer: Hint: try with substitution $$\sqrt{x^2-3x+2}=x+t$$ than explicate $x$ in function of $t$ and obtain a fraction integral.


Using a variable inside of a Jquery Selector

Question: I am trying to use a variable inside of a JQuery Selector in conjunction with an Id to select the proper input value since I have multiple forms. How can I use a variable and an id selector together?
My Code:
$("form").submit(function() {
    var id = $(this).attr("id"); //this grabs the id of the form being submitted
    var name = $("id #name").val();    <-- this is the line in question
});

Thanks!
Comment: By using standard javascript string-concatenation, `$('#'+id+' #name').val();`
Comment: Given that `id` is supposed to be unique, you can just say `$("#name").val()`.
Comment: Why do you grab the form id? You can use the submitted form element.
Answer: Since IDs are supposed to be unique, all you really need is $('#name').
In any case, if you want to find an element inside another one and you already have a reference to that element, don't concatenate selectors (what if the element does not have an ID?). Use traversal methods instead, such as .find. For example:
var value = $(this).find('input[name="name"]').val();

Have a look at all the traversal methods: http://api.jquery.com/category/traversing/tree-traversal/.
In case you really have to build a selector dynamically, use string concatenation, as already mentioned. A selector is nothing but a string. Example:
$('input[name="' + inputName + '"]')

Comment: +1. I was almost finished typing a comment about using `'input[name="name"]'` when you edited it in.
Answer: You're simply concatenating a string:
id + ' #name'

which makes
var name = $(id + " #name").val();

which is odd, because id is probably not an element, so you'll need to add a #:
'#' + id + ' #name'

which is still odd, because you're using id's strangely.
Answer: Simply build up the selector string like any other string:
var name = $("#" + id).val();

Answer: You can concatenate the string to create the right selector, or you can use the way:
$('#name', this).val(), that is the same as write $(this).find('#name').val()


Which notes can you double in a IV6 chord built on raised ^6?

Question: In the progression from IV6 to V65 in minor you need to raise both scale degree 6 and 7 but what notes can you double in the IV6 chord? Could the raised note be doubled in the upper parts or is this avoided? What is the best option?
Answer: I guess you mean the subdominant 36-chord by IV6 (and not the sixte ajoutée). I also suppose you mean the raised third in the IV6 chord. Then you can double any note, but it traditionally considered preferable not to double the third (which is in the bass), unless you need to to avoid parallels or bad intervals (which usually happens when you have chains of 6-chords. Thus you are not allowed to double leading tones.
So in this case you could say that it is somewhat nescessary to double the third (unless you want to allow for jumps in voices), as if you double a note in a different octave, you get:
A doubled root, so one root has to ascend into the root of the dominant. Thus the fifth of the subdominant has to fall into the third of the dominant, which is a leading tone and must not be doubled.
Or a doubled fifth, one of which has to fall into the third of the dominant, which is again not allowed.
If you double one note in the same octave you could have for the subdominant the fifth once and above the root twice. This could then go into fifth, seventh and root of the dominant, but this will not sound very elegant, as all voices move upwards.


Simplifying logarithm question

Question: Without worrying about the background, I have a question that asks to solve for n. Pardon my formatting, but it seems understandable this way for the time being until I edit it:
$$4n^2 = 256 \log_2n$$
I'm not looking for the answer (it's 16), but I want to know the process to begin simplifying the right side.
Thank you in advance
Answer: One way to solve it :
Since $n$ is an integer, and you have a base-2 $log$, then $n$ can be written as : $$n = 2^{k}$$ with $k > 0$ (at first).
After rearranging the initial expression, you end up with :
$$k = 2^{2k-6}$$
Now, you can see that :
$k > 3$ and $k$ is even. So, if you try with $k=4$... $$2^{2*4 -6} = 2^{8-6} = 2^2 = 4 = k$$
And since $n=2^k$, you have $n=2^4= 16$.
Comment: Thank you, I see how this works. But I think the key is "so, if you try with..." - that's how I got 16 in the first place. Is there an algebraic way of simplifying this equation instead of guess and check?
Comment: @user246854 In general, there is no simple way of solving the equation. Equations of this type often do not have integer solutions. The method described is not really that bad, since you need to solve the equation $k=2^{2k-6}$, and you know that sooner or later, $2^{2k-6}$ will grow faster than $k$, so you only have a finite number of values to check.
Comment: Yes. Besides using the Lambert W function (used by g.kow in his answer), there is no simple way in general.
Answer:
\begin{align} 4n^2 &= 256 \log_2n \end{align}

This kind of equations can be solved in terms of the Lambert W function,
which provides a solution to equation of the form $x\exp(x)=y$
as $x=\operatorname{W}(y)$, hence we need
to rearrange the terms in original equation
in order to group terms $x$ and $\exp(x)$ together:
\begin{align}
n^2 &= 64 \frac{\ln(n)}{\ln(2)} \\
\ln(n) n^{-2} &=  \frac{\ln(2)}{64}\\
-2\ln(n) n^{-2} &=  -\frac{\ln(2)}{32}\\
\ln(n^{-2}) n^{-2} &=  -\frac{\ln(2)}{32}\\
\ln(n^{-2}) \exp(\ln(n^{-2})) &=  -\frac{\ln(2)}{32}\\
\ln(n^{-2}) &= \operatorname{W}\left(-\frac{\ln(2)}{32}\right) \\
n^{-2} &= \exp\left(\operatorname{W}\left(-\frac{\ln(2)}{32}\right)\right) \\
n &=\exp\left(-\frac{1}{2}\operatorname{W}\left(-\frac{\ln(2)}{32}\right)\right) \\
\end{align}
Since $-\mathrm{e}^{-1}<-\frac{\ln(2)}{32}<0$,
there are two real solutions, corresponding
to the two real branches of the Lambert W function,
$\operatorname{W}_0$ and $\operatorname{W}_{-1}$:
\begin{align}
n &=\exp\left(-\frac{1}{2}\operatorname{W}_{0}\left(-\frac{\ln(2)}{32}\right)\right)
\approx 1.01113448176 \quad (1)\\
n &=\exp\left(-\frac{1}{2}\operatorname{W}_{-1}\left(-\frac{\ln(2)}{32}\right)\right)
=16 \quad (2).
\end{align}
In case if the solution has to be an integer,
(1) has to be ignored.
But the second solution is exact and integer,
since
\begin{align}
\operatorname{W}_{-1}\left(-\frac{\ln(2)}{32}\right)
&=
\operatorname{W}_{-1}\left(-\frac{1}{128}\ln(16)\right)
\\
&=
\operatorname{W}_{-1}\left(
-2\ln(16)\exp(-2\ln(16))
\right)
=-2\ln(16).
\end{align}

Simplifying logarithm question


How to setup sorbet to work with a Rails 7 application?

Question: note: I'm not using and I want to know if it is possible without sorbet-rails.
I'm trying to add sorbet to an existing/standard Rails 7 application.
I followed the instruction here: https://sorbet.org/docs/adopting.
I added the gems to the Gemfile followed by bundle install.
gem 'sorbet', :group => :development
gem 'sorbet-runtime'
gem 'tapioca', require: false, :group => :development

After that:
bundle exec tapioca init
bin/tapioca dsl
bin/tapioca gem
bin/tapioca require
bin/tapioca gem --all
bin/tapioca annotations

After running all that, if I ran bundle exec srb tc, I get about 23 errors. Most of them related to generated rbi files. For exemple:
...
sorbet/rbi/dsl/sessions_controller.rbi:19: Unable to resolve constant ActionHelper https://srb.help/5002
    19 |    include ::Turbo::Streams::ActionHelper
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sorbet/rbi/dsl/rails/conductor/base_controller.rbi:22: Unable to resolve constant ActionHelper https://srb.help/5002
    22 |    include ::Turbo::Streams::ActionHelper
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sorbet/rbi/dsl/rails/conductor/base_controller.rbi:22: Unable to resolve constant ActionHelper https://srb.help/5002
    22 |    include ::Turbo::Streams::ActionHelper
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sorbet/rbi/dsl/rails/conductor/action_mailbox/incinerates_controller.rbi:19: Unable to resolve constant ActionHelper https://srb.help/5002
    19 |    include ::Turbo::Streams::ActionHelper
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sorbet/rbi/dsl/rails/conductor/action_mailbox/incinerates_controller.rbi:19: Unable to resolve constant ActionHelper https://srb.help/5002
    19 |    include ::Turbo::Streams::ActionHelper
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Errors: 23

After applying a workaround for the Turbo issues described here (https://github.com/Shopify/tapioca/issues/671), I'm left with issues related to .require method not found.
app/controllers/people_controller.rb:48: Method permit does not exist on String component of T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) https://srb.help/7003
    48 |    params.require(:person).permit(
                                    ^^^^^^
  Got T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) originating from:
    app/controllers/people_controller.rb:48:
    48 |    params.require(:person).permit(
            ^^^^^^^^^^^^^^^^^^^^^^^
  Did you mean format? Use `-a` to autocorrect
    app/controllers/people_controller.rb:48: Replace with format
    48 |    params.require(:person).permit(
                                    ^^^^^^
    https://github.com/sorbet/sorbet/tree/c77e3a550a6bb9c1a0772fabf433d6763a86f33d/rbi/core/kernel.rbi#L1547: Defined here
    1547 |  def format(format, *args); end
            ^^^^^^^^^^^^^^^^^^^^^^^^^

app/controllers/people_controller.rb:48: Method permit does not exist on Numeric component of T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) https://srb.help/7003
    48 |    params.require(:person).permit(
                                    ^^^^^^
  Got T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) originating from:
    app/controllers/people_controller.rb:48:
    48 |    params.require(:person).permit(
            ^^^^^^^^^^^^^^^^^^^^^^^
  Did you mean format? Use `-a` to autocorrect
    app/controllers/people_controller.rb:48: Replace with format
    48 |    params.require(:person).permit(
                                    ^^^^^^
    https://github.com/sorbet/sorbet/tree/c77e3a550a6bb9c1a0772fabf433d6763a86f33d/rbi/core/kernel.rbi#L1547: Defined here
    1547 |  def format(format, *args); end
            ^^^^^^^^^^^^^^^^^^^^^^^^^

app/controllers/people_controller.rb:48: Method permit does not exist on T::Array[T.untyped] component of T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) https://srb.help/7003
    48 |    params.require(:person).permit(
                                    ^^^^^^
  Got T.any(String, Numeric, T::Array[T.untyped], ActionController::Parameters) originating from:
    app/controllers/people_controller.rb:48:
    48 |    params.require(:person).permit(
            ^^^^^^^^^^^^^^^^^^^^^^^
  Did you mean format? Use `-a` to autocorrect
    app/controllers/people_controller.rb:48: Replace with format
    48 |    params.require(:person).permit(
                                    ^^^^^^
    https://github.com/sorbet/sorbet/tree/c77e3a550a6bb9c1a0772fabf433d6763a86f33d/rbi/core/kernel.rbi#L1547: Defined here
    1547 |  def format(format, *args); end
            ^^^^^^^^^^^^^^^^^^^^^^^^^
Errors: 3

Is there anything missing? What is the proper way of doing this?
Note: workaround for the .permit issue can be found here https://github.com/Shopify/tapioca/issues/1122
Answer: The turbo ones are a known issue, you can take a look at https://github.com/Shopify/tapioca/issues/671 for a workaround.
Comment: Thank you. That works for the turbo issue. I'm only left with the `.permit` missing after applying `.require` on `params`.
Comment: To fix the .permit issue, I had to apply the following workaround: https://github.com/Shopify/tapioca/issues/1122


Calcular o tempo decorrido após criação de um registro

Question: Gostaria de saber como calcular o tempo entre a criação de um registro (created_at) e o horário atual. Meu intuito é exibir essa diferença em segundos, minutos, horas ou dias que isso ocorreu.
Existe algum método/gem para realizar essa tarefa?
Answer: Resolvi a questão utilizando o seguinte método time_ago_in_words
Em sua view utilize o código:
há <%= time_ago_in_words(notification.created_at) %>

Caso sua data passada como parâmetro no método seja 19:00 13/12/2017 e o horário atual seja 19:07 13/12/2017, o resultado será: há 07 minutos. Funciona também quando a diferença é para segundos, horas e dias.


Calculus Trigonometric Integral

Question: I have been trying to solve this particular problem and can not figure out where I have gone wrong in my solution. This is a picture of my solution, if anyone could help point out where I have gone wrong it would be appreciated.
http://i.imgur.com/j0xGdM3.jpg
Comment: I know that by expanding the correct solution out I get the same expression that I arrive at but it also has (-3/16) added onto it. So clearly I've lost information somewhere along the way, but I can't figure out how!
Answer: First of all, your expression in your answer is not necessarily different from the answer.  Use the double-angle formula twice to try to recover an expression in terms of powers of $\cos{x}$.  But an easy way to see how the given answer is generated is by substitution:
$$\int dx \cos^2{x} \, \sin{2 x} = 2 \int dx \, \sin{x} \, \cos^3{x} = -2 \int d(\cos{x}) \, \cos^3{x} = -\frac12 \cos^4{x} + C$$

Calculus Trigonometric Integral


react navigation how to pass navigation object to tabBarButton?

Question: I am using create Bottom Tab Navigator , version 6 , is there a way to pass navigation object from Tab.Screen to TabButton ?  taking in account props of tabBarButton  that I must also pass them to my custom component (TabButton) , here is my code thanks for your help :
 <Tab.Screen key={index} name={item.route} component={item.component}
            options={{
              headerShown: false,
              tabBarButton: (props) => <TabButton {...props} item={item} />
            }}
          />

Answer: you can pass navigation and tabBarButton props in this way,
The options function receives the navigation prop and the route prop for that screen, so you may also use route there.
 <Tab.Screen key={index} name={item.route} component={item.component}
    options={({ navigation }) => ({
       headerShown: false,
       tabBarButton: (props) => <TabButton {...props} navigation={navigation} item={item} />
    })
  }
  />

Comment: this did not work with me
Comment: can you please share what issue you are facing after with this solution
Comment: you are right , it was a typo error :) thanks
Answer: I just added a global variable and affect  to it props.navigation , like so :
  return (
          <Tab.Screen key={index} name={item.route} component={item.component}
            options={( props ) => {
              _navigation = props.navigation
              return{
                tabBarButton: (props) => <TabButton {...props} item={item} navigation={_navigation} />
              }
            }
          }
          />
        )

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Here's the example how you can do it
      <Stack.Screen
        name={"ComponentName"}
        component={ComponentScreen}
        options={(props) => {
          return {
            header: () => (
              <CustomHeaderComponent
                title={"SomeCoolTitle"}
                {...props}
              />
            ),
          };
        }}
      />

Comment: thanks @szymekk147 for your reply , in your example what if I want also pass props of header ? , I mean passing props of header and Stack to CustomHeaderComponent?


Error : Index was outside the bounds of the array, String array

Question: After trying a few error checking methods I have come to the conclusion I need help solving this problem.
How am I not catch this "index out of range" error and what can i do to avoid this problem in the future.
string line = Console.ReadLine();
string[] nums = line.Split();
int m = Convert.ToInt32(nums[0]);
int n = Convert.ToInt32(nums[1]);
int k = Convert.ToInt32(nums[2]);
int[,] a = new int[m, n];
Input(a);
static void Input(int[,] a)
{
    for (int i = 0; i < a.GetLength(0); i++)
    {
        string[] nums = Console.ReadLine().Split();
        {
            for (int j = 0; i < a.GetLength(1); j++)
            {
                a[i, j] = int.Parse(nums[j]); // where i get the problem //
            }
        }
    }
}

Comment: You're getting an `IndexOutOfRangeException` but you haven't told us what the index is or the range, which suggests that you haven't actually determined that for yourself. You need to debug your code first.
Comment: Classic C&P Error.
Answer: for (int j = 0; i < a.GetLength(1); j++)

Look very carefully at that line. One of these things is not like the others.


How can I use perl debuggers pretty print for a hash in normal program code?

Question: In Perl debugger you can very nice output a hash like:
  DB<1> x \%my_hash

How can I use the debugger output method 'x' in my programm to log pretty formated hash data in my logfile?
Comment: Use `Data::Dumper` instead?
Answer: Use Data::Dumper. It is a core module, so no installation required. It is a good debugging tool.
use Data::Dumper;

...

print Dumper \%my_hash;

Comment: Holy Bat Crapman!  TY!
Comment: @DanielSantos You're welcome. A bit unexpected after 8 years. :)


Jquery click event doesnt work

Question: Click event doesn't work... use Angular with Jquery, have multiple click events in the file, but this one particular doesn't work

Comment: There's a good chance your angularjs hasn't executed by the time jquery tries to attach the event handler.
Comment: Are you getting any errors?
Comment: No no errors, when paste the code into the console, it works, when do it from editor, it doesnt
Comment: This example works https://jsfiddle.net/aesL4jjh/
Comment: @JAT yeap it does...
Comment: @Jack possibly to put .on(click)...
Comment: how can I attach the event handler after the Angular is done loading...?
Answer: I'd do this "the angular way":

In your css
li{
transition: opacity .5s;
}

.fadedout{
opacity: 0;
}

Or actually use ng-show and ng-animate: http://www.nganimate.org/
Answer: Does it work if you try it like this?
 $(document).ready(function(){

    $(".phone-tumbs").on('click', '.additionalImgs',function(){
        $(this).fadeOut();
    });

});

Comment: no it didn't I tried with binding before, it really got to work cause it binds it after everything is loaded but for some hell reason it doesnt
Answer: I just ran into this same problem.
Your code is fine, see this fiddle
The problem, like one of the comments mentioned, is that angular hasn't finished rendering the element.
You can see this by running the jQuery function right above your click function. You'll see the length is 0.
console.log($(".additionalImgs"));

So now you have to find a way to delay the binding of your click event until you know the element is actually there.
Unfortunately this is an area that Angular doesn't handle very well. You can read more about it in this feature request
The first thing I always try is using $timeout. It waits until the end of the digest cycle to fire it's callback code, even if you leave the time empty
$timeout(function(){
     $(".additionalImgs").click(function() {
          $(this).fadeOut();
     });
});

This blog post has a nice solution, creating a directive that fires a callback when the last ng-repeat element has been rendered. http://www.nodewiz.biz/angular-js-final-callback-after-ng-repeat/
The easiest solution to this particular problem is to use ng-click on your ng-repeat element.

Jquery click event doesnt work


Variance and covariance in the context of deterministic variables

Question: Questions:

Can we talk about:
variance of a deterministic variable?;
covariance between a deterministic variable and a stochastic variable?;
covariance between two deterministic variables?
Are these concepts well defined in sample?; in population?

Motivation
Take a simple regression
$$y = \beta_0 + \beta_1 x + \varepsilon.$$
Suppose the regressor $x$ is stochastic. The OLS estimate of $\beta_1$ will be
$$\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$$
where hats denote sample counterparts of the population concepts. No problem here.
Now suppose $x$ is deterministic. I am not sure if I can use terms like variance and covariance in this context. Should I exchange $\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$ for something like
$$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum(x_i-\bar{x})(y_i-\bar{y})}{\frac{1}{n-1}\sum(x_i-\bar{x})^2}$$
to be correct? But then again, how meaningful is $\bar{x}$ when $x$ is deterministic? So should I go all the way to
$$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum_{i=1}^n(x_i-\frac{1}{n}\sum_{j=1}^n x_j)(y_i-\frac{1}{n}\sum_{j=1}^n y_j)}{\frac{1}{n-1}\sum(x_i-\frac{1}{n}\sum_{j=1}^n x_j)^2}?$$
I am picking on details here and this may not be too important; my main questions are listed at the top of the post.
Answer: All five questions have "yes" answers--but we have to be careful about what they mean.

"Variance of a deterministic variable."
Let's understand a "deterministic variable" to be a univariate dataset.  It's just a bunch of values $X=x_1, x_2, \ldots, x_n$, with no probability model.  By definition its variance is
$$\text{Var}(X) = \frac{1}{n}\sum_{i=1}^n \left(x_i - \bar X\right)^2$$
where $$\bar X = \frac{1}{n}\sum_{i=1}^n x_i$$ is its mean.  There is no justification whatsoever to use $n-1$ instead of $n$ in any of these fractions--and this is never legitimately done--because no estimates are being made.
We may always think of $X$ as defining a "population."  This is the definition of a population variance.
"Covariance between a deterministic variable and a stochastic variable."
One way to understand this is to assume it refers to a sequence of the form $(x_1, Y_1), (x_2,Y_2), \ldots, (x_n,Y_n)$ where the $x_i$ are numbers and the $Y_i$ are random variables.  Then we may define the random variable $$\bar Y = \frac{1}{n}\sum_{i=1}^n Y_i,$$ via which the covariance of $x$ and $Y$ is defined as
$$\text{Cov}(x,Y) = \frac{1}{n}\sum_{i=1}^n (x_i - \bar x)(Y_i - \bar Y).$$
It is a linear combination of the $Y_i$ and consequently is itself a random variable.  This notation is frequently used as a shorthand in linear regression calculations.
"Covariance between two deterministic variables."
"Two deterministic variables" can be considered a dataset of ordered pairs $(x_1, y_1), (x_2,y_2), \ldots, (x_n,y_n)$.  The covariance can be defined exactly as in (2) and interpreted similarly.  In fact, this is a direct consequence of (1): after all, covariances are variances.
"Are these concepts well defined in samples?"
Because they are well-defined for any dataset, they are well-defined for a sample.  Note that similar expressions with $n-1$ in the (outer) denominator are estimators: they are not the sample variance or sample covariance.
"Are these concepts well defined in populations?"
Because they are well-defined for any dataset, and a population can be considered a dataset (when fully enumerated), they are well-defined for a population.
Comment: Can you please explain how we would use these definitions to calculate the correlation between $X$ and $Y$ when $(X_i, Y_i)=(Z_1+i, Z_2+i)$ with $Z_1, Z_2 \overset{\mathrm{i.i.d.}}{\sim}\mathcal{N}(0, 1)$ for deterministic $i=1,\ldots,n$?
Comment: @Statmerkur The bilinearity of covariance implies the addition of $i$ does not change the covariance, while the independence of the $Z_i$ implies that covariance must either be $0$ or undefined.  Because the $Z_i$ have finite variances, the covariance will be $0.$
Comment: Thank you. However, if I understand you correctly, the correlation estimate in this little `R` simulation `n <- 100; cor(rnorm(n) + 1:n, rnorm(n) + 1:n)` should be close to $0$  -- but it is actually close to $1$. The latter does make sense to me as the two sequences are identical up to a small noise component.  Am I getting something wrong here?
Comment: @stat You don't understand correctly if you expect that correlation to be near $0,$ but I cannot guess what the nature of the misunderstanding might be.
Comment: I don't expect that correlation to be near $0$. Rather, I'm interested in how one would calculate the expected correlation in such a case. I was then confused about what you said above since, I thought, by the same reasoning the correlation between $X$ and $Y$ when $(X_i, Y_i)= (Z_{1,i}+i,Z_{2,i}+i)$ with $Z_{1,i}, Z_{2,i}\overset{\mathrm{i.i.d.}}{\sim}\mathcal{N}(0,1);i=1,\ldots,100$ would also have to be $0$. And I think the `R` code calculates the correlation in one particular realization of this sequence.
Comment: @Stat The rules of covariance continue to apply.  The `R` code treats `1:100` as the equivalent of its empirical distribution.  You can confirm this by computing the covariance directly or using bilinearity: `x <- rnorm(n);
y <- rnorm(n);
z <- 1:n;
(c(Covariance=cov(z+x, z+y), Sum=cov(z, z) + cov(z, y) + cov(z, x) + cov(x, y)))`
Comment: That makes sense to me. In your definition, the covariance between a deterministic variable and a random variable is itself a random variable. Taking expectations, we get $\mathbb{E}[\mathrm{Cov}(X,Y)] = \mathrm{Var}(S)$ and $\mathbb{E}[\mathrm{Var}(X)]=\mathbb{E}[\mathrm{Var}(Y)]=1+\mathrm{Var}(S)$, where $S=1,\ldots,n$. But the expected correlation between $X$ and $Y$, as the expectation of a ratio distribution, doesn't seem to be immediately available. Am I right here?
Comment: @stat By definition, all covariances are *numbers.*
Comment: You wrote "the covariance of $x$ and $Y$ is defined as [...]. It is a linear combination of the $Y_i$ and consequently is itself a random variable." in your original answer. So I'm a little bit confused now.
Comment: @stat I agree.  Consider asking a specific question in a new thread.  Please note that the present thread concerns several distinct settings in which "covariance" has distinct meanings.  You have to pay attention to which setting you are in and what exactly you mean by "covariance"!
Answer: The simple answer to your first three questions is no: it makes no sense in general to talk about variance or covariance involving a deterministic variable.
However, if we begin with a deterministic variable but then use some method of imposing a probability distribution on it, it then becomes a random variable, and the concept of variance then makes sense. For example, any deterministic variable can become a random variable simply by imposing a degenerate (i.e., constant) distribution on it; in this case, the variance (along with its covariance with any other random variable) becomes 0.
A more interesting way of imposing a distribution on deterministic random variables is to use the empirical distribution, based on an observed sample. That is, if you observe $x_1,\dots,x_n$ in a sample, then we can define a discrete probability distribution on $x$ by $$P(x=x_0)=\frac1n \cdot\text{the number of $i$ such that $x_i=x_0$}$$
for all $x_0$. For example, in the case where $x_1,\dots,x_n$ are all distinct, we get $P(x=x_i)=\frac1n$ for each $i=1,\dots,n$. If we use this probability distribution on $x$, then the mean of $x$ becomes simply the sample mean $\overline x=\frac1n\sum_{i=1}^n x_i$, and the variance of $x$ becomes $\hat\sigma^2=\frac1n\sum_{i=1}^n (x_i-\overline x)^2$.
This same idea can be applied in the situation where we have observed vectors $(x_1,y_1),\dots,(x_n,y_n)$. We can define a joint probability distribution on $(x,y)$ again by using the empirical distribution, and the covariance between $x$ and $y$ then becomes $$\text{Cov}(x,y)=\frac1n\sum_{i=1}^n (x_i-\overline x)(y_i-\overline y)$$


Comparar primeiros caracteres de duas colunas distintas em excel

Question: Existe alguma função no excel que me permita comparar os primeiros n caracteres de texto que eu quiser?
<code>Por exemplo

Tenho a palavra Joaquim e Joana, comparo por "Joa" e ele me retorna verdadeiro ou falso.
</code>
Comment: Você pode usar a função `=EXT.TEXTO()`, para extrair a quantidade de caracteres de uma string e posteriormente usar a função `=EXATO()` para comparar duas strings
Answer: Fórmula utilizada:

Resultado obtido:
Comment: Muito obrigado!!!


If $\phi$ is an automorphism of the group $\Bbb R^+$ under multiplication satisfying $\phi(4)=7$, then find $\phi(2)$.

Question:
Let $\Bbb R^+$ denote the real numbers. Suppose $\phi:\Bbb R^+\to\Bbb R^+$ is an automorphism of the group $\Bbb R^+$ under multiplication with $\phi(4)=7$.
Find $\phi(2)$, $\phi(8)$, and $\phi(1/4).$

I've done this problem in groups of integers modulo $n$ but I am not sure how to start here.  Please explain what $\phi(4)=7$ is.
Thank you!
Comment: Hint: $\phi(1) = 1$ and $1=x \cdot \frac{1}{x}$. This, plus the homomorphism property should get you there.
Answer: If $\phi(4)=7$, then $7=\phi(4)=\phi(2\cdot 2)=\phi(2)\phi(2) = \phi(2)^2$.  Can you take it from there?
Comment: got it! thanks just needed to get started.  I didn't think it was that easy.
Answer: Hint If $a \in \Bbb R^+$ satisfies $a^2 = 4$, then because $\phi$ is a homomorphism, we have
$$\phi(a)^2 = \phi(a^2) = \phi(4) .$$
It's interesting to note that we cannot, however, conclude the value of, e.g., $\phi(3)$ from the given information.

Additional hint To compute $\phi\left(\frac{1}{4}\right)$ it will be useful to recall that any homomorphism maps the identity to the identity.
Comment: Thanks. I just need to see that to get started!
Comment: You're welcome, I'm glad you found it helpful!


Give a role permission to add and edit their terms in a taxonomy

Question: In Drupal 7 I am trying to give users the ability to add terms to a taxonomy and then edit only the terms they have created.
I'm using the Taxonomy access fix module to give users permission to add terms in specific taxonomies. However, Drupal does not provide an "edit own terms" permission like it does for nodes. Users can either edit all terms in the taxonomy, or not have editing permission.
Is there any solution for this?
Answer: If drupal doesn't provide any "edit own terms" permission, then better do it programatically if you wish.
While accessing term page, load/check for the owner of term and allow them to access edit page.
Answer: There are a number of modules that do this that can be found through a simple google search.
https://www.google.com/search?num=100&q=taxonomy+access+drupal+permissions&oq=taxonomy+access+drupal+permissions
This looks great https://www.drupal.org/project/taxonomy_access


Implementing Hover Intent

Question: I just finished developing this Wordpress theme:
http://www.minnesdiner.com/
Everything is working well, but I'm not 100% happy with the navigation.
The sliding position indicator works smoothly, but I'd like to integrate the hover intent jQuery plugin to prevent the sliding indicator from sliding when the user unintentionally passes over the nav.
Any ideas as to how I could integrate this plugin? I'm currently firing a separate jQuery function for each nav item and passing coordinates to the sliding indicator based on which item is being hovered upon.
Here's my current jQuery code:
 $(document).ready(function() {

        var $currentpos = $("#menu-indicator").css("left");
        $("#menu-indicator").data('storedpos', $currentpos);

        $(".current-menu-item").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: $currentpos}, 150);
        });
        $(".menu-item-26").delay(500).mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "52px"}, 150);
        });
        $(".menu-item-121").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "180px"}, 150);
        });
        $(".menu-item-29").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "310px"}, 150);
        });
        $(".menu-item-55").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "440px"}, 150);
        });
        $(".menu-item-27").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "570px"}, 150);
        });
        $(".menu-item-164").mouseenter(function () {
        $("#menu-indicator").stop().animate({left: "760px"}, 150);
        });

        $delayamt = 400;
        $("#header-row2").click(function () {
        $delayamt = 5000;
        });
        $("#header-row2").mouseleave(function () {
        $("#menu-indicator").stop().delay($delayamt).animate({left: $currentpos}, 600);
        });

});

As you can see, I need to bind mousover and mouseout to separate elements (list-item and containing div).
Thanks!
Comment: Post your code, please. I've implemented something similar in another question, see if that helps: http://stackoverflow.com/questions/5697718/jquery-menu-hover/5697749#5697749
Answer: If all you want to do is avoid the user triggering the slide by mousing over the nav, I would just setTimeout in your hover function to call your sliding code after a certain amount of time has passed, and clear the timeout on the mouseout event. No extra plugin needed.
For example:
var hover_timer;
$('.menu-item').hover(
    function() {
        hover_timer = setTimeout(function() {
            ...
        }, 500);
    },
    function() { clearTimeout(hover_timer); }
);

EDIT: by the by, you should be combining all those hover functions into one. You can do something like:
$('.menu-item-26').data('slider-pos', '52px');
$('.menu-item-121').data('slider-pos', '180px');
...

And then in the code to slide, call it back:
$this = $(this);
$('#menu-indicator').stop().animate({left: $this.data('slider-pos')}, 150);

And that's just a start - you can generalize it even more, I bet.
Comment: Thanks! That seems like a good solution. Will I need to create a separate hover_timer variable for each menu item?
Comment: Ok... I tried to implement it. Anything look wrong here? http://www.minnesdiner.com/wp-content/themes/minnes_diner/inc/navigation_slider.js
Comment: you're only attaching the handler to `menu-item-26`. try `$('.menu-item')` instead
Comment: (ignore the comment that I just deleted :)
Comment: @coryetzkorn - eek, sorry, I had the arguments for `setTimeout` switched. Should work now.
Comment: I think we're close! http://www.minnesdiner.com/wp-content/themes/minnes_diner/inc/navigation_slider.js
Comment: Yup! so, the scope of `$list_item = $(this)` is wrong. You need to set it outside of the `setTimeout` function, just one level above. The reason is that inside `setTimeout`, `this` actually refers to `window`.
Comment: Beautiful! Thanks so much for your help. The site is now 100% how I imagined. Rock on!

Implementing Hover Intent


WPF MVVM table layout from data binding

Question: Lets suppose that I have the following models:
public class PageModel  //INotifyPropertyChanged...
{
    public int RowCount { get; set; }
    public int ColumnCount { get; set; }
    public ObservableCollection<BaseItemModel> PageItems { get; set; }
}

public abstract class BaseItemModel  //INotifyPropertyChanged...
{
    public string Name { get; set; }
    public int Row { get; set; }
    public int Column { get; set; }
}

public class ConcreteItem1 : BaseItemModel
{
    public bool Value { get; set; }
}

public class ConcreteItem2 : BaseItemModel
{
    public float Value { get; set; }
}

What I would like to do in WPF (without doing too much in the code-behind) is lay out the controls for the ConcreteItem1 and ConcreteItem2 in a table/grid format. The problem is I don't know how to approach this from a data binding standpoint.
It seems to me that UniformGrid would be the control of choice, but somehow embedding that as the layout for an items control?
What I'm aiming for is something like this:

Where the Rows/Columns is fixed and the controls scale to fill the available space.
So, how can I lay out controls data bound to a model in a table/grid format with fixed rows/columns?
Answer: Set the ItemsPanel property to an ItemsPanelTemplate with a UniformGrid that specifies the number of columns:
<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

The number of rows are dependant on the number of items in the ItemsSource.

WPF MVVM table layout from data binding


Avoid username output as a class of an article tag

Question: Drupal 7 generates a username class for the article tag, something like : class="node node-page node-published node-not-promoted node-not-sticky author-username odd clearfix".
I'd like to avoid to have the username output in the code for security reason.
I have tried the userone module, but it doesn't work for this.
I am thinking about some Jquery code, but a better way would be to avoid the username to be output at all.
I was looking in the core modules but I didn't find the php file that generates this author-[username] class.
Any help?
Answer: I think you can blame Omega for that one, in omega_alpha_preprocess_node() you'll find this:
$vars['attributes_array']['class'][] = drupal_html_class('author-' . $vars['node']->name);

I think you've got two options:

Remove that preprocess function altogether, using hook_theme_registry_alter(), and duplicate it into MYTHEME_alpha_preprocess_node(), minus the offending line.
Implement MYTHEME_alpha_preprocess_node(), search through the $vars['attributes_array']['class'] array, and remove it from there.
Answer: I can't see this class on clean drupal installation. check it here
so class generate on your theme and their templates. check node.tpl.php and remove statement that generate this class.
Answer: One solution is to add the following code in the template.php file of the Omega subtheme and the username class for the article tag in the HTML code will not be displayed (thank you @Jance):
function [MYTHEME]_preprocess_node (&$vars){
  $count = 0;
  foreach($vars['attributes_array']['class'] as $class){
  if(substr( $class, 0, 7 ) === "author-"){
  unset($vars['attributes_array']['class'][$count]);
  }
  $count += 1;
  }
}