Can we do .net web application in testing with Java selenium code?

Question: I need to configure the pipeline in AZURE Devops  but the thing is Web Application is in .Net and testing is happening in Java Selenium . Please help can we configure both the things in AZURE Devops pipeline?
As per RnD i can take the build from MSBuild for .Net and Maven for Java but how to do testing for the above scenerio.
Thanks in advance.
Answer: 1.If you're familiar with C#, maybe you can consider using C# Selenium code to test .net web application so that you can use official VSTS task to run the Selenium test, and you can easily follow this document to configure the CI/CD process.
(A msbuild/VSbuild task to build both two projects and use VSTS task to execute the tests.)
2.Here's one possible direction if you do want to use .net web app + java selenium test: In build pipeline you should have msbuild task to build the web app and maven task to build java code.
In the end of the build pipeline you should have one Publish Artifact task to publish the outputs of this build pipeline.
Now in release pipeline, instead of using VSTS task, you may use maven task(One issue I saw)/CMD/Powershell task to execute the tests. As I know the selenium tests can be executed in command-line and there're many topics about it.
Answer: Java selenium test is used to do web UI automated tests, it doesn't care what technology the web app used.
So, in Azure DevOps pipeline, you just need to build your web app through Dotnet Core task, run it by calling dotnet run command, then build and run Java selenium test project through Maven task.


Learning to interact with an audience

Question: Performing musicians practice our instruments away from the stage in order to make the best music we can. How can we practice audience interactions?
In many performances, interacting verbally and nonverbally with the audience is integral to the experience: talking about the history of a song, pumping up the crowd, playing to particular people in the audience, making transitions between one piece and another, stalling for time while retuning an instrument, ....
But there are pitfalls: awkward personal stories, running out of things to say, rambling, ....
What practice techniques/exercises can be used outside of performance to develop these interactive, audience engagement skills?
Comment: I kind of appreciate the idea that being a musician doesn't have anything to do with music.
Comment: @ElementsinSpace Music is culture. People doing things with people, for people. It's not a natural science where substances are measured and analyzed under a microscope in a laboratory and theories are compared with measured results. The whole "objective truth" ideal that's implied in the design of this site is absurd, when it comes to music.
Comment: I don't see what this has to do with music at all. It's a question about being a musician and performing, but it's not about music.
Comment: Note: This is a sort-of-duplicate of [Talking with the audience in a show](https://music.stackexchange.com/questions/34054/talking-with-the-audience-in-a-show). It was decided in [a chat discussion](https://chat.stackexchange.com/rooms/440/the-practice-room) that the topic was better served by a new question. Hopefully this will serve.
Comment: It's very borderline. And I think the skill can only be learned/honed while at gigs. Some are naturals, others just keep on playing...
Comment: As an audience member, I *hate* being told the history of a song, awkward jokes, and most especially exhortations to join to the mailing list. And when I formed my most recent band, I requested that we never do those things, and our shows were very well liked. They are not necessary. Aside from the answer about practicing as if it's a gig, the best way to practice gigging is to gig a lot. Also attend gigs and think critically about what other bands do. Model your gigs after your favorite bands. Some almost never have banter and it works. Other talk a lot and it works.
Comment: Just one helpful technique among many: Find a riff that you can loop on auto-pilot while talking. Preferably one that leads into the next piece. Maybe a iii-vi-ii-V loop, if that's not too cheesy.
Answer: This is going to sound funny, but every time I practice, I do so by performing as though I am front of the live audience.
I strap my guitar on, plug it in thru my pedal board and amps, and I stand up to the mic stand that is plugged into the music room PA system.
Whether practicing by myself solo, or in a full band practice session, I perform each song as though the audience is out there in front of me.
I keep eye contact with fictitious audience members, I introduce each song with the same patter that I intend to use during live gigs, and move around and smile as though we are in the club, bar, or open air stage.
Practicing while seated (in front of sheet music or the computer) isn't doing me any good at all. There's no point in it for me.
My band mates have gotten used to this quirky habit of mine, but they accept it as part and parcel of 'professional preparation'.
Comment: My most recent band, the band mates were 100% on board with this. We didn't always practice this way because we also had writing focused practices where we spent a lot of time talking and experimenting with different song structures, etc. But as we geared up for gigs we wrote set lists and ran them down just like we planned to at the show. All facing the same direction instead of each other, etc.
Comment: Same here. Last practices before a gig were always "performing to the wall". We also made sure to time our "fake gigs" to make sure we are not over or under estimating the lengths of our sets. Also, we made sure to really "lock in" to the tempo of all songs. A good way to do that was to find a line of text or a specific guitar phrase that only worked in a specific tempo. E.g. there was one of our songs which had a line of text that was pretty impossible to sing of the tempo was too fast. So, you'd only have to sing that one line to yourself to get the tempo of the song.
Comment: Same here.  I would add to that practicing in front of a full-length mirror. Look at what the audience sees.

Learning to interact with an audience


How can I block all external IPs to endpoints behind AWS ELB?

Question: OK - so I have a developer that does not want our REST endpoints to be accessible externally with the only access allowed is localhost and the internal network scheme. Our internal network scheme is 10.10.x.x.
The way we did this is with the < LocationMatch > switch in the .conf file as follows:
<LocationMatch "/foo/bar/*">
  Order deny,allow
  Deny from all
  Allow from 10.10
  Allow from 127
</LocationMatch>

Now, the challenge we are having is that the AWS Load Balancer has an X-Forward-Host rule on it so all original source IPs and if I do Allow from 10 - obviously, will allow access to all endpoints externally because of this.
As stated before, our internal IP is 10.10 so I can do allow from 10.10 and that would resolve it but if I make more regions then the network scheme could be 10.20.x. 10.30.x.x 10.40.x.x and then it becomes a bit of an administrative nightmare.
So, what makes sense is someone mentioned to do something on the http.conf level:
<Directory />
    #Example..
    SetEnvIF X-Forwarded-For "(,| |^)192\.168\.1\.1(,| |$)" DenyIP
    SetEnvIF X-Forwarded-For "(,| |^)10\.1\.1\.1(,| |$)" DenyIP
    Order allow,deny
    Deny from env=DenyIP
    Allow from all
</Directory>

found from this blog
So, I am unsure how to follow this format and ensure that it denies all external IPs to these directories.
Would the http.conf file have something like:
<VirtualHost>
    #Example..
    SetEnvIF X-Forwarded-For "(,| |^)*\.*\.*\.*(,| |$)" DenyIP
</VirtualHost>

and my other conf file with the < LocationMatch > rules have:
<LocationMatch "/foo/bar/*">
  Order deny,allow
  Deny from env=DenyIP
  Allow from 10.
  Allow from 127
</LocationMatch>

Thanks for your help!
Comment: Should we understand from this that your APIs are not on their own servers, but are on servers (and an ELB) that also serve up content that should be publicly accessible?
Answer: Rather than modifying apache, use Security Groups!

Create a security group for your Elastic Load Balancer. Allow in-bound access from 0.0.0.0/0 for ports 80 & 443.
Create a security group for your apache server(s). Allow in-bound access from the ELB Security Group (a security group can reference another security group). Also add access so you can SSH into the server(s).

That's it! The security groups will block traffic that attempts to access your apache server(s) without passing through the Load Balancer.
See:

Amazon EC2 Security Groups for Linux Instances
Configure Security Groups for Your Load Balancer


GLS (nlme) model with interaction and unbalanced data

Question: I have a dataset of soil pH data and two explanatory factors, one with 5 levels (land use)and another one with >100 levels (soil type). Data exploration and comparison of several GLS models fit with nlme suggest that there is an interaction between the two factors. I use GLS instead of lm because there seems to be some heterogeneity in the residuals depending on Soil Type, that I would like to fix with GLS (varIdent). I can test the significance of  the interaction with the likelihood-ratio test (ML), but I don't know how to include the interaction term and the vaIdent (by Soil type) with the unbalanced data.
Ideally, I would write the model like this:
gls0 <- gls(pH ~ SoilType * LandUse, weights = varIdent(form=~1|SoilType), data=mydata)
But it gives the following error (because the data is unbalanced):
  computed "gls" fit is singular, rank 312

So I create a new factor with the interaction, fit the model, and check that the interaction term is significant:
mydata$ii <- droplevels(interaction(mydata$SoilType, mydata$LandUse))

gls.ii <- gls(pH ~ ii, data = mydata, na.action = na.omit)
gls.m1 <- gls(pH ~ SoilType + LandUse, data=mydata)
anova(update(gls.ii, method = "ML"),
      update(glsm1, method = "ML"))
# or
gls.m1 <- gls(pH ~ SoilType, data=mydata)
anova(update(gls.ii, method = "ML"),
      update(glsm1, method = "ML"))

My first isssue is that I cannot fit the model gls.ii <- gls(pH ~ ii, weights = varIdent(form=~1|ii), data = mydata, na.action = na.omit) for memory issues (Error: cannot allocate vector of size 17.8 Gb). This is why I tested the interaction term without including the error variance term in the models.
But my second question is, is there another way I can fit the model with unbalanced data (without eliminating observations to make it balanced), specifying both variables? this way I could try to include weights = varIdent(form=~1|SoilType) instead of weights = varIdent(form=~1|ii).
Thanks.
Answer: There's a lot going on here so I'll take a stab at addressing some of the issues.
Unbalanced data terminology
The "unbalanced data" terminology is misleading in my view.  When we have several groups and measure the value of a response variable (e.g., pH) for different numbers of study units within each group, we say that the groups are unbalanced. In your case, the groups would be all possible combinations of SoilType and LandUse. It's not clear from your description what your study unit is (e.g., soil sample) but hopefully you have several study units per group.
Combinations of levels of SoilType and LandUse
What I think you mean by "unbalanced data" is the fact that you did not consider all possible combinations of levels of SoilType and LandUse in your study - you only considered a subset of these combinations.  This would explain the error message you get from R regarding the singular gls fit. You can verify if this is the case for your data using the R command:
with(mydata, table(SoilType, LandUse))

The command will show you how often each possible combination of levels of SoilType and LandUse appears in your data. If a particular combination does not appear at all in your data, the contingency table produced by the above command will show an entry of 0 for it.
Addressing missing combinations of levels of SoilType and LandUse
If you are missing some of all possible combinations of SoilType and LandUse but you try to fit a gls model including an interaction between SoilType and LandUse, you will get the dreaded singular fit message from R.
This is because the design matrix for your model is degenerate. See this excellent post on Degenerate design matrices for more details: https://rstudio-pubs-static.s3.amazonaws.com/6311_a09169ad892f4f5499874751a5fa822d.html.
To circumvent this message, you would need to "manually" define a variable which indicates what specific combination of levels of SoilType and LandUse you are dealing with for each of the study units represented in your data. For example:
mydata$Combination <- interaction(mydata$SoilType,
                                  mydata$LandUse)

mydata$Combination <- droplevels(mydata$Combination)

Then you can fit a gls model which does not use the weights = option like this:
gls(pH ~ Combination, data = mydata)

Here, I assume for simplicity there are no missing values in your data.
Simple example
The link on degenerate design matrices includes a simple example where Combination would be obtained by listing those combinations present in the data for two factors: f1 and f2.  (In your case, f1 would be SoilType and f2 would be LandUse). In the example, f1 has 2 possible levels: a and b; f2 has 2 possible levels: A and B.  All possible combinations of levels of f1 and f2 would be: aA, aB, bA, bB. However, in the data underlying that example, only the combinations aA, bA and bB are represented. If the gls() model is fitted as:
gls(y ~ 1 + Combination, data = etc.)
then R will look at the levels of Combination: aA, bA and bB. It will then set aside the first level, aA, and report 3 lines of output. The first line of output will report the estimated mean of y when Combination = aA. The second line of output will report the difference in the estimated mean value of y between Combination = bA and Combination = aA. The third line of output will report the difference in the estimated mean value of y between Combination = bB and Combination = aA. (Combination is denoted by f12 in the example).
If you compare the model gls(y ~ 1 + Combination, data = etc.) against the model gls(y ~ 1, data = etc.), you will be able to test these hypotheses:
Ho: there is no difference in the mean value of y across any of the combinations of levels of f1 and f2 represented in the study
Ha: there is a difference in the mean value of y across at least two of the combinations of levels of f1 and f2 represented in the study
The null hypothesis Ho corresponds to the model gls(y ~ 1, data = etc.), whereas the alternative hypothesis Ha corresponds to the model gls(y ~ 1 + Combination, data = etc.).
Of course, if Ho is rejected in favour of Ha, one would have to detect which specific combinations are different from each other by performing post-hoc comparisons of combinations.
Another possibility here would be that we know upfront we are only interested in comparing certain combinations - in other words, we would have some planned comparisons of combinations in mind from the study design phase: say, we would only want to compare the mean value of y for combinations bB and bA. Then we wouldn't need to test Ho against Ha - we would simply proceed to perform the comparisons of combinations of interest. This can be done by setting up and testing/estimating contrasts of combinations.
This is simple enough to do with just 2 levels per factor. But in your case, you'll have a large number of combinations, so you may either want to consolidate your LandUse definition to a smaller number of levels, or identify some specific combinations of interest, etc. Otherwise, you will have a massive number of comparisons on your hands. In any event, adjusting for multiplicity of comparisons will be a must!
Non-Constant Variability
After fitting the model gls(pH ~ Combinations, data = mydata), you can plot its residuals against SoilType to see whether there is evidence of non-constant variability across SoilType. If there is, fit a model like:
gls(pH ~ 1 + Combination,
    weights = varIdent(form=~1|SoilType),
    data = mydata)

Then, if you are able to fit the model without running into memory allocation issues, you would still need to consider performing multiple comparisons of combinations of levels. In particular, should you perform all possible comparisons or just a select few identified at the study planning stage?
If you can't fit the above model due to memory allocation issues, you may have no choice but to consolidate the levels of LandUse.  Just use a command like:
table(mydata$LandUse)

and merge levels which are minimally represented in the data with levels that are maximally represented provided that makes substantive sense.


How to prove that this argument is valid?

Question: I've been stuck on this problem for a while, mainly because I'm not sure if I'm using predicate symbols correctly , and partyl because I can't figure out how to get to the conclusion.  Ive done questions like this before , but for some reason i just cant figure this out. I hate to ask , but please help!

Every truck has a radioSome trucks have a CD player Therefore some trucks have both a radio and a cd player.

I believe the following to be the starting point.

forall xT(x) implies R(x)thereexists xT(x) implies C(x)
Comment: The secon premsie needs "and" and not "implies".
Answer: Your choice of symbols is fine:
$T(x)$: $x$ is a truck
$R(x)$: $x$ has a radio
$C(x)$: $x$ has a CD player
Your symbolization of the first statement is also correct:
$\forall x (T(x) \rightarrow R(x))$ : All trucks have a radio
But your symbolization of the second statement was not correct. You said:
$\exists x (T(x) \rightarrow C(x))$ : Some trucks have a CD player
Your symbolization reads: there is something such that if it is a truck, then it has a CD player.  But notice that if there is anything in the world that is not a truck, then that very non-truck object will make that statement true, since the antecedent of the conditional will be false, and that will make the whole conditional true (check its truth-table: if the 'if' part is false, any 'if ... then' statement is automatically true). So: your symbolized sentence could be true without any trucks having any CD player, so this is not what you want.
Long story short: you really don't want to use a conditional in combination with an existential: that is almost always asking for trouble. Instead, use an $\land$. So, the second statement should be:
$\exists x (T(x) \land C(x))$
To symbolize the conclusion you do a similar thing:
$\exists x (T(x) \land (C(x) \land R(x))$ Some trucks have both a radio and a CD player
OK, so as a whole argument, you have:
$\forall x (T(x) \rightarrow R(x))$
$\exists x (T(x) \land C(x))$
$\therefore \exists x (T(x) \land (C(x) \land R(x))$
Now, how do you prove this valid?  It really depends on what system you are using (and hence what inference rules are available for you to use), but a typical proof would go something like this:

$\forall x (T(x) \rightarrow R(x))$ (premise)
$\exists x (T(x) \land C(x))$ (premise)
$T(a) \land C(a)$ Existential Elimination 2
$T(a)$ Simplification 3
$T(a) \rightarrow R(a)$ Universal Elimination 1
$R(a)$ Modus Ponens 4,5
$C(a)$ Simplification 3
$C(a) \land R(a)$ Conjunction 6,7
$T(a) \land (C(a) \land R(a))$ Conjunction 5,8
$\exists x (T(x) \land (C(x) \land R(x))$ Existential Introduction 9
Comment: Thank you so much , I can't believe I got stuck here. Just one thing , you said my symbolisation of the conclusion was incorrct , but i only symbolised the two hypotheses.
Comment: @FutureSci You are correct ... I was too focused on the conclusion!  I'll edit my answer.
Answer: $$\forall\ t \in T: R(t)$$
and
$$\exists\ t\in T: C(t)$$
implies
$$\exists\ t\in T: R(t)\land C(t).$$
Proof: choose some $t$ such that $C(t)$; by the first predicate, $R(t)$ holds. Then $R(t)\land C(t)$ as well.


Bootstrap vs numerical integration

Question: My understanding of the bootstrap approach is based on Wasserman's framework (almost verbatim):

Let $T_n = g(X_1, ..., X_n)$ be a statistic ($X_i$ is the iid sample
  drawn from distribution $F$). Suppose we want to estimate $V_F(T_n)$ - the
  variance of $T_n$ given $F$.
The bootstrap approach follows these two steps:

Estimate $V_F(T_n)$ with $V_{\hat{F}}(T_n)$, where $\hat{F}$ is the empirical
  distribution function.
Approximate $V_{\hat{F}}(T_n)$ using simulation.

Do I understand correctly that the simulation in step 2 could be replaced with a precise calculation, except that it is infeasible for practically useful values of $n$? Here's my thinking: $V_{\hat{F}}$ precisely equals an integral of $T_n(X_1, ..., X_n)d\hat{F}(X_1)d\hat{F}(X_2)...d\hat{F}(X_n)$. $\hat{F}$ is a step-function, with a finite number $n$ steps; so we can ignore all points except the $n$ points where $d\hat{F}(x)$ has non-zero mass. So the integral is precisely equal to a sum of $n^n$ terms. Once $n$ exceeds 14, a simple direct calculation is impossible.
But all we're trying to do is calculate an integral. Why not replace the brute-force bootstrap simulation with any of the traditional numerical algorithms for taking integrals? Wouldn't it result in much higher precision for the same computational time?
Even something as simple as splitting the sample space in sections (perhaps with smaller volumes where sample statistic varies faster), and estimating the value of the statistic in each section by using the middle point, seems to be better than blind bootstrap.
What am I missing?
Perhaps bootstrap works so well and so fast that there's no need to do anything more complicated? (For example, if the loss of precision in step 1 is so much greater than in step 2, then improvements to step 2 are rather useless.)
Answer: The bootstrap works remarkably well. If you want to estimate the mean, variance and some not-too-extreme quantiles of the distribution of some low-dimensional $\hat\theta(Y)$, a few hundred to a few thousand re-samples will make the Monte Carlo error negligible, for many realistic problems. As a happy by-product, it also gives you a sample of $\hat\theta(Y^*)$, that can be used for diagnostic procedures, if desired, and it's not too difficult to get acceptably-good measures of how big the Monte Carlo errors actually are.
Fitting a regression model e.g. a thousand times over is (today) not a big deal, either in terms of CPU time or coding effort.
In contrast, numerical integration (excluding Monte Carlo methods) can be difficult to code - you'd have to decide how to split the sample space, for example, which is a non-trivial task. These methods also don't give the diagnostics, and the accuracy with which they estimate the true integral is notoriously hard to assess.
To do most of what the bootstrap does, but quicker, take a look at Generalized Method of Moments - for inference based on regression models (and much else) you can think of it as a quick, accurate approximation to what the non-parametric bootstrap would give.
Comment: Thanks. Since step 2 is handled pretty well, I'm curious, can GMM or any other technique address the imprecision in step 1 (where we estimate the variance of the true distribution with the variance of the empirical distribution)?
Comment: "Plain vanilla" GMM uses pretty straightforward approximations to the true covariance. Use of higher-order approximations (saddlepoint approximations and the like) can be used, but you'd have to code them yourself, and possibly make slightly-stronger assumptions than typical GMM to ensure you're getting the "best" approximation.
Answer: The simulation most often used in bootstrapping for the numerical computation of the variance could in principle be replaced by an exact computation or an alternative approximation of the integral. One should, however, be aware that a "brute-force" simulation as an alternative to other numerical integration techniques is actually a good idea. The answer to the question "Wouldn't it result in much higher precision for the same computational time?" is no.
But why is that so? The thing is that standard numerical integration in high-dimensions scales badly with the dimension. If you are to divide the space into regular grid points, say, with $r$ grid points in each coordinate, you end up with $r^n$ grid points in total. The approximation achieved by simulation (know as Monte Carlo integration) can be viewed as a clever choice of function evaluations. Instead of time consuming grid evaluations we only evaluate the function we integrate at selected points. The error is, due to the random nature of the selected points, random, but can usually be controlled by the central limit theorem.
There are other methods such as quasi-Monte Carlo integration, that I know virtually nothing about, that make clever function evaluations based on quasi-random numbers instead of the pseudo-random numbers that we use for ordinary Monte Carlo integration.

Bootstrap vs numerical integration


Closed under finite union and Closed under countable union

Question: Since union of sets is defined to be independent of the number of sets as in Wikipedia

If M is a set whose elements are themselves sets, then x is an element of the union of M if and only if for at least one element A of M, x is an element of A.

I was wondering why for a class of subsets of a set, it being closed under finite union and it being closed under countable union are not same?
Similar question for intersection.
Thanks and regards!
Answer: Starting from a initial collection of sets being allowed to take countable unions and intersections lets you create many more sets that being allowed to take only finite unions and intersections. Therefore it seems plausible to me that the former can take you out of your starting collection even if the latter does not.
You can find examples in any standard measure theory text. Here is a very simple one. Let
$$A_n=\{1,2,3,\ldots,n\}$$
Let $\Omega$ be the collection of the sets $A_n$ for $n \in \mathbb{N}$.
Then for a finite set of indices, $n_1,n_2,\ldots,n_k$ say, the union
$$A_{n_1} \cup A_{n_2} \cup \cdots \cup A_{n_k} = A_{\max\{n_1,\ldots,n_k\}}$$
and hence belongs to $\Omega$. So $\Omega$ is closed under finite unions.
But the countably infinite union
$$\cup_{n=1}^{\infty} A_n = \{1,2,3,\ldots\}$$
and hence does not belong to $\Omega$. So $\Omega$ is not closed under countable unions.
Comment: i would like to ask why countably infinite union does not belong to $\Omega$?
Answer: Hmm.  There is a somewhat sneaky and quite false conclusion being made here.  It's true that the Wikipedia definition doesn't mention the number of sets.  However, that doesn't mean that union and intersection are "independent of" the number of sets.  I can't even figure out what this would mean.  To state an obvious counterexample, adding another set to your union will give a set with at least as many elements as before, and adding another set to your intersection will give a set with at most as many elements as before.  (Not even in the sense of cardinality, but just the simple fact that
$$\left(\bigcup_\alpha A_\alpha\right)\cup B\supset \bigcup_\alpha A_\alpha$$
and the dual statement for intersections.
Jyotirmoy's example shows that the countable union of finite sets isn't finite.  Another one comes from topology.  A topology on a set $X$ is defined to be a set of subsets of $X$ that is closed under unions and finite intersections.  We call such sets "open," and they're roughly a way of saying what points are close to each other.  A typical example is the Euclidean topology on $\mathbb{R}$, which consists of the open intervals $(a,b)$ and their unions.  This is well-defined because any finite intersection of open intervals is either the empty set or another, smaller open interval.  On the other hand, the set $\bigcap_n (-1/n,1/n)$ is just the point $\lbrace 0\rbrace$, which is definitely not a union of open intervals.
On the other hand, countable intersections are still kind of important in the same general situation.  A $\sigma$-algebra is a set of subsets of $X$ that is closed under complementation and countable intersections (and thus also countable unions).  You can use such a thing to define a "measure," which is an assignment of a sort of "size" to each set in the $\sigma$-algebra.  The algebra of Lebesgue-measurable on $\mathbb{R}^n$ is probably the best example, but you can turn any topology into a $\sigma$-algebra, called its Borel algebra, just by iterating countable intersections and countable unions.  A set that's a countable intersection of open sets is called a $G_\delta$, from the German words "gebiet Durchschnitt" meaning "open intersection."  So we know, for example, that every $G_\delta$ in $\mathbb{R}$, though not necessarily open, has a Lebesgue measure.


Setar atributo de uma outra classe Python

Question: Eu estou estudando python e gostaria de entender como posso definir um atributo de uma classe com base em atributos de outra classe.
Eu vou para o exemplo para ficar mais claro, é apenas um exemplo do que preciso para minha pequena aplicação django, onde no cadastro de uma pessoa, irei setar o cargo dela com base nos cadastros de cargos.
<code>    {class Pessoa(models.Model):

    nome = models.CharField(max_length=20, null=False)
    cargo = ##abrir opções de Cargos cadastrados em "Cargos"

class Cargos(models.Model):

    nome_cargo = models.CharField(max_length=20, null=False)}
</code>
Comment: @MauryDeveloper oi, consegui resolver, na verdade era um relacionamento, respondi a pergunta pois consegui entender aqui, Obrigado
Comment: Você quer uma classe em outra classe?
Comment: Nesse link tem uma explicação sobre os relacionamentos do Django: [Relacionamentos de Tabela DJANGO](https://www.treinaweb.com.br/blog/relacionamento-1-1-1-n-e-n-n-com-django/)
Answer: Pessoa deve ter um relacionamento com Cargo, que nesse caso, é um relacionamento 1,n. O Django usa o ForeignKey para esse tipo de relacionamento.
<code>class Pessoa(models.Model):
    nome = models.CharField(max_length=20, null=False)
    cargo = models.ForeignKey('Cargos', on_delete=models.CASCADE)

class Cargos(models.Model):
    nome_cargo = models.CharField(max_length=20, null=False)}
</code>


Preciso recuperar a soma dos maiores valores de cada mes

Question: SELECT SUM(valor_parametros) FROM (SELECT valor_parametros,cnpj,data_movimento FROM (SELECT valor_parametros,cnpj,data_movimento,id FROM  movimento GROUP BY MONTH(data_movimento) ORDER BY id DESC)  movimento where YEAR(data_movimento)='2020' ORDER BY id DESC) AS T GROUP BY cnpj

por exemplo: o cnpj 13566400130 teria que me retornar 10.2 do dia 2020-05-08 ,mas o valor de 10.20 do 2020-04-06 teria que retornar 20.40
Answer: Para buscar os valores agrupados por mês e CNPJ e ter a soma dos valores, como você comentou em seu exemplo e na imagem, você pode utilizar a cláusula group by junto ao sum.
Por exemplo, a consulta abaixo lhe retornaria o mês (extraído da data_movimento), o CNPJ e a soma da coluna valor_parametros, agrupados pelo próprio mês e CNPJ. Desta forma, terá para cada mês cada CNPJ e a soma de valor_parametros respectivo.
SELECT MONTH(data_movimento), cnpj, SUM(valor_parametros)
FROM movimento
GROUP BY MONTH(data_movimento), cnpj

Caso não seja exatamente esta sua dúvida, precisarei de mais detalhes para poder te ajudar!


Set of all polynomials of degree 4 or 6 with usual addition and scalar multiplication is a vector space or not?

Question: I understand that since its usual addition, any two polynomials of degree 4 or 6, when added will result in a polynomial of degree 4 or 6 again.
i.e. a+b belong to set V(say).
Again if i add any such polynomial with a polynomial with zero in its coefficient will result in the same polynomial. so this implies that a+0=a(existence of unique zero element in v)
Similarly it satisfies existence of additive inverse and scalar multiplication too.
So, am i wrong somewhere? Or is it not a vector space?
Comment: Check the degree of the sum $f(x)+g(x)$ of $f(x)=x^4+x^3$ and $g(x)=-x^4+x^3+x^2$ (also check the degree of the zero polynomial).
Comment: Does the zero polynomial have degree 4 or 6?
Comment: @HenningMakholm we can take any degree either 4 or 6.
Comment: @Parul: So you've redefined "degree"?
Comment: oh, so since zero polynomial's degree is not defined, when we add a polynomial of degree 4 or 6 to it, we get a polynomial whose degree is not defined again. Am i correct now?
Answer: No. More generally, the set of polynomials of degree $d$ is not a subspace of the vector space of polynomials, for two reasons:

It does not have a zero element, since $0$ has no degree. In some contexts, on may accept the convention that $0$ has a degree, but this degree is either $-1$ or $-\infty$, not any $d\ge 0$.
The sum of two polynomials of degree $d$ is not necessarily of degree $d$: for instance, if $d=3$, $f(x)=x^3$, $g(x)=-x^3+x+1$, then $f(x)+g(x)=x+1$.

However, as is well known, the set of polynomials of degree at most $d$ is a vector space (of dimension $d+1$).


Rodapé não aparece na primeira página - Laravel DomPDF

Question: Tenho o seguinte código na minha aplicação para gerar um relatório em PDF:
$head = ''
      . '<title>Relatório</title>';

$header = '
Cabeçalho
';

$footer = '
Rodapé
';

$content = '
'
         . '
Relatório
'
         . 'Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

'
         . '
';

$html = $head.$header.$content.$footer;

$pdf = \PDF::loadHTML($html);

return $pdf->stream();

Fiz baseado nessa resposta, mas não sei por que motivo o rodapé não aparece na primeira página, somente da segunda em diante. O cabeçalho aparece corretamente em todas.
Estou usando Laravel 5.1 com o laravel-dompdf.
Comment: Use ID ao invés de CLASS para ver se funciona.
Comment: deu um erro: DOMNode::cloneNode(): ID head already defined
Comment: Mas é só para colocar ID no Header e no Footer. Desculpe.
Comment: mesmo assim da erro, onde eu deixo ID da esse erro. e se eu ponho class ele não poe o rodapé na primeira.
Comment: se tiver como ao menos tirar o cabeçalho também da primeira pagina somente tambem serviria
Answer: Experimenta adicionar o conteúdo dentro da main-content, assim ele não ficará totalmente a esquerda e será mais visível, além disso no rodapé é bom colocar o z-index já que ele é fixo.

Rodapé

Answer: Veja se assim funciona.
<?php

$head = '
         <title>Relatório</title>';

$header = '
Cabeçalho
';

$footer = '
Rodapé
 ';

$content = '
'
         . '
Relatório
'
         . 'Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

'
         . '
';

$html = $head.$header.$content.$footer;

$pdf = \PDF::loadHTML($html);

return $pdf->stream();

Comment: Se não funcionar, é preciso usar classes mesmo. Nunca usei essa biblioteca para o Laravel.
Comment: Infelizmente continuo com o erro DOMNode::cloneNode(): ID head already defined
Comment: pois é a questão é que com classes da esse bug de não carregar o rodapé na primeira pagina, tenso...
Comment: Copia meu código e roda ele aí. Atualizei.
Comment: agora o rodapé não aparece em nenhuma pagina rs
Comment: Ah Mano... Espera.
Comment: Atualizei o código. Roda agora.
Comment: voltamos a estaca 0, primeira pagina sem o rodapé. Já revisei isso mil vezes e não encontro nada errado... to quase considerando pesquisar uma nova forma de gerar o PDF pq pode ser bug nesse domPDF que to usando.
Comment: Pode ser mesmo. No tópico que você citou que eu ajudei a menina lá era isso também.
Comment: Pois é, vou pesquisar outro aqui, caso consiga eu até posto aki depois. De qualquer forma muito obrigado @Zoom
Comment: Vou dar -1 porque chute não é proposta de resolução de problema.
Comment: @dvd obrigado zézão do asp.


Combining related probabilties

Question: I need to calculate the probability of both L and D occurring P(L,D), but they are not mutually independent. I have estimated the probability of P(L) and P(D) with two distinct models and I also know P(L|D) and P(D|L). As far as I can see it I have two different estimates of P(L,D):
P(L) * P(D|L) and
P(D) * P(L|D)

am I best off just averaging these two estimates for a combined P(L,D)?
Comment: I suspect you might get better answers on http://stats.stackexchange.com/
Answer: These two ways of computing the joint distribution should be the same to within numerical precision.  If your algorithms are giving you different answers for these two ways, it is a bug in your code.
For a pair of binary variables, all that you need to do is maintain the occurence count
of each of the four outcomes: (L,D), (!L,D), (L,!D), (!L,!D).
If we let Z=N(L,D)+N(!L,D)+N(L,!D)+N(!L,!D)
then the probability you care about is just:
P(L,D)=N(L,D)/Z

The other (marginal, conditional) probabilities are:
P(L)=[N(L,D)+N(L,!D)]/Z
P(D)=[N(L,D)+N(!L,D)]/Z

P(L | D ) = N(L,D)/[ N(L,D)+N(!L,D)]
P(D | L ) = N(L,D)/[ N(L,D)+N(L,!D)]

with a little algebra you can see that P(L|D)P(D)=N(L,D)/Z=P(D|L)P(L)
This points to how one could combine disparate estimates into a single one: convert them back into "counts" and then add these counts.  A case where this could occur is wheen we have two independent samples S1, S2.  Suppose that you estimated
P(L |D ), P(D) from sample S1 and P(D |L), P(L) from sample S2.  In addition
to the probabilities, we'll need to know count of the the number of samples in each of the samples: N1,N2.  Note: the results only depend on the ratio N1/N2, so if you didn't have the counts, but knew that the sample sizes were always the same, you could substitute N1=N2=1 in what follows.
N(L,D | S1 ) = N1*P(L | D) P(D)
N(L,D | S2 ) = N2*P(D | L) P(L)

N(L,D | S1+S2) = N(L,D|S1)+N(L,D|S2)
P(L,D | S1+S2) = N(L,D|S1+S2)/(N1+N2)

Which in the case of N1==N2 is just averaging them; but that is only true in the special case where the sample size is the same;  otherwise the result is a weighted average.
This is a simplified version of Bill's answer to this question on CrossValidated which handles the cases where the estimators may be correlated and/or involve estimating quantities other than empirical probabilities.
Comment: If they don't satisfy the axioms of probability theory, then you probably shouldn't treat them/describe them as such; in which case your question is "how do I combine two arbitrary heuristic measures of belief?", which is ill formed.  But anyway, I've added additional description of how to combine things that might help, but really, the answer is: estimate the probabilities directly.
Comment: P(L) and P(D) are produced by different estimation models. They are not true probabilities.

Combining related probabilties


Is p-value of R-squared and adjusted R-squared a thing?

Question: I'm currently reading a paper which utilises a multiple regression and reports the adjusted $R^2$ with a p-value, and I'm wondering what this p-value refers to. Can you calculate p-values for adjusted $R^2$? It separately reports the p-values of the t-statistics for each exogenous variable so it can't be t-statistics.
Comment: Because a p-value for an adjusted $R^2$ is nonsense (an adjusted $R^2$ is not a property of the distributional model), I suspect the intention is that the adjusted $R^2$ is a test statistic being used to test the hypothesis that the *true* $R^2$ is nonzero.
Comment: Could you post the link to the paper? Otherwise it is only possible to guess
Comment: I reposted my comment as an answer. It's always hard to prove a negative... and I toned down my comments on post hoc power from "deeply problematic" to "problematic", because in the end, it's not misleading, it's just vacuous.
Comment: @StephanKolassa, you should consider to make this comment as the answer as it answers the question very well. The only other possible answer I can think of is bootstrapped estimates.
Comment: @StephanKolassa thank you for your answer! It does say in the paper that it refers to post-hoc power. Could I ask why this is so problematic?
Comment: The R squared, under the null, has a beta distribution with a certain expectation, which, if I recall correctly, equals the difference between the two R-squared.
Comment: @MichaelM, the null distribution of $R^2$ is discussed here: https://stats.stackexchange.com/questions/130069/what-is-the-distribution-of-r2-in-linear-regression-under-the-null-hypothesis
Answer: I am not aware of much theoretic understanding of the distribution of $R^2$ or adjusted $R^2$ under the null hypothesis, whether asymptotic or not, which would be required to calculate a $p$ value. As POC notes, it might be possible to obtain a $p$ value through bootstrapping. Alternatively, one could run a permutation test. However, if the authors of the paper did something like this, one would expect that they noted it in the text.
What is indeed common is reporting the $p$ value of an $F$ test for the ANOVA between a given model and an intercept-only model. It may well be that the authors' software reported the $F$ statistic (with its degrees of freedom), the $R^2$ and the $p$ value for the $F$ test, and the authors only reported $R^2$ and $p$.
What is a little more concerning to me is the "power" column, which I fear refers to post hoc power, which is problematic. It simulates understanding we do not have, because if a significant effect was found, then the study was by definition sufficiently powerful to detect this effect as significant. Post hoc power reasons in a circle. The proper place for power calculations is in planning a study and its sample size, using effect sizes "we would be sorry to miss". On post hoc power, I like to recommend Hoenig & Heisey (2001).
Comment: The distribution of $R^2$ is so closely related to the distribution of the correlation coefficient that I'm *sure* you know how to find it under the null hypothesis $R^2=0$ (making the implicit Normality assumptions, of course).
Comment: You wouldn't consider the overall F-test to be some kind of test of $R^2$, if the residual variance of statistically significantly lower than the total variance?
Comment: @Dave: yes, $R^2$ and $F$ of course hang together very closely, so one could consider the $F$ test in an ANOVA a kind of a test for $R^2$.
Comment: @Dave, this one discusses $F$ and $R^2$: https://stats.stackexchange.com/questions/597947/relationship-between-f-fisher-and-r2/598006#598006
Comment: @Christoph $R^2$ is indeed a property of the underlying model: it is not merely a sample quantity.  The *adjusted* $R^2$ clearly is a sample quantity (because it depends on sample size).  For instance, in a Bivariate normal model of ordinary regression with correlation parameter $\rho,$ the population $R^2$ equals $\rho^2.$ The point about boundaries is good, but is obviated when you instead test the equivalent hypothesis $\rho=0$ against $\rho\ne 0:$ there's no longer any boundary!
Comment: Given whuber's first comment and Sextus's answer, I find the first sentence surprising. While it is phrased as your knowledge rather than some consensus, do you still stick to it?
Comment: @whuber, how should we interpret a null like $R^2=0$ when $R^2$ is a sample quantity. Population $R^2$? Also, we would be testing on the boundary of a parameter space, no, which often is not so trivial?
Answer:
$R^2$ and adjusted $R^2$ are computed based on a decomposition of the sum of squares, $SS_{total} = SS_{model}+SS_{residual}$, and can be related to F-statistics in ANOVA which is based on the same sum of squares values.
For simple linear regression an example is given here: Is there a relation between the p-values of coefficients and the $R^2$ in an OLS regression?

It separately reports the p-values of the t-statistics for each exogenous variable so it can't be t-statistics.

The models contain several variables for which you can seperately compute p-values, by computing t-values, or computing ANOVA by comparing with a model that drops a single factor (unless the factor being a categorical variable, this should give the same result).
The p-value for the entire model is an ANOVA comparison between a null model and the entire model. In such a case $R^2$ can be related to the F statistic and it's p-value in a similar way as the simple linear regression linked above.
(In the case of the 'log-dimensionless jerk' the model is actually just a simple linear regression and the 'p-value of the parameter', is the same as the 'p-value of the entire model'.)

Example computation in R
### generate some data
x1 = c(1,5,3,7,2,5,4,9,0)
x2 = c(1,1,1,1,0,0,0,0,0)
set.seed(1)
noise = rnorm(9)
### simulate a measurement
y = 2 + x1 + x2 + noise

### compute two models
mod_full = lm(y ~ 1 + x1 + x2) ## intercept plus both variables
mod_null = lm(y ~ 1) ## only intercept

### compare the full model with an intercept only model
anova(mod_full,mod_null)
# p-value = 0.0001191

### provide p-values of individual variables
summary(mod_full)
# x1 p-value = 3.99e-05
# x2 p-value = 0.2013

The p-values for the variables are evaluated with a t-test and result in
Call:
lm(formula = y ~ 1 + x1 + x2)

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.8019     0.5646   3.191   0.0188 *
x1            1.1151     0.1045  10.672 3.99e-05 ***
x2            0.8171     0.5694   1.435   0.2013

The p-value for the model is evaluated with an ANOVA test and results in
Model 1: y ~ 1 + x1 + x2
Model 2: y ~ 1
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1      6  4.323
2      8 87.867 -2   -83.544 57.976 0.0001191

Comment: Digressing, instead of computing t-tests for the individual variables one can also do an ANOVA test with type III sums `car::Anova(mod_full, type = "III")`.
Answer: The adjusted coefficient of determination is a monotonically increasing function of the F-statistic, so both statistics give the same evidentiary ordering in a goodness-of-fit test.  Specifically, it can be shown that:
$$\begin{align}
F
&= \frac{df_\text{Res}}{df_\text{Reg}} \cdot \frac{R^2}{1-R^2} \\[6pt]
&= \frac{df_\text{Res}}{df_\text{Reg}} \cdot \frac{(n-1) - (n-p-1)(1-R_\text{Adj}^2)}{(n-p-1)(1-R_\text{Adj}^2)} \\[6pt]
&= \frac{df_\text{Res}}{df_\text{Reg}} \cdot \frac{p + (n-p-1)R_\text{Adj}^2}{(n-p-1) (1-R_\text{Adj}^2)}, \\[6pt]
\end{align}$$
which gives:
$$R_\text{Adj}^2 = \frac{(n-p-1) df_\text{Reg} \cdot F - p \cdot df_\text{Res}}{(n-p-1) df_\text{Reg} \cdot F + (n-p-1) df_\text{Res}}.$$
Since this is a monotonically increasing function of $F$, the goodness-of-fit test for the $R_\text{Adj}^2$ statistic ought to be identical to the standard F-test.
Answer: Assuming the authors used R (I did not read the paper!), they likely used the cor.test function with default parameters to obtain those numbers. Here is the relevant section from the online help:

If 'method' is '"pearson"', the test statistic is based on
Pearson's product moment correlation coefficient 'cor(x, y)' and
follows a t distribution with 'length(x)-2' degrees of freedom if
the samples follow independent normal distributions.  If there are
at least 4 complete pairs of observation, an asymptotic confidence
interval is given based on Fisher's Z transform.


Message Queue with 'Message Barrier' Feature?

Question: Is there a message queue implementation that allows breaking up work into 'batches' by inserting 'message barriers' into the message stream? Let me clarify. No messages after a message barrier should be delivered to any consumers of the queue, until all messages before the barrier are consumed. Sort of like a synchronization point. I'd also prefer if all consumers received notification when they reached a barrier.
Anything like this out there?
Comment: What is the language/platform?
Comment: Any language, any platform. I'm simply interested in a queue that supports this feature because I'd like to know how it's implemented and how well it works in practice.
Comment: Do you want to stop at the barrier until all messages are "delivered" or until they are "acknowledged"? Delivered messages may re-appear on the queue, if the consumer process/session fails before acknowledgement.
Answer: I am not aware of existing, widely-available implementations, but if you'll allow me I'd propose a very simple, generic implementation using a proxy, where:

producers write to the proxy queue/topic
the proxy forwards to the original queue/topic until a barrier message is read by the proxy, at which point:

the proxy may notify topic subscribers of the barrier by forwarding the barrier message to the original topic, or
the proxy may notify queue subscribers of the barrier by:

periodically publishing barrier messages until the barrier has been cleared; this does not guarantee that all consumers will receive exactly one notification, although all will eventually clear the barrier (some may receive 0 notifications, others >1 notifications -- all depending on the type of scheduler used to distribute messages to consumers e.g. if non-roundrobin)
using a dedicated topic to notify each consumer exactly once per barrier

the proxy stops forwarding any messages from the proxy queue until the barrier has been cleared, that is, until the original queue has emptied and/or all consumers have acknowledged all queue/topic messages (if any) leading up to the barrier

the proxy resumes forwarding

UPDATE
Thanking Miklos for pointing out that under JMS the framework does not provide acknowledgements for asynchronous deliveries (what is referred to as "acknowledgements" in JMS are purely a consumer side concept and are not proxiable as-such.)
So, under JMS, the existing implementation (to be adapted for barriers) may already provide application-level acknowledgements via an "acknowledgement queue" (as opposed to the original queue -- which would be a "request queue".)  The consumers would have to acknowledge execution of requests by sending acknowledgement messages to the proxy acknowledgement queue; the proxy would use the acknowledgement messages to track when the barrier has been cleared, after having also forwarded the acknowledgement messages to the producer.
If the existing implementation (to be adapted for barriers) does not already provide application-level acknowledgements via an "acknowledgement queue", then you could either:

have the proxy use the QueueBrowser, provided that:

you are dealing with queueus not events, that
you want to synchronize on delivery not acknowledgement of execution, and
it is OK to synchronize on first delivery, even if the request was actually aborted and has to be re-delivered (even after the barrier has been cleared.)  I think Miklos already pointed this problem out IIRC.

otherwise, add an acknowledgment queue consumed by the proxy, and adapt the consumers to write acknowledgements to it (essentially the JMS scenario above, except it is not necessary for the proxy to forward acknowledgement messages to the producer unless your producer needs the functionality.)
Comment: The producer can detect if there are un-delivered messages on the queue, using a Queue Browser, but the producer cannot detect when a message is acknowledged by a consumer. I think this problem can only be solved if there is a custom communication protocol between the proxy and the consumers.
Comment: @Miklos, can you elaborate?  I don't see a problem with either the proxy or producer getting the acknowledgments as long as both the proxy and the consumers are using the same acknowledgment mode and, e.g. in the case of the `CLIENT_ACKNOWLEDGE` mode, the proxy forwards the acknowledgements to the producer, too.
Comment: the acknowledgement is received and handled by the JMS server, not the message producer. In this sense the proxy is also a message producer. The JMS server is decoupling the consumer from the producer: the producer will not know what the consumer does, who it is, how many there are. This is a basic principle of asynchronous messaging.
Comment: @Miklos: correct, I had not properly captured the concept of JMS message acknowledgement being purely a consumer side concept during my initial JMS documentation reading.  I am updating the response accordingly.
Answer: You could achieve this using a topic for the 'Barrier Message' and a queue for the 'batched items' which are consumed with selective receivers.
Publishing the Barrier Message to a topic ensures that all consumers receive their own copy of the Barrier Message.
Each consumer will need two subscriptions:

To the Barrier Topic
A selective receiver against the batch queue, using selection criteria defined by the Barrier Message.

The Barrier Message will need to contain a batch key that must be applied to the queue consumers selection criteria.
e.g. batchId = n
or   JMSMessageID < 100
or   JMSTimestamp < xxx
Whenever a barrier message is received,

the current queue consumer must be closed
the queue selection criteria must be modified using the content of the Barrier Message
a new selective consumer must be started using the modified selection criteria

If you are going to use a custom batch key for the selection criteria such as 'batchId' above, then the assumption is that all message producers are capable of setting that JMS property or else a proxy will have to consume the messages set the property and republish to the queue where the selective consumers are listening.
For more info on selective receivers see these links:

http://java.sun.com/j2ee/1.4/docs/api/javax/jms/Message.html
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/jms/QueueSession.html#createReceiver(javax.jms.Queue,%20java.lang.String)
Comment: And how do a consumer know when it has consumed all pending messages? So that the barrier can be removed (or a new barrier can be set, if you prefer). Except if you count how many messages have been produced and consumed (which is hard because of concurrency and transactions), there is not way to know that as per the JMS spec.
Comment: @crowne, can you clarify for the readers whether or not there is a potential race condition just before a new selective consumer is started, i.e. is there any chance that any messages sent after the barrier, but before a new selective consumer is started, will be ignored by the new selective consumer?


Why is a bilinear map $M \times N \to B$ the same as a homomorphism $M \to Hom_R(N,P)$?

Question: Eisenbud's "Commutative Algebra" states that:
It is elementary that a bilinear map $M \times N \to P$ is the same as a homomorphism $M \to Hom_R(N,P)$
While this makes some intuitive sense I keep hand waving an explanation to myself.
I would really like to see it done out at least once.
Answer: Assume $\varphi: M\times N \to P$ is a bilinear map, then the corresponding homomorphism is $\phi: M\to \hom_R(N,P)$, with $\phi(m)(n)=\varphi(m,n)$. We can check $\phi(m)$ is a homomorphism from $N$ to $P$ using the fact that $\varphi$ is bilinear.
Convesely, if  $\phi: M\to \hom_R(N,P)$ is a homomorphism, then the corresponding bilinear map is $\varphi: M\times N \to P$, with $\varphi(m,n)=\phi(m)(n)$.
Answer: Hint: To a bilinear map $f:M\times N\rightarrow P$ associated $H_f:M\rightarrow Hom_R(N,P)$ defined by $H_f(m)(n)=f(m,n)$.
And to $H:M\rightarrow Hom_R(N,P)$ associate $H_b:M\times N\rightarrow P$ defined by $H_b(m,n)=H(m)(n)$  show that the correspondence are inverse each other
Answer: Given a map $f : M\times N \to P$ which is linear in the second argument, there is an associated map $F : M \to \operatorname{Hom}_R(N, P)$ defined by $F(m)(n) = f(m, n)$. If $f$ is also linear in the first argument (i.e. $f$ is bilinear), then $F$ is a homomorphism.
Conversely, given a map $G : M \to \operatorname{Hom}_R(N, P)$, there is an associated map $g : M\times N \to P$ given by $g(m, n) = G(m)(n)$. Note that $g$ is linear in the second argument, and if $G$ is a homomorphism, $g$ is also linear in the first argument (i.e. $g$ is bilinear).
This establishes a natural bijection between bilinear maps $M\times N \to P$ and homomorphisms $M \to \operatorname{Hom}_R(N, P)$.
Answer: Eisenbud's statement is morally correct, but not strictly true with the usual set-theoretic representations of functions (or any representation that I know of). Writing $X \to Y$ for the set of set-theoretic functions from $X$ to $Y$, then there is a 1-1 correspondence between $X \times Y \to Z$ and $X \to (Y \to Z)$ that associates $f:X \times Y \to Z$ with $x \mapsto y \mapsto f(x, y)$ and associates $g : X \to (Y \to Z)$ with $(x, y) \mapsto g(x)(y)$. This is known (to computer scientists and logicians at least) as currying and uncurrying.
If you look at functions that are required to preserve algebraic structure, this correspondence doesn't work in general. However, for modules over a ring, the correspondence does restrict to a 1-1 correspondence (indeed an isomorphism of modules) between bilinear maps $M \times N \to P$ and homomorphisms $M \to \mbox{Hom}_R(N, P)$. ($\mbox{Hom}_R(N, P)$ is a subset of the set $N \to P$ of all functions from $N$ to $P$). This is the sense in which Eisenbud means the two things are the same.


Is option type in F# reference type?

Question: Is uint64 option type reference type or value type? I am having some performance issues related to this. please clarify.
Answer: As None is implicitly represented as null, Option is a reference type.
The F# spec gives the following definition which requires option to be a reference type:
[<DefaultAugmentation(false)>]
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type 'T option =
    | None
    | Some of 'T
    static member None : 'T option
    static member Some : 'T -> 'T option
    [<CompilationRepresentation(CompilationRepresentationFlags.Instance)>]
    member Value : 'T
    member IsSome : bool
    member IsNone : bool

Answer: type Option<'T> =
        | None :       'T option
        | Some : Value:'T -> 'T option

from FSharp Source Code shows that is a reference type.

Is option type in F# reference type?


How many different color combinations (red-black-black-red-red-black) are possible in a deck of cards?

Question: I have regular deck of playing cards and I want to find out how many color combinations there are in the deck. The cards fall into two categories: red and black. Here are the givens.
Total $52$ items;
$2$ distinct, repetition;
$26$ black;
$26$ red;
Cards like $7$ of diamonds and king of hearts are red, while cards like the ace of spades and jack of clubs are black.
Comment: This isn't a homework problem. I'm just curious of what it would be and if there is a formula of it.
Comment: You won't get any answers unless you show what you've already did. This isn't somewhere to go post your homework problems.
Comment: Are you asking how many sequences of red and black cards there are or how many times the pattern red-black-black-red-red-black can appear in the sequence?
Answer: HINT
Just focus on one color (say, red), and think about the position of the 26 red cards in the deck (positions range from 1 to 52). That is, the red cards take up 26 of the 52 possible positions ... so how many sets of 26 numbers out of 1 through 52 are there?
Comment: I'm a little confused in what you mean by how many sets of 26 numbers out of 1-52 are there.
Comment: OK, suppose the first 26 cards are all red.  Then they take up positions 1 through 26.  So this would correspond to the set $\{ 1,2,3,..., 26 \}$.  Now suppose the first 25 cards are all red, and also the very last one.  That would correspond to the set $\{ 1,2,3,..., 25, 52 \}$.  And if every second card is red, we get the set $\{ 2,4,6,...,48,50,52 \}$.  In other words, every color combination corresponds to a selection of 26 numbers out of the numbers 1 through 52.
Comment: I understand. This would be a very big number. Impossible to count. What method can we use to get this number? Factorial? If so, I know we can't just use 26! I'm stuck here not knowing what to do.
Comment: @TH3F145H Yes, a very big number indeed! OK, so what I had hoped my HINT would point you towards is the 'choose' function ... if you are unfamiliar with that function, look it up.
Comment: Is it C (52, 26)?
Comment: @TH3F145H You got it!
Comment: Thanks for your help! Really appreciate it!
Comment: @TH3F145H You're welcome!  :) Since you are new: please know that you can accept my answer by checking the checkmark on the left.


ImportError: No module named pycurl - developing an OpenStack Horizon Plugin

Question: I'm developing an openstack horizon plugin that should poll some info via a ReST API. I'm following this tutorial:  http://docs.openstack.org/developer/horizon/topics/tutorial.html
So in the file /opt/stack/horizon/openstack_dashboard/dashboards/mydashboard/mypanel/views.py I have:
from horizon import tabs
from horizon import views

from openstack_dashboard.dashboards.mydashboard.mypanel import tabs as mydashboard_tabs

import sys
import pycurl

Resulting in ImportError: No module named pycurl
If I load python and check, pycurl is loadable:
oink@ubuntu14-devstack:/opt/stack/horizon/openstack_dashboard/dashboards/mydashboard/templates/mydashboard/mypanel$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pycurl
>>> pycurl
<module 'pycurl' from '/usr/lib/python2.7/dist-packages/pycurl.so'>

OpenStack is running python version 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2], which matches my line interpreter. How would I be able to use pycurl in an OpenStack Horizon view? (Or, what is a good mechanism to poll a ReST API from Horizon?)
Comment: try import pycurl.so. Just a try though :-)
Comment: Nope, `ImportError: No module named pycurl.so`.
Answer: Virtualenv is in the way?
Meanwhile I'm using this hack:
import sys
sys.path.append("/usr/lib/python2.7/dist-packages")
import pycurl


Print to console values between to integers infinitely in JavaScript

Question: I would like to console.log values between 1 and 5 infinitely with a small delay of few seconds using JavaScript. I am trying to run the following code, but it stops after printing 1.

    var z = 0
    setTimeout(function() {
      if (z==6) {z=0};
        z+=1;
        console.log(z);
    }, 2000);

Is it possible to implement this using setTimeout function?
Answer: You are looking for setInterval:

var z=0;
setInterval(function() {
  if (z==6) {z=0};
  z+=1;
  console.log(z);
}, 2000);
Answer: setTimeout() just performs the function once. you need use setInterval().:
var z=0;
setInterval(function() {
if (z==6) {z=0};
z+=1;
console.log(z);
}, 2000);

Answer: Here's a potential solution.  It's not implemented "infinitely" so the browser doesn't die, but you could increase i to your liking I suppose.
for (let i = 0; i < 100; i++) {
    setTimeout(function() {
    console.log(i % 5 + 1);
  }, 2000 * i);
}

Comment: Same as @Alexander's answer- this is blocking, and is problematic.


Can you use a percentage as an independent variable in multiple linear regression?

Question: I'm having difficulty finding a definitive way to determine whether I can use a percentage measure as an independent variable in multiple linear regression or not.
From my understanding, the percentage can't be considered a true continuous measure for some reason and violates some assumptions of the regression model.
Edit 1: For example, I have seen the argument that percentage data is discrete because the underlying data that the percentages are calculated from is discrete.
Can someone explain why percentages aren't true continuous measures and in what cases I could use a percentage as an independent variable?
Edit 2: For further clarity, I will explain what I'm hoping to accomplish specifically below here. The goal is to use a dependent variable (length of time) and claim it explained by several independent variables (some dummies, one a percentage that isn't restricted to any certain values for any observation). I know the assumption for linear regression is that the independent variables will be continuous measures, which is why I utilize dummy variables for the dichotomous categorical variables. I'm just trying to make sure I don't need to utilize a different analytical technique altogether because of the percentages being technically discrete (is this even necessarily true?).
Edit 3: In the interest of complete specificity,
DV - Length of maternity leave taken.
IV's - percentage of normal salary paid by employer during leave, and other dummies not relevant to the question.
Comment: Can you point us to, and ideally edit into your question, the reasons why people have told you not to do this so someone here can argue against them?
Comment: Why percentages can't be continuous? Also, why the restriction on continuous IVs?
Comment: Oops,  actually that's if it is your outcome variable. Still length of time cannot be <0 so still a problem. Time to event is asked for.
Comment: If you have a particular research problem or data set in mind, please provide some details. You are more likely to get a useful answer if your question is more specific. Also, please follow the advice from @mdewey about editing your question to include the arguments you've heard against percentages as independent variables.
Comment: I've edited the question to be more specific. The general rule I'm attempting not to violate is this one from my textbook:

Linear regression is based off of three assumptions.
1. Linearity
2. Normality (This one being the one I'm most worried I'm violating in some way.)
3. Homoscedasticity

Under normality it states that both the dependent variable and independent variables should be continuous and normally distributed. Categorical independent variables, however, may be incorporated as dummy variables.

I get the feeling that percentages aren't capable of being dummies, though.
Comment: Is a bigger problem that percentages are bounded to be between 0 to 100, but that standard linear regression will not respect this and happily predict values below 0 or above 100? Depending on the setting this can cause completely nonsensical and invalid results.
Answer: The assumption of normality to which you refer does not apply to any of the predictors (after all how could a binary predictor be normal?) nor does it apply to the outcome. What it applies to is the residuals from your model. So at this stage before you have fitted the model you do not know whether it holds or not. Similarly the usual check for homoscedasticity is based on looking at the residuals in a plot against the fitted values. The question of continuity is more subtle but no measured variable even if theoretically continuous is going to be so when actually measured to finite precision.
If I was modelling length of stay I would be more worried about the skew and also the issue of whether some have been censored because they have not returned to work yet. Have you considered using a time to event model (also known as the Cox model or proportional hazards)?
Another concern, depending on the rules in your jurisdiction, is that if maternity pay is at a certain level for $j$ moths, a lower level for $k$ months, and the stops, you will get bunching of values at $j$ and $k$ (I would have thought).
Comment: @SeanConner : analyzing time-to-event is an important basic research design. It allows you to handle cases where maternity leave (in your example) is still in progress and hasn't ended yet. How could you handle such cases with linear regression? It's important to match the correct analysis design to the particular problem at hand.
Comment: Thank you so much for your help! All of these points are quite valid. Unfortunately, I'm unfamiliar with the Cox model, and at a glance, it seemed above my current knowledge of statistics. Fortunately, I'm not gunning for publication just yet. This is merely a practice in developing basic research designs.
Comment: @EdM, definitely agree with you there. The particular data set I'd be using would strictly sample from women where leave has concluded. Furthermore, I'd be strictly sampling women who have already returned to work or resolved to not return for at least one year. I don't think I've violated the temporal precedence requisite of causal inference. Correct me if I'm wrong, please.
Answer: Percentages can be considered continuous on the interval [0,1].  There is no reason why percentages can't be independent variables in linear regression.  In fact, there is no requirement that independent variables need to be continuous.  Indicator variables are often used as independent variables in regressions.
Comment: Thank you so much for your help! This certainly makes sense.
Comment: Do you happen to have any sources that corroborate this? It does seem to contend with my text book, and I'm sure my professor will want confirmation from some citation.
Comment: Why would anyone give me a negative vote for this reply.
Comment: I know a lot of books on regression.  I do not think they specifically address the issue of using proportions as predictor variables.
Answer: Suppose you have a model
$$Y = B_1 X_1 + B_2 X_2 + E,$$
where $E \sim Nor(0,1)$
Let $X_3$, $X_4$ be the percentages and $S_1$, $S_2$ be the total of $X_1$, $X_2$ respectively
then, $X_3 = X_1/S_1*100$ and $X_4 = X_2/S_2*100$.
Then the model with percentage will be,
$Y = B_3 X_3 + B_4 X_4 + E'$
The estimates will be $B = ((X'X)^{-1})X'Y$ and the relation between the estimates are,
$B_3 = B_1/S_1*100$ and $B_4 = B_2/S_2*100$.


Mediation analysis: interpret a prop. mediated 95% upper CI > 1

Question: I am using the R mediation package.
The output of the mediate command is as follows:
Causal Mediation Analysis

Quasi-Bayesian Confidence Intervals

                          Estimate 95% CI Lower 95% CI Upper p-value
ACME (control)           -0.001633    -0.002128         0.00  <2e-16 ***
ACME (treated)           -0.001251    -0.002040         0.00  <2e-16 ***
ADE (control)            -0.001082    -0.003008         0.00   0.296
ADE (treated)            -0.000700    -0.001937         0.00   0.296
Total Effect             -0.002333    -0.003881         0.00   0.022 *
Prop. Mediated (control)  0.677185     0.471999         1.66   0.022 *
Prop. Mediated (treated)  0.496793     0.178559         2.01   0.022 *
ACME (average)           -0.001442    -0.001940         0.00  <2e-16 ***
ADE (average)            -0.000891    -0.002488         0.00   0.296
Prop. Mediated (average)  0.586989     0.329850         1.85   0.022 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Sample Size Used: 19727

Simulations: 1000

As you can see the proportion mediated upper 95% CI interval for the treated group is 2.01.
How should I interpret this proportion greater than 1?
Answer: In the documentation for the mediate function you can read this:

the "proportions mediated", or the size of the average causal
mediation effects relative to the total effect.

So, a proportion mediated that is greater than 1 would indicate that the size of the mediation effect is larger than the total. This could happen if the directions of the main and mediated effect were opposite.  This is equivalent to suppression in ordinary regression. If the direct effect is very small, then the proportion mediated could be far greater than 1.
Then the question of whether there is mediation at all becomes kind of philosophical. If there is no effect, is there anything to mediate?
Comment: I didn't understand if the cause is (1) the total and mediated effect being in opposite direction or (2) the direct effect being very small or (3) both....
Comment: It doesn't seem to give you the main effect or the mediated effect, so it's hard to tell.
Comment: I don't understand your reply. It is telling me that, on average, 59% of the effect is mediated, that's how I interpret the "Prop. Mediated (average)".


Model selection in mixed-effects model with collinearity trouble

Question: In a model aimed to assess the influence of land use measures on ecosystem functioning, I have one log-transformed dependent variable (the ecosystem function), and 5 fixed-effects independent variables (1 continuous, 3 binary, 1 categorical).
I've fitted a mixed effects model (with two random effects, spatial and temporal, that remain the same) and now I am trying to find the best model. Initially I wanted to do this by manual stepwise elimination of insignificant variables using the anova(model) command and then comparing likelihood-ratio tests between models. The first model looks like this:
> model0 <- lme(dep_var ~ bin_1 + bin_2 + bin_3 + log(cont_1) + cat_1, random=~1|season/site, method="ML", data=abvpp2)
> anova(model0)
                numDF denDF  F-value p-value
(Intercept)         1   319 9384.037  <.0001
bin_1               1    72    2.972  0.0890
bin_2               1    72    0.007  0.9338
bin_3               1    72   12.423  0.0007
log(cont_1 + 1)     1    72    1.655  0.2023
cat_1               2    72   29.382  <.0001

After dropping the least significant variable bin_2:
> model1 <- lme(dep_var ~ bin_1 + bin_3 + log(cont_1) + cat_1, random=~1|season/site, method="ML", data=abvpp2)
> anova(model1)
                numDF denDF  F-value p-value
(Intercept)         1   319 9257.012  <.0001
bin_1               1    73    2.931  0.0911
bin_3               1    73   12.260  0.0008
log(cont_1 + 1)     1    73    1.616  0.2077
cat_1               2    73   28.361  <.0001
> anova(model0,model1)
       Model df      AIC      BIC    logLik   Test L.Ratio p-value
model0     1 10 517.3610 557.2506 -248.6805
model1     2  9 516.6558 552.5564 -249.3279 1 vs 2 1.29476  0.2552

Pretty straightforward up to here. But after dropping cont_1 next, I get this:
> model2 <- lme(dep_var ~ bin_1 + bin_3 + cat_1, random=~1|season/site, method="ML", data=abvpp2)
> anova(model1,model2)
       Model df      AIC      BIC    logLik   Test L.Ratio p-value
model1     1  9 516.6558 552.5564 -249.3279
model2     2  8 522.7970 554.7087 -253.3985 1 vs 2 8.14122  0.0043

cont_1 does seem to have some explanatory power, in spite of it's insignificance in the anova. Apparently, this is due to multicollinearity between the variables, since the order of fitting them in the model changes significances in the anova output drastically (sometimes insignificant variables even become significant when fittet AFTER another variable with usually more explanatory power).
I am now a little unsure about how to select my model. Even though some variables are correlated (r=-0.33 and r=0.62), they explain different measures and dropping one of them beforehand would be hard to justify. I would be very grateful for some ideas on model selection while dealing with collinearity in LME models and avoiding stepwise commands.
Answer: Since you have a small number of variables, you could actually do all possible regressions and choose the best one (AIC or BIC criterion). The leaps package in R does this when there are no random effects. There's probably something out there that can do it with random effects as well. Worst case, you write your own function and loop your way through the $2^5$ options.
But as an old-fashioned statistician, I have to make the following points:

A choice based on expert knowledge of what actually matters in this situation is preferable to a data driven answer.
If the purpose of the study was to determine which variables matter, and if you have control over the independent variable, it would be a good idea to select a balanced design so the impact of each variable and its interactions can shine forth.
Comment: Thank you for the quick answer! I will try the leaps package.
Indeed the purpose is to determine which/if variables matter, which is why I have a hard time solely relying on the AIC, since in some cases it means excluding variables with a significant F-statistic (even though mostly with coefficients not different from zero, when looking at the summary).
Unfortunately, a balanced design is not possible.


Mann whitney U test

Question: I would like to compare the nutrient intake of males with that of females. One of the assumptions of the Mann Whitney test U test is that the two variables must not be normally distributed. The nutrient intake of males is normal but not of females. Would this be a problem? Also, the data is on intake of seven nutrients. To do the comparison wouldn't I have to do the Mann whitney test 7 times? Is there any other alternative? The following are the qq plots I obtained for women and men respectively.
Answer:
One of the assumptions of the Mann Whitney test U test is that the two variables must not be normally distributed.

This assertion is quite false. Not only is that not an assumption of the Mann-Whitney, it's actually a very good test at the normal, having an asymptotic relative efficiency of $3/\pi$ - around 95.5%. Do you have a book or other reference that makes the claim here?

The nutrient intake of males is normal

I doubt you have any basis on which to assert this as a fact. I doubt it's true. What makes you think it is?

Would this be a problem?

If the distribution shapes differ, it might be a problem, depending on how you wanted to interpret the test results.

Also, the data is on intake of seven nutrients.

This is very important. You should probably lead with it.

To do the comparison wouldn't I have to do the Mann whitney test 7 times? Is there any other alternative?

One of the issues with doing multiple univariate tests is that you can easily miss clear changes in the multivariate distribution that are not strong on any one variable. Which you do depends on which questions are important to answer.
How non-normal are the data? What's the dependence structure like?
Comment: 1) So you did a hypothesis test of multivariate normality? Failure to reject normality doesn't mean your data are normal. It just means the sample size was too small to find the non-normality you have. Hypothesis tests of normality don't answer the question you want to answer here.  2) it's not necessarily helpful to formally test normality if you're then choosing what procedure you use on the basis of the outcome of that test.  3) "How non-normal" == What kind of non-normality is present and how severe is it?
Comment: I don't presently have sufficient information to offer a suggestion. I've asked several questions which cover part of what I'd need to know. If possible a Q-Q plot of each response and a scatterplot matrix of their values would help. I have some followup questions.
Comment: @user52672 Glen_b's first point is the most important: the Mann Whitney test **most assuredly does NOT assume that data must not be normal**. Where either one, both or neither of your groups have normally distributed scores is irrelevant to whether or not you can use the test, period.
Comment: Thank you for your reply. What do you mean by 'how non-normal'? I checked the normality of intakes of men using MVN package in R software.
Comment: Please suggest a procedure to check the equality of intakes of men and women.

Mann whitney U test


How to Identify Port to a Process?

Question: I'm running a RedHat 5.5 and I was wondering how I can identify a port to a process.
This is the output of netstat and I'm trying to find the process associated with port 35670:
$ netstat -tulnp
tcp        0      0 0.0.0.0:35670               0.0.0.0:*                   LISTEN      -

I tried the following to get the associated process to this port, but to no avail:
$ lsof -nl | grep TCP
$ fuser 35670/tcp

This finally worked for me.
$ rpcinfo -p
100021    3   tcp  35670  nlockmgr

Without doing the command above, how would you have detected that port 35670 is associated with nlockmgr.
The weird thing is nlockmgr does not show up when I do this:
$ ps aux

Comment: Of course there is one possibility why a process would not show up with the standard tools, but still be present.  If your system has a rootkit, then processes could be running that would occasional appear to be invisible, and the standard tools may display unusual results.
Comment: I thought of rootkit as well, but rpcinfo -p gave me the process name associated with it. So, I removed the idea that it could be a rootkit.
Answer: You have to execute netstat -tulnp as root. Otherwise you get the - instead of the process name.
This is what the manpage says:
PID/Program name
   Slash-separated pair of the process id (PID) and process name of the process that owns the socket.  --program causes  this  column
   to  be  included.   You will also need superuser privileges to see this information on sockets you don't own.  This identification
   information is not yet available for IPX sockets.

With one exception: portmapper See this
Comment: carmen, your example shows $, which is not root.
Comment: I did execute all of the commands as root.
Comment: After googling around, nlockmgr uses IPX socket which is why netstat could not identify the process. Thanks. But if netstat cannot detect process associated with IPx, what program can do it?
Answer: You can use nmap with -sV option to determine service info:
# nmap -sV -p 35670 localhost

Why is rpc.lockd obscured from netstat/lsof output?
Answer: Instead of netstat you can use ss:
[mvutcovi@mvutcovi-lap ~]$ sudo ss -tulnp
Netid    State     Recv-Q    Send-Q         Local Address:Port          Peer Address:Port
udp      UNCONN    0         0              192.168.122.1:53                 0.0.0.0:*        users:(("dnsmasq",pid=1698,fd=5))
udp      UNCONN    0         0             0.0.0.0%virbr0:67                 0.0.0.0:*        users:(("dnsmasq",pid=1698,fd=3))
udp      UNCONN    0         0                    0.0.0.0:68                 0.0.0.0:*        users:(("dhclient",pid=1980,fd=7))

How to Identify Port to a Process?


What is the best (secure) way to run PHP code on a Drupal 8 system?

Question: I am pretty new with Drupal. I have installed Drupal 8.17 on my webserver and now I am configuring it.
It runs on Ubuntu 16.04 with Apache 2.4 and PHP-7.0, the DBMS is PostgreSQL 9.5.
I would like to execute some PHP code is some pages. I have read that there was PHP Filter in Drupal 7, but it is now moved to modules and it warns user than:

Warning
  Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site.
  There are better alternatives out there that do not expose such vulnerabilities on your site.

But I cannot find any alternative over the web. Then I found Drupal SE, and I am asking for user advice: What is the best way (I mean secure way) to run PHP code on a Drupal 8 system?
I must connect another PostgreSQL DB, perform query on it and display results in Drupal. Essentially this will be done in pages that only administrator can read an modify.
Answer: Some Drupal devs are keen on never putting PHP code in the Database, but this means you will have to know the intricacies of Drupal 8 in order to figure out how to expose what you need by creating a custom module. This can be a time sink if you just want to do something super simple.
But if you aren't that hardcore, turning on the PHP is fine if you just don't have the time or need to create a custom module to say print something out from the $user array.
I personally just use the PHP module on my sites. It's quick and efficient vs making a custom module. Obviously deciding on which approach to take depends on the site and client your working with. Does it have valuable user data? Does it have millions of user hits a day? Or is it just a purely informational site with only a few hits a day? Do you think the client would mess around with other parts of the site or are they just purely just updating content?
Comment: Thank you for making this clear, do you have a good reference about how to create a module for Drupal
Comment: follow this guide: http://www.drupalwoo.com/content/blog/my-first-drupal-8-module --- fyi it doesnt work at the end, but someone in the comments posted an updated one on github. use that. but read this page fully to get a clear understanding of how it works. I just did this like 2 hours ago. it really helped.
Comment: You mean you have installed the module that was previously a built-in filter?
Comment: your looking for to use this right? http://drupal.org/project/php -- that enables the PHP text format in any text area input. if u dont use that. u have to custom code a module to do what u want with php.


Continuous Multistate Ada-boost method?

Question: I recently read this simple introduction to Adaboost as a review after learning about it a few years ago.  This is in preparation for actually using it to solve a problem I am working on which is slightly different than anything addressed in this paper or that I have found online.  Now in the problem I am trying to solve there is a continuous scale, rather than the binary problem addressed in the paper (and almost everywhere online) or even the distinct multistate (kind of like an enum) problems they mention at the end of the paper.  Imagine experts scoring some performance on a continuous scale between 1-10 where scores like 8.4 mean twice as good as 4.2.
The way that they did the multistate version in the paper was to break it into a series of binary tasks but this completely defeats the point since it throws out a lot of the information about what the scale means and just makes it a named class.  I was wondering what methods people know of for this continuous problem and if an adaboost idea can still be used.  thanks.
Answer: What you are describing is called "Ordinal Regression" (see e.g. here).
There is a boosting algorithm which I think was derived from Freund's RankBoost algorithm for ranking, called ORBoost.
You might find, however, that Ordered Logistic Regression is easier to implement for your problem.

Continuous Multistate Ada-boost method?


Como mostrar anúncios intersticiais depois de carregar a tela inicial?

Question: Preciso de ajuda, eu gostaria de exibir um anúncio intersticial após a tela inicial carregar, mas meu código está dando a seguinte falha:

java.lang.IllegalStateException: isLoaded must be called on the main UI thread.

Aqui está o meu código:
public class SplashScreenActivity extends AppCompatActivity {

    InterstitialAd mInterstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        // FIREBASE INTERSTICIAL
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-2565065222479596/3931476543");

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });

        requestNewInterstitial();

        Toast.makeText(this,"* Necessário Acesso a Internet *",Toast.LENGTH_LONG).show();

        Thread timerThread = new Thread() {
            public void run() {
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                    else
                    {
                        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                    }
                }

            }
        };
        timerThread.start();

    }

    // FIREBASE INTERSTICIAL
    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}

DEBUG:
    01-22 16:27:03.048 13840-13970/? E/AndroidRuntime: FATAL EXCEPTION: Thread-6
    Process: idea.tisco.pepavideos, PID: 13840
    java.lang.IllegalStateException: isLoaded must be called on the main UI thread.
    at oc.b(:com.google.android.gms.DynamiteModulesA@11951448:20)
    at com.google.android.gms.ads.internal.a.d(:com.google.android.gms.DynamiteModulesA@11951448:98)
    at com.google.android.gms.ads.internal.client.ak.onTransact(:com.google.android.gms.DynamiteModulesA@11951448:14)
    at android.os.Binder.transact(Binder.java:499)
    at com.google.android.gms.internal.zzep$zza$zza.isReady(Unknown Source)
    at com.google.android.gms.internal.zzfa.isLoaded(Unknown Source)
    at com.google.android.gms.ads.InterstitialAd.isLoaded(Unknown Source)
    at company.ts.SplashScreenActivity$2.run(SplashScreenActivity.java:50)

Mesmo após a depuração, não consegui entender o motivo do erro.
Gostaria apenas de exibir um intersticial logo após a tela inicial ou quando eu abrir a atividade principal.
Muito obrigado!
Comment: Vale a pena lembrar que começar um interstitial logo após a abertura da tela inicial fere as regras do Google. Você pode ter sua conta suspensa por causa disso.

https://support.google.com/admob/answer/6201362?hl=pt-BR&ref_topic=2745287
Answer: Quando você cria uma thread no Android, você não pode modificar a thread de interface do usuário diretamente. É necessário utilizar o método runOnUiThread.
Dessa forma:
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }
});

E para carregar o InterstitialAd, basta adicionar o código abaixo no seu método onCreate
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-2565065222479596/3931476543");
mInterstitialAd.loadAd(new AdRequest.Builder().build());

Comment: Obrigado Valdeir. Funcionou, não apareceu mais o erro.
Mas não sei pq o interticial não apareceu, ele sempre cai no else.
Comment: runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mInterstitialAd.isLoaded()) {
                                    mInterstitialAd.show();
                                    Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                                    startActivity(intent);
                                }
                                else
                                {}
Comment: Como o banner ainda não foi carregado a condição `if (mInterstitialAd.isLoaded()) {` sempre será falsa. Editei minha resposta.
Comment: Muito Obrigado, Valdeir.
Perfeito!!!
Obrigado por contribuir com seu conhecimento, me ajudou demais.
Abraço!


reutilização de Javascript entre sites hospedados em linux

Question: Antes de gastar energia tentando implementar isso, gostaria de saber se alguem sabe se isso é uma má prática e se realmente funciona
tenho alguns sites hospedados com a pasta root da seguinte maneira:
Site 1:
/var/www/site1/html/
Site 2:
/var/www/site2/html/
Site 3:
/var/www/site3/html/
tenho alguns arquivos JS que utilizo nos 3 sites, quando atualizo em um, preciso copiar para os outros (sim já tá fedendo demais essa situação)
minha dúvida é, posso colocar esses arquivos na pasta:
/var/www/
e nos sites colocar algo como:

?
Comment: Sugestão: remova a tag `JavaScript` porque sua dúvida não tem a ver com isso.
Answer: Você pode rever sua estrutura de arquivos, como mencionado acima, mas eu sugiro algo mais simples. Aloque seus arquivos JavaScript em um domínio/subdomínio acessível na internet e vincule-os em seus projetos, da mesma forma que utilizamos bibliotecas através de CDNs. Assim você pode utilizar até em outros projetos fora deste servidor de forma segura. Ex.
Domínios:
www.meusite1.com.br
www.meusite2.com.br
www.meusite3.com.br
Endereço JS:
  js.nomegenerico.com.br/[seuscript].js
Obs: Se optar por fazer alterações na estrutura de pastas, cuidado com as permissões.
Answer: Depende da sua configuração. Mas antes de mais nada é preciso lembrar que Javascript é interpretado pelo Navegador, portanto o script precisa estar acessível a todos pela web.
Se você define um site com a raiz na pasta /var/www/site1/html/ e tenta acessar uma pasta em /var/www/scripts usando ../../scripts, isso não deveria funcionar. Lembrando que o navegador abre pela web, portanto nem seria uma URL válida pois seria abaixo da raiz do domínio.
Se você simplesmente define seus sites em /var/www e acessa cada um com o nome da pasta na frente do domínio, funcionaria.
Acho que a pergunta que você tem que fazer é se faz sentido que isso fique estruturado assim. Querendo ou não esta pasta abaixo do root vai fazer parte da estrutura interna do seu site se você usar ela assim.
Os sites 1, 2, 3 tem alguma relação entre si ou somente compartilham essas bibliotecas javascript? E cada qual tem seu domínio?
Quais problemas novos essa config vai causar? (se for migrar por exemplo, já vai ser mais complicado).
Você poderia ter uma pasta de trabalho com os Javascript (onde você modifica eles) e ter um script de instalação (Bash ou Makefile) que copia/substitui os arquivos para os sites (todos ou somente um deles) e depois já seta permissões/usuario.
No caso usaria algo como make site1 ou make all pra copiar.
Assim ainda ficaria o site todo contido dentro de sua pasta, mas ficaria fácil de atualizar. Penso que também ficaria mais fácil de testar essas libs antes de instalar em produção também.
De fato os scripts só precisam estar visíveis na web para sua página acessar. Mas usar scripts vindos de outros domínios costuma ser bloqueado pelos navegadores por razões de segurança.
Outra opção seria liberar o uso de links simbólicos (symlinks) no apache ou nginx. Por padrão essa opção costuma ficar desligada por questões de segurança, pois com isso ligado fica extremamente fácil de publicar/acessar qualquer pasta do servidor na Web.
Para evitar usar symlinks, pode-se usar hardlinks (links não simbólicos), que basicamente duplicam os arquivos, mas mantém o mesmo inode no disco. Assim os arquivos vão continuar únicos, mas vão possuir mais de uma referência na árvore do disco. Bem complexo de manter e normalmente não recomendável a não ser que tenha um motivo real pra isso.
O maior problema é manter um ponto de falha tão crítico para tantos sistemas.
Qualquer problema com essa pasta e todos os sites vão sofrer.
Trabalhar como repositório instalável evita todos esses problemas e ainda permite trabalhar mais tranquilo em um ambiente de testes.
Comment: E se eu usar um link simbólico?
Comment: Eu até ia sugerir symlink como opção, mas tanto apache quanto nginx normalmente precisam de configurações adicionais para que symlinks funcionem. Por padrão costuma ficar desligado isso. Além disso acaba abrindo mais uma vulnerabilidade no sistema pois fica fácil montar qualquer pasta do servidor na Web. Vou editar a resposta para incluir mais informações sobre isso.
Comment: Optei por usar scripts de instalação, deu certinho, fica mais trabalhoso mas pelomenos ficou mais fácil de colocar scripts testados em produção.


How to include two files by category id

Question: I have one file that I want to put in this file two other files that they will be dynamic. The main file is this:
<!doctype html>

<meta charset="utf-8">
<title>Gaming Ventus Let's Play - VLet's Play</title>
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="stylesheet" type="text/css" href="../styles/article_style_readmore.css">
<link rel="stylesheet" type="text/css" href="../../styles/styles_content_static_contact/styles_alltemplate_static_contact.css">
<link rel="stylesheet" type="text/css" href="../styles/readmore_mainbody_style.css">

<link rel="stylesheet" type="text/css" href="../../test/test2/Untitled-3.css">

        <form>
          <input type="text" id="search">
          Search
        </form>

Home

Reviews

News

Videos

Photos

Contact Us

  /****************************************************************\
  <?php

    include('function_art_result_readmore.php');
    include('function_art_result_readmore_photos.php');

  ?>
  \****************************************************************/

        About!

        Reviews!

        News!

        Videos!

        Photos!

Copyright Ventus Gaming

<?php
//Ayto einai to apotelesma otan patas to read more dhladh ta post mona tous
?>

So in the asterisk section I have this two files that I want to include... That files have mysql code and php code. So I want to include them like something like this:
<?php
  if ($CatID == 8) {
    include('function_art_result_readmore.php');
  } else {
    include('function_art_result_readmore_photos.php');
  }
?>

But this is not working, is just for example. So I want to open the include file by category id so I have both files whenever I want.
Of course if there is another solution I accept it :)
Thank you in advance!
Comment: From where do you get the current category ID?
Comment: I have a database and there I have the Category_ID column..if is that you are asking for.
Answer: Pass the category ID in the request (either GET or POST using the code below):
if(isset($_REQUEST['category_id']) &&  $_REQUEST['category_id'] == '8') {
  include('function_art_result_readmore.php');
} else {
  include('function_art_result_readmore_photos.php');
}

`
Comment: pass the category id in request param either GET/POST.. http://localhost/Phpnbaer/admin_login_bg/includes/article_result_readmore_img.php?article_id=31&category_id=8 (I Passed as GET request param in this sample link)
Comment: Not working :/ it opens this file: function_art_result_readmore_photos.php in all categories.
Comment: Can you paste the request url ?
Comment: you mean this? http://localhost/Phpnbaer/admin_login_bg/includes/article_result_readmore_img.php?article_id=31
Comment: Sorry I was not in pc. So i try it now and it worked perfectly... Thanks a lot! Just edit your above anwer to complete it if you want :)

How to include two files by category id