t-test with logistic and Gumbel distributions

Question: I know that one of the basic assumptions of a t-test is that the data is drawn from a Gaussian distribution.
Using an Anderson-Darling test, I've found that the datasets I am working with are either drawn from a logistic distribution or a Gumbel distribution (both centered around 0, and both closely resemble a Gaussian).
I was wondering if I can safely use the two-sided t-test (e.g. the scipy.stats.ttest_ind function) with this type of distribution or is there another alternative to the two-sided t-test that is better recommended for the logistic and Gumbel distributions?
Comment: There are several different $t$-tests, including the one-sample $t$-test, the independent-samples $t$-test, and the dependent-sampels $t$-test. Which do you mean?
Comment: assuming that $x$ is uniformly distributed (perhaps under a null hypothesis), then IIRC $log(x/(1-x))$ is normally distributed.
Answer: The independent t-test is fairly robust to deviations from normality if they are not too severe and if the sample sizes are roughly equal and the variances roughly equal.
But, since there are many nonparametric tests of location, why not use one of them?
E.g. Mann-Whitney test, which tests whether a value from one sample is equally likely to be smaller or larger than a value from the other sample. (This test is also known as Wilcoxon Mann Whitney)
Answer: For something more-or-less like the logistic -- somewhat heavier tailed and peakier than normal, I'd suggest the Wilcoxon-Mann-Whitney test.
Firstly, it's distribution-free so the fact that you don't know the distribution isn't of much concern with regard to significance level.
Secondly, it has excellent power as a test of location shift (which is what I assume you're mainly concerned with) for distributions like the logistic. You'll be hard-pressed to beat it.
Unless you have a more specific comparison in mind (like "Well, actually I want to compare lower quartiles"), I think this one's almost a no-brainer.
That said, a t-test doesn't have bad power in this situation -- just a bit lower (e.g. the relative efficiency at a sample size of 30, when the Wilcoxon power is about 0.5 is in the ballpark of 95%). Its significance level is not much affected either -- it's just a little lower than the nominal level.

However, I must add a comment on your phrasing here (converting and expanding on a comment I made much earlier):

Using an Anderson-Darling test, I've found that the datasets I am working with are either drawn from a logistic distribution or a Gumbel distribution

No, you didn't find that. Failure to reject a logistic doesn't mean you actually have a logistic. Failure to reject a Gumbel doesn't mean you actually have a Gumbel.
The Anderson Darling test cannot tell you that data were drawn from some specific distribution. Indeed those unrejected nulls are almost certain to be false. (Further, because the logistic and Gumbel are very different, if there's any case where you fail to reject both, you haven't pinned down the distribution much at all.)


How to print table headers on multiple pages for Internet Explorer and Google chrome?

Question: I am working on a project in which I have to print data having multiple columns and rows.
I want to print headers on every printing page so that it will be easier to understand with the headers on every page. I know THEAD but it supports only Firefox. I want it for IE and chrome. Please help me.
Comment: This > http://stackoverflow.com/questions/7211229/having-google-chrome-repeat-table-headers-on-printed-pages would help you to make it happen.
Answer: http://www.evagoras.com/2011/02/10/printing-table-headers-on-every-page/
This link helped me to solve it.
It is running successfully on IE.

Thanks for all your responses.
Answer: Put your headers in an actual
 element. That seems to work for me in the past. I'm on my phone right now so cannot test it in the specific browsers you mentioned.
References

http://www.quackit.com/html/tags/html_thead_tag.cfm


Erro de bibliotecas java em projeto

Question: As bibliotecas do meu projeto não estão importando as classes do *util e outras várias também, não sei o que está havendo, pois quando crio um projeto novo essas classes e bibliotecas funcionam. Abaixo um print do erro.
Ja tentei dar Clean no projeto inteiro.
Comment: Vai em propriedades-> java--> jre---> e adiciona a JDK que o problema sera resolvido.
Comment: valeu amigo consegui resolver
Comment: Por gentileza poste a sua reposta como resposta, ao invés de comentário
Answer: Seu problema está relacionado a importação do jdk, faça isso em:
<code>Properties (do seu projeto) > Java Build Path > Libraries e informe o caminho do seu jdk.
</code>

Erro de bibliotecas java em projeto


Writing columnated data to a .txt file. C++

Question: I am extremely new to C++. I have been asked to write a text file that contains columns of data. Specifically four columns comparing the real value of exponential(x) with my series expansion function to multiple degrees. x will range from 0 to 1 at intervals of 0.04.
for example
  x | exp(x) | M1 | M2 | M3 |
  0 |   1    | 1  |  1 |  1 |
0.04|   1.15 |1.01|1.09|1.12|  (values in example are not exact)
 .  |
 .
 .

However I'm struggling to get my data into neat columns in the text (.txt) file and I simply don't know how to format it.
ExpSeries() is my series function.
int main()
{
    std::ofstream demoFile;
    demoFile.open("Test3.txt");
    if (!demoFile)
        return 1;
    double i = 0;
    //demoFile << exp(2) << std::endl;
    for (i = 0; i < 1; i = i + 0.04) {
        demoFile << exp(i);
        demoFile << ExpSeries(i, 2);
        demoFile << ExpSeries(i, 3);
        demoFile << ExpSeries(i, 4) << std::endl;
    }

    demoFile.close();
    return 0;
}

Comment: Take a look at [`std::setw`](http://en.cppreference.com/w/cpp/io/manip/setw).
Comment: Please dont edit the question after you got answers. Especially dont try to fix stuff you were actually asking for
Comment: There is also [Boost Format](http://www.boost.org/doc/libs/1_62_0/libs/format/doc/format.html), but that may be overkill for a beginner looking to achieve something quite simple.
Answer: You need to set the width of your output with setw parameter
use the same fixed value for every column.
Answer: If you use std::setw and std::setprecision from <iomanip> you can format it quite nice & easy.
demoFile << "  x  | exp(x) |  M1  |  M2  |  M3  |" << std::endl;
demoFile << "................................." << std::endl;

double i = 0;
for (; i < 1.0; i += 0.04){
    demoFile << std::setprecision(2) << std::fixed; //set some precision for nice format
    demoFile << std::setw(4) << i << " |";
    demoFile << std::setw(7) << exp(i) << " | ";
    demoFile << std::setw(4) << ExpSeries(i, 2) << " | ";
    demoFile << std::setw(4) << ExpSeries(i, 3) << " | ";
    demoFile << std::setw(4) << ExpSeries(i, 4) << " | ";

    demoFile << '\n';
}

Here you can see the ouput (just some example doubles, but same settings):
   x  | exp(x) |  M1  |  M2  |  M3  |
 .................................
 0.00 |   0.00 | 0.00 | 0.00 | 0.00 |
 0.04 |   0.08 | 0.12 | 0.16 | 0.20 |
 0.08 |   0.16 | 0.24 | 0.32 | 0.40 |
 0.12 |   0.24 | 0.36 | 0.48 | 0.60 |
 0.16 |   0.32 | 0.48 | 0.64 | 0.80 |
 0.20 |   0.40 | 0.60 | 0.80 | 1.00 |
 0.24 |   0.48 | 0.72 | 0.96 | 1.20 |
 0.28 |   0.56 | 0.84 | 1.12 | 1.40 |
 0.32 |   0.64 | 0.96 | 1.28 | 1.60 |
 0.36 |   0.72 | 1.08 | 1.44 | 1.80 |
 0.40 |   0.80 | 1.20 | 1.60 | 2.00 |
 0.44 |   0.88 | 1.32 | 1.76 | 2.20 |
 0.48 |   0.96 | 1.44 | 1.92 | 2.40 |
 0.52 |   1.04 | 1.56 | 2.08 | 2.60 |
 0.56 |   1.12 | 1.68 | 2.24 | 2.80 |
 0.60 |   1.20 | 1.80 | 2.40 | 3.00 |
 0.64 |   1.28 | 1.92 | 2.56 | 3.20 |
 0.68 |   1.36 | 2.04 | 2.72 | 3.40 |
 0.72 |   1.44 | 2.16 | 2.88 | 3.60 |
 0.76 |   1.52 | 2.28 | 3.04 | 3.80 |
 0.80 |   1.60 | 2.40 | 3.20 | 4.00 |
 0.84 |   1.68 | 2.52 | 3.36 | 4.20 |
 0.88 |   1.76 | 2.64 | 3.52 | 4.40 |
 0.92 |   1.84 | 2.76 | 3.68 | 4.60 |
 0.96 |   1.92 | 2.88 | 3.84 | 4.80 |

Answer: You can use setw to set the column width:
#include<iomanip>
using namespace std;
...
demoFile << setw(4) << exp(i);
demoFile << setw(5) << ExpSeries(i, 2);

You may also need to use std::fixed and std::precision to ensure the right number of decimal places.
Comment: Thanks guys, was a mixture of not knowing std::cout was doing (setw is much more self explanatory) and missing  when using the exponential function- silly mistake
Answer: In a string, you can use
    /t

Between variables. For example
  "exp(x) /t M1 /t M2"

The /t is a tab. @stack_danny is showing the proper way.


Putting two buttons into one UITableViewCell

Question: Hey guys, this is driving me absolutely crazy! Been searching for hours and can't seem to figure out a solution. Any ideas how to do something like this:

Notice how there are two buttons inside of the tableviewcell, asnd notice how the grouped tableview has a background.
Any ideas?
Thank you!
Comment: You cant make this kind of view using table view these are custom view on scrollView.
Answer: why you are thinking this is a uitableview.. you can easily implement this in uiscrolview.. just put a uiscroll view on uiview and put all the elements on it.. I have implemented several interfaces like you posted using uiscrollview... it will be very difficult to implement it in uitableview because .. when you touch on the tabs you need to open the new tab's interface and for that you have to reload the uitableview.. and manage all the interface.. which will be a pain ...
Comment: Yea that's what I was afraid of, that's a huge job to redesign it =S. Maybe we'll just do it in v2.0
Answer: Thats basically a UIView on a UIScrollView, no UITableView involved.


Prove that the vectors of the set is a basis.

Question: Let $1\leq n\in \mathbb{N}$. Let $\mathcal{E}:=(e_1, \ldots , e_n)$ the standard basis of $\mathbb{R}^n$. We define $\displaystyle{e_i':=\sum_{j=1}^ie_j}$.
I want to show also that $(e_1', \ldots , e_n')$ is a basis of $\mathbb{R}^n$.
For that we use induction.
Base case: Do we start from $n=3$ that we have above or from $n=1$ ?
Inductive Hypothesis: We assume that it holds for $n=k$.
Inductive Step: We want to show that it holds for $n=k+1$. Could you give me a hint how we can show that if we have an additional element and a higher dimension we get again a basis?
Comment: We cannot represent the vector $e_{k+1}$ with any linear combination of $e'_1, \cdots, e'_k$ but we can with $e'_1, \cdots, e'_k, e'_{k+1}$  Therefore $e'_{k+1}$ is independent from $(e'_1, \cdots, e'_k)$.  This shows that the vectors are independent.  And if we have $n$ of them, span the space.
Comment: Why not start from $n=1$ for the base case?  (I don't see $3$ above)
Comment: We can't represent the vector $e_{k+1}$ with any linear combination of $e_1', \ldots , e_k'$ because $e_{k+1}$ has a $1$ at the position $k+1$ but all the other vectors have there $0$, correct? So we use the inductive hypothesis to assume that the set $(e_1', \ldots , e_k')$ is linearly independent and since $e_{k+1}'$ is linearly independent from that set we get that the set $(e_1', \ldots , e_k', e_{k+1}')$ is linearly independent? @DougM
Comment: @J.W.Tanner Ah sorry, I forgot to add the part of the previous subquestion. It was: Let $n=3$. Calculate $e_1', e_2', e_3'$ and show that $(e_1', e_2', e_3')$ is a basis of $\mathbb{R}^3$. $$$$ But we start at the induction with $n=1$, or not?
Answer: It suffice to prove $\mathrm{rank}\{e_1', \cdots , e_n'\}=n$.
Consider the linear transformation bewteen these two sets of vectors:$$(e_1', \cdots , e_n')=(e_1, \cdots , e_n)\begin{pmatrix}
1 & 1 & 1 & \cdots & 1\\
0 & 1 & 1 & \cdots & 1\\
0 & 0 & 1 & \cdots & 1\\
\vdots & \vdots & \vdots & \ddots &\vdots \\
0 &  0& 0 & \cdots & 1
\end{pmatrix}=(e_1, \cdots , e_n)A.$$
Note that $\det A=1 \neq 0$. Therefore $\mathrm{rank}\{e_1', \cdots , e_n'\}=\mathrm{rank}\{e_1, \cdots , e_n\}=n$.
Comment: In that way we don't use induction, do we? This is an other way, or not?
Comment: Yes, it is. I think this is the most direct way to do it. You can also use induction. What you reply to Doug M is actually okay.


Diferenças de desempenho entre structs e classes

Question: Sei que a diferença de structs e classes é que structs tem seus membros públicos por padrão, e que structs pertencem a C (mas nada impede de usar em C++).
Na prática quando se cria um objeto para classes ou uma estrutura, quem é o mais lento? Qual vai ocupar mais memória? Quem tem seu acesso mais rápido?
Answer: Em C++ não há a menor diferença a não ser a já citada na pergunta, então não há como ter diferença de performance de qualquer tipo ou consumo de memória. Poderiam ter optado por não ter criado a palavra-chave class ou poderiam ter criado ela substituindo a struct, se não quisesse manter compatibilidade com C. Daria na mesma.
Coloquei no GitHub para referência futura.
Comment: @Zorkind não pode? Pode discorrer sobre isto? E porque isto compila? https://ideone.com/LwcDwD E por que está nesta documentação? http://en.cppreference.com/w/cpp/language/initializer_list
Comment: Entretanto, embora não tenha sido perguntado pelo OP existem diferenças entre as duas, por exemplo: structs não possuem construtores, não são considerados OO portanto não podem ter relacionamentos de herança, não podem possuir métodos, etc.
Comment: ok, me enganei sobre o construtor, por algum motivo tinha na cabeça que não podia, mas e quanto ao resto? :-)
Comment: Mesma coisa, tá tudo no *link* que eu passei.
Comment: Ah eu tava com C# na cabeça com relação a herança, desculpe https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct :-)
Comment: Porém de qualquer maneira os construtores em Struct funcionam de forma diferente de Classe então eu não estou totalmente errado hahahaha
Comment: C# permite construtores https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-structs
Comment: Em C++ é idêntico.
Comment: eu falei com relação a herança no doc que eu passei está claro que Struct não pode herdar de outro Struct em C# :-)
Comment: Outra fonte confirmando tudo que eu falei, não pode ter construtor default e não pode ter herança, em C# https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/structs
Comment: Structs e classes não têm diferença alguma além do modificador de acesso padrão. Em algumas implementações, não tem diferença nem pro linker.


Time-aligned sound samples

Question: if you were to provide an application and a set of samples that a user can use to compose rhythms to be played back by a sequencer, whithout having to care about time-aligning, how would you save those samples?
Percusive instruments seem to align to the beat at the start of the sound (at the onset) but, is this the case for all instruments?
Should I align my samples at an offset, e.g. 100ms, leaving leading space for sounds that align with the beat after some sound has already been made?
Should I dynamically align the samples? E.g. is it correct to say that the sample aligns with the beat at the point where the sound has its peak volume?
Thank you.
Answer: Maybe I'm not understanding something about the question, but why do you say non-percussive instruments don't align to the beat?
If I'm playing a MIDI keyboard, for example, I want the sample to begin playing as soon as possible when I press the key. If there's any kind of appreciable delay, it throws off my performance. Especially at higher tempos. The onset of sound should occur as soon as possible.
If you're thinking in terms of a typical ADSR envelope, the peak volume will occur at some brief time after the initial onset of sound, and then decay from there (this initial period of sound, between the onset and the peak is the Attack Phase). So maybe you're asking if the onset of the sample should precede the beat by the length of the attack phase? (so the peak occurs on the beat?). I don't think this is the case, since it would imply that musicians are actually constantly playing slightly ahead of the beat.
Furthermore, it will probably depend on what instrument you're using -- lots of instruments don't actually follow the ADSR envelope. Basically, any bowed string instruments, woodwinds, or brass are capable of starting at a very soft pitch, and gradually increasing in volume over the entire length of the note, so that the peak comes right at the end. Or they could even swell and fade multiple times.
Comment: Actually, for instruments with long attack (like strings), they _will_ "play" "ahead" of the beat such that the peak attack lines up with the rhythm. You can't do this with a MIDI keyboard, but perhaps the question is about samples to be played back by a sequencer?
Comment: @NReilingh You can do it with a MIDI keyboard. It's not different from the string instrument on that regard, you just "play" "ahead" too.
Comment: Yes, the samples are to be played back by a sequencer. I assumed that some instruments don't have their onset aligned with the beat, if that can be said. I will update my question to reflect those things. Cheers
Answer: If a human is playing the samples, I would prefer it if this latency was consistent, and as close to zero as possible.
Whenever I make my own samples, I zoom right in and trim any 'silence' from the start of the sample.  All my samples are saved like this.
I'm not 100% sure if I would notice 100ms of silence at the start of my samples, but I would expect them to play as soon as I'd triggered them.  Some smartphone apps of this nature are unplayable because they're not responsive enough.
You can always factor in a quantisation feature if your sounds work best when absolutely synchronised. (delay the playback if triggered early, play sample from just-after-the-start if triggered late, like aligning all the sounds to a 'grid')

When sequencing, it's just as important to have samples aligned correctly too.  The easiest way to do this is also to trim any silence from the start of your samples.  That is usually all that is necessary.
If you find some of your samples are 'out of time' even with the samples trimmed, then you're either:

Playing the sample at the wrong time.  Many sequencers allow you to offset the trigger for sample playback, e.g. not starting immediately, but after a few 'ticks'.  This is one way of achieving a 'triplet' when sequencing in 4/4 time.
Playing the sample at the wrong rate.  Can be true of longer, rhythmic samples.
Playing a sample that contains leading noise e.g. reverse cymbal, in which case, it's being triggered at the wrong time, you can't add a delay to all the other samples to compensate, you simply have to sequence it to play earlier.

Should you dynamically align the samples?  That's very ambitious, you'd need to calculate a known-offset for each sample, either pre-calculated or on-the-fly.  It might also take a bit of getting used to for the user, e.g. if I placed my reverse cymbal sound where I wanted it to peak rather than where I wanted it to begin.  I guess it's no different than left/center/right justification for word processors.
It might actually be a cool feature, but I wouldn't want it to be dynamically calculated (but an operation to calculate a suggested point might help), I would want to be able to set my own 'alignment markers' to control where the sample starts, since playing a sample like this at different pitches/rates would all require them to be started at different times.
Comment: Appreciate your considerations around my question. Please read updated question. Thank you!
Comment: @clapas, I have added my thoughts around sequencing.
Comment: Thank you Lee, your thoughts are very helpfull; my conclusion is that trimming the leading silence is the best way and, for cases like the reverse cymbal, I should sequence it earlier. Cheers.

Time-aligned sound samples


Windows App Certification Kit Warning

Question: I have an app that developed for Windows 7 & 8. Developed in VS2010 using C++/CLI. When tried to certify with Windows App Certification Kit, it shows a warning.
Binary analyzer
Warning: The binary analyzer test detected the following errors:
File C:\Program Files (x86)\MyApp\msvcr100.dll has failed the ExecutableImportsCheck check.
File C:\Program Files (x86)\MyApp\msvcp100.dll has failed the ExecutableImportsCheck check.
Impact if not fixed: If the app doesn't use the available Windows protections, it can increase the vulnerability of the customer's computer to malware.
How to fix: Apply the SAFESEH, DYNAMICBASE, and NXCOMPAT options when you link the app.

How can I avoid this warning from my app.
Answer: It makes no sense to use WACK on your project.  It was made to verify WinRT apps, the kind that are published through the Store and run on Windows 8.x or Windows Phone.  They need to be safe to run in a very restricted sandbox that makes a very small subset of the winapi available.  Limited for security, deployment and power-consumption reasons, what WACK verifies.  A desktop DLL like msvcr100.dll cannot meet them.  Such apps are built with another CRT, vccorlibxxx.dll
You cannot build such an app with VS2010, VS2012 or higher required.  Nor can it run on Win7.  You simply need to stop using the tool.

Update: it does appear that WACK was updated in the 8.1 SDK to also verify Windows Logo requirements for desktop apps.  This is obscure.  Judging from the command help that's displayed when I run appcert.exe /? in an elevated command prompt, you must first create an installer for your app.  Then you can run appcert with the -apptype desktop and the -setuppath yourinstaller.exe to have it perform the validation.  Some additional command line options appear to matter, like -appusage.  I don't know what they mean.
Do keep in mind that this is only useful if you need the Windows Logo certification.  There ought to be additional information in the logo program documentation about this.  Consider contacting Microsoft if you have Windows Logo program questions.
Comment: But here
http://dev.windows.com/en-us/develop/app-certification-kit
it says that WACK (from version 3.3)Supports, Desktop apps for Win 8, 8.1 and Windows 7
Comment: Okay, that's obscure.  Judging from the appcert.exe command help (type appcert.exe /? in an elevated command prompt), you'll first need to create an installer for your program.  Then you must run appcert.exe with the -apptype desktop and -setuppath yourinstaller.exe options.  Some more obscure options seem to matter, like -appusage, not sure what they mean.  Never heard of anybody doing this, good luck with it :)
Comment: @HansPassant - Perhaps due to the buzz about supporting non-metro apps in the Windows Store next year.  http://www.dailytech.com/Microsoft+to+Allow+NonMetro+Apps+Into+the+Windows+Store+Next+Year/article36674.htm

Windows App Certification Kit Warning


Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

Question: When I try to create a component in the angular cli, it's showing me this error. How do I get rid of it ?

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module.

I'm using angular cli version: 1.4.1
Answer: Specify the module using the --module parameter.
For example, if the main module is app.module.ts, run this:
ng g c new-component --module app

Or if you are in an other directory then
ng g c component-name --module ../

Comment: in my case it was
`ng g c admin/manageUsers ---module ../app`
Comment: in my case i had to make sure i was in the app folder when doing it
Answer: Try This: It is working for me
ng generate component componentName --module=app.module
Comment: Works for me. Thx. [Angular CLI: 1.7.4 // Node: 9.8.0 // OS: linux x64 // Angular: 5.2.9 ]
Comment: module = module name
Answer: This is caused since the generation tried to add your component to a module, i.e. to add this line
import { MyComponent } from './Components/my-component/my-component.component';

but it found 2 modules.
As stated here, they fixed it to a situation where as long as in the root src/app folder you have only 1 module, you're fine, so just move the secondaries modules to a sub-folder.
Otherwise you have to use --module
Comment: This seems the most useful answer, saving you from having to specify the module all the time, thanks.
Comment: Thanks for remind, finally I found the second module: RoutingModule, and moved it to sub-folder
Comment: Yep. Moved my additional modules to a `modules` subfolder, and all is good now.
Answer: It is working for me
ng g component component-name --skip-import

Comment: one important thing to note, is that this method dont automatically import these componets in the app.module.ts . So this has to be done manually.
Comment: Then you are forced to import manually. That's one very big bad recommendation that you gave. Mentioning the module is way much better!
Answer: for me this command working:
ng g c new-component --module app

Answer: There are two ways to solve this issue.
1) Skip (using --skip-import in command) default import and create component and once component is created import it manually wherever you want to use it.
ng generate component my-component --skip-import

2) Provide module name explicitly where you want it to be imported
ng generate  component  my-component --module=my-module.module

Answer: Just a small update to Zisha's answer.
In my project all the modules were placed in a folder called "modules" and all the components are placed in "components" folder under "src/app"

so to create a component under a specific path, I used the following syntax :

ng g c components_path/component_name --module modules_path/module_name

example :

ng g c components/login --module modules/app
Comment: I dunno, but, isn't a "better' design practice to place your components in their related modules?
Answer: Angular CLI: 6.0.8
Node: 10.4.0
OS: linux x64
Angular: 6.0.4
In case there is a feature module (e.g. manager.module.ts inside the e.g. "/manager" sub-folder) with the routing module externalized into the separate NgModule (e.g. manager-routing.module.ts) the error message:
More than one module matches. Use skip-import option to skip importing the component into the closest module.
does not appear and the component is properly generated and added to the manager.module.ts module.
BUT BE CAREFUL the naming convention! the name of the routing module must terminate with "-routing"!
If the routing module is given a name like e.g. manager-router.module.ts, CLI will complain with the error message and expect you to provide --module option to automatically add the component import:
ng generate component some-name --module=manager.module.ts

or
ng generate component some-name --skip-import

if you prefer to add the import of the component manually
Comment: The `-` did the trick! I had `lib-name.routing.module.ts` instead of `lib-name-routing.module.ts`.
Answer:
When app or lib have multiple nested modules

myApp
  > src
    > app
      app.module.ts
      > routes
        > login
          > auth
          login.module.ts

Angular CLI

ng g component routes/login/auth/my-auth --module=routes/login/login.module.ts

NRWL NX Angular CLI

ng g component routes/login/auth/my-auth --project=myApp --module=routes/login/login.module.ts

Result

myApp
  > src
    > app
      app.module.ts
      > routes
        > login
          > auth
            > my-auth
              my-auth.component.ts etc...
          login.module.ts

Answer: In my case, it seems ng is not registered into my environment path. I have been using npm run command to run the ng commands. Be aware in order to pass arguments you need an extra -- as per the npm run specification.
Example:
npm run ng g c components/scheduling **--** --module=app

Or:
npm run ng g c components/scheduling **--** --skip-import

Comment: The two asterisks before and after the -- are not needed, but this did fix my problem, so thank you.
Answer: I was getting below error when trying to create a new component under a folder.
error: More than one module matches. Use skip-import option to skip importing the component into the closest module.
I have used below command and new component got created successfully under a folder.
 ng g c folderName/my_newComponent ---module ../app

Answer: You have to give the specify module name like
ng g c your-component --module module-name

Where module-name should be that you want to update with newly created component.
Answer: My project was created using Visual Studio Community 2017 and it creates 3 separated modules: app.browser.module, app.server.module and app.shared.module
In order to create my components I checked above answers and found my module to be app.shared.module.
So, I run:
ng g c componentName --module=app.shared.module

Answer: When there is more than one module under app folder, generating a component with below command will fail:
ng generate component New-Component-Name

The reason is angular CLI detects multiple module, and does't know in which module to add the component. So, you need to explicitly mention which module component will be added:
ng generate component New-Component-Name --module=ModuleName

Answer:
Angular CLI: 8.3.1

when you have multiple module.ts files inside a module, you need to specify for which module file you are generating component.
ng g c modulefolder/componentname --module=modulename.module

for e.g. i have shared module folder inside which i have shared.module.ts and material.module.ts like this
shared
  > shared.module.ts
  > material.module.ts

and i want to generate sidebar component for shared.module.ts
then i will run following command
ng g c shared/sidebar --module=shared.module

if you want to export the component then run following command
ng g c shared/sidebar --module=shared.module --export

Answer: Just to add another piece of info to this for anyone like me who happens along that just has a single application.
I had my application set up with the main app.module.ts and I had routing with the routing module in it's own folder under the main application.  I went through and did some 'cleaning up' since I had a few other things that needed to be organized better.  One thing I did was move the routing.module.ts to the root folder; since it was the only file in the folder I figured it didn't need it's own folder.
This worked fine at first but next time I tried to generate a new component (some time later, through the WebStorm IDE) it failed with this message.  After reading through this I tried putting the routing module back into a separate folder and it worked again.
So note of warning to others, don't move the routing module into your root folder!  I'm sure there are other ways to deal with this too but I'm happy with it in it's own folder for now and using the IDE generator like I was previously.
Answer: you have to mention only the module starting name before the .module extension
for example if your module name is user-account.module.ts
then in the command provide like
ng g c newComponent --module=user-account

Answer: when you have more than one module, you need to specify module name
 ng g c componentName --module=modulename.module

Answer: Angular CLI: 8.3.4
Node : 10.16.3
Angualr : 4.2.5
I used "dotnet new angular" command to generate the project, and it has generated 3 different modules in app folder (Although a simple test with ng new project-name just generates a single module.
see the modules in your project and decide wich module you want - then specify the name
ng g c componentName --module=[name-of-your-module]

You can read more about modules here:
https://angular.io/guide/architecture-modules
Answer: if you are creating in specific module go to that path and run
ng g c componentname
else create module first
ng g module modulename
cd arc/app/modulename
go to modulename path and create the component
Answer: try ng g component header --module app
it is work for me
Comment: works in angular 6. I moved the routes to `app.routing.module.ts` hence the error
Answer: I had this warning when had this in angular.json config:
"prefix": "app_ng"

When changed to "app" all worked perfectly fine.
Answer: There is a way to create a standalone component in Angular 16. so, you would not need to create the component into a given module.
ng generate component component-name --standalone

Standalone components, directives, and pipes are new features in Angular v16. So you can easily use components that are not tied to modules, like in other frameworks like React or Vue.
Answer: As a hack, below steps, worked for me.
1) Move *.module.ts files from src/app to a location out of the project.
2) Execute command to create component [ng g c component-name]
3) Move back the *.module.ts files to src/app/
Comment: For this solution, check if the component is also registered in the relevant module. Running the command using the cli should do so. I guess the negative point has been because of this issue.


Vaadin 14 Label/span/text line break in word if exceed max width

Question: is there any option to continue one word in other line if it length exceed max width?
In my code line breaks are working correctly when word isnt long enough to exceed max width. when i have too long word in my text component then it is drawing outside the layout area.
Comment: Have you tried https://stackoverflow.com/questions/18225302/how-can-i-wrap-or-break-long-text-word-in-a-fixed-width-span ?
Comment: Does this answer your question? [How can I wrap or break long text/word in a fixed width span?](https://stackoverflow.com/questions/18225302/how-can-i-wrap-or-break-long-text-word-in-a-fixed-width-span)
Answer: adding
<code>word-wrap:break-word
</code>
worked for me


How to delay jquery events for google analytics

Question: I am using jquery to log clicks on anchors to google analytics.
I have code like the following, that wires up the event:

$(document).delegate("a[rel='mylink']", "Click", function (e) {
//log to google analytics
console.log('tracking link');
_gaq.push(event);
e.preventDefault();
});

The problem is that the href seems to be followed too quickly for this event to fire.
Is there a way to delay the following of the href until the event has been fired/completed?
I can see in the console that it gets as far as 'tracking link' but then it moves on before the google analytics push event completes.
Any advice appreciated.
Comment: How do you know the analytics event hasn't completed?  In my experience there can be *very* long delays before they show up in the analytics interface.
Comment: I can see in fiddler that the event has not gone across the wire. If I remove the e.preventdefault then I see the event in fiddler but then the href does not load.
Answer: Google Analytics records data by making requests for a tracking pixel. As you've found, the request can be canceled when a new page is opened in the same window.
Note: a delay is only necessary if the link being opened in the same window. I use some variation of the following for a click function:
function(e) {
  _gaq.push(['_trackEvent', ...]);
  if (this.target != '_blank') {
    e.preventDefault();
    var url = this.href;
    setTimeout(function() {location.href = url}, 150);
  }
}

Answer: i solved this problems with google analytics with putting the logic into the window load function
jQuery(window).load(function(){

})


Prove the following Injective and Surjective function

Question: Prove that the following function is bijective (both injective and surjective):
$$f(x,y) = (x^2+y+x-2, x+3)$$
Usually I know how to do these, but the fact that the first x is squared, throws me off course. How can I tackle this problem?
Thanks
Answer: Suppose $f(x_1,y_1)=f(x_2,y_2$; then
\begin{cases}
x_1^2+y_1+x_1-2=x_2^2+y_2+x_2-2\\
x_1+3=x_2+3
\end{cases}
Can you deduce from this that $x_1=x_2$ and $y_1=y_2$? If so, you have proved that the function is injective.
Next, given $(a,b)$, can you find $(x,y)$ such that
\begin{cases}
x^2+y+x-2=a\\
x+3=b
\end{cases}
so as to prove that the function is surjective?
Comment: Though  I do understand the inyective part, I fail to do the same for the surjective. What should I look for with that set of equations??
Comment: @user143899 You have to solve it for $x$ and $y$. Since this is possible for any pair $(a,b)$ (just observe that $x=b-3$ and substitute in the first equation), the function is surjective.
Answer: If $f(x,y)=f(u,v)$ then $x+3=u+3$ so $x=u$. Now, $x^2+y+x-2=x^2+v+x-2$; hence, $y=v$. We have proved the injectivity.
For surjectivity, suppose that take any $(a,b)\in\Bbb R^2$. Suppose that $f(x,y)=(a,b)$. Then $x+3=b$ and $x=b-3$. Then, $(b-3)^2+y+b-3=a$ and $y=a-(b-3)^2-(b-3)=$$=a-(b-3)(b-2)$. Indeed, it can be easilty checked that $f(b-3,a-(b-3)(b-2))=(a,b)$, so $f$ is surjective.
Answer: Because the inverse map is
$$f^{-1}(a,b) = (b-3, a-(b-1)(b-4))$$


AWS CloudFormation give EC2 instance SSH Keys to other servers


Is the 2nd movement of Mozart's Piano Sonata nº 7 in C, K.309, a "large rounded binary"?

Question: My analysis of the form of the movement is, currently, that it is a large ternary with written out repeats of the main theme and the subordinate theme complex + return of the main theme together, something like a 'rounded large binary'. A summary of the analysis is below:

Main theme: cc. 1-17
Main theme (repeated): cc. 17-33
Subordinate theme complex: cc. 33-45
Main theme (returned): c. 45-52
Subordinate theme complex + main theme returned (repeated): cc. 53-72
Coda: cc. 73-79

The problem is that the second section of a large ternary is normally an interior theme or at best, a "subordinate theme complex within the framework of the minore" (Analyzing Classical Form, p. 582), which is not the case since we are in the subordinate key. Also, are repeats "allowed" in large ternaries?
I analyzed the main theme as follows, the line and dashes indicate measures and beats, respectively, and the number below them are measure numbers:

And the subordinate theme complex as:

Standard abbreviations for cadences are used, and the remaining abbreviations translate as:

BId - basic idea
CId - cadential idea
Cnt - continuation
Cad - cadential idea
N.C. - No cadence

Were it not for the repetitions, the case here might be of a sonata without development with a truncated recapitulation, I think.
As I'm not all that used to analyzing slow movements I may be missing something basic here, I apologize if that is the case.
Answer: The movement is in rounded binary form. A very clear analysis is given on YouTube in the comment section of the linked video.

In summary:
A section (1st period)

mm. 1–8: theme a, antecedent phrase
mm. 9–16: theme a1, consequent phrase

A section

mm. 17–24: theme a2
mm. 25–32: theme a3

B section

mm. 33–40: theme b
mm. 41–44: theme c

A' section

mm. 45–52: theme a4

B section

mm. 53–60: theme b1
mm. 61–64: theme c1

A' section

mm. 65-72: theme a5

Coda

mm. 73–79
Comment: @FelipeMartins Fair enough. When I get a chance, I'll fill out my own analysis and deemphasize the video.
Comment: I do not particularly like the analysis in the video. It equates what I see as a particular variation _process_, for a reference to the theme and variations form. As variations, as in written out repeats, are very common outside theme and variations, I don't think that form is particularly relevant here.
Comment: Apart from that, it is interesting to see here the 'large rounded binary' interpretation.
Comment: Also, the analysis does not comment on the fact that the paired 'variations' form a compound period, which I think is a very relevant formal aspect.
Comment: @FelipeMartins I don't understand your comment. There is no reference to "theme and variations"; it is in complete agreement with the idea of a variation process and makes no claim toward anything other than a standard rounded binary. As far as the fact of a period goes, I've alluded to that in my summary, but it doesn't change the fact of the overall rounded binary structure.
Comment: The title of the prat of the video description that describes the form of the movement reads: "Mvt 2: Andante un Poco Adagio [Rounded-Binary form]
*Combination of Ternary Form (AABA'BA') and Theme & Variations." Your summary does not reference it. As I said, I do not like the analysis _in the video_, I think your summary is much better.
Answer: After some thinking, I realized the form may be considered, simply, a small ternary with written-out repeats and with a compound period for an A section. Although it is not a normative situation, I believe it is not explicitly 'forbidden' as is the case of a large ternary with a subordinate theme. Following that, the full analysis will be as below (click the image if it is too small).

What is called the subordinate theme complex in the OP is a modulating B section with a retransition (see Analyzing Classical Form, p. 223, by William Caplin) and the A' section is a compound consequent, which results from the normative shortening of the A section by removing its antecedent phrase.
I am tempted to call the overall form a 'compound small ternary', but I believe the creation of a such a new category, in the context of the theory of formal functions, would be warranted only if there were numerous other examples of the same formal type. Which begs the question: are there?
One should also ask if an 'expanded' small ternary like this one is appropriate for a full-movement form. I also do not know.
Comment: Since the OP specifically asks about _rounded binary_ it seems worth mentioning that Caplin in _Classical Form_, in the _Small Ternary_ chapter, says: "one of the most vigorous debates in the history of theory concerns whether the simple form under consideration her...consists essentially of two or three parts." He's pointing out rounded binary and small ternary are "essentially the same form."


Is it a Markov process?

Question: Consider the random variable $S_t:= x+ t-\sum_{i=1}^n X_i$,
where $X_i \in \mathbb{N}_0$ and i.i.d.
Can I state that I deal with a Markov process here?
Comment: Have you checked whether it satisfies the definition of a Markov process? (And if you are having trouble doing so, where are you stuck?)
Comment: @angryavian: I have to check that $S_{t+1} $ only depends on the value which $S_t$ takes. But it doesn't depend on anything because the $X_i$ are i.i.d. Where do I make a mistake?
Comment: The $X_i$ are independent but the $S_t$ are not because they are defined in terms of some of the same $X_i$'s.
Comment: I thought the sum of i.i.d random variables is i.i.d?
Comment: What does "the sum is i.i.d." mean? "i.i.d." means "independent and identically distributed". The sum is independent from what? The sum is identically distributed to what?
Comment: @MishaLavrov: I mean $X_1+X_2$ is independent to $X_1+X_2+X_3$
Comment: Is that right? $S_{t+1}$ only depends on $S_t$ because of the term $x+t$ Did I get that right?
Comment: No, that's not right. I will say more in an answer.
Comment: ok thank you very much:)
Answer: I assume that you mean $S_t = x + t - \sum_{i=1}^t X_i$, not $\sum_{i=1}^n$. The conclusion is the same either way, but the sum going up to $t$ makes more sense as a process to look at.
We pick the sequence $X_1, X_2, X_3, \dots$ independently from whichever distribution they're drawn from, but we only do it once. So two partial sums like $X_1 + X_2$ and $X_1 + X_2 + X_3$ are not independent. For example:

$\Pr[X_1 + X_2 = 1]$ and $\Pr[X_1 + X_2 + X_3 = 0]$ can in general be positive probabilities, assuming that the $X_i$ distribution can be $0$ or $1$ with positive probability.
If the two sums were independent, then $\Pr[X_1 + X_2 = 1 \text{ and } X_1 + X_2 + X_3 = 0]$  would also be a positive probability: the product of the two probabilities above.
However, $\Pr[X_1 + X_2 = 1 \text{ and } X_1 + X_2 + X_3 = 0]$ must be $0$, since $X_1+X_2=1$ and $X_1+X_2+X_3=0$ together imply that $X_3 = -1$.

For your random process, we have $S_{t+1} - S_t = 1 - X_{t+1}$, because the other terms all cancel in the difference. This means that, given $S_t$, everything about $S_{t+1}$ is determined entirely by $X_{t+1}$.
This should let you check the definition of a Markov process and conclude that this sequence is one.
Comment: Thank you for answer. But I can state that $\sum_{i=1}^{t}X_i$ is independent from $X_{t+1}$?
Comment: Yes, because $(X_1, \dots, X_t)$ are independent from $X_{t+1}$, and $\sum_{i=1}^t X_i$ is a function of $(X_1, \dots, X_t)$. The difference is that there are no random variables in common on both sides.
Comment: Thank you. Your example was really helpful:) I do not understand why you consider the difference between $S_t$ and $S_{t+1}$. I only have to ensure that $P(S_{t+1 }=k_{t+1}| S_t=k_t,...S_1=k_1)=P(S_{t+1 }=k_{t+1}| S_t=k_t)$
Comment: The difference helps me see that $S_{t+1}$ only depends on the earlier terms via $S_t$; if you are happy checking this condition directly, then that's also fine.
Comment: That is the problem. I can really check this defintion. How would you go on from your point of view?
Comment: Well, if you write $S_{t+1} = S_t + 1 -X_{t+1}$, then $\Pr[S_{t+1} = k_{t+1} \mid S_t = k_t, \dots]$ becomes $\Pr[X_{t+1} = 1 + k_t - k_{t+1} \mid S_t = k_t, \dots]$, and $X_{t+1}$ is independent of all of those.
Comment: Thank you very much:)
Comment: But $X_{t+1}$ is also independent of $S_t$ ?
Comment: Yes, so both $\Pr[S_{t+1}=k_{t+1} \mid S_t =k_t, \dots, S_1=k_1]$ and $\Pr[S_{t+1}=k_{t+1}\mid S_t = k_t]$ simplify to $\Pr[X_{t+1}=1-k_t-k_{t+1}]$, which is how we know that they're equal.
Comment: Thank you. Sorry for the further question :(

Is it a Markov process?


Preciso 'ler' o valor de uma variável que é local declarada em uma função, por em escopo de outra função, em script Python

Question: Tenho um código que é muito semelhante ao seguinte
def um():
   x = 'abc'
   print(x)

def dois():
   y = 'bcd'+ 'x'
   print(y)

Acontece que, como x é local em função um, a função dois não consegue ler o x, retornando um erro que informa 'x não foi declarado'.
Answer: Na função um está pedindo para imprimir o valor x,
o correto seria retornar esse valor. Já na função dois, a variável y recebe a concatenação de duas strings: 'bcd' e x.
Acredito que a intenção seja ter acesso a variável x da função um.
E mais uma vez está imprimindo a variável em questão ao invés de retorná-la.
def um():
x = 'abc'
return x

def dois():
    y = 'bcd' + um()
    return y

print(dois())


Check: Convergence of an infinite series

Question: More a check than a question - I just need to ensure that my logic is correct (I always had trouble with this):
Show whether the series
$$\sum_{n=110}^{\infty}\frac{1}{3^{n}n^{3}}$$
Is divergent, convergent or absolutely convergent.
Solution - We consider:
$$\sum_{n=110}^{\infty}\frac{1}{3^{n}n^{3}} < \sum_{n=110}^{\infty}\frac{1}{n^{3}n^{3}}
 < \sum_{n=110}^{\infty}\frac{1}{n^{6}}$$
Hence absolutely converges since $\frac{1}{n^{6}}$ is a generalized harmonic series with $p=6$. I can do this, since $\frac{1}{n^{3}}>\frac{1}{3^{n}}$
 , and if I can show a greater series converges, then the lesser series must also converge by the comparison test. This whole changing inequalities (which always seemed rather arbitrary to me) in order to show properties is the bit that I always have to get checked because I struggle with it.
Thanks all!
P.S. How do I get my mathematical expressions to appear bigger? My indices always end up squashed to oblivion.
Comment: One way to make the fractions more readable is to use the double dollar signs, or the command '\displaystyle{}'.
Comment: This is a [polylogarithm](http://en.wikipedia.org/wiki/Polylogarithm).
Answer: For one thing, the sums of both
$\frac1{3^n}$ and $\frac1{n^3}$
converge, so the sum of their product
certainly converges.
For a larger fraction,
use dfrac instead of frac.
Here is the above fractions
using dfrac:
$\dfrac1{3^n}$ and $\dfrac1{n^3}$
Answer: Your proof is fine.

A nice generalization of what you've done is the following:

If $\{a_n\}$ is a sequence for which $\sum_{n = N}^{\infty} |a_n|$ converges, and $\{b_n\}$ is any bounded sequence, then $$\sum_{n = N}^{\infty} |a_n b_n|$$ converges.

To prove this, let $M$ be any bound on $\{b_n\}$ and use a comparison test with the sequence $M |a_n|$. In particular, since $1/3^n$ is bounded (by $1/3^{110}$, for example), and $1/n^3$ gives rise to a convergent $p$-series, the product must also converge.


Don't remove the last one row jQuery

Question: I have this form that fills a table using jQuery, the code works fine the problem is that I don't know how to disable the delete button when I have just one row. I mean I don't want remove the row if is the last one remaining.
Form
<form name="prescor" id="prescor" method="post" action="#">

    Cantidad
    <input name="cant" type="text" id="cant" autocomplete="off" onKeyUp="subtotal()" pattern="[0-9]*." step="any">
    Artículo
    <input name="idarti" type="text" id="idarti" autocomplete="off" >

    Precio
    <input name="prec" id="prec" autocomplete="off" onKeyUp="subtotal()">
    Total
    <input name="tota" type="text" id="tota" readonly>
    <input name="agregar" type="button" value="Agregar" onclick="fn_agregar()" />

    Cant.
    Artículo
    Precio
    Subtotal

    No. Lineas:

The script
$(document).ready(function(){
fn_eliminar();
fn_cantidad();
});

function fn_cantidad(){
var n = $("#grilla tbody").find("tr").length;
$("#span_cantidad").text(n);
};

function fn_agregar() {
cadena = "
";
cadena = cadena + "<input type='text' name='cantidad[]' value='" + $("#cant").val() + "' readonly size='1' required>	";
cadena = cadena + "<input type='text' name='idarticulo[]' value='" + $("#idarti").val() + "' readonly size='2' required>	";
cadena = cadena + "<input type='text' name='precio[]' value='" + $("#prec").val() + "' readonly size='4' required>	";
cadena = cadena + "<input type='text' name='subtotal[]' value='" + $("#tota").val() + "' readonly size='7' required>	";
cadena = cadena + "	";
$("#grilla tbody").append(cadena);
document.getElementById("idarti").value="";
document.getElementById("cant").value="";
document.getElementById("prec").value="";
document.getElementById("tota").value="";
fn_eliminar();
fn_cantidad();
};

function fn_eliminar()
{
    $("a.elimina").click(function()
    {
        id = $(this).parents("tr").find("td").eq(0).html();
        $(this).parents("tr").fadeOut("normal", function()
        {
            $(this).remove();
            fn_cantidad();
        })
    });
}

Answer: In the remove handler check whether there is only one item left if so don't do anything.
Also use event delegation to handle the remove element click, In your code you were applying multiple click handlers to the remove element because every time you call fn_eliminar it will add a new click handler to all the previously present remove elements
$(document).ready(function () {
    fn_eliminar();
    fn_cantidad();
});

function fn_cantidad() {
    var n = $("#grilla tbody").find("tr").length;
    $("#span_cantidad").text(n);
};

function fn_agregar() {
    cadena = "
";
    cadena = cadena + "<input type='text' name='cantidad[]' value='" + $("#cant").val() + "' readonly size='1' required>	";
    cadena = cadena + "<input type='text' name='idarticulo[]' value='" + $("#idarti").val() + "' readonly size='2' required>	";
    cadena = cadena + "<input type='text' name='precio[]' value='" + $("#prec").val() + "' readonly size='4' required>	";
    cadena = cadena + "<input type='text' name='subtotal[]' value='" + $("#tota").val() + "' readonly size='7' required>	";
    cadena = cadena + "	";
    $("#grilla tbody").append(cadena);
    document.getElementById("idarti").value = "";
    document.getElementById("cant").value = "";
    document.getElementById("prec").value = "";
    document.getElementById("tota").value = "";
    fn_cantidad();
};

function fn_eliminar() {
    $("#grilla tbody").on('click', 'a.elimina', function () {
        if ($('#grilla tbody tr').length == 1) {
            return;
        }
        var id = $(this).closest("tr").find("td").eq(0).html();
        $(this).closest("tr").fadeOut("normal", function () {
            $(this).remove();
            fn_cantidad();
        })
    });
}

Comment: Thanks for your help the solution was

    if ($("#grilla tbody tr").length > 1){
    $(this).parents("tr").fadeOut("normal", function(){
        $(this).remove();
        fn_cantidad();
    });
    }
Answer: You may count the number of rows in the table..
for example,
HTML

              col 1
              col 2
              col 3
              Action

              col 1
              col 2
              col 3

               <button type="button" class="remove-row"> DELETE </button>

JQUERY
$(document).on('click', '.remove-row', function(){
     var rows = $('.invoice-table').find('tbody').children('tr').length;
     if(rows > 1)
     {
        $(this).closest("tr").remove();
     }
     else
     {
        alert("There must be at least one row in the table");
     }
});

Don't remove the last one row jQuery


Drupal 8: Node preview when using Page Manager

Question: I am using the Page Manager module in D8 to show the full node view pages. Drupal also provides a button to preview the content when creating/editing it. Is there a possibility to actually preview the page using the page manager layout?
Thanks for the answers!
Vasi.
Answer: Not ouf the box because page_manager is about routes, and node preview is a completely different route than viewing a node.
Something like Display suite and probably also Panelizer (never really used it myself) whould probably work there though.
That said, it should be possible to build something too with Page Manager too by creating a second page (with a duplicated page variant(s) that you need to keep in sync somehow) that overides the preview route, but you also need to somehow write a context provider that loads the node based on the passed tempstore argument and also a write a block that replicates the UI elements for selecting the view mode and going back to edit
Comment: Thanks for the reply Berdir! Yeah, I already thought about this solution (good point with the need to replicate the UI elements for selecting the view mode and go back to edit), was thinking that maybe there is an easier option here. I suppose not...


For javascript the call to api "gapi.auth.authorize" for google analytics not getting executed.

Question: I have been trying to use Google Analytics Core Reporting API with JavaScript.
I am new to it and I was trying to use the sample code provided by google for core_reporting_api_v3.
But after the core_reporting_api_v3.html file is ran it calls auth_util.js.
Code from auth_utils.js:
function checkAuth()
{
    gapi.auth.authorize({client_id: clientId, scope: scopes}, handleAuthResult);
}

function handleAuthResult(authResult)
{
    alert("made it");
    if (authResult)
    {
        gapi.client.load('analytics', 'v3', handleAuthorized);
    }
    else
    {
        handleUnAuthorized();
    }

Here in checkAuth() function there is a call made to google api gapi.auth.authorize with the client Id, scopes, immediate(tried for both :true/false)  and callback function. And it should pop-up an authorization window for user authorization. After that the callback function is called.
But this pop-up window never appears. Please help me with this, I am not getting what the problem is. One might think the problem is with credentials but I am using the same credentials using python and getting the results successfully. Is there any way I can track the process going behind in the browser like: what call is being made and where is the process getting stuck? Is there any tutorial for writing this gapi.auth.authorize call in raw form in javascript as a REST API?
Answer: i had a similar issue, so modified the samples to suit. Also the order the includes seemed to effect it.
Here is what worked for me:

In the google API Console-https://code.google.com/apis/console -
setup new project, saved client Key and API key.
Set the callback URI to the calling file.
Under "Services" Turned on Analytics API, Google Cloud Storage and
Prediction API. After this it started Authing OK.

Here is the code i used that worked for me.
Within calling page- as saved as RedirectURI in the console:

Here is the code i've used to get around it Saved in hello_analytics_api_v3_auth.js:

    function handleClientLoad() {
        gapi.client.setApiKey(apiKey);
        window.setTimeout(checkAuth,1);
    }

    //  3. Check if the user has Authenticated and Authorized
    function checkAuth() {
        // Call the Google Accounts Service to determine the current user's auth status.
        // Pass the response to the handleAuthResult callback function
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);

    }
    //  4. Update the UI based on the user's authorization status
    function handleAuthResult(authResult) {
      if (authResult) {
        // The user has authorized access
        // Load the Analytics Client. This function is defined in the next section.
        loadAnalyticsClient();
      } else {
        // User has not Authenticated and Authorized
        handleUnAuthorized();
      }
    }
    //  3. Create An Analytics Service Object
    function loadAnalyticsClient() {
      // Load the Analytics client and set handleAuthorized as the callback function
      gapi.client.load('analytics', 'v3', handleAuthorized);
    }

Hope it helps you with your issue.
-Joel
Comment: I am having the same problem, The script doesn't reach to execute the code in 'handleAuthResult'. Looks like gapi.auth.authorize doesn't call 'handleAuthResult'. Any suggestions?


How to convert PHP Logic to Views API

Question: I am writing a module to convert serialized value stored in database by the Composed Field Module. The serialized value is like:
a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}
The PHP Unserialize value of above serialized data returns the following array:
print_r(unserialize('a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}'));
Array
(
    [1] => First Subfield
    [2] => Second Subfield
    [3] => Third Subfield
)

I called the Module as composed_views
So far I have made few files like: composed_views.info, composed_views.module,
composed_views_handler_subfields.inc contains:
class composed_views_handler_subfields extends views_handler_field {
  /**
  * Render the unserialized value.
  */
  public function render($values, $index) {
    $uns = unserialize($values) // $values = serialized data from database
    return $this->get_value($uns[$index]); // $index = array index of serialized data
  }
}

In composed_views.views.inc
For eg: The table names are field_one, field_two
The data column are field_one-composed, field_two-composed respectively

I want to Query those tables
and send the serialized data to render function defined in composed_views_handler_subfields.inc file

So, far the structure is like this:
function composed_views_views_data() {
  $data['composed_views_table'] = array();
  // The actual code I am seeking help with
  return $data;
  }

Any help how to do with this with views would be appreciated.
Comment: With views GUI or views API? Could you create entities from the data? https://drupal.org/project/entity
Comment: With ViewsAPI, I cannot create entity from the data, as the reason of using composed_field is to define the field directly in the content type.
Answer: There is some discussion in several places about this, including an issue in the Composed Field issues queue.
The module author writes;

I haven't investigated the mechanics behind it but theoretically all that needs to be done is to somehow implements the process that those modules do on retrieving the field value from the database and then unserialize and concatenate the retrieved value.

The problem of course with storing serialised data is the inability to effectively query it using any type of relational db (No indexes.)
You can always build a query using a LIKE on the serialised data ...
WHERE field_one-composed LIKE '%query%';

But that's horrible. :(
My comment on the initial question stands; do you want to achieve this using the GUI or through code? I'll update this answer based on your response.
While I appreciate this is not the question, I'm curious about why you chose this module for your use case?
Comment: Hi, it doesn't really matter if you could guide me to use this via GUI or ViewsAPI. In GUI, I don't want to use ViewsPHP as it has security implications, but if you have some solutions using GUI then I guess it'd be great to hear
Answer: As I mentioned in your other question, once views is able to fetch the data, you can change what it takes as a result by modifying the handler's set_items method.
However, the field handler is meant to display fields. If you're looking to change how Views filters behave, you'll have to extend and modify the filter handler.

How to convert PHP Logic to Views API


Declaração de String

Question: Estou declarando uma variável assim:
private String[,] soloMarciano;

Pode fazer isso no Java? Pois preciso ler duas posições X e Y.
Comment: Pode explicar melhor o que quer fazer? Qual resultado espera?
Answer: O que você esta querendo chama-se matrizes ou vetores bidimensionais, achei neste link uma explicação bem ampla a respeito do funcionamento deles.
Mas resumindo, você pode declarar um array bidimensional 2 por 4 (8 elementos) da seguinte forma:
String[][] xy = new String[2][4];

Comment: É importante também salientar na sua resposta, que o tamanho do vetor seja definido antes de seu uso, pois seu tamanho não é dinamico como no caso do [ArrayList](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
Answer: Você pode declarar e inicializar a string de duas dimensões dessa forma dessa forma:
private string[][] soloMarciano = {{"a","b"},{"c","d"}};

ou declarar e inicializar ela assim:
private string[][] soloMarciano;

soloMarciano[0][0] = "a";

soloMarciano[0][1] = "b";

soloMarciano[1][0] = "c";

soloMarciano[1][1] = "d";

Para ler a letra "a", você pode usar um System.out.println([0][0]);
A letra "b", use System.out.println([0][1]);
A letra "c", use System.out.println([1][0]);
A letra "d", use System.out.println([1][1]);

Declaração de String


Exchange 2013 - Discovery Search Mailbox Cleanup - Delete Search Folders

Question: this is interesting, i couldn't find a simple way to delete search-folders from "Discovery Search Mailbox". The search-folders were created when I ran "Search-Mailbox" command on any user-mailbox to do some search.
Some one said to use ECP and use mail-control, but I am on Exchange 2013 and I have EAC, there is no mail-control.
https://social.technet.microsoft.com/Forums/Lync/en-US/d19585f5-19bb-4f9b-a22e-724b2758183e/discovery-search-mailbox-how-do-i-clean-it-up-after-a-search-was-completed?forum=exchangesvradminlegacy
the other way is to delete and re-create the default discovery mailbox in Exchange. I do not want to delete the whole discovery mailbox to just remove a folder which was created by search.
https://technet.microsoft.com/en-us/library/dn750894(v=exchg.150).aspx
i cannot delete it in Outlook as it give me permission denied message. when checking permission, it shows only "default" and "anonymous" with "None" permission level. i could add my name though, but it only applies to that folder only, the child folders not inherited, and even after giving me permission as owner, i am not able to delete (which may be ok because child folders in the tree does not have my name as owner). i dont see the Discovery Search Mailbox in OWA.
I am on Exchange 2013. On server I have EAC (Exchange Admin Center) but not ECP. On EAC i do not see mail control feature. This should have been a simple task or command to just remove search-recovery folder from "Discovery Search Mailbox". I have four folders in that mailbox for the same search query, each time a different target folder. One of them was created from "in-place eDiscovery & hold" menu in EAC. I can delete that saved-search under "in-place eDiscovery & hold" and that will probably delete the folder (I am not sure about this part), but the other three folders were created by search-mailbox command (similar search queries on same user-mailbox) and using different target folder in "Discovery Search Mailbox", how do I remove those? There should be some powershell commands to remove those folder. I am not sticky to powershell commands only, as long as the folders are removed and mailbox is cleaned-up.
I need help. How do I make it work?
Answer: Did you already find a way to do this? I know it's been a few months, but there are a few ways to do this, none of them explicitly "simple". Option 1 is the easiest way to delete the results of a specific search. Option 2 clears everything!
There are ways to use Exchange Web Services (EWS) to target a specific folder, but that's a lot more to document and quite honestly, unless you have to deal with a LOT of Discovery Searches, this should do and may even give you some ideas for procedures of your own.
I am on 2016 and it's been a bit since 2013 so forgive me if this does not go EXACTLY to plan and I am very VERY busy all the time and I may not see any questions you have, I will try and keep an eye on the thread though.
This will require PowerShell to your Exchange Server(s) or Office 365 Tennant.

Get the name of your Discovery Search Mailbox(es) - going to refer to these as DSM going forward.
Get-Mailbox -Resultsize unlimited -Filter {RecipientTypeDetails -eq 'DiscoveryMailbox'} | Format-Table DisplayName, PrimarySmtpAddress -AutoSize

Option 1

Grant yourself access to the Discovery Search mailbox - replace   ""   with a display name result from the list. Replace   ""   with your primary smtp email address on Exchange 2013. Remove the -AutoMapping:$false if you want to see this DSM in Outlook automatically (can take a bit to appear). I prefer to work with this separate via OWA.
Add-MailboxPermission '<DisplayName>' -User <your exchange email address - primary>' -AccessRights FullAccess -InheritanceType all -AutoMapping:$false

Now go to Outlook (if you removed AutoMapping) or OWA if you did not
In OWA click on your User Name/Avatar in the upper right, and open another mailbox
Type the PrimarySmtpAddress of the DSM from step #1 above in the field indicating which mailbox to open and GO.
Delete the folders/items you need to and then empty the recycle bin
Clean the dumpster of the DSM. You may have to run this a few times since only the first 10,000 results will be processed in the search. Replace   ""   with the DSM's primary smtp address from step #1 above.
Get-Mailbox -ResultSize Unlimited -Filter {PrimarySmtpAddress -eq '<PrimarySmtpAddress>'} | Search-mailbox -DeleteContent -Force -SearchDumpsterOnly

This last step will clear everything JUST from the dumpster (the deleted deleted items).
Option 2
Just run a modified step 7 from above. Replace   ""   with the DSM's primary smtp address from step #1 in option #1 above.
Get-Mailbox -ResultSize Unlimited -Filter {PrimarySmtpAddress -eq '<PrimarySmtpAddress>'} | Search-mailbox -DeleteContent -Force -SearchDumpster

This will process the first 10,000 results and you may have to run it more than once. It will give you some idea of what it did at the end of processing. If the result is 10,000 items, run it again, it needs to be either zero or some number LESS than 10,000 for everything to be gone.
Again, super busy, but I thought I could help if you still needed it since this is what I did on Exchange 2013 and now 2016, did not have to change any processes (except if Office 365 is involved, then you have to connect to the service first).
Comment: ...and just a side note - once you delete the folder from the deleted items, you could just let it slide into oblivion on it's own in 14 days, unless I am mistaken and DSM's do not process recoverable deleted items the same way. The steps I mention specifically completely remove the content from the DSM and cannot be recovered.

It has been my experience that if you delete the search that created the folder, the contents will be removed. Unfortunately I have been bit by this one too many times and came up with the above to handle the matter
Comment: sorry for the delay. i haven't found found a way on this. i even asked Microsoft in their forum, not anything that would work. I will check your options and see if it works. thanks for your reply.
Answer: Remove-Mailbox "DiscoverySearchMailbox{D919BA05-46A6-415f-80AD-7E09334BB852}"
https://technet.microsoft.com/en-us/library/dn750894%28v=exchg.150%29.aspx?f=255&MSPPError=-2147217396
Comment: i already mentioned that there is a way to delete and recreate the whole discovery search mailbox, but thats the last resort I want to do. why would I need to delete and recreate the mailbox completely when I just want to delete one folder which I created by a mail-box search? does not make sense.


On a piano, are the effects of holding notes and the sustain pedal the same for a single chord?

Question: Building from this question, I learned that it is possible to notate a tie that is held by the pedal and not the hands.  To me that's a bit strange - if the pedal were not held down in that passage, the effect would be different because the right hand is playing more notes that would not be sustained.
That brings me to the question: if I play a chord without the pedal and hold it for 3 seconds, and if I play the chord with the pedal, releasing it after I play it so that the pedal holds the notes, are the effects going to be the same?
I recognize that I can just go ahead and play this myself (I have), and personally I couldn't tell a difference.  But, since there is an obvious physical difference (the pedal either is or is not being pressed), I was wondering if internal to the piano there is a difference that would make a musician choose one option over the other.  Remember, I'm asking about a single chord.  I recognize that there is a big difference if multiple chords or notes are played successively.
Comment: I notice that you left out a possible scenario. You play a chord along with the pedal and hold both down for 3 seconds. This will sound the same as "play the chord with the pedal, releasing it after I play it so that the pedal holds the notes." In both cases, the hammers will strike the string for the note, and the dampers on all strings will remain lifted until you release the pedal.
Comment: But do note there is a difference once you start playing more than one note or chord--see https://music.stackexchange.com/q/42614/12300. Keeping your fingers on the notes when you can will help with maintaining an even legato.
Answer: Playing a chord lifts the dampers from just the strings of the notes played.   Depressing the pedal lifts the dampers from ALL the strings.  A lot more resonance.
I'm amazed that you can't hear the difference! Maybe you aren't playing a real piano, but a basic-grade electronic imitation that doesn't model this important part of the piano sound?
Comment: Correct. I haven't had a real piano in many years I'm afraid. I have a Yamaha Arius from 2007, so probably not designed to model that resonance
Comment: On a multi-pedal piano "the pedal" may actually be the sostenuto pedal, which only keeps existing dampers raised.
Comment: @MichaelStachowsky Usually with three pedals, one is the damper aka sustain, one is the sostenuto aka sustain, and one is the una corda aka soft. What do the three pedals on your piano do, exactly?
Comment: @MichaelStachowsky from the photo your piano indeed has three pedals. You may be using the wrong one.
Comment: There are three.  One is the damper, one is (I believe it's called) sostenuto, and one is sustain.  I used the sustain pedal to run my little experiment
Comment: One dampens the sound, one sustains any key held before or played after it, and one keeps notes that are already pressed before the pedal is pressed sounding.
Comment: @MichaelStachowsky if your digital piano has a midi/usb out, try and download a trial copy of [pianoteq](https://www.pianoteq.com/), it is a reasonably faithful physical model that should be enough to try and "get" the feeling of sympathetic resonance vs una corda.
You *might* just enjoy more playing it as well.
Comment: Note that digital pianos and virtual instruments *today* usually model sympathetic string resonance caused by having the damper pedal down, but this was less common in the past, and for lower-priced products today, there may be problems caused by limited polyphony, since additional voices are used for the resonant strings.
Answer: One of the most distinctive features of the piano (as opposed to e.g. the harpsichord or the clavichord) is the sympathetic resonance. Whenever you hit one string, all the strings sympathetic to that one (*) will vibrate along with it. Usually the dampers get rid of this resonance immediately, but holding down the damper pedal lets it shine through.
Try this: hold down middle C (C4) and/or the G above it (G4), then keep holding them after the sound's died away. This keeps their dampers off so they can resonate properly.
Then, while still holding those keys, strike and release the C below middle C (C3). When you release C3, its own sound will be cut off—but the other strings will still be sounding! This is the extra sound that you get when you hold down the damper pedal, except the damper pedal gives you every sympathetic note, all at once. It's a much richer, warmer sound.
(*) How "sympathetic" two strings are comes down to how well their harmonic series overlap. Try the experiment again, but this time hold down D4 and strike C4. You won't hear much resonance, because those strings aren't very sympathetic to each other.
Comment: This is one example of so-called **finger pedaling**, although more commonly that means continuing to depress certain keys longer than notated, instead of a silent depress of keys not notated.
Answer: Using the pedal, there is sympathetic vibration from other strings that would otherwise  be dampened.  This leads to more of a "chorus" kind of sound.  You can amplify the effect by striking a chord strongly and very shortly and right after releasing the keys pressing the pedal.  While the strings of the struck keys will still contribute more to the resulting sound, the contribution of the other strings becomes quite more obvious.
Comment: I asked about this technique several years ago. What is it called?
Comment: @Tim I'm not sure it has a name, actually; usually the description is just written out like in this answer.
Comment: @Tim That would be *laissez vibrer*, often written as notes tied to nothing.
Comment: @ericw31415 - Isn't *laisser vibrer* simply leaving the pedal down. My effect is playing a chord percussively, staccato), then using the pedal *after* the keys have been released, but the notes are still sounding.
Answer: On my old Acrosonic Baldwin (1947), I have played with the center pedal down to get a kind of resonance that's similar to "hall" on electronic pianos.
Of course, I have to stay at the upper end and steer clear of bass notes as those will just sustain indefinitely when center pedal is down.
Side note:  What's that pedal really used for, anyway, and does it have a name?
Comment: The middle pedal is called the _sostenuto_; originally, it would keep the dampers off for *every note being held at the moment the pedal was pressed*. But this was really hard to implement on an upright piano, so uprights tend to "cheat": the sostenuto instead keeps the dampers of for *all the bass notes* (since those are usually what you want to sustain).
Comment: (For a fuller answer, feel free to ask that as a question!)
Comment: @Draconis, the bass notes held by the sostenuto pedal is how my baby grand works as well. I have never seen it do differently, on any piano I have checked. (Keeping in mind that I wasn't fiddling around looking at the pedals and their effects on the dampers when I had opportunity to rehearse or perform on a real concert grand.)
Comment: @HeatherS. Huh, interesting! I've never seen a grand with that sort of sostenuto, but I've only played on a few pianos myself, so I'm ready to believe it.
Comment: @Draconis, I never imagined differently because I never saw a need to sustain higher notes. Besides, the highest notes don't have dampers anyway.


Quero fazer um botão que altere o background da página. Escrevi em js mas não sei porque não funciona

Question: <!doctype html>

        <title>ABC</title>
        <meta charset="utf-8">

            <button id="bblue" onclick="changebgtoblue()">blue</button>

Answer: 3 coisas erradas no teu código:

Em HTML não podes comentar atributos, remove esse /* */
A propriedade background-color em JavaScript não pode ter -, tem de ser escrito em camelCase, ou seja: backgroundColor
coloca o script no final do body, ou usa onload para correr o script. O teu código JavaScript ainda não sabe da presença do código HTML pois ele ainda não foi lido.

Exemplo corrigido:

#bblue {
  background-color: lightblue;
  padding: 10px;
}

  <button id="bblue" onclick="changebgtoblue()">blue</button>


Não consigo executar um script de uma pagina externa

Question: Boa noite venho, tentando criar um script em javascript que quando o usuário clicar em uma palavra dentro de um menu no site, apareça um span com um texto. Consegui fazer o script e funcionou perfeitamente quando estava na pagina index.html, mas quando passei a script para a pagina.js, ele deixou de funcionar.
Só para esclarer esse basicamente é TCC do meu grupo, estamos montando um site para uma clinica médica, nosso programador mudou de escola durante a pandemia, perdemos o contato com ele é nosso projeto, então eu sou o responsável pela programação, agradeço a ajuda desde já, e aceito qualquer dica que estivem dispostos a compartilhar.
edição: Basicamente o que eu quero fazer é quando o usuário clicar em qualquer um dos nomes da especialidades, apareça um span falando sobre a especialidade.

function iniciapop(popid) {
    const pop = document.getElementById(popid);
    if (pop) {
        pop.classList.add('mostrar');
        pop.addEventListener('click', (e) => {
            if (e.target.id == popid || e.target.className == 'fechar') {
                pop.classList.remove('mostrar');
            }
        });
    }
}
const abrir = document.querySelector('.logo');
abrir.addEventListener('click', () => iniciapop('popup'));
body {
    padding: 0 auto;
    margin: 0 auto;
}
.header {
    width: 100%;
    }

    .Menu-Principal {
        width: 100%;
    background-color: #252323;
    height: 60px;
}

.logo {
    padding: 10px;
    background: black;
    height: 40px;
}
.header-2 {
     background-color: #ffffff;
    width: 980px;
    margin:0 auto;
    padding:15px;
     /*Ajustar padding para 0*/
}
.Tela-100 {
     width: 100%;
    float:left;
    position: relative;
}

.Menu-Secundario {
    border-bottom: 5px solid #efefef;
    height: 80px;
    background-color: #ffffff;
}

.menu ul li {
    display: inline-block;
    color: #8b8b8b;
    margin-left:15px;
    height: 38px;
}

.menu ul li:hover {
    border-bottom: 2px solid #00bac6;
}

.menu ul li a:hover {
    color:#00bac6;
}
.menu ul li a {
    color: #8b8b8b;
    text-decoration: none;
    font-size: 22px;
    /* text-transform: uppercase */
}

.menu {
    width:56%;
    float:left;
    margin-left: -23px;
}
.Busca {
width: 27%;
float: left;
padding: 10px;
text-align:center;
}

.busca input{
    margin-top: 3px;
    height: 33px;
    width:190px;
    padding:12px;
    background-image: url('../img/BuscaIcon.png');
    background-repeat: no-repeat;
    background-position: 93%;
    border: 1px solid #d6d6d6;
}

.login {
width: 15%;
float: left;
margin-left: 2px;
}

.login ul {
    padding: 0;
}

.login ul li {
    display: inline-block;
    color: #8b8b8b;
    height: 38px;
    margin-left: 5px;
}

.login ul li:hover {
    border-bottom: 2px solid #00bac6;
}

.login ul li a:hover {
    color:#00bac6;

}
.login ul li a {
    color: #8b8b8b;
    text-decoration: none;
    font-size: 22px;
}

.blocos-1{
    padding: 0px;
    margin: 0px;
    width: 100%;
    position: relative;
}

.bloco-texto-1{
    min-width: 490px;
    background-color: #54789b; /* or #54789b  #007fff */
    font-family: sans-serif;
    float: left;
    width: 50%;
    overflow: hidden;
    height: 600px;
}

.textprinci{
    color: #ffffff;
    margin-left: 4%;
    overflow: hidden;
    margin-top: 20px;
}

.textprinci p mark{
   color: #233547;
    background-color: #54789b;
}

.textprinci p1{
    font-size: 45px;
    margin-left: 7% !important;
}

.textprinci p{
    font-size: 20px;
}

.bloco-img1{
    min-width: 490px;
    float: right;
    width: 50%;
    overflow: hidden;
}

.bloco-img1 img{
    height: 600px;
}

.list-1{
    margin-left: 4%;
    margin-top: 20px;
}

.list-1 ul-1{
    color: #ffffff;
    width: 48%;
    float: left;
}

.list-1 ul-2{
    color: #ffffff;
    width: 51%;
    float: left;
}

.list-1 ul-2 a, ul-1 a {
    text-decoration: none;
    color: white;
    font-size: 25px;
    font-family: sans-serif;
}

.title{
    background-color: #233547; /*or #1a6295 */
    height: 130px;
}

.title h1{
    color: #ffff;
    text-transform: uppercase;
    text-align: center;
    width: 100%;
    margin: 0;
    padding: 0;
    font-size: 50px;
    padding-top: 3%;
}

.blocos-2{
    padding: 0px;
    margin: 0px;
    width: 100%;
    position: relative;
}

.bloco-img-2{
    float: left;
    width: 50%;
}

.bloco-img-2 img{
    width: 100%;
}

.bloco-text-2{
    background-color: #233547;
    width: 50%;
    float: right;
    min-width: 490px;
    font-family: sans-serif;
    overflow: hidden;
    height: 656px ;
}

.textprinci-2{
    color: #ffff;
    margin-left: 4%;
    margin-top: 20px;
}

.textprinci-2 p1{
    font-size: 45px;
}

.textprinci-2 p{
    font-size: 20px;
}

.textprinci-2 p mark{
    color: #7be9e7;
    background-color: #233547;
}

.list-2{
 margin-left: 4%;
}

.list-2 ul-3{
    color: #ffffff;
    /*width: 48%;
    float: left;*/
}

.list-2 ul-3 a{
    text-decoration: none;
    color: white;
    font-size: 25px;
    font-family: sans-serif;
}

.popup-container{
width:100%;
height:100%;
background:rgba(0,0,0,.5);
position:fixed;
top:0px;
left:0px;
z-index:2000;
display:none;
justify-content:center;
align-items:center;
}

.popup-container.mostrar{
    display:flex;
}

.pop{
background:#ffff;
width:60%;
min-width:300px;
padding:40px;
border:10px solid #111a23;
box-shadow: 0 0 0 10px white;
position:relative;
}

.fechar {
position:absolute;
font-size:1.2em;
top:0px;
right:0px;
width:50px;
height:50px;
border-radius:50%;
border:4px solid white;
background:black;
color:white;
cursor:pointer;
box-shadow: 0 4px 4px rgba(0,0,0,.3);
}

@keyframes pop{
from {
opacity:0;
transform:translated3d(0, -60px, 0);
}
to{
opacity:0;
transform:translated(0, 0, 0);
}
}

.mostrar .pop{
animation: pop .3s;
}

.pop h1{
    font-size:40px;
    font-family: sans-serif;
}

.pop p{
    font-size: 25px;
    font-family: sans-serif;
}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="./css/pagEspecialidades.css">

    <title>Imperium Especialidades</title>

Home

Sobre Nos

especialidades

Exames

Contato

                <input placeholder="Pesquise" type="text" />

Login

Cadastro

Especialidades

                    <p1>
                        Especialidades Médicas
                    </p1>

                        Para a prevenção ou tratamento de determinadas doenças, é necessário dirigir-se a um médico
                        especialista.

                        A Clínica oferece várias especialidades médicas com acolhimento diferenciado e
                        profissionais dedicados a cuidar do seu problema de maneira específica.  Clique na
                            especialidade
                            para
                            mais informações.

Acupuntura

Angiologia

Cardiologia

Clínica Médica

Dermatologia

Endocrinologia

Gastroenterologia

Ginecologia

Neurologia

Obstetrícia

Oftalmologia

Ortopedia

Otorrinolaringologia

Pediatria

Pneumologia

Psiquiatria

Radiologia

Reumatologia

Urologia

                    <p1>
                        Especialidades Odontológicas
                    </p1>

                        A Clínica Rio de Janeiro oferece vários tratamentos odontológicos para deixar seu sorriso mais
                        bonito e saudável. Clique na especialidade para mais informações.

Cirurgia e Traumatologia Buco – Maxilo – Facial

Endodontia

Implantodontia

Odontogeriatria

Odontologia estética

Odontopediatria

Ortodontia

Periodontia

Prótese Dentária

                <button class="fechar">x</button>

Qualquer coisa

                <form>

O odontopediatra atua na prevenção, manutenção e reabilitação da saúde bucal da criança, educando
                        sobre saúde bucal, fazendo o diagnóstico, a prevenção, o tratamento e controle dos problemas da
                        saúde bucal infantil.

                </form>

Comment: Eu costumo empacotar esse tipo de função de "evento na escuta" em uma função `onload`, para esperar o carregamento do HTML... Ocorre que como está no header, a função é carregada antes do elemento...
Answer: Esse tipo de erro se dá pelo fato do script ser executado antes do carregamento completo do DOM.
Existem algumas formas de previnir esse erro.
Eu utilizo:
window.onload = function() { ... Code }
Tem outras abordagens
https://stackoverflow.com/questions/26107125/cannot-read-property-addeventlistener-of-null/26107174
Se eu lembrar de alguma resposta daqui do site que aborda mais profundamente eu edito.
Answer: Obrigado, consegui uma abordagem que se encaixa no meu cenário pelo link, tambem não sabia sobre o window.onload = function(){}, pesquisei e apliquei algumas vezes, me ajudou com algumas problemas futuros.
Agradeço muito :).