How is prior knowledge possible under a purely Bayesian framework?

Question: This is more of a philosophical question, but from a purely Bayesian standpoint how does one actually form prior knowledge?  If we need prior information to carry out valid inferences then there seems to be a problem if we have to appeal to past experience in justifying today's priors.  We're apparently left with the same question regarding how yesterday's conclusions were valid, and a kind of infinite regress seems to follow where no knowledge is warranted.  Does this mean that ultimately prior information must be assumed in an arbitrary way, or perhaps based on a more "frequentist" style of inference?
Comment: What about prior knowledge coming from past experiments?
Comment: That's the question I'm asking.  How did *those* experiments generate actual knowledge?
Comment: You yourself are the product of a stochastic probabilistic process. (Unless you have much higher prior belief in your specific divine creation than I). So I suppose, yes, possessing consciousness and having the ability to reason and incarnating as the dsaxton who chose Pi Day to ask this question can be seen as being based on something like an infinite sequence of possible repetitions over an infinite multiverse. But that's probably overthinking it.
Comment: @dsaxton, for example by producing estimates of, say, the effectiveness of a drug, which we then seek to update via a new sample.
Comment: Right, but does this then reduce to a kind of "cumulative" frequentism?
Comment: Prior captures what you know about the phenomenon. For instance, you went to school many years ago. Now, you have to estimate the mean height of 2nd grade students in your local school district. Based on your own experience, you think that the height is probably "around 4 feet". So, you could capture your prior as Gaussian distribution $\mathcal{N}(4,0.01)$, or $4\pm 0.1$ feet. You can use this prior before getting the data and estimating the mean height. The problem in practical setting is that once you saw the data once, you can't re-use the same prior, because it must have changed now.
Answer: Speaking of prior knowledge can be misleading, that is why you often see people speaking rather about prior beliefs. You do not need to have any prior knowledge to set up a prior. If you needed one, how would Longley-Cook manage with his problem?

Here is an example from the 1950s when Longley-Cook, an actuary at an
  insurance company, was asked to price the risk for a mid-air collision
  of two planes, an event which as far as he knew hadn't happened
  before. The civilian airline industry was still very young, but
  rapidly growing and all Longely-Cook knew was that there were no
  collisions in the previous 5 years.

Lack of data about mid-air collisions was not a problem to assign some prior to it that lead to pretty accurate conclusions as described by Markus Gesmann. This is extreme example of insufficient data and no prior knowledge, but in most real life situations you would have some out-of-data beliefs about your problem, that can be translated to priors.
There is a common misconception about priors that they need to be somehow "correct", or "unique". In fact, you can purposefully use "incorrect" priors to validate different beliefs against your data. Such approach is described by Spiegelhalter (2004) who describes how a "community" of priors (e.g. "skeptical", or "optimistic") can be used in decision-making scenario. In this case it is not even prior beliefs that are used to form priors, but rather prior hypotheses.
Since when using Bayesian approach, you include both the prior and data into your model, information from both sources will be combined. The more informative is your prior comparing to data, the more influence it would have, the more informative is your data, the less influence would your prior have.
Eventually, "all models are wrong, but some are useful". Priors describe beliefs that you incorporate in your model, they do not have to be correct. It is enough if they are helpful for your problem, as we are dealing only with approximations of reality that are described by your models. Yes, they are subjective. As you already noticed, if we needed prior knowledge for them, we would end up in a vicious circle. Their beauty is that they can be formed even when confronted with shortage of data, so to overcome it.

Spiegelhalter, D. J. (2004). Incorporating Bayesian ideas into health-care evaluation. Statistical Science, 156-174.
Comment: Special thanks for the reference to Spiegelhalter 2004. I like this sentence from the closing paragraph: "The general statistical community,
who are not stupid, have justifiably found somewhat
tiresome the tone of hectoring self-righteousness that
has often come from the Bayesian lobby."
Comment: it's appealing technically but logically inconsistent. It basically kills the whole Bayesian statistics' basis about beliefs, subjective probabilities etc. If you have many priors, why not have infinite number of priors? In this case how is this different from frequentist approaches? Once you run infinite number of priors, your outcome will converge to pure frequentist result or uninformative prior or something along those lines.
Comment: +1 but I agree with @Aksakal that multiple priors and even the whole approach of Bayesian "model checking" (as e.g. advertised greatly by Andrew Gelman) is not exactly pure Bayesian. For a pure Bayesian, the idea of "validating different beliefs" does not make any sense. You have your beliefs; you get new data; you update your beliefs, and that's all there is to it. Gelman and Shalizi have a paper on [Philosophy and the practice of Bayesian statistics](http://www.stat.columbia.edu/~gelman/research/published/philosophy.pdf) that talks about this conundrum but I never managed to read it through.
Comment: Community of priors is a clear bastardization of Bayesian approach. Unless one has multiple personalities, there can't be multiple priors. The prior is supposed to capture your prior belief, all that you know about the phenomenon. If you have multiple priors, you'll run into even more philosophical issues than Bayesian approach already has.
Comment: @Aksakal using them as described by Spiegelhalter is pretty appealing: use different priors and compare the outcome and check how much do they influence the outcome. Besides, they are nice example of that prior does not have to be "correct".
Comment: @Aksakal when creating single prior you "weight" the different sources of evidence "in your head" to come up with something -- how does it differ from setting multiple priors, one per source of belief?
Comment: @amoeba you can also check his book "Bayesian Approaches to Clinical Trials and Health-Care Evaluation".
Answer: I think you're making the mistake of applying something like the frequentist concept of probability to the foundations of the subjective definition. All that a prior is in the subjective framework is a quantification of a current belief, before updating it. By definition, you don't need anything concrete to arrive at that belief and it doesn't need to be valid, you just need to have it and to quantify it.
A prior can be informative or uninformative and it can be strong or weak. The point of those scales is that you don't have any implicit assumptions about the validity of your prior knowledge, you have explicit ones, and sometimes that can be "I have no information." Or it can be "I am not confident in the information I have." The point is, there is no requirement that prior knowledge is "valid". And that assumption is the only reason your scenario seems paradoxical.
By the way, if you like thinking about the philosophy of probability, you should read The Emergence of Probability by Ian Hacking and its sequel, The Taming of Chance. The first book especially was really illuminating in how the concept of probability came to have dual and seemingly incompatible definitions. As a teaser: did you know that until fairly recently, calling something "probable" meant that it was "approvable", i.e. that it was "approved by the authorities" or that it was a generally well respected opinion. It had nothing whatsoever to do with any concept of likelihood.
Comment: Interesting statement about the meaning of "probable". Until fairly recently is until when exactly? I find [11 occurrences of "probable" in the works of Shakespeare](http://www.opensourceshakespeare.org) and they seem to have the usual meaning. That's 400 years ago.
Comment: Looking at all those quotes, I actually think if you read them with the original definition in mind, they make more sense. But the best examples in Emergence are from Gibbon's Decline and Fall of the Roman Empire, one from Gibbon's personal notes and one from a footnote.

The personal note read: "Let us conclude, then, though with some remainder of scepticism, that although Livy's narrative has more of probability, yet that of Polybius has more of truth."

And the footnote, to Chapter xxiv of decline and fall, reads: "Such a fact is probable but undoubtable false."
Comment: Another really interesting one, also from Emergence, is from a mid 1700s writer named Thomas Church, in response to David Hume's attack on the credibility of miracles...
Comment: Quoting from Emergence:
"The author is at pains to insist that credibility is relative to the evidence. Church grants, 'that in common discourse, it is not unusual to call any thing credible or incredible, antecedent to our consideration of its proof. But if we examine our ideas, this will be found to be a loose unphilosophical way of expressing ourselves. All that can be meant is, that such a thing is possible or impossible, probable or improbable, or, at farthest, happening very frequently, or very seldom [1750, p. 60]."
Comment: But going back to shakespeare quotes, actually, those are pretty fascinating examples. Because most of them do make sense of a sort when defining probable in  the modern way, but all of them also make sense if you read them to be referring to how "believable" or "plausible" the subject being referred to is or should be.
Comment: This one, from All's Well That Ends Well, is, I think unambiguously defined in the original way:
"None in the world; but return with an invention and
clap upon you two or three probable lies: but we
have almost embossed him; you shall see his fall
to-night; for indeed he is not for your lordship's respect."
Referring to probable, or believable, lies.
Comment: By now I am confused; I thought that "plausible" or "believable" *is* the modern meaning of "probable". But in your answer you wrote about "approved by the authorities", which is a whole different meaning.
Comment: Well, the modern definition according to Mirriam-Webster, is "likely to happen or to be true but not certain". http://www.merriam-webster.com/dictionary/probable whereas "plausible" is defined as "possibly true : believable or realistic". One of Hacking's main early points is that for middle age philosophers especially, credibility of an idea had a lot to do with how many preceding respectable authorities approved it, or how "probable" it was. And the modern definition was an attempt to redefine credibility in terms of appeals to empirical observation, not appeals to authority.
Comment: "The authorities" in my original definition is ambiguous, and I understand why that would be confusing. A better way to say it might be that calling something probable mean that it was "approvable by the authorities, or by generally respected, intelligent people and institituions." A good illustrative example of this is Catholic probabilism, which is discussed at length in Emergence, since Pascal spent most of his public life attacking it. https://en.wikipedia.org/wiki/Catholic_probabilism


How can I return to normal view (View Track Waveforms) in Reaper

Question: I switched to "Peaks View" for moment. Now I can't get back to tracks looking like standard Waveforms. Will only show Peaks, Spectral Peaks, etc.
Anyone know how to get back to normal?
Answer: Options: Peaks Display Mode : Show Normal Peaks


"This addon could not be installed because it appears to be corrupt" Firefox Developer Edition

Question: I already set xpinstall.signatures.required to false.
The extension loads fine in about:debugging but not in about:addons (where it matters).
The error persists regardless of whether I add the activeTab, tabs, or <all_urls> permissions.
Using Firefox Developer Edition 109.0b3 (64-bit).
Manifest:
{
  "manifest_version": 2,
  "name": "My Extension",
  "description": "Description of my extension",
  "version": "1.0",
  "icons": {
    "48": "icon.png"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"]
    }
  ],
  "web_accessible_resources": [
    "web-accessible-resource.html"
  ]
}

Zipped extension:
extension.zip
├ content-script.js
├ icon.png
├ manifest.json
└ web-accessible-resource.html

Thanks in advance for any help.
Answer: It appears that you miss an "applications": { "gecko": { "id": "X@Y" } } at the end of your manifest.json (see also https://github.com/puemos/hls-downloader/issues/285)


Prove that inequality $AM \cdot AN + BM \cdot BN + CM \cdot CN \geq DM \cdot DN$

Question: Let $ABCD$ be the regular tetrahedron, and $M, N$ points in space. Prove that: $$AM \cdot AN + BM \cdot BN + CM \cdot CN \geq DM \cdot DN$$
Maybe use Ptolemy's inequality
solve it?
Comment: Give Cartesian coordinates $A=(1, -1, -1), B=(-1, 1, -1), C=(-1, -1, 1), D=(1, 1, 1), M=(x, y, z), N=(a,b,c)$ then it's proving $\sum_{cyc}\sqrt{((x-1)^2+(y+1)^2+(z+1)^2)((a-1)^2+(b+1)^2+(c+1)^2)} \ge \sqrt{((x-1)^2+(y-1)^2+(z-1)^2)((a-1)^2+(b-1)^2+(c-1)^2)}$
Comment: Let $M=B$ and $N=C$ (or circular) then we have equality:$$AM \cdot AN + BM \cdot BN + CM \cdot CN = DM \cdot DN$$
Comment: You also obtain equality if $M=N=\frac{A+B+C-D}{2}$
Comment: Indeed, this is just Ptolemy's inequality. See my solution. You have to be a little subtle in the application though.
Answer: Yes this is just Ptolemy's inequality.
Suppose that the isometry (i.e. rotation/reflection) swapping $(A,B)$ and $(C,D)$ sends $M$ to $L$. Now it suffices to show that $$BL\cdot AN+AL\cdot BN+DL\cdot CN\geq CL\cdot DN.$$ Ptolemy's inequality gives the following: $$\begin{align*}BL\cdot AN+AL\cdot BN&\geq LN\cdot AB\\LN\cdot CD+DL\cdot CN&\geq CL\cdot DN.\end{align*}$$ Since $AB=CD$, adding the two gives the desired inequality.
Comment: Very, very nice. Using this and the fact that Ptolemy's inequality is an equality only if the four points are coplanar and concyclic, one can show that equality is attained exactly in the cases mentioned in the comments above: either $M=N=\frac{A+B+C-D}{2}$ or $M\ne N$ and $\{M,N\}\subset \{A,B,C\}$.


Using IKVM-compiled Java .dll in VBA/Excel?

Question: I am looking to be able to execute code from a Java project inside an Excel VBA sheet. Elsewhere on SO, I have discovered IKVM, which is a .NET implementation of Java which allows converting a .jar into a .dll. I was hoping this would let me access the classes/methods from the .jar inside the VBA editor, but I am having trouble doing so.
I have tried using the declare statement in VBA (in many different permutations, attempting to make it work) but the most common error refers to entry points in the .DLL.
I have also tried registering the .DLL as a reference in Excel, but it gives a boilerplate error and does not register it.
As a reference, I've been testing it using the following class before bothering to test it with the whole project:
public class IKVMTest {
    public static void print(String s) {
        System.out.println(s);
    }
}

This class is compiled by Eclipse and exported into IKVMTest.jar. At this point, I use ikvmc -target:library IKVMTest.jar to receive IKVMTest.dll. For simplicity's sake, this .dll and the Excel sheet I am testing in are dumped in the IKVM bin folder (since there are some dependencies on the IKVM .dll files).
If I could get it working for this sample test, I could get it working for the project overall.
Comment: I posted an example here: http://stackoverflow.com/questions/14967080/how-do-i-make-a-dll-created-with-ikvm-com-visible/14975883#14975883
Answer: Have you tried making your .NET assembly COM visible so you can use VBA to instantiate it?
using [ComVisible(true)] on the class and methods generated by the IKVM code might make it visible as a COM object to your VBA app.
Have a look here for reference: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comvisibleattribute.aspx#Y1600
Also, have a look here:  How to call a .net assembly in VBA using COM Interop
http://blogs.msdn.com/b/smondal/archive/2009/08/31/how-to-call-a-net-assembly-in-vba-using-com-interop.aspx
Comment: No, the comvisible needs to be applied to .NET assemblies. Using the IKVM that generates a dll from a jar you will then need to update those dlls to include the comvisible or use the utility exe so you can make it visible to your VBA project.
Comment: Question, while I look through the two links you gave: using ComVisible(true) is something that I would apply to a VBA class, right? Does that imply I need to make a wrapper class in VBA for all the Java classes that I would like to refer to?


How can I identify the foreground 'app' in OS?

Question: I am an Android developer and I want to write an if statement in my application. In this statement I want to check which app is run which time in my mobile like Facebook, messenger,You Tube,chrome etc when its open and when its close. How can I do this programmatically?
Answer: I'm not sure what you mean with the if statement part but I guess that what you are looking for is UsageStatsManager.
Take into account that this API requires the permission android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.


Batch File - FOR LOOP

Question: Let me set the stage of my issue. I have a folder (FOLDER_ABC). Within that folder, there is a folder for my application, including a unique and always changing version number (application-v1.3.4). Within that folder, there is the application (application-v1.3.4.exe) - which will also change periodically.

C:\FOLDER_ABC\application-v1.3.4\application-v1.3.4.exe

In this section below I create a directory listing of the FOLDER_ABC for any folders starting with application* and store that folder name into a file called directory.txt. I then create a perameter and store that directory into it. I'm doing it this way, versus applying the direct full path to the directory or file, since the versions will change and I don't want to hard code the batch script.
cd C:\FOLDER_ABC\
dir  application* /b /ad>"C:\FOLDER_ABC\directory.txt"
set /p verdir= <C:\FOLDER_ABC\directory.txt

Here is my issue. In the section below, I'm trying to get my batch script to run the application*.exe file, and continue on with my batch file. It currently runs my application, but it hangs and doesn't continue the rest of my batch script. I'm really new to all this coding so I appreciate the help. I assume it could be something related to me not closing the FOR loop properly? How can I get it to continue on to :FINISH?
cd "C:\FOLDER_ABC\%verdir%\"
FOR /f "tokens=*" %%G IN ('dir /b *.exe') DO %%G;

:FINISH
ECHO THE END
exit

Figured it out, but didn't have enough StackOverflow credits to answer my own question. My solution is listed below. Thanks everyone. You pointed me in the right direction.
cd "C:\FOLDER_ABC\%verdir%\"
FOR %%G in (*.exe) DO START %%G

Answer: Try using the START command:
FOR /f "tokens=*" %%G IN ('dir /b *.exe') DO START %%G;

There may be other better ways if achieving what you want, for example, if you know that the exe always has the same name as its directory, and that there will be only one such directory, you could do the following:
FOR /D %%i in (application-v*) DO START %i\%i.exe

UPDATE
From comments:

My only issue, which I just realized, is that the application folder and application name are not always identical.

In that case, you could try something like:
for /d %%i in (application-v*) do for %%j in (%%i\*.exe) do start %%j

Comment: My only issue, which I just realized, is that the application folder and application name are not always identical. I want it to start any .exe within the app folder. C:\FOLDER_ABC\application-v1.3.4\Helloworld-v1.3.4.exe
Comment: I tried adding the app version to a parameter, just as I did with the folder, but I recieved the following error: 'C:\FOLDER_ABC\application-v1.3.4\application-v1.3.4.exe' is not recognized as an internal or external command, operable program or batch file.
Answer: you can try:
FOR /f "delims=" %%G IN ('dir /b /a-d *.exe') DO start "" "%%~G"

Answer: I'm not sure if this is your problem, but it is possible that the ; is causing problems. You do not terminate commands with ; in batch files.
There is no need for a temporary file. Your code can be greatly simplified with FOR:
pushd c:\folder_abc
for /d %%F in (application*) do cd "%%F"
for %%F in (*.exe) do "%%F"

:FINISH
ECHO THE END
exit /b

Comment: Thanks. Yeah, I figured out something similar that worked. I added it to the question above. Didn't have enough credits to answer my own question. Thanks! And the ";" was a typo. Sorry about that.

Batch File - FOR LOOP


why does the same repeated measures anova using ezANOVA() vs. aov() yield different distributions of model residuals?

Question: I am attempting to do a repeated measures anova using r with the aov() command from the {car} package. I wanted to be sure that I wrote my code for this approach correctly (see below), so I cross-checked the results against same repeated measures anova model using the ezANOVA() command from the {ez} package.
What I found was that the results from each anova were the same, but the residuals of each model using the respective packages were distributed differently. Using the aov() command, the residuals were non-normally distributed whereas using ezANOVA() they were normally distributed.
###############################
#aov() using the {car} package#
###############################

mod.aov <-aov(rating~(factor1*factor2) + Error(id/(factor1*factor2)), data=datalong)

shapiro.test(residuals(mod.aov))

Shapiro-Wilk normality test
data:  residuals(mod.aov)
W = 0.9961, p-value = 0.036

pearson.test(residuals(mod.aov))

Pearson chi-square normality test
data:  residuals(gain.aov)
P = 50.4, p-value = 0.004086

##################################
#ezANOVA() using the {ez} package#
##################################

mod.ez <- ezANOVA(data = datalong,
                  dv = .(rating),
                  wid = .(id),
                  within = .(factor1, factor2),
                  detailed = TRUE,
                  return_aov = TRUE)

shapiro.test(residuals(mod.ez$aov))

Shapiro-Wilk normality test
data:  residuals(mod.ez$aov)
W = 0.9876, p-value = 0.449

pearson.test(residuals(mod.aov$aov))

Pearson chi-square normality test
data:  residuals(mod.ez$aov)
P = 7.75, p-value = 0.6532

I do not understand whether the residuals of each model are different because of my code, or because of the differences between way the packages perform the analyses. Can anybody help? I can provide additional information if needed. Thanks.
Answer: First, there is no aov function in the car package, so I'm guessing you are referring to aov from the stats package.
Second, by comparing the QQ-plots of the residuals obtained via aov and ezANOVA, you are apparently not using the same data - the aov plot shows many more data points than the ezANOVA plot.
Third, I suspect that since you're not using identical data, this is the reason why you get different residuals. I just compared the residuals with a toy example, and both aov and ezANOVA yield identical results:
library(ez)

rating <- c(8, 9, 6, 5, 8, 7, 10, 12, 7, 5, 2, 3, 4, 5, 2, 6, 1, 2, 3, 1, 5, 6, 7, 8, 6, 5, 8, 9, 8, 7, 2, 1)
group <- factor(rep(1:4, each=8, len=32))
id <- factor(rep(1:8, times=4))
df <- data.frame(id, group, rating)

mod.ez <- ezANOVA(df, rating, id, within=group, return_aov=T)
mod.aov <- aov(rating ~ group + Error(id/group), df)

res.ez <- sort(proj(mod.ez$aov)[[3]][, "Residuals"])
res.aov <- sort(proj(mod.aov)[[3]][, "Residuals"])

res.ez - res.aov

plot(res.ez, res.aov)

So except for numerical errors, the residuals from the two methods are identical.


Find an IP that is known to be on a DNSBL

Question: I am configuring Zabbix to check my IPs against several DNSBLs.  My IPs are currently not blacklisted.  My monitoring needs to be tested, to verify that it will alert properly if one of my IPs does become blacklisted. How can I obtain, for testing, a known bad IP, one that is on a DNSBL?
Details
I've searched for published blacklists, but haven't found any.  I'm guessing that publishing the lists would aid spammers, or have other bad side-effects.
Zabbix will call a Ruby script.  That script will probably just shell out to rblcheck, since the lists it checks seem like a good start:
<code>$ rblcheck 184.108.40.206
22.214.171.124 not listed by sbl.spamhaus.org
126.96.36.199 not listed by xbl.spamhaus.org
18.104.22.168 not listed by pbl.spamhaus.org
220.127.116.11 not listed by bl.spamcop.net
18.104.22.168 not listed by psbl.surriel.com
188.8.131.52 not listed by dul.dnsbl.sorbs.net
</code>
The DNSBLs that rblcheck uses is configurable.  I can add or remove DNSBLs as needed, either permanently, or for testing.
Comment: Each DNSBL has its own test IP addresses for this purpose.
Comment: They're different for each DNSBL, of course, and usually buried in their documentation. 127.0.0.2 is pretty common.
Comment: @MichaelHampton That's perfect, thanks!  How does one go about finding the test IP addresses?  I haven't found the right search recipe for this (Googling for "DNSBL test addresses", for example, just yields forms and instructions for testing addresses).  I can't find anything in the spamhaus FAQ, nor spamcop's.
Comment: @MichaelHampton Thanks.  Do you want to paste those comments into an answer so I can vote it up?
Answer: You could use spamcop statistics to find an IP.
It give netblock in the /24
You can see here; https://www.spamcop.net/w3m?action=map;net=cmaxcnt;mask=65535;sort=spamcnt
From that page after you can click the SB link, and you will have directly some IP
An example; https://talosintelligence.com/reputation_center/lookup?search=126.96.36.199%2F24


How can I route automated emails through an email function in my module?

Question: I was unable to get HTML mail to use a template properly, so I have a mymodule_mail function that sends emails when a response is required from the user
function billiondollar_mail($key, &$message, $params) {
global $base_url;

$message['headers'] = array(
    'MIME-Version' => '1.0',
    'Return-Path' => 'email@example.com',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'From' => 'XXXX <firstname.lastname@example.com>',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
);

I have a switch case on $key that loads in html header and footer plus the email body.
I'm wondering if there's some way I can make the system emails (some sent via trigger/actions and the registration confirmation ones) use that same system. Right now they are in plain text, which is incongruous with the rest of the system.
If I can get them using that hook function I will need to know what $key value it would have and how to insert the message content.. presumably one of the $params
Answer: I think this is what you're looking for:
http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7
"hook_mail_alter() allows modification of email messages created and sent with drupal_mail()... All core modules use drupal_mail() for messaging, it is best practice but not mandatory in contributed modules."


Design of a Dental RCT in Which Patients Can Act as Their Own Control

Question: I've been asked to help determine the design of an RCT.  The design is primarily interested in the benefit of using a laser on some dental procedure in addition to a local anti-biotic and scaling, versus just the anti-biotic and scaling.
The outcome us gum attachment loss.  A dentist will probe the area between the tooth and gum to measure the depth where there is no attachment between the two.  This is done on a tooth by tooth basis and is measured in mm.  The aim of the RCT is to determine efficacy of the laser (meaning, does attachment loss decrease when using the laser in addition to drug and scaling).
Because there are two groups (Laser + drug + scaling v. drug + scaling), it would be easy to suggest randomizing subjects to one of the two and measure attachment loss on a single tooth or set of teeth.  I would run an ANCOVA controlling for baseline attachment loss plus other clinical factors associated with attachment loss (like smoking status).
I believe there is the option to also use patients as controls for themselves, which should improve efficiency.  Under the assumption that all teeth in the mouth are exchangeable, the proposition would be:

Randomly select one side of the mouth to receive treatment (laser + drug + scaling) and the other receive control (drug + scaling).

Match two teeth on either side on baseline attachment loss.

Treat those teeth and measure improvement after treatment.

Compare the difference in attachment loss between the two teeth and perform a regression on this.

To be clear, if $y_t$ was the attachment loss after treatment on the treated tooth, and $y_c$ was the attachment loss after treatment on the control tooth, then the ANCOVA would be on $\delta = y_t - y_c$.
I'm interested in the knowing if I my conception on matching teeth is valid and if the analysis I good, or if there is some other analysis I might be able to perform which might be better suited.
Answer: This split-mouth design is pretty common in dental research and sounds pretty reasonable. You want to make sure the sides are truly randomly selected (and at least vaguely comparable a-priori, because otherwise e.g. comparing one side that barely needed treatment vs. side that was in a really bad shape might not be ideal) and similarly the selection of the teeth to be matched. You also want to do as much as possible to minimize bias in the outcome assessment (ideally done by a person that's not aware which side was treated which way, or for consistency reasons always by the same person for all patients).
Analysis-wise, forming a subject difference is one way of proceeding that makes perfect sense. An alternative is to run e.g. a model with a subject random effect (modeling the average for each side), or to even model separately each tooth.
Given that you intend to always use two teeth per side, the different options shouldn't make too much of a difference. However, this also limits you:

Patients with only one side needing treatment (or only needing treatment for one tooth on one of the two sides) cannot be used (while with the last option that would be possible).
You cannot adjust for any covariates on a tooth level (e.g. some pre-treatment assessment, something you can measure from an X-ray or whatever else might make sense), while with the last option you could.
Comment: I'm fond of the idea of a subject random effect.  It might be feasible for us to measure all teeth within each treatment, meaning I could estimate a model in which teeth are nested within subject with a fixed effect of treatment and other covariates as Jacob mentions.
Answer: I like the idea of randomizing each side of the mouth for each patient, and also matching teeth. I wonder if it's best to match by position of the teeth (i.e. using symmetry of the mouth) rather than by baseline loss, especially since you're also controlling for baseline loss. I'm not sure what the consequences of the different matching would be.
In terms of modeling, I would use a random effects model. Enumerate the teeth on the right side from $t=1,..,T$, and assume that each of these teeth can be matched to the left side. For each measurement (2T measurements per subject) we note the subject, the tooth, the side, the treatment/control status, and covariates of the patients. Then the model in lme4 would be
<code>fit <- lmer(y~ treatment + covariates + (1|subject) + (1|subject:tooth), data = dat)
</code>
and you would look at the coefficient for treatment


How to delete some elements from UITableViewController with CoreData?

Question: So i can add some city from API and when i try to delete some city from UITableViewController then all cities are deleted. Can someone help me please where i made mistake. I gave an example of the code below
//this is my delete func from CoreData
 func deleteCity() {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        if let cities = try? context.fetch(fetchRequest) {
            for city in cities {
                context.delete(city)
            }
        }

        do {
            try context.save()
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    //this is how i create cities array
    func fetch() -> [Weather] {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        do {
            let cities = try context.fetch(fetchRequest)
            return cities.map({Weather(name: $0.cityName ?? "", temp: $0.cityTemp)})
        } catch  {
            return []
        }
    }

    //and this how i try to delete city from UITableViewController

  override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let actionDel = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in
            self.cityTemps.remove(at: indexPath.row)
            self.coreDataManaer.deleteCity()
            DispatchQueue.main.async {
                tableView.reloadData()
            }
        }
        let actions = UISwipeActionsConfiguration(actions: [actionDel])
        return actions
    }

Answer: Your deleteCity() function actually deletes all cities. Here's why:
First your fetch request fetches all cities, since there's no predicate:
let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

Then your loop goes through the results of the fetch and deletes every city it finds-- which is all of them.
if let cities = try? context.fetch(fetchRequest) {
    for city in cities {
        context.delete(city)
    }
}

It sounds like you want to delete only the city that the person swipes on, which is the city at indexPath in the last function above. You could change your fetch request, but you probably don't need to do that. In your data source methods (for example your tableView(_:cellForRowAt:) function) you already have a list of the cities you're showing, probably in an array. To delete a single city then, you'd do something like

Get the correct city from that array
Delete that city from the managed object context.


Create View and show tax terms that use the same term as the content

Question: everyone,
I am currently trying to create a view, but unfortunately I can't get a result.
Initial situation:
ContentType A uses a term from Tax B
Tax C uses a term from Tax B
Now I would like to have all terms of C listed on the page of A, which have the same tax term of B as A.
Example:
A= content of the topic "software"
Tax B = various industries (software, consulting, finance, construction, medicine....)
A has the term "software" from Tax B
Tax C = Various companies
C also has a term from Tax B, e. g. Microsoft is assigned to "software".
Now I would like to list beside the article about software all companies, which have also assigned the term "software".
What I've done so far:
1) View created as a block, output of taxonomy terms of vocabulary C (company)
2.) Taxonomy Term field: Name added to output
3.) Context filter taxonomy term:  (B) added
If the filter value is NOT available: Provide default value: Taxonomy term ID from URL
[x] Load standard filter of the term page
[x] Load default filter of the node page (good for related vocabulary blocks).
------[x]Industry
If I test the view in the preview with a TID from Tax B, then it works, too. But unfortunately not on the website.
Can you help me with that? I would appreciate a helpful answer!
Greetings,
Alex
Comment: Are you placing the view on a node or taxonomy term page? Sounds like you are doing something similar to http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8
Answer: It works in your test because you're giving it a TID, but in actual practice, that won't be in the URL when you're viewing the content. Therefore, your contextual filter shouldn't be a taxonomy term, but the content ID from the URL, use that to get the node's taxonomy terms (B), and then you might be able to directly get other items, filtered as taxonomy terms (C) that share those, or else you might need to use relationships.


Drupal 7: How can I get path for node or term in drupal with php code?

Question: I must build a block that retrieves children of a specific term id by selecting it through $node->title of a page.
So, I get it with taxonomy_get_termBy_name.
With this $term->tid I can get children of it by calling taxonomy_get_children().
Ok, it returns an array of children.
For each child I must take name and path in order to build an .
How can i retrieve these properties?
I am unable to find a module that performs these operations, so I must build my own block.
Answer: You can use the l() function to do this.
Example:
<code>$link = l('Link Title', 'node/' . $node_id);
$link = l('Link Title', 'taxonomy/term/' . $term_id);
</code>


Google Analytics Content Experiments A/B testing server-side code without page refresh

Question: Basically, we want to A/B test 2 different page layout headers. There are some structural differences (it's not just switching out the CSS).  We also don't want to wait for Google to flip the coin to determine which variation the visitor should see; instead, we want to choose the variation server-side and avoid a page redirect.
The code below does what I hoped it would; the UTMX cookie it generates looks identical to the one that the Google-supplied javascript would generate if I didn't omit it from the head tag.
Server-side PHP code:
<code>public function setUtmxCookie($cookieName, $experimentsString)
{
    $domainHash = $this->getDomainHash($_SERVER['SERVER_NAME']);
    $cookieVal = $domainHash . $experimentsString;
    $expire = time() + 60 * 60 * 24 * 30;
    $domain = '.' . $_SERVER['SERVER_NAME'];
    setrawcookie($cookieName, $cookieVal, $expire, '/', $domain);
}

private function getExperimentsFromUtmxCookie($cookieName)
{
    if (isset($_COOKIE[$cookieName])) {
        $cookieVal = $_COOKIE[$cookieName];
        $experimentsArray = array();
        $experimentMatches = preg_split('/\./', $cookieVal);
        $domainHash = array_shift($experimentMatches); //remove the first item.  All that will remain in $experimentMatches is an array of experimentIds with their combos.
        foreach ($experimentMatches as $m) {
            $segments = preg_split('/:/', $m);
            $experimentsArray[$segments[0]] = $segments[1];
        }
        return $experimentsArray;
    }
    return array();
}

private function getExperimentsString($cookieName, $experimentId, $variation)
{
    $experiments = $this->getExperimentsFromUtmxCookie($cookieName);
    $experiments[$experimentId] = $variation;
    $experimentsString = '';
    foreach ($experiments as $key => $val) {
        $experimentsString .= '.' . $key . ':' . $val;
    }
    return $experimentsString;
}
</code>
Why isn't my Google Analytics Content Experiments dashboard showing any visitors to my experiment, then?  Did I set the utmx cookie imperfectly?  Other than setting the UTMX cookie, is GACE looking for anything else?
Comment: We're now thinking about using a different approach: use Amazon load-balancers (AWS ELB) to deploy the "original" to some servers and the "variation" to one other server. We'll use a 3 to 1 ratio (75% of visitors will get the original) since we use 4 load-balanced servers.  We've enabled "stickiness" to keep individuals' experiences consistent.  The huge advantage to this approach is that there won't be conditional (if/else) code to remove after the experiment afterwards.  Just a normal merge from a branch back into trunk.
Answer: We've been using a totally different approach for the past couple months: Amazon load-balancers (AWS ELB) plus Google Analytics (not Content Experiments).  (See my comment above.)  As we hoped, it has greatly improved our experience with merging back to trunk.
<code>_gaq.push(['_setCustomVar', 2, varName, varValue, 2]);//https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables
_gaq.push(['_trackPageview']);//This must come AFTER the setCustomVar
//varName should be whatever you want to call the experiment
//varValue should be something like "original" for the original and "variation" for the variation.  We just use "trunk" and [name of variation branch].
</code>
Obvious drawbacks are that Google doesn't do the math for us (telling us whether the variation has statistically significantly outperformed the original) and that we can't easily run multiple experiments at once.  We also wouldn't be able to have many variations (we'd need to add more load-balanced instances than we'd want).
But for our purposes (e.g. given how important it is to us not to have a page refresh), it has worked better than other approaches.
Comment: Nice approach, I know this is old but I assume that the customVariable and the trackPageView are only to track how many visitors each variation has, but,Did you use some event tracking or something to measure the effectiveness of one variation over the other?
Comment: I can't remember the details of what I was doing in 2012, but yes, I must have somehow recorded events (the numerator of the fraction).
Answer: @danmaz74 took an interesting approach to this using only Google Analytics on the client side as well:
https://github.com/danmaz74/ABalytics
Comment: Client-side solutions aren't very useful for A-B testing layouts (as mentioned in the question).


Qual a diferença entre classe interna, classe aninhada e classe anônima?

Question: Frequentemente leio a respeito desses 3 tipos de classes quando estou pesquisando algo sobre java, mas a verdade é que muitas vezes causa uma certa confusão sobre o que cada uma delas realmente é e se tem alguma diferença entre si.
O que são classes internas, aninhadas e anônimas? Pode-se definir que são a mesma coisa entre si ou são coisas diferentes?
Answer: Segundo J Steven Perry da Makoto Consulting Group
Classe aninhada
são todas as classes que estão dentro de outra classe.
Exemplo:
public class calculadora {

public class soma{/* código */ }

}

Este tipo de classe é utilizado para manipular dados de processamento interno, mas é limitada pela classe que precisa dela.
Geralmente se usa este tipo de classe quando ambas as classes estão Intimamente ligadas. A classe aninhada terá acesso aos dados primitivos declarados pela classe que a chamou.
Nota: é um tipo de classe interna.

Como a classe aninhada tem um escopo, ela está limitada pelas regras
  do escopo. Por exemplo, uma variável de membro pode ser acessada
  apenas por uma instância da classe (um objeto). O mesmo é verdade para
  uma classe aninhada. Suponha que você tenha o seguinte relacionamento
  entre um Manager e uma classe aninhada denominada DirectReports, que é
  uma coleção dos Employees que se reportam a esse Manager:
public class Manager extends Employee {

    private DirectReports directReports;

    public Manager() {
        this.directReports = new DirectReports();
    }

    ...

    private class DirectReports {  . . .  }
}

Assim como cada objeto Manager representa um único ser humano, o
  objeto DirectReports representa uma coleção de pessoas reais
  (funcionários) que se reportam a um gerente (Manager). O DirectReports
  será diferente de um Manager para outro. Nesse caso, faz sentido que
  ele faça referência à classe aninhada DirectReports no contexto da
  instância de Manager que a encerra, assim ela foi feita private.

Da mesma forma eu usei no primeiro exemplo... imagine a classe calculadora:
public class Calculadora extends Calculos{
   private  Soma soma;

   public Calculadora(){
      this.soma = New Soma();
   }

   public class Soma {}
}

A soma é um conjunto de cálculos que eu chamei internamente e mostrei, e como está private será acessada somente pela classe de contexto, no caso, a classe Calculadora.
E se eu quiser utilizar pública?
Exemplo respondido pelo @Maniero em outro post do site.
Não da pra receber diretamente igual é como privado:

É necessário uma referência para a classe mãe por isto antes precisa
  criar uma instância para dela e nesta instância acessar a classe
  interna. Veja este exemplo que peguei de um tutorial sobre classes
  internas:
public class InnerClassTest {
    public void foo() {
        System.out.println("Outer class");
    }

    public class ReallyInner {
        public void foo() {
            System.out.println("Inner class");
        }

        public void test() {
            this.foo();
            InnerClassTest.this.foo();
        }
    }

    public static void main(String[] args) {
        InnerClassTest o = new InnerClassTest();
        InnerClassTest.ReallyInner i = o.new ReallyInner();
        i.test();
    }
}

Classes Internas:

Imagem disponível nas referências
Vamos uma por uma, a primeira já foi definida,classes aninhadas, que é uma classe interna e a mais comum dentre todas.
Classe interna Estática

Uma classe estática não tem acesso aos membros da instância da classe
  encapsulada, somente os membros estáticos, tem a mesma visibilidade de
  uma classe externa.

public class Calculadora {

  public static class Soma{
    int a = 1;
    int b = 2;
  }
}

Neste exemplo a classe soma tem dois atributos inteiros, a e b:

a sempre será 1
b sempre será 2

pois são estáticos... não se alterarão.
Classes internas de métodos
Métodos também tem classes? Sim!
protected  void Calcular(){

    class Calculo{
        private int soma;

        public void setSoma(int soma) {
            this.soma = soma;
        }

        public int getSoma() {
            return soma;
        }
    }
}

Neste caso a classe estará definida pelo escopo do método, não pode ser declarada como estática, e, a classe apenas poderá ser acessada por outras classes deste método.
Classe anônima
Toda classe que não é declara explicitamente mas esta sendo chamada no código, representa o comportamento de uma classe ou de uma interface.
 protected  void Calcular(){
          int a,b;
          Calculo calculo = new Calculo;
          calculo.somar({
public void somei(){

}
});// parece o click listener

}

Partindo do exemplo que não existe necessariamente uma classe para o método somar, mas , sem declaração ela esta lá , ou seja classes anônimas são classes internas que funciona como uma subclasse do tipo do objeto, não de onde esta sendo referenciado (no caso objeto do tipo somar).

Pode-se definir que são a mesma coisa entre si?

Encerrando, Classe aninhada é um tipo de classe interna, que usamos comumente, enquanto as anônimas nem tanto, já que funciona como uma sub chamada no método já instanciado, não é comum, e algumas vezes vai dificultar a leitura do código, já que a classe poderia estar declarada antes...
Então em geral classes aninhadas e anônimas são classes internas... e classe interna é todas aquelas que estão sendo chamadas dentro de alguma outra classe, método, ou anonimamente(sem declaração) em uma chamada da classe "pai" com um método em questão.
Referências:
Classe aninhadas
Classes internas
Classes internas
Classes internas
Classe anônima
Classe interna anônima
Comment: Ótima resposta! :)


Salvando ID de uma tabela com duas Primary Keys com Hibernate

Question: Olá, eu estou tendo um problema ao salvar dados em uma última tabela.
Bom, essa tabela tem duas foreign keys e as mesmas são primary keys:

Ao ir no Controller, salvar a tabela, eu uso os códigos a seguir:
 itv.setId();
    itv.setIngresso(ing);
    itv.setVenda(ven);
    itv.setItvqtde(Integer.valueOf(request.getParameter("txtqtde")));

    itvDao.salvarItemVenda(itv);
    response.sendRedirect("my-tickents-buy.jsp");

Aqui está o meu ItemVendaDao:
 public void salvarItemVenda(ItemVenda itv){

    try {

    s = new ConnectionFactory().getSessionFactory();
    tx = s.beginTransaction();
    s.save(itv);
    tx.commit();
    s.close();

    JOptionPane.showMessageDialog(null, "Item venda salva com sucesso");

    } catch (Exception e) {

        tx.rollback();

      JOptionPane.showMessageDialog(null, "Erro ao salvar item venda" +e.getMessage());
      s.close();

    }

}

O que é preciso colocar no itv.setId()?
Quando mapeio ele cria esse método para salvar o Id do item venda, sendo que o ID do item venda são dois: o objeto do ingresso e o objeto da venda, ambos já estão sendo salvos acima com o código:
 itv.setIngresso(ing);
    itv.setVenda(ven);

Novamente, o que é preciso colocar no itv.setId()?
Aqui está o ItemVenda.java (mapeado automaticamente pelo hibernate)
public class ItemVenda  implements java.io.Serializable {

 private ItemVendaId id;
 private Ingresso ingresso;
 private Venda venda;
 private int itvqtde;

public ItemVenda() {
}

public ItemVenda(ItemVendaId id, Ingresso ingresso, Venda venda, int itvqtde) {
   this.id = id;
   this.ingresso = ingresso;
   this.venda = venda;
   this.itvqtde = itvqtde;
}

public ItemVendaId getId() {
    return this.id;
}

public void setId(ItemVendaId id) {
    this.id = id;
}
public Ingresso getIngresso() {
    return this.ingresso;
}

public void setIngresso(Ingresso ingresso) {
    this.ingresso = ingresso;
}
public Venda getVenda() {
    return this.venda;
}

public void setVenda(Venda venda) {
    this.venda = venda;
}
public int getItvqtde() {
    return this.itvqtde;
}

public void setItvqtde(int itvqtde) {
    this.itvqtde = itvqtde;
}

E o ItemVendaId.java está da seguinte forma:
public class ItemVendaId  implements java.io.Serializable {

 private int itvvencodigo;
 private int itvingressocodigo;

public ItemVendaId() {
}

public ItemVendaId(int itvvencodigo, int itvingressocodigo) {
   this.itvvencodigo = itvvencodigo;
   this.itvingressocodigo = itvingressocodigo;
}

public int getItvvencodigo() {
    return this.itvvencodigo;
}

public void setItvvencodigo(int itvvencodigo) {
    this.itvvencodigo = itvvencodigo;
}
public int getItvingressocodigo() {
    return this.itvingressocodigo;
}

public void setItvingressocodigo(int itvingressocodigo) {
    this.itvingressocodigo = itvingressocodigo;
}

Answer: Inicialmente, vou recomendar você ter uma chave primária para cada tabela. essa chave primária seria seria um campo de ID.
Se precisar que suas chaves estrangeiras sejam únicas na tabela use o atributo UNIQUE.
Vou recomendar você usar anotações JPA nas suas tabelas para auxiliar o Hibernate (se já estiver usando xml recomendo mudar para Anotações):
@Entity
public class ItemVenda  implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name = "ingresso_id")
    private Ingresso ingresso;

    @ManyToOne
    @JoinColumn(name = "venda_id")
    private Venda venda;

    private int qtde;

    //getters e setters omitidos
}

Você teria também as classes Venda e Ingresso com seus respectivos campos.
E teria apenas estas três tabelas. A tabela ItemVenda ficaria com os campos:
id, ingresso_id, venda_id, qtde
Sempre deixando o Hibernate tomar conta disso para você.
Neste caso o seu método setId() da classe ItemVenda só seria utilizado em casos de update.
Comment: Então você me recomendaria a criar uma ID na tabela do item venda? Ficaria assim:

create table itemvenda(

itvcodigo integer not null auto_increment primary key,

);
Comment: Exatamente e esse seria o código para criação manual. Ainda assim, recomendo que você configure o Hibernate para criar/atualizar automaticamente as tabelas para você (considerando que ainda esteja em fase de desenvolvimento e não existem dados importantes no banco).
Answer: Se o conjunto de duas ou mais colunas que, combinadas, nunca se repetirão, você não precisa (e nem deve) criar uma coluna extra somente para servir como chave primária (como @Shura16 sugeriu). Você só estará criando uma coluna totalmente desnecessária visando somente a sua facilidade no desenvolvimento e fugindo da performance e boa integridade de dados no banco de dados.
No seu caso, você precisa criar uma chave composta. Simples assim.
Na JPA existem duas formas de fazer isso. Uma é através de IdClass e a outra, que eu recomendo, é através de EmbeddedId e Embeddable.
Digamos que você tem uma Classe A, uma Classe B e, uma terceira, Classe C onde a sua chave primária é composta da união de Classe A e B.
Ficaria assim:
Classe A:
@Entity
@Table(name = "CLASSE_A")
public class ClasseA {

    @Id
    @Column(name = "CLASSE_A_ID")
    private Long id;

}

Classe B:
@Entity
@Table(name = "CLASSE_B")
public class ClasseB {

    @Id
    @Column(name = "CLASSE_B_ID")
    private String id;

}

Antes de criar a classe C, você deverá criar uma classe que irá incorporar a Classe A e Classe B. Esta classe que irá representar a sua chave composta.
Classe C PK:
@Embeddable
public class ClasseCPK {

    @Column(name = "CLASSE_A_ID", nullable = false)
    private Long classeAId;

    @Column(name = "CLASSE_B_ID", nullable = false)
    private String classeBId;

}

Observe a anotação @Embeddable em ClasseCPK. Isto serve para informar ao JPA que esta classe servirá como uma chave composta.
Repare também que os seus atributos são somente uma referência ao tipo dos atributos de Classe A e B. Ou seja, Long e String.
Finalmente a nossa Classe C ficará assim:
Classe C:
@Entity
@Table(name = "CLASSE_C")
public class ClasseC {

    @EmbeddedId
    private ClasseCPK pk = new ClasseCPK();

    @ManyToOne
    @JoinColumn(name = "CLASSE_A_ID", referencedColumnName = "CLASSE_A_ID", nullable = false, updatable = false, insertable = false)
    private ClasseA classeA;

    @ManyToOne
    @JoinColumn(name = "CLASSE_B_ID", referencedColumnName = "CLASSE_B_ID", nullable = false, updatable = false, insertable = false)
    private ClasseB classeB;

}

E isto termina o mapeamento.
Mais um detalhe. Só mande o Hibernate criar as tabelas/colunas para você se o seu projeto for pequeno/amador. Se for um projeto grande e importante, como para uma instituição financeira e afins, nunca deixe o Hibernate interferir na estrutura do banco de dados, pois este mesmo banco de dados poderá (e muito provavelmente será) ser utilizado em outros sistemas e de diferentes linguagens.
Bônus: Caso uma entidade sua referencie uma outra que possui chave composta, você deverá usar a anotação @JoinColumns.
Answer: Olá,
Respondendo diretamente a sua pergunta "..o que é preciso colocar no itv.setId()?"
Conforme o seu código esse ID é formado por um objeto ItemVendaId, então basta instanciá-lo no momento de gravar que tudo deve funcionar.
Como você não mostrou o código das classes Ingresso e Venda, estou chutando o nomes dos ID's deles. Segue exemplo:
itv.setId(new ItemVendaId(ven.getitvvencodigo(), ing.getitvingressocodigo()));
itv.setIngresso(ing);
itv.setVenda(ven);
itv.setItvqtde(Integer.valueOf(request.getParameter("txtqtde")));
itvDao.salvarItemVenda(itv);
response.sendRedirect("my-tickents-buy.jsp");

Em todo caso, assim como os outros colegas que responderam antes, não recomendo esse tipo de mapeamento.


Fitting known equation to data

Question: I have measured growth rates over a range of temperatures (temperature response curve) and would like to fit an already established equation/model to it. I'm very new to R and have trouble coding it right.
This is my data:
    x <- c(37.8,
   34.8,
   32.25,
   29.65,
   26.75,
   24.4,
   21.45,
   19.15,
   16.2,
   13.7,
   10.95,
   8.2,
   5.4)
    y <- c(0.0381,
   0.018133333,
   1.057033333,
   2.3395,
   2.5188,
   2.6132,
   2.398466667,
   2.082966667,
   1.687366667,
   1.389233333,
   0.9835,
   0.639833333,
   0.3757)

The equation I'm trying to fit is as follows:
$y=(3.5-x/10)(x/25)^{(5/2)}$
There is also another data set:
x2 <- c(34.8, 32.25, 29.65, 26.75, 24.4, 21.45, 19.15, 16.2, 5.4)

and
y2 <- c(0.033966667, 1.5153, 2.226266667, 2.3462, 2.096766667, 2.0986, 1.941866667, 1.5183, 0.2717)

I tried modifing code that I found here to my equation but have been unsuccessful so far. Can someone help with this with a step by step guide for dummies?
Updated model for my dataset:
$$y = Y_{max}\frac{T_{max}-x}{T_{max}-T_{opt}}\left(\frac{x}{T_{opt}}\right)^{(T_{opt}/(T_{max}-T_{opt}))}$$
Comment: Your function doesn't appear to contain any unknowns. In what sense is there an "fitting" going on? Also ... when you write the  "(x/25)exp(5/2)" part do you actually mean (x/25)^(5/2)? That looks a lot more like the shape of your data (but the entire function is only about 37% of what it should be). Even with that change the function isn't quite right, but it's sort of closeish.
Comment: Hi Glen, fitting is the wrong word I guess then. I basically want to see how well my data fits to the equation. There are some unknowns in the original equation that can be filled with measurements. The following equation can be used too: y=((35−x/(35-z))(x/z)^(z/(10))
Comment: With the previous version of your "updated model," y can never reach a value greater than 1. The peak for y occurs at $x=T_{opt}$, and at that value of x, y=1. I edited your question to add an additional parameter $Y_{max}$ to cover this. I also put the additional data set (which I now use for examining differences between parameter values) into your question directly, as comments (unlike questions) can be lost. Make sure that you are checking plots by eye and that you have reasonable fits before you start worrying about differences between fitted parameters from different experiments.
Answer: Fitting data to an equation without free parameters
First, let's clarify what it means "to see how well my data fits to the equation" when you have a fixed equation as in your original question. You have data on $x$ and $y$, and your equation:
$$y=(3.5-(x/10))(x/25)^{5/2}$$
has no free parameters. Here's a plot; data points are circles, the equation a solid curve:

So to answer your original question, your data don't fit that equation very well.
Fitting parameters of an equation to match data
Second, "fitting an equation" generally means having a general form of a relation between $y$ and $x$ in mind, but the details of the form depend on some additional unknown parameters of the equation. "Fitting" then means using the data to estimate the values of the parameters that best match the data, say by minimizing the sum of the squares of the discrepancies between the curve and the data. That is what's implicit in the form of the equation in your comment. (I corrected an apparently missing parenthesis so that it matches your original parameter-free equation at $z=25$):
$$y = \frac{35-x}{35-z}\left(\frac{x}{z}\right)^{(z/10)}$$
Now there is something to "fit": find the value of $z$ that comes closest to your data. The simplest R function to do this is nls. (The R code I used is at the end of the answer.) The best fit to your $x$ and $y$ data is provided by a $z$ value of 33.1, not the value of 25 that would match your first parameter-free equation. It comes closer, but doesn't do very well, either, substantially below most of the true values:

It looks like your equation might have an even more general form, like:
$$y = \frac{a-x}{a-z}\left(\frac{x}{z}\right)^{(z/b)}$$
where $z$, $a$ and $b$ are parameters whose values might be estimated from the data. With that more general form, you can come fairly close to your data, at $z=34.0$, $a=36.7$, and $b=17.8$:

Dangers in fitting equations
Third, you must be very careful if you head down this fitting path. As John von Neumann allegedly said, "With four parameters I can fit an elephant, and with five I can make him wiggle his trunk." Overfitting is a serious temptation when you start playing with data.
In a case like yours you have to think about what the parameters might mean in the real world. It seems that there are competing processes that lead to a peak in growth rate ($y$) at a certain temperature ($x$), and if the parameters $z$, $a$ and $b$ have definite meanings in terms of those competing processes then you might be justified in doing this type of fit. You might, say, learn something about how those processes differ from one strain of bacteria to another. But if such parameters (or the fixed values in your original equation) were simply chosen by someone to make some earlier set of data fit a particular curve then you are headed for big trouble.
Comparing fits to different data sets
If you want to compare the parameter values fitted to two different data sets, it's best to start by examining whether the overall fits differ between the data sets. There is a "useful and rather easily overlooked" way to do this with nls as Peter Dalgaard put it in a recent answer on R-help. (It can be found at the very bottom of the nls help page.)
Instead of working with separate vectors of $x$ and $y$ values from different experiments, construct a pooled data frame containing all the data. Each row should contain an $x$ value, the associated observed $y$ value, and a factor variable indicating the specific experiment. (Make sure the experiments are coded as factors, not as numbers.)
nls then allows you to fit different sets of parameter values to different experiments. Instead of specifying general parameters like Topt in your call, you can subscript the parameters by experiment, e.g. Topt[expt], where "expt" is the name of the factor distinguishing experiments.
Thus you can use anova to compare a fit to all the data, ignoring individual experiments, against a fit that allows different parameter values for different experiments. If these fits aren't statistically distinguishable, then you shouldn't be looking at differences of individual fitted parameter values among experiments. There's an example below where I present R code.
If the fits do differ, then you can consider comparing fitted parameter values. In the limit of very large samples the fitted values should have normal distributions, but it's not clear what "large" means for nonlinear fits and the meaning might differ depending on the equation. Thus there will be questions about the validity of p-values.
If you are willing to assume normality, nls reports standard errors for the parameter values, which you can use to obtain p-values under that assumption. A  z-test can provide a rough overview, but it would probably be better to use the approach of Welch's t-test, which allows for different standard errors and degrees of freedom between two parameter estimates. To apply that approach, note that terms like $\frac{s_i^2}{N_i}$ in the formula for Welch's test are equivalent to $SE_i^2$ in the nls output.
R code
In terms of R code, it was simplest to define a general function for your temperature-response curve:
trcFunc <- function(x,z,a,b){((a-x)/(a-z))*((x/z)^(z/b))}

then give specific values for the parameters that matched your original equation, to compare your data to the curve:
plot(x,y)
curve(trcFunc(x,25,35,10),add=TRUE)

For fitting, I used the nls function, for example for $z$ alone
Zfit <- nls(y~trcFunc(x,z,35,10),start=list(z=30))

or for all 3 parameter values
ZABfit <- nls(y~trcFunc(x,z,a,b),start=list(z=30,a=35,b=10))

Get the fitted parameter values with
ZABfit
Nonlinear regression model
  model: y ~ trcFunc(x, z, a, b)
   data: parent.frame()
    z     a     b
33.98 36.74 17.84
 residual sum-of-squares: 1.228

Number of iterations to convergence: 5
Achieved convergence tolerance: 1.35e-06

and compare data and curve:
plot(x,y,main="fit z, a, b")
curve(trcFunc(x,33.98,36.74,17.84),add=TRUE)

New form for relation; comparing fits With the new general form for the relation of $y$ to $x$ in an edit to the OP, a new general function for fitting is defined as:
newFunc <- function(x,Topt,Tmax,Ymax){Ymax*((Tmax-x)/(Tmax-Topt))*(x/Topt)^(Topt/(Tmax-Topt))}

For comparing two experiments, take expt1 as the data at the beginning of the question and expt2 as the second data set (x2,y2) toward the end, and construct a pooled data frame as suggested above. Then the fit ignoring the differences between experiments is:
fitPool <- nls(y~newFunc(x,Topt,Tmax,Ymax),data=newDF,start=list(Topt=25,Tmax=35,Ymax=2.5))

and that allowing separate parameter values for the two experiments is:
fitSeparate <- nls(y~newFunc(x,Topt[expt],Tmax[expt],Ymax[expt]),data=newDF,start=list(Topt=c(25,25),Tmax=c(35,35),Ymax=c(2.5,2.5)))

The pooled and separate fits are not significantly different:

> anova(fitPool,fitSeparate)
Analysis of Variance Table
Model 1: y ~ newFunc(x, Topt, Tmax, Ymax)
Model 2: y ~ newFunc(x, Topt[expt], Tmax[expt], Ymax[expt])
  Res.Df Res.Sum Sq Df  Sum Sq F value Pr(>F)
1     19     1.9215
2     16     1.4410  3 0.48046  1.7782 0.1918

Warning on choice of starting values
Note that, as can happen in non-linear curve fitting, what you get as the "best" fit can depend on what you provide as an initial guess for the parameter values. With your data, if I provided an initial guess of 26 for $z$ and fixed values of 35 and 10 for $a$ and $b$:
Zfit26start <- nls(y~trcFunc(x,z,35,10),start=list(z=26))

the value returned for $z$ is 13.1,which doesn't fit very well at all:

This happened because the program wasn't set up to evaluate an entire range of $z$ values and got stuck in what's called a "local optimum" when it started searching from $z=26$. If I tried starting values of $z$ from 20 to 25 then the nls program returned an error:
Error in numericDeriv(form[[3L]], names(ind), env) :
  Missing value or an infinity produced when evaluating the model

while starting values of 19 or less gave the poorly fitting estimate of 13.1 for $z$. With a non-linear curve fit you can't count on getting the "global" optimum without doing a lot of exploration.
Comment: Hi Ed, thanks a lot for your detailed answer and comments! This helps me a lot!
Comment: @Kay I added an additional caution about choice of initial parameter values in non-linear curve fitting that was illustrated nicely by your data, and corrected a couple of errors in my earlier post.
Comment: Hi Ed, thanks a lot for following up on that. I've noticed the same trends when I change the starting values. I'm comparing 3 different temperature settings and I can make an educated guess for the starting values to not run into the mentioned problems. There is a third parameter that can be added to the equation which gives an even better fit, but as you pointed out might not have a biological meaning. I will try and compare the equation I have with each other and see which one has the best fit AND most biological meaning.
Comment: I also have this dataset:x <- c(34.8,
          32.25,
          29.65,
          26.75,
          24.4,
          21.45,
          19.15,
          16.2,
          5.4)
y <- c(0.033966667,
          1.5153,
          2.226266667,
          2.3462,
          2.096766667,
          2.0986,
          1.941866667,
          1.5183,
          0.2717)
Which has two optima and gets me into trouble as the general equation does not seem to work very well on my end.
Comment: The choice of starting parameter values can be crucial. I had no problem with your second dataset when I used starting values of $z=30,a=35,b=10$, which ended up being very close to the optimum values ($z=33.1,a=35.1,b=12.3$). The instability may come from the way $z$ appears in your equation: increasing $z$ makes the first factor blow up (to infinity at $z=a$) and although it decreases the second factor it raises the exponent of the second factor.
Comment: Hi Ed, thanks a lot again for your help with my curve. I've fitted the model to two of my datasets and was wondering how I could compare the coefficients of the two models. I want to test if the temperature optimum shift is significant. Can you point me where I could find how to do such a test? Thank you!
Comment: @Kay : Use calculus to find the temperature optimum as a general function of the parameters. Next make sure you saved the outputs from `nls` (as I did in my examples, e.g., `ZABfit`) for each model. Then use the `deltaMethod` function in the R `car` package to estimate the standard error of the the temperature maximum for each of your fits, by providing the general formula for the temperature maximum as the argument "g". You then will have for each model an Estimate of the temperature maximum and its standard error. Then you do a standard comparison of the 2 values given their standard errors.
Comment: Thanks Ed! The model summary also gives me a standard error `# Estimate Std. Error t value Pr(>|t|)
#Topt 24.45320    0.16900  144.69   <2e-16 ***
 # Tmax 34.82563    0.13087  266.11   <2e-16 ***` Can I use those too or are they different to your approach? What do you mean with standard comparision? Like a t-test? I've done those before on a dataset but not with "just" a value and its standard error.
Comment: @Kay it seems that you are now using a different form of equation for `nls` than what we first discussed, where `Tmax` didn't seem to be a parameter itself. Depending on the new equation form there might be different or better ways to compare across experiments. Consider editing your post to add the new form at the end of the question. In the meantime, a simple approximate test is to use $\sqrt{SE_1^2+SE_2^2}$ as the estimate of the standard error of the difference between coefficients, and use that in a  _z_-test.
Comment: I've added the model that I'm using to my original question. If I understand it correctly, I can do the z-test for all my coeffiecients (`Topt, and Tmax`)?
Comment: The z-test is a good way to start. It assumes that the distributions of the parameter values among repeated experiments have normal distributions, which is true in the limit of large numbers of cases. Unfortunately, what constitutes a large number of cases for nonlinear models is a difficult problem that may differ among nonlinear models. I'll suggest another approach in an edit to my answer when I have more time in a day or two.
Comment: OMG this is awesome! Thank you so much. I just used the approach you added to your original answer and I get the following output of the anova `Res.Df Res.Sum Sq Df   Sum Sq F value  Pr(>F)
1     57    0.28152
2     55    0.24198  2 0.039544  4.4941 0.01557 *` But I also noticed that my coefficients are slightly different to the ones I get when I just run the datasets seperately. So according to the anova my two models are in general significant different? Now I would do the suggest Welch's t-test?
Comment: Make sure that the fits look OK before you proceed; you should show these when you publish. Slight differences in coefficients of combined versus individual analyses maybe aren't surprising. You have shown that the fits differ significantly, so you can look at coefficient differences between fits. Some might challenge the assumption of normality of fitted coefficient values needed for the Welch t-test, but it's probably the best you can do. The significant difference of fits (which only depends on normality of residual errors) supports the idea that there should be differences in coefficients.
Comment: Ok, I will check that. I don't want to speak for everyone in my field but I am relatively sure that most of my colleagues are not so fluent in statistics. As as long as I point out my assumption I guess it should be fine. Thank you very much EdM for being my personal statistician! Where did you learn all this? Is there a good book you can recommend?

Fitting known equation to data


Does there exist a Frequentist or Non-Bayesian solution to Gull's Lighthouse Problem?

Question: Does there exist a Frequentist or ODE or Non-Bayesian solution to Gull's Lighthouse Problem which is correctly modeled with cauchy distribution?
See The Lighthouse Problem and Dave Harris' answer to this thread: Bayesian lighthouse location estimation.
Answer: Interesting problem indeed. Three non-Bayesian solutions follow.
Classical Physicist's view
Here's my physicist's solution to it.
$$\alpha=median[x_k]=F^{-1}(1/2)$$
$$\beta=F^{-1}(3/4)-F^{-1}(1/4)$$
Here $F$ is the empirical CDF of Cauchy distribution, or you could also call it a quantile (percentile) function.

Cauchy distribution (aka Breit-Wigner in physics) has no mean, but it is symmetric. So, the median is a decent estimate of the $\alpha$.
Since, it has no variance either, in physics when using this distribution the notion of width at half height is used to describe its dispersion. It happens so that the width at half height of PDF is $\beta$ and corresponds to the span between first and third quartiles (interquartile range).
MLE
Maximum likelihood estimation, of course, is more efficient. However, mine is very simple and intuitive.
OLS (doesn't work)
There's also a terrible regression solution. Look at the quantile function of the distribution:
$$Q(p; \alpha,\beta) = \alpha + \beta\,\tan\left[\pi\left(p-\tfrac{1}{2}\right)\right]$$
It appears that, we can convert it into OLS problem (assuming $x_k$ are ordered!):
$$x_k = \alpha + \beta\,\tan\left[\pi\left((k-1/2)/N-\tfrac{1}{2}\right)\right]$$
$$x_k = \alpha + \beta\,z_k,$$
where $z_k=\tan\left[\pi\left((k-1/2)/N-\tfrac{1}{2}\right)\right]$
OLS will give you immediately the estimates $\hat\alpha,\hat\beta$.
The problem is that, OLS assumes finite variance, and we don't have it with Cauchy. So, the output of OLS is garbage. Here's R code to experiment and see how my first method is pretty robust.
alpha <- 10 # unkonwn true values
beta  <- 30 # this is known for now
##################
set.seed(123)
N       <- 1024
theta_k <- runif(N,-pi/2,pi/2)
x_k     <- beta * tan(theta_k) + alpha
q123 = quantile(x_k,c(1/4,1/2,3/4),type=1)
print("alpha")
print(q123[2])
print("beta")
print((q123[3] - q123[1])/2)

y = sort(x_k)
x = tan(pi*((seq(1:N)-0.5)/N-1/2))
fit = lm(y~x)
print(fit)

Outputs:
alpha <- 10 # unkonwn true values
beta  <- 30 # this is known for now
##################
set.seed(123)
N       <- 1024
theta_k <- runif(N,-pi/2,pi/2)
x_k     <- beta * tan(theta_k) + alpha
q123 = quantile(x_k,c(1/4,1/2,3/4),type=1)
print("alpha")
print(q123[2])
print("beta")
print((q123[3] - q123[1])/2)

y = sort(x_k)
x = tan(pi*((seq(1:N)-0.5)/N-1/2))
fit = lm(y~x)
print(fit)

Comment: The solution is obtained through quantile regression?
Comment: I wouldn't call it a quantile regression. That term is reserved for a different kind of technique, but OLS solution does use quantiles
Answer: Since $x \sim Cauchy(\alpha, \beta)$ and you want to estimate the position of the lighthouse, wich is $(\alpha, \beta)$, your problem is simply to make inference on a Cauchy distribution. Here you will find what you need: https://en.wikipedia.org/wiki/Cauchy_distribution#Estimation_of_parameters


How do I check if a session id already exists in redis

Question: I have the following code and I am not sure how to check if the session key exists already, because I do not want to create another redis session if it already exists.
The request object is new with every call but I know that the event.sender.id is the same on each request.
<code>     // If not set then create the session object
     if (!req.session.key) {
       console.log('Set session variable');
       req.session.key = event.sender.id;
       console.log('*** SESSION CREATED WITH ' + event.sender.id);
     }
</code>
Answer: Server.js
<code>const redis = require("redis");
const client = redis.createClient();
const hostname = '127.0.0.1';
const port = 6379;

client.on("error", function (err) {
    console.log("Error " + err); });

var session_id_key = event.sender.id ; //your id

client.exists("key",session_id_key, function (err, replies) {

    if(!err && replies===1){

        console.log("THE SESSION ID ALREADY PRESENT ");
    }else{
        console.log("THE SESSION ID DOES NOT PRESENT");
    } });
</code>
The Answer is :
THE SESSION ID ALREADY PRESENT


Problema em montar uma matriz em C

Question: Estou com um problema com uma matriz que montei para seja digitado letras e estas transformadas em números da tabela ascii, mas ela não imprime
Onde estou errando? Alguém pode me ajudar?
#include <stdio.h>
#include <stdlib.h>
int main(){
 char i, j, m[3][3];
 char tecla[0];

 //captura os elementos
 for(i=0;i<3;i++)
 for(j=0;j<3;j++){
 printf("Elemento[%d][%d]= ",i,j);
 tecla[0] = getche();
 scanf("%c",&m[i][j]);
 }
 //EXIBIR VALORES ORIGINAIS
 printf("\n::: Valores Originais :::\n");
 for(i=0;i<3;i++){
 for(j=0;j<3;j++)
 printf("%c ",m[i][j]);
 tecla[0] = getche();
 printf("\n");
 }

Comment: @WilliamHenrique Não "corrija" a identação de perguntas onde os problemas de identação são parte do problema da pergunta!
Comment: Tem certeza que deseja criar um vetor de tamanho zero?
Comment: Observe os `{` e `}` desses laços `for`. Parece estar errado.
Comment: Queria que as letras digitadas fossem exibidas no final, e isso não acontece, mesmo com a mudança sugerida por vocês
Comment: O meu código somente apresenta a última letra digitada
Comment: @VictorStafusa blz mano! obrigado pelo toque!
Answer: Acho que o que você queria era isso:
#include <stdio.h>
#include <stdlib.h>
int main() {
    char i, j, m[3][3];
    char tecla;

    //captura os elementos
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            printf("Elemento[%d][%d] = ", i, j);
            tecla = getche();
            scanf("%c", &m[i][j]);
         }
     }

     //EXIBIR VALORES ORIGINAIS
     printf("\n::: Valores Originais :::\n");
     for (i = 0; i < 3; i++) {
         for (j = 0; j < 3; j++) {
             printf("%c ", m[i][j]);
         }
         printf("\n");
     }
     tecla = getche();
}

Sempre use o { e o } para evitar cometer erros. Por exemplo, nesse código que você postou:
 //EXIBIR VALORES ORIGINAIS
 printf("\n::: Valores Originais :::\n");
 for(i=0;i<3;i++){
 for(j=0;j<3;j++)
 printf("%c ",m[i][j]);
 tecla[0] = getche();
 printf("\n");
 }

Observe que o for de dentro não tem o {. Isso faz com que o tecla[0] = getche(); e o printf("\n"); estejam fora do for interno. Se você sempre usar o { em todos os laços for, não terá esse problema. Identar tudo de forma adequada também te ajudará bastante.
Além disso, char tecla[0]; declara um array de zero posições e você escreve na primeira posição dele (a posição 0), que já está fora do array. Isso não faz sentido, é mais fácil usar apenas uma variável comum char tecla;.
Comment: Sim concordo. Irei seguir o conselho e ser bem mais conservador no que toca edições de código.
Comment: Infelizmente fui eu que indentei mal lol, muito devido à forma confusa como haviam `{` e `}` em falta. Vou dar um jeito, mas não invalida o uso muito aconselhado de `{` `}` claro.
Comment: @Isac É por causa de situações como essa que criei isso: https://pt.meta.stackoverflow.com/q/6300/132
Comment: Eu percebo de facto o seu ponto de vista mas é bem difícil ler o código todo corrido sem nenhuma indentação, dai que tenha indentado. Na maior parte dos casos não afeta interpretação mas neste de fato afetou. Podemos sempre retroceder nas edições e voltar ao estado não indentado e reaplicar o ajuste de tags
Comment: @Isac Sim, claro. Mas eu sempre sou extremamente conservador em relação a editar o código da pergunta porque já vi inúmeros casos onde identar direito é parte da resposta.

Problema em montar uma matriz em C


Solving $\frac{\partial z}{\partial x} + \frac{\partial z}{\partial y} = 0$ by changing variables

Question:
Transform the differential equation $\frac{\partial z}{\partial x} + \frac{\partial z}{\partial y} = 0 $ by introducing new variables $x = u+v$ and $y=u-v$. then solve it.

I which I could show some effort but I don't even know where to start and I can't find anything about this in my course literature (the subject is very basic multi-variable calculus and I found the question in an old exam).
Could anyone show me how to solve this?
Comment: Typo? I think you want to have $\partial_x z + \partial_{\bf y}z = 0$.
Comment: @martini ah yes of course. thank you!
Answer: So, let's start as given in the hint. We define a "transformed" version of our solution $z$ by introducing $g(u,v) = z(u+v, u-v)$. Then
$$ z(x,y) = g\left(\frac 12(x+y), \frac 12 (x-y)\right) $$
This gives
\begin{align*}
  \partial_x z &= \frac 12 \partial_u g + \frac 12 \partial_v g\\
  \partial_y z &= \frac 12 \partial_u g - \frac 12 \partial_v g
\end{align*}
Hence
$$ 0 = \partial_x z + \partial_y z = \partial_u g $$
So $g(u,v) = \phi(v)$ for some function $\phi$, that is
$$ z(x,y) = \phi\left(\frac 12(x-y)\right). $$
Comment: Is $\phi$ really a solution of the PDE? Note that: $\phi_x + \phi_y = \phi'(x+y)$. Am I wrong?
Comment: @Dmoreno Thanks, corrected.
Comment: You're welcome @martini!
Answer: If you are purely interested in how to solve this kind of equations, you might find this useful.
There's no need of using this sort of 'out of the blue' change of variables if you are introduced to the method of characteristics for solving 1st order PDEs. In your case, the PDE is also linear and can be written as follows:
$$a(x,y)  \, p +  b(x,y)\, q = f(x,y,z), \quad p = \partial_x z, \quad q = \partial_y z,$$ and $a = 1, b = 1$ are known functions of your independent variables and $f = 0$ is a linear function on $z$. The method of characteristics then reads:
$$\frac{\mathrm{dx}}{a} = \frac{\mathrm{dy}}{b} = \frac{\mathrm{dz}}{f} \Rightarrow \frac{\mathrm{dx}}{1} = \frac{\mathrm{dy}}{1} = \frac{\mathrm{d}z}{0}.$$ The two first equalities tell us that:
$$ \mathrm{d}x - \mathrm{d}y = 0,$$ so $x-y=c$ (constant) somewhere. The fraction $\mathrm{d}z/0$ leads to setting $z=k$ (constant), again, somewhere. If you put $k$ as a function of $c$, then you solution becomes:
$$z = k(c) = k(x-y),$$
where $k(\cdot)$ is an arbitrary function of $x-y$, i.e., the characteristic curve of the equation.
Hope this helps!
Cheers.
Answer: If you change your variables using a Lie group, you can find the most general solution of this pde.  Use $$G(x,y,z)=(\lambda x,\lambda^\beta y,\lambda^\alpha z)\lambda_o=1$$  such that $x'=\lambda x$, $y'=\lambda^\beta y$, $z'=\lambda^\alpha z$, then
$$
\frac{\partial z'}{\partial x'}+\frac{\partial z'}{\partial y'}=\frac{\lambda^\alpha \partial z}{\lambda \partial x}+\frac{\lambda^\alpha \partial z}{\lambda^\beta \partial y}=0$$
For invariance, $\lambda^{\alpha -1}=\lambda^{\alpha -\beta}$ or $\beta=1$ and there are no restrictions on $\alpha$.  Thus we have found an invariant Lie group, one which preserves the structure of the smooth manifold and leaves the pde unchanged.  Since
$$
\lambda^\alpha z(x,y)=z(\lambda x,\lambda y)
$$we can take partial derivatives of both sides, setting $\lambda=\lambda_o=1$, and get
$$
\alpha z=x z_x + y z_y
$$The characteristic equations
$$
\frac{dz}{\alpha z}=\frac{dx}{x}=\frac{dy}{y}
$$have two independent integrals, $$\frac{z}{y^\alpha}$$ and $$\frac{y}{x}$$  These are constants of integration which are group stabilizers for polynomials (which include DEQ's), and this is verified by noting that $$\frac{z'}{(y')^\alpha}=\frac{\lambda^\alpha z}{(\lambda y)^\alpha}=\frac{z}{y^\alpha}$$ and $$\frac{y'}{x'}=\frac{y}{x}$$  Sophus Lie's idea was that if an invariant infinite continuous group can be found (a Lie group), then the DEQ is in the kernel of the group with the stabilizers which form an embedded subspace.  The pde should then "fall apart" into the group stabilizers and thus be expressed as an ODE.  Here's how it works.
The most general solution of your pde is found by setting one independent stabilizer equal to an arbitrary function of the other one.
$$
\frac{z}{y^\alpha}=f\bigg(\frac{y}{x}\bigg)
$$If we rename $\frac{y}{x}=\mu$ where $\mu$ is the argument of the function, we get
$$
z=y^\alpha f(\mu)
$$
$$
z_x=y^\alpha f_\mu\mu_x=y^\alpha f_\mu \bigg(\frac{-y}{x^2}\bigg)=-y^{\alpha -1}\mu^2 f_\mu
$$
$$
z_y =\alpha y^{\alpha -1} f+y^\alpha f_\mu \mu_y =\alpha y^{\alpha -1}f +y^{\alpha -1}\mu f_\mu
$$
Putting these back into the pde, the y-terms drop out and we have
$$
-\mu^2 f_\mu +\alpha f+\mu f_\mu =0
$$which simplifies to
$$
\frac{f_\mu}{f}=\frac{\alpha}{\mu^2 -\mu}
$$or
$$
\frac{d}{d\mu}ln f=\frac{\alpha}{\mu^2 -\mu}
$$After integration we have
$$
lnf=\alpha\bigg[ln\bigg(\frac{\mu-1}{\mu}\bigg)\bigg]+ln C=lnC\bigg(\frac{\mu-1}{\mu}\bigg)^\alpha
$$Thus,
$$
f=C\bigg(\frac{\mu-1}{\mu}\bigg)^\alpha=C\bigg(\frac{\frac{y}{x}-1}{\frac{y}{x}}\bigg)^\alpha=C\bigg(1-\frac{x}{y}\bigg)^\alpha
$$Because $z=y^\alpha f(x,y)$, the most general solution is
$$
z=C(y-x)^\alpha
$$This solution is easily checked.


Centralizar cards em dispositivo móvel

Question: Não estou conseguindo fazer com que esses cards fiquem centralizados quando no dispositivo mobile, já me disseram para eu usar media queries, porém nesse sentido eu teria que criar uma nova classe para atribuir o código css, ou seja, não estaria tirando proveito do que o bootstrap oferece. Há algum nome de classe que me possibilite realizar esse tipo de coisa.
Segue o código:

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Notem que eles estão responsivos, porém não ficaram centralizados!
Answer: Use a classe nativa .mx-auto nos cards:
Informações sobre classes de espaçamento você encontra na documentação oficial, em português.

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Nome da pessoa

Some quick example text to build on the card title and make up the bulk of the card's content.

        Currículo em anexo

Comment: Realmente não precisa ler toda a doc. Ele serve mais para referência quando precisa. Boa sorte!
Comment: era exatamente disso que estava precisando, já estou lendo a `doc`, porém as vezes leio por demanda, o que exatamente irei utilizar. Vou dar uma lida no que me mandou!

Centralizar cards em dispositivo móvel


Convert a node from one content type to another, using a rule set

Question: I want to convert a node from one content type ("Project") to another one ("Project follow up"), basing on the comparison between the current date (using PHP) and the value of a field date ("Project signup date," which is a CCK date field). Currently, I am using a rule set that will be scheduled based on a check that a rule does when the project is created. The rule set than checks (upon a successful cron run) if the date is higher than the field date (using the date timestamp); the rule set will then convert the node from "Project" to "Project followup."
As I keep getting errors when testing the rule/rule set, I must ask if I'm doing it right. What are the proper PHP evaluation and token replacement pattern? The following are the replacement tokens, and my default PHP code.
Replacement tokens
<code>[node:field_pdate-value]     The raw date value.
[node:field_pdate-view]      The formatted date.
[node:field_pdate-timestamp] The raw date timestamp.
[node:field_pdate-yyyy]      Date year (four digit)
[node:field_pdate-yy]        Date year (two digit)
[node:field_pdate-month]     Date month (full word)
[node:field_pdate-mon]       Date month (abbreviated)
[node:field_pdate-mm]        Date month (two digit, zero padded)
[node:field_pdate-m]         Date month (one or two digit)
[node:field_pdate-ww]        Date week (two digit)
[node:field_pdate-date]      Date date (YYYY-MM-DD)
[node:field_pdate-datetime]  Date datetime (YYYY-MM-DDTHH:MM:SS)
[node:field_pdate-day]       Date day (full word)
[node:field_pdate-ddd]       Date day (abbreviation)
[node:field_pdate-dd]        Date day (two digit, zero-padded)
[node:field_pdate-d]         Date day (one or two digit)
[node:field_pdate-dS]        Date day (one or two digit) with ordinal suffix (st, nd, rd or th)
[node:field_pdate-time]      Time H:i
</code>
PHP code
<code>php echo time();
</code>
Comment: What kind of comparison do you want to do?
Comment: The PHP code is not making any comparison; it is just outputting the time of when it is executed.
Answer: Node Convert might help you with the node conversion from one type to another. http://drupal.org/project/node_convert
I'm not sure if you can use this module to do it programmatically, but it might help to look at this structure and run something similar on a cron job.
Comment: Node_convert has good field-mapping support: how to deal with the data in fields when migrating from one type to another. That is the hardest part of migrating.


Goodness of Fit (question about fitting procedure)

Question: I have some vector with data $X$ that I suspect is exponentially distributed (after some visual evaluation).
I have fitted the exponential distribution to the data with the maximum likelihood estimator: $\lambda=(\frac{1}{N}\sum_{i=1}^N x_i)^{-1}$ for $x_i\in X$. $X$ contains about 9000 observations.
My problem relies is in how to assess the goodness of the fit. I have tried the Chi-square method and the Kolmogorov-Smirnov method by computing the likelyhood of $X$ being an observation of the fitted distribution. When I do this the $p$ value is very very small; the test absolutely rejects the hypothesis. But visually the fit looks really good. So I think I'm doing something wrong.
Checking some literature I have seen the following method:

Fit the distribution with $X$, say we get a distribution $D_X$. Compute the Kolmogorov-Smirnov distance of the fit.
Sample artificial data from $D_X$.
Compute the KS distance now between the sampled artificial data and $D_X$.
Repeat 2-3 many times to obtain distances $d_1,d_2...$.
Compare $d_1,d_2..$ with $d$.

But I don't really understand this method because it looks like we assess the goodness of the fit without using the original data $X$.
I wonder if anyone has some advice on this.
Thanks in advance.
Comment: How much data do you have? With a large data set, these tests will reject based on even small differences. What you have to ask yourself is whether  the fit is good enough for your application, which is quite possibly a different criteria than accept/reject your goodness of fit tests. You might be better off looking at effect sizes in operational regions.
Comment: I'm not sure what the purpose of this method is, though it appears to be constructing a confidence interval for the null hypothesis that $D_X$ is the correct distribution. Can you cite a reference? There is violation of the K-S assumption of independence when you estimate the model and test it on the same set of data. Bootstrapping can overcome this. The method you've described is a bootstrap, but I don't think its the correct one for addressing that issue, where I think you'd be sampling the original data.
Comment: Link? On second thought, I think what may be off here is step 3. It seems you'd want to take your sample and fit a _new_ (in this case) exponential distribution and do a K-S of your sample from 2 against _it_ rather than $D_X$. If this is correction for the flexibility in choosing the parameter of fit from the same data, then I think you'll even more likely reject.
Comment: Yes, in section 3.1 of that first link, the bootstrap is refitting for the K-S, the suspected missing part of step 3 above. Section 2.1 of the same  says for certain distribution families, exponential being one, the modified critical values do not depend on the initially estimated parameter -- they are scale and translation invariant. So, there should be a table of modified k-s critical values specific to exponential distribution that have been fit with the same data. Googling turns up an example, where as expected, the critical values are smaller, meaning you are even more likely to reject.
Comment: Hi A. Webb and thank you. The vector $X$ has 9000 values. It looks good enough for my application but I would like to justify it if possible. Does the method I described from the literature make any sense?
Comment: Thanks again. Yes it makes sense what you say.
I found the method in a pdf online; there is no author specified.
Comment: I did not find that link again, but trying to find it I found some lecture notes in which the method is specified and apparently it is correct:
https://pdfs.semanticscholar.org/1b85/f2b451b8bbcbc9e5cfbfe317b0fd2464b2e9.pdf
The original source seems to be:
http://link.springer.com/article/10.1007/BF02613687
Comment: Yes, I guess I will try something bootstrapping from the original data $X$ as you first suggested. Thank you for your time.
Answer: Keep in mind with null hypothesis significance testing (NHST) what you are actually testing is whether an effect is statistically detectable under the null hypothesis, not that its size is "significant" in the more typical modern meaning. Now also consider that NHST is often conducted with the null hypothesis being 0 effect, and it shouldn't be surprising that the null is rejected for any real world phenomena with enough data.
For example, let's say we have the null hypothesis that a given wheel is circular. If we measure a few dozen points with a crude ruler, we will likely not reject the null and happily keep rolling. But, if we precisely measure with a microscope at thousands of points, we will always eventually accumulate enough evidence to reject the null if our tools are sensitive enough. After all no real wheel is completely exactly circular. Even if it could have somehow been machined perfectly, gravity and temperature will still have deformed it.
This is analogous to your situation, where in the comments you've indicated that you have 9000 data points. This gives the NHST a lot of power to detect even small deviations. It's kind of like looking at that wheel under the microscope to see if it's perfectly round. What's the point? You should have known it wasn't perfectly round to begin with. The point is will the thing roll well enough? If we're talking about tires for go-charts there is going to be a completely different answer than roller bearings used in an MRI. Likewise, if your data comes from the real world, then of course it does not have a perfect exponential distribution. And even if you have all the reason in the world to believe the process that created it should be exponential, the real world likely has deformed it or its measurement somehow or other. The question is, is it good enough.
You need to specify what is good enough for your application and how to measure it. Perhaps the K-S statistic -- maximum distance between the ECDF and the hypothesized distribution is the most appropriate -- perhaps it's not. But, if you do use it, you should specify a different null hypothesis than the default of maximum distance of 0. Rather, specify that it is within your maximum tolerable distance of $t$, whatever $t$ is for your application. So your null becomes $|d| < t$ rather than the completely unrealistic $d = 0$.
The bootstrap method in the link you provided in your comments can help you develop this modification. It's intent is bootstrap corrected critical values for the problem of fitting distribution from the same data you are testing again. As noted in my comments, the procedure in the linked notes is similar to the one you have in your original post, but your step 3 is off -- you need to refit to an new $D_X^*$ at each iteration and measure against those rather than always $D_X$. With minor modification you also use this bootstrapping procedure to get estimates the critical values, or better, confidence intervals for a null specified within some tolerance range $|d| < t$ rather than precisely 0 difference $d = 0$.
Comment: Good answer and well put. Maybe you can help a bit with this one: http://stats.stackexchange.com/questions/266574/indepence-of-observations-in-real-life-examples>
You seem to know a lot.