iOS coreplot in Xcode 4.2

Question: I have the app compiling, but I see no graph.
RaceDetailView.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"

@interface RaceDetailView : UIView <CPTPlotDataSource, CPTPlotSpaceDelegate>

@property (nonatomic, retain) NSArray *plotData;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) CPTGraphHostingView *layerHostingView;
@property CGFloat labelRotation;

- (void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds;
- (void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds;
-(NSUInteger)numberOfRecords;
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;

@end

RaceDetailView.m
#import "RaceDetailView.h"

@implementation RaceDetailView

@synthesize layerHostingView;
@synthesize labelRotation;
@synthesize title;
@synthesize plotData;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        title = @"my race chart";

        plotData = [[NSMutableArray alloc] initWithObjects:
                    [NSNumber numberWithDouble:20.0],
                    [NSNumber numberWithDouble:30.0],
                    [NSNumber numberWithDouble:60.0],
                    nil];

        CPTGraph *graph = [[[CPTXYGraph alloc] initWithFrame:frame] autorelease];
        //[self addGraph:graph toHostingView:layerHostingView];
        layerHostingView.hostedGraph = graph;
        //[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
        [graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];

        [self setTitleDefaultsForGraph:graph withBounds:frame];
        [self setPaddingDefaultsForGraph:graph withBounds:frame];

        // Setup scatter plot space
        CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
        plotSpace.allowsUserInteraction = YES;
        plotSpace.delegate = self;

        // Grid line styles
        CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
        majorGridLineStyle.lineWidth = 0.75;
        majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];

        CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
        minorGridLineStyle.lineWidth = 0.25;
        minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];

        CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle];
        redLineStyle.lineWidth = 10.0;
        redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5];

        // Axes
        // Label x axis with a fixed interval policy
        CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
        CPTXYAxis *x = axisSet.xAxis;
        x.majorIntervalLength = CPTDecimalFromString(@"0.5");
        x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"1.0");
        x.minorTicksPerInterval = 2;
        x.majorGridLineStyle = majorGridLineStyle;
        x.minorGridLineStyle = minorGridLineStyle;

        x.title = @"X Axis";
        x.titleOffset = 30.0;
        x.titleLocation = CPTDecimalFromString(@"1.25");

        // Label y with an automatic label policy.
        CPTXYAxis *y = axisSet.yAxis;
        y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
        y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"1.0");
        y.minorTicksPerInterval = 2;
        y.preferredNumberOfMajorTicks = 8;
        y.majorGridLineStyle = majorGridLineStyle;
        y.minorGridLineStyle = minorGridLineStyle;
        y.labelOffset = 10.0;

        y.title = @"Y Axis";
        y.titleOffset = 30.0;
        y.titleLocation = CPTDecimalFromString(@"1.0");

        // Rotate the labels by 45 degrees, just to show it can be done.
        labelRotation = M_PI * 0.25;

        // Set axes
        //graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
        graph.axisSet.axes = [NSArray arrayWithObjects:x, y, nil];

        // Create a plot that uses the data source method
        CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
        dataSourceLinePlot.identifier = @"Data Source Plot";

        CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
        lineStyle.lineWidth = 3.0;
        lineStyle.lineColor = [CPTColor greenColor];
        dataSourceLinePlot.dataLineStyle = lineStyle;

        dataSourceLinePlot.dataSource = self;
        [graph addPlot:dataSourceLinePlot];

        // Auto scale the plot space to fit the plot data
        // Extend the y range by 10% for neatness
        [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
        CPTPlotRange *xRange = plotSpace.xRange;
        CPTPlotRange *yRange = plotSpace.yRange;
        [xRange expandRangeByFactor:CPTDecimalFromDouble(1.3)];
        [yRange expandRangeByFactor:CPTDecimalFromDouble(1.3)];
        plotSpace.yRange = yRange;

        // Restrict y range to a global range
        CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f)
                                                                  length:CPTDecimalFromFloat(2.0f)];
        plotSpace.globalYRange = globalYRange;

        // set the x and y shift to match the new ranges
        CGFloat length = xRange.lengthDouble;
        //xShift = length - 3.0;
        length = yRange.lengthDouble;
        //yShift = length - 2.0;

        // Add plot symbols
        CPTMutableLineStyle *symbolLineStyle = [CPTMutableLineStyle lineStyle];
        symbolLineStyle.lineColor = [CPTColor blackColor];
        CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
        plotSymbol.fill = [CPTFill fillWithColor:[CPTColor blueColor]];
        plotSymbol.lineStyle = symbolLineStyle;
        plotSymbol.size = CGSizeMake(10.0, 10.0);
        dataSourceLinePlot.plotSymbol = plotSymbol;

        // Set plot delegate, to know when symbols have been touched
        // We will display an annotation when a symbol is touched
        dataSourceLinePlot.delegate = self;
        dataSourceLinePlot.plotSymbolMarginForHitDetection = 5.0f;

        // Add legend
        graph.legend = [CPTLegend legendWithGraph:graph];
        graph.legend.textStyle = x.titleTextStyle;
        graph.legend.fill = [CPTFill fillWithColor:[CPTColor darkGrayColor]];
        graph.legend.borderLineStyle = x.axisLineStyle;
        graph.legend.cornerRadius = 5.0;
        graph.legend.swatchSize = CGSizeMake(25.0, 25.0);
        graph.legendAnchor = CPTRectAnchorBottom;
        graph.legendDisplacement = CGPointMake(0.0, 12.0);
    }
    return self;
}

- (void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
    graph.title = title;
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.color = [CPTColor grayColor];
    textStyle.fontName = @"Helvetica-Bold";
    textStyle.fontSize = round(bounds.size.height / 20.0f);
    graph.titleTextStyle = textStyle;
    graph.titleDisplacement = CGPointMake(0.0f, round(bounds.size.height / 18.0f)); // Ensure that title displacement falls on an integral pixel
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
}

- (void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
    float boundsPadding = round(bounds.size.width / 20.0f); // Ensure that padding falls on an integral pixel
    graph.paddingLeft = boundsPadding;

    if (graph.titleDisplacement.y > 0.0) {
        graph.paddingTop = graph.titleDisplacement.y * 2;
    }
    else {
        graph.paddingTop = boundsPadding;
    }

    graph.paddingRight = boundsPadding;
    graph.paddingBottom = boundsPadding;
}

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    return [plotData count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    NSNumber *num;
    if (fieldEnum == CPTPieChartFieldSliceWidth) {
        num = [plotData objectAtIndex:index];
    }
    else {
        return [NSNumber numberWithInt:index];
    }

    return num;
}

@end

Edit: You may note that this is from the CorePlot example SimpleScatterPlot.
Answer: Why is this code in a UIView? This code normally resides in a view controller (UIViewController). The Plot Gallery app that you pulled the example from is a little more complicated because it uses the plots in multiple places--in the main view area and also to make the thumbnail images for the list or browser view.
Do you ever set the layerHostingView? Is it in the view hierarchy and visible?
Check your datasource as @danielbeard suggested. The correct field names for scatter plots are CPTScatterPlotFieldX and CPTScatterPlotFieldY.
Comment: `layerHostingView.hostedGraph = graph;` is in play. From what I could tell in the examples, this is how you use the `layerHostingView`. Also, I was using a `UIViewController` for all this and just switch to a `UIView` for what I would call not-much-of-a-reason. Regardless, this should still work. +1 for help.
Comment: I think you answered my other question, but I dare say this had something to do with the `layerHostingView`. A *lousy* mistake on my end. Thanks.
Answer: You are setting up a scatter plot, then in the numberForPlot method you are asking for the CPTPieChartFieldSliceWidth, is this intended? Can you see grid lines at all, or is the whole graph area just blank?
Comment: Good point. And no I don't see any lines at all. It's all a blank white. I should probably see a graph layout at minimum.. Of course, that's IF everything is set up correctly. +1 for help.
Comment: Ah, I realize now that the `CPTPieChartFieldSliceWidth` is code from the *example* I pulled it from. Fortunately it's restricted by logic to where it should never run in my scenario, but would in the example I snagged it from. Regardless, It's out now.

iOS coreplot in Xcode 4.2


Função infixa para pós-fixa

Question: Estou fazendo um código que converte uma função infixa para a notação pós-fixa, exemplo: 4+2 para 42+. E não estou conseguindo fazer a prioridade dos elementos, por exemplo, quando faço a expressão 4+2*8, espero o resultado 428*+, mas está imprimindo 42*8+, por conta da prioridade matemática que está errada em meu código:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define max  1000
    #include <stdbool.h>

    typedef struct key{
        char tipo;
    }TipoItem;

    typedef struct pilha{
        TipoItem item[max];
        int topo;
    }Pilha;

    void criapilha(Pilha *pi){
        pi->topo=0;
    }

    void empilha(Pilha *pi,TipoItem c){
        if(pi->topo == max){
            printf("Pilha cheia.\n");
            return;
        }
        else{
            pi->item[pi->topo] = c;
            pi->topo++;
        }
    }

    int vazia(Pilha pi){
        return (pi.topo == 0);
    }

    void desempilha(Pilha *pi,TipoItem *x){
        char c;
        if(vazia(*pi)){
                //printf("Pilha vazia.\n");
            return;
        }
        else{
            *x = pi->item[pi->topo-1];
            pi->topo--;
        }
    }

    void printa(Pilha *pi){
        if(pi->topo == 0){
            printf("Pilha vazia.\n");
            return;
        }
        else{
            int i;
            for(i=0;i<pi->topo;i++){
                printf("%c ",pi->item[i]);
            }
        }
    }
    int prioridade(char a, char b){
        if('a' <= 'c')
            return 1;
        else
            return 0;
    }
    int main(){
        Pilha pi; criapilha(&pi);
        TipoItem elemento,pop;
        char funcao[max];
        int i,j=0;

                    int p = prioridade('a','b');
                    printf("%d",p);
                            scanf("%[^\n]",funcao);

                        for(i=0;i<strlen(funcao);i++){
                           elemento.tipo = funcao[i];
            if(elemento.tipo == '-' || elemento.tipo == '+' || elemento.tipo == '/' || elemento.tipo == '^' || elemento.tipo == '*' || elemento.tipo == '(' || elemento.tipo == ')'){
                        if(pi.topo == 0 || elemento.tipo == '('){
                            empilha(&pi,elemento);
                        }
                        else if(pi.topo == 0 || elemento.tipo == ')'){
                            while(pi.topo>0 && pop.tipo!= '('){
                                    printa(&pi);
                                    desempilha(&pi,&pop);
                                  }
                                  desempilha(&pi,&pop);
                        }else{
                            while(pi.topo > 0){
                                printa(&pi);
                                desempilha(&pi,&pop);
                            }
                            empilha(&pi,elemento);
                        }
                    }else{
                        printf("%c",elemento.tipo);
                    }
                }
                //printf("%c",elemento.tipo);
                while(pi.topo > 0){
                    printa(&pi);
                    desempilha(&pi,&pop);
                }

    return 0;
    }

Comment: Você precisa de uma função que retorna a prioridade do operador. Multiplicação e divisão possuem maior prioridade do que adição e subtração, que por sua vez possuem prioridade maior do que parêntesis. A ideia, quando o operador não for `(` e `)`, é desempilhar da pilha enquanto a prioridade do item no topo da pilha for maior do que a prioridade do elemento atual. Veja [esse artigo](http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html) (em inglês) com uma solução em Python. Você está bem perto!
Comment: Sim, eu estou tentando, mano ja fiz umas 10 funcao aqui e não deu certo para comprar as paradinha.
Comment: estou com o código aqui, ta quase pronto, so falta ele comparar as prioridades quando nao precisa ele faz tudo certinho, se quiser da uma olhada no codigo
Comment: Tranforma todos os numeros e simbolos para ASCII, mete por ordem e crescente e transforma de volta.
Answer: O problema está no tratamento da prioridade das operações. Tenha em mente que uma operação com prioridade menor ou igual não pode estar em cima de uma operação com prioridade maior. Eu confesso que não entendi o propósito da sua função prioridade. Eu recomendo que você construa uma função booleana que receba dois operadores e retorne se o da esquerda tem a prioridade maior ou igual que o da direita. Então, você pode alterar o trecho:
while(pi.topo > 0){
         printa(&pi);
         desempilha(&pi,&pop);
}

por:
while(pi.topo > 0 && checaPrioridade(pi.topo, elemento)){
         printa(&pi);
         desempilha(&pi,&pop);
}

Isto deve resolver o problema.

Função infixa para pós-fixa


How to get IzPack tocheck for an existing version of the software?

Question: I have an application for which we use IzPack to create the installer. The installer is working fine in its current state, however, I need to add functionality that enables it to check whether an existing version of the software has been installed.
I understand IzPack supports this out of the box using its CheckedHelloPanel, unfortunately that only works for Windows, as it appears to depend on the windows registry.
Is there a way to configure IzPack such that it is able to detect existing installations?
I need to be able to detect whether there is one and merely display a message notifying the user... Bonus points for how to give the user the option to trigger the uninstaller of the existing installation.

Assume that the software will only be installed using the new installer
IzPack only: please do not suggest alternatives, as we cannot change that now
If you suggest using <validator>, please include a code sample of the validator class, because I have considered this, but don't know where to start
Answer: I wrote this to allow my application to be installed over the jboss install.
public class JBossChecker {

 private static boolean tempJBossEnv;
 private static boolean tempJBossDirectoryExists;

 static {
  String s = System.getenv("JBOSS_HOME");
  tempJBossEnv= (s!=null);

  if( tempJBossEnv) {
   File f = new File(s);
   tempJBossDirectoryExists= ( f.exists() && f.isDirectory());
  }
  hasJBossEnv =tempJBossEnv;
  hasJBossDir = tempJBossDirectoryExists;
 }

 public static boolean hasJBossDir;
 public static boolean hasJBossEnv;

 public static void main(String[] args){
  System.out.println("Jboss environment "+hasJBossEnv);
  System.out.println("Jboss directory "+hasJBossDir);

 }
}

Then the installer has a section like
<conditions>
     <condition type="java" id="jbossEnv">
             <java>
                 <class>au.com.codarra.ela.installer.JBossChecker</class
                 <field>hasJBossEnv</field>
             </java>
             <returnvalue type="boolean">true</returnvalue>
 </condition>

 <condition type="java" id="jbossDir">
             <java>
                 <class>au.com.codarra.ela.installer.JBossChecker</class>
                 <field>hasJBossDir</field>
             </java>
             <returnvalue type="boolean">true</returnvalue>
 </condition>

</conditions>

<installerrequirements>
 <installerrequirement condition="jbossEnv" message="Your system does not have the environment variable JBOSS_HOME set. Cannot update your system. Is XXXX installed on this system?" />
 <installerrequirement condition="jbossDir" message="Your system does not have a directory at the location in the environement variable JBOSS_HOME . Cannot update your system. Is XXXX installed on this system?" />
</installerrequirements>

<dynamicvariables>
 <variable name="INSTALL_PATH" value="${ENV[JBOSS_HOME]}"/>
</dynamicvariables>

<jar src="c:\dev\xxxx\build\installer.jar" />

The bit at the end makes sure izpack adds it to the installer jar.
Comment: @Tim could you please indent/ reformat the java code? It's not getting parsed by SO.
Comment: @Tim thanks for reformatting the code! I have another question: Where do you put your class, `JBossChecker` - how do you ensure it's loaded onto the classpath when the installer is run?
Comment: The last line of code *jar* merges this jar into the izpack installer created. So it works as written.
Comment: I've asked another related question - would you happen to know other ways to invoke a Java class from izpack? http://stackoverflow.com/questions/2475527/calling-java-classes-from-izpack
Comment: Izpack currently doesn't do other ways of accessing arbitrary java.
But you can make event listeners for various izpack events and processing event listeners can get called in the processing panel.
Answer: It only works on Windows, because only Windows has a registry.  However, in Linux apps traditionally don't have customized unified locations.  For example your run scripts would go in a bin folder, your binaries would go in /opt, your documentation would go in /var, etc.  The idea that there's one single "your-app" directory that is selected by the user and contains everything related to the application is a Windows concept.
So anyway, the way to solve this in Linux is to install the various parts of your app in non-user-defined locations.  That way you know exactly where your app would be if it was already installed.
Comment: Thanks Gabriel, that is a good strategy, but I wanted to know how one would accomplish that, specific to IzPack?
Comment: That's just basic IzPack functionality... copying your binaries to various locations.  Take a look at the packs element in the IzPack docs:  http://izpack.org/documentation/installation-files.html#the-packs-element-packs


How do I disable Drupal 7 Theme Debug? "drush vset theme_debug 0" NOT WORKING

Question: I enabled theme debug on my drupal 7 installation using drush vset theme_debug 1, But Now I can't disable theme debug using drush vset theme_debug 0, What the wrong, Is there any wrong or mistakes in the drush command above?
I also tried to comment out $conf['theme_debug'] = TRUE; in the settings.php and then replaced with $conf['theme_debug'] = FALSE; but none works.
Any help and suggestions on this issue?
Thanks
Comment: Do you have file local.setting.php?
Comment: Hi @Jonh, Thanks for quick replying. I don't have local.setting.php. I can see there is a file called default.setting.php & setting.php in sites/default directory.
Comment: try to execute `drush vset theme_debug 0` with `--debug`  to see if there is any errors!
Answer: If using drush vset theme_debug 0 doesn't work. Try disabling the theme debugging on your settings.php file, adding the below line of code:
$conf['theme_debug'] = FALSE;

Don't forget clear the cache.
Comment: Hay @heilop, After restoring a backup, `drush vset theme_debug 0` started working again. Thanks for your answer. You suggestion also working now.
Comment: Thanks for your suggestion, I actually did that but NO LUCK. You can check my question description where I mentioned this. However, I may messed up everything, getting a lot of error log message.
Comment: @AbuZafor, You're welcome!


Are there statistical lessons from the "Bible Code" episode

Question: Although this question is somewhat subjective, I hope it
qualifies
as a good subjective question according to the faq guidelines.
It is based on a question that Olle Häggström asked me a year ago
and although I have some thoughts about it I do not have a
definite answer and I would appreciate some help from others.
Background:
A paper entitled "Equidistant letter sequences in the book of Genesis," by
D. Witztum, E. Rips and Y. Rosenberg
made the extraordinary claim that the Hebrew text of the
Book of Genesis encodes events which
did not occur until millennia after the text was written. The paper was
published by "Statistical Science" in 1994 (Vol. 9 429-438), and was offered
as a "challenging puzzle" whose solution may contribute to the field of statistics.
In reply, another paper entitled "Solving the Bible code puzzle"
by B. McKay, D. Bar-Natan, M. Bar-Hillel and G. Kalai appeared in
Statistical science in 1999 (Vol. 14 (1999) 150-173). The new paper
argues that Witztum,
Rips and Rosenberg's case is fatally defective,
indeed that their result merely reflects on
the choices made in designing their experiment and
collecting the data for it. The paper presents
extensive evidence in support of that conclusion.
(My own interests which are summarized in Section 8
of our paper are detailed
in another technical report with Bar Hillel and Mckay
entitled "The two famous rabbis experiments: how
similar is too similar?" See also this site.)
The questions:
Olle Häggström's specific question was:

"I once suggested that your paper
might be useful in a statistics course
on advanced undergraduate level, for
the purpose of illustrating the
pitfalls of data mining and related
techniques. Would you agree?"

In addition to Olle's question let me ask a more general question.

Is there something related to
statistics that we have learned,
(including perhaps some interesting
questions to ask) from the Bible Code
episode.

Just to make it clear, my question is restricted to
insights related to statistics and not to any other aspect of this episode.
Comment: David, the Choice of "War and Peace" as a control text (More precisely the beginning of the Hebrew translation of "War and Peace" of the same length as the Book of Genesis) was done by the original researchers. The story according to Aumann is this: When Bob Aumann who carefully followed the experiment told Kenneth Arrow about the marvelous findings in "Genesis", Arrow asked what about "War and Peace". Aumann then started reporting about the war and peace situation in Israel but it turned out that what Arrow asked about was if the same phenomenon cannot be found in "War and Peace".
Comment: By the way, you are free to post your own answers.  I'd be very interested, as you have presumably weathered a lot of analyses of the whole experience.
Comment: One thing that statistics must be, is complete. For instance, I introduced professor Dror Bar-Natan to an additional Bible Code format, and was asking if he would examine it. He basically said that what was done, was done. In his opinion, his contributions in "Solving the Bible code puzzle", and many other contributions in the study of Bible Codes, had proven that Bible Codes were just a farce. However, he had studied just one possible bible code language of an infinite number of possible code languages, yet rejecting 1 language was said to be enough to reject all other languages. Logical ???
Comment: this is an interesting subject. I am curious why you (McKay et al 1999)  would choose 'War and Peace' as a control rather than, for example, random strings of letters (perhaps weighted by their observed frequencies). In other words, is it sufficient for the text to be sufficiently long, or does it have to be sufficiently long and comprehensible (or sufficiently long and of some literary value)?
Comment: The Bible code episode would be a good illustration of the strengths of the Bayesian view of probability.  In particular, the Bayes factor $P(D|H)/P(D|not H)$ are insufficiently large given that we would assign a small prior probability to $P(H)$.  (H being the hypothesis there exists some mechanism whereby world events are encoded in the Bible.)
Comment: @Sean - be cautious about accidentally performing a p-value hacking [link](https://xkcd.com/882/).  The human search for significance is our primary motivation in being, so it is important that we not treat it in a dangerously casual or a neglectful manner.
Comment: Dear Iterator, yes, yes, I plan to do it at one time.
Comment: Apparently not, if you consider that this still hasn't been answered. More seriously though: There actually there were some insights in the question and the comments. The main insight seems to be that you need a control if you want to demonstrate that something is unusual.
Answer: Edit This is one of those questions whose answer may elicit negative reactions irrespective of whether or not the answer is correct. There have been several deleted answers so far, and it is doubtful that any answer will satisfy a majority of readers. Frankly, I do not care, but also any answer has to deal with the conundrum of belief in the bible as well as a belief in statistics, and they mix like oil and water. Nevertheless, it is possible to walk that thin line of truth by due consideration of what is in play, but it is not simple to do so.
There is a lot of wisdom in the bible, but given the preceding text, it is unlikely to be efficiently unpacked using numerology, as there is no unique textural version of the bible to refer to. Thus, my answer to the question Is there something related to statistics that we have learned, (including perhaps some interesting questions to ask) from the Bible Code episode [Sic, ?] is that most of the learning is from the negative side of the argument, i.e., what not to do, and why not. That does not mean that one cannot analyze the bible numerically, just that it is unlikely to yield very much in the way of useful information when too many assumptions are made. For example, if we want to use the bible to help calculate when King David was born, we will likely have better luck than when back-calculating when the Earth was created from an entire series of assumed dates.
There are two types of information. Statistical information differs from religious information in that the former is based upon disbelief and the latter on belief; oil and water. Let us illustrate them in practice. George Box famously said "Essentially, all models are wrong, but some are useful." What that implies is that when we formulate a hypothetical explanation, what we have done does not illustrate any fundamental truth, but rather a "working hypothesis," that has the property of explanatory power that makes it useful. Such is the way of the statistician, condemned to perpetually search for words to express the truth, but words are, at best a convention. So statistics assumes everything is wrong until proven otherwise, and religion assumes the opposite, what then is the truth?
Truth is not in words but rather behind them. In specific, each of us sees only our own personal world view, for example, we need faith to believe that life is worth living. Thus, truth is a first person phenomenon and words are not truth; they are shared values that by their nature have no insight of their own such that no matter how well we choose our words, it takes an individual, each of us, to actually have an insight that implies any feeling of mystery, wonder or appreciation. That is, we live in our own skins and our existence is a first person, subjective, phenomenon. The closest truth comes to being a shared value is for mathematics, but problems ensue as soon as we presume to apply mathematics to a hypothetical situation. Thus we can argue about whether in Exodus God told Moses "I am He who am," or the more literal translation "I am that which am," but the mystery is not in the words but rather in the first person context that inspired them. Kepler said, in effect, that it was unnecessary to postulate angelic intervention to explain the moon's orbit. William of Ockham, an English Franciscan friar, was excommunicated for leaving Avignon without permission. One can suspect that the principle of parsimony that he espoused was not especially popular with establishmentarians.
In statistics, we would generally refer to models with supernumerary postulates as overfit or predictive/extrapolative, and testing for overfitting or extrapolation is not merely a matter of doing controlled experiments as comparison between two models does not address the parsimony or predictive accuracy of either one. As Einstein intimated, one should only postulate the least number of relevant variables that adequately explains the data, and no fewer. Note the implication of deterministic data interpretation. If a predictive model is based upon an assumption, then whichever prediction is being made either has to be related to some hypothesis that is verifiable and deterministic, or we are engaging in what physicists call 'hand-waving'.
Re: Olle Häggström's question "...illustrating the pitfalls of data mining and related techniques." This can happen if one fails entirely to postulate a pre hoc deterministic context. In this case, the numerical analysis invites no deterministic interpretation, and invites us to discount hypothesis testing, and as such the interpretation invokes faith, not science. Such efforts, if done conscientiously, are likely to be futile, and even the declaration of a miraculous event is often based upon faith-based determinism. As if we needed further on this, Newton spent most of his lifetime's intellectual activity looking for numerical structure within the bible, and yet was silent on that topic. It is plausible to ascribe that failure, along with Newton's secret failure to deduce chemistry having only alchemy as a starting point, to problems that he could not solve. Thus, even physicists, including Newton who was arguably the first physicist, can fall victim to their own unverifiable imaginings. Nor has this ever ceased to be problematic. For example, string theorists have faith that eventually something verifiable will eventually result from their current multi-dimensional exercises in pure mathematics, and so far, there is nothing of the sort.
Many modern theologians would argue against a literal interpretation of the mere wording of biblical Divine inspiration, as in the contrary case we would pay undue attention to concepts such as what constitutes a firmament (vault) in the heavens that opened to let the waters come forth upon the Earth (Genesis). It is plausible that the concept of the Earth's being late bombardment epoch supplied by water from ice asteroids formed in the region beyond the solar system's snow line, as it contains words that would have been anachronisms in biblical times, is a reasonable substitute for the rather more terse concept of a firmament. What is perhaps astounding, is that there are modern equivalents to "Let there be light" but I caution that that could refer to several events in modern cosmology, e.g., the ending of the dark universe several hundred million years after the big bang, or the illumination of the sun a mere 4.6 billion years ago. Furthermore, there is no general agreement on these concepts, as some interpretations of the bible are literal and deny the existence of anything older than 6000 years ago, again from counting up numbers as cited in the bible. Keep in mind that scribes hand copied text 2000 years ago, so that minor changes in actual text, as exemplified by the Dead Sea Scrolls, would have been inevitable, which brings up the question of how one can do precise numerology on paraphrased text. All of this is beside the point, which is that the bible has a clear evolution in time of what constituted ethical comportment, and that today, there are multiple versions variously accepted by different sects and religions as dogma, not all of which can have identical numerological significance. One view of orthodoxy for biblical interpretation is that the text was divinely inspired, but written by humans whose ability to express themselves was limited, thus looking for hidden code in the umpteenth translation or paraphrasing of the original text, lost in time, is an exercise in futility.
Comment: I was unable to detect an answer to the questions in this post.  Could you point it out or make it more prominent?
Comment: @whuber OK, I agree to do that.
Comment: @whuber Done, as per your request. Gee, we seem to communicate quite frequently. Anyway, I hope to have shed some light on the subject, in particular, for any postulate, one has to examine the unspoken assumptions, which in this case, are so numerous as to virtually exclude an unambiguous interpretation.


If $b^{-1}ab=a^k$, prove that $b^{-r}a^sb^r=a^{sk^r}$

Question: Let $G$ be a group and $a,b \in G$. If $b^{-1}ab=a^k$, prove that $b^{-r}a^sb^r=a^{sk^r}$.
I see that $a^k$ and $a$ are conjugates in $G$. I could only go as far as the following:
$$b^{-1}ab=a^k \implies b^{-1}a^sb=a^{sk} \implies b^{-r}a^sb^r=b^{-(r-1)}a^{sk}b^{r-1}.$$
Any idea what to do next?
Comment: Hint: $ b^{-2}ab^2 =   b^{-1}a^k b = a^{k^2}$
Comment: Because you have noticed that $b^{-1}a^s b = a^{sk}$
Comment: @Focus I did not get your complete hint. How is $b^{-1}a^kb=a^{k^2}$?
Comment: @Focus Cool! Got it. Thanks :)
Answer: Let $G$ be a group and $a,b \in G$. We know that $b^{-1}ab=a^k$. This implies that $b^{-1}a^sb=a^{sk}$. Then $b^{-1}a^{sk}b=a^{sk^2}$ and $b^{-r}a^sb^r=b^{-(r-1)}a^{sk}b^{(r-1)}$. We assume $b^{-(m-1)}a^{sk}b^{(m-1)}=a^{sk^m}$, where $m \in \mathbb{Z}^{+}$. Then $b^{m}a^{sk}b^m=b^{-1}a^{sk^m}b=a^{sk^{(m+1)}}$. Hence, by principle of mathematical induction, $b^{-(r-1)}a^{sk}b^{(r-1)}=a^{sk^r}$, for any $r \in \mathbb{Z}^{+}$. Hence, $b^{-r}a^sb^r=b^{-(r-1)}a^{sk}b^{(r-1)}=a^{sk^r}.$


Paragraph input in pygame

Question: im tryna make a python gui application  using pygame but now i realised that its meant for games specifically and not for regular applications... ive done the most part but now im stuck at a point where i wanna take input in a paragraph box from a user but i cant really find a way to do it, is there really a way to do that or do i have to switch to a completely different module and start from scratch
import pygame

pygame.init()
screen = pygame.display.set_mode((600,600))
app_fps = pygame.time.Clock()
bg = pygame.image.load('Moment-Book/GUI/assets/login_bg.jpg')
font = pygame.font.Font(None,32)
active_color = pygame.Color('dodgerblue2')
inactive_color = pygame.Color('white')
back_button = pygame.image.load('Moment-Book/GUI/assets/back_button.png')

class InputBox():
    def __init__(self,max_len,x,y,width,height,text = ''):
        self.color = inactive_color
        self.len = max_len
        self.rect = pygame.Rect(x,y,width,height)
        self.text = text
        self.text_surf = font.render(text,True,self.color)
        self.active = False

    def event_handler(self,event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        self.color = active_color if self.active else inactive_color

        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE or len(self.text)>self.len:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode

                self.text_surf = font.render(self.text,True,self.color)

    def draw(self,screen):
        screen.blit(self.text_surf, (self.rect.x+5,self.rect.y+5))
        pygame.draw.rect(screen,self.color,self.rect,2,border_radius=2)

    def update(self):
        width = max(200, self.text_surf.get_width()+10)
        self.rect.w = width

back_rect = pygame.Rect(30,30,45,45)

def login():
    inputbox = InputBox(15,180,305,140,32)
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if back_rect.collidepoint(event.pos):
                    running = False
            inputbox.event_handler(event)

        screen.blit(bg,(-167,0))
        screen.blit(back_button,(back_rect.topleft,back_rect.bottomleft))

        inputbox.draw(screen)
        inputbox.update()

        pygame.display.update()
        app_fps.tick(60)

this is a sample code of my login page where i take input but its just the username and password, how do i take inputs in paragraphs because when i try this the text goes outside the screen
Comment: **Never** post crucial information, especially code or errors, in images or external links, as mentioned in [mre]. All crucial information should be included in the question itself as formatted text. Links and images are almost always only for additional info that can aid the question.
Comment: oh im sorry but then how do i put all of the files in this question?
Comment: You need to create a [mcve]. You try to create an example that illustrates the issue you have, with minimal but complete code. Then you put the code in code blocks. You can have several code blocks for each file
Comment: edited now, thanks for the info!
Answer: You must combine the answers to the following questions:

How to create a text input box with pygame?
Rendering text with multiple lines in pygame

Use the code for the text input box form How to create a text input box with pygame? and render the texture using the drawText function from Rendering text with multiple lines in pygame.
Minimal example based on the code from the question:

import pygame

pygame.init()
screen = pygame.display.set_mode((600,600))
app_fps = pygame.time.Clock()
font = pygame.font.SysFont(None,32)
active_color = pygame.Color('dodgerblue2')
inactive_color = pygame.Color('white')

textAlignLeft = 0
textAlignRight = 1
textAlignCenter = 2
textAlignBlock = 3

def drawText(surface, text, color, rect, font, align=textAlignLeft, aa=False, bkg=None):
    lineSpacing = -2
    spaceWidth, fontHeight = font.size(" ")[0], font.size("Tg")[1]

    listOfWords = text.split(" ")
    if bkg:
        imageList = [font.render(word, 1, color, bkg) for word in listOfWords]
        for image in imageList: image.set_colorkey(bkg)
    else:
        imageList = [font.render(word, aa, color) for word in listOfWords]

    maxLen = rect[2]
    lineLenList = [0]
    lineList = [[]]
    for image in imageList:
        width = image.get_width()
        lineLen = lineLenList[-1] + len(lineList[-1]) * spaceWidth + width
        if len(lineList[-1]) == 0 or lineLen <= maxLen:
            lineLenList[-1] += width
            lineList[-1].append(image)
        else:
            lineLenList.append(width)
            lineList.append([image])

    lineBottom = rect[1]
    lastLine = 0
    for lineLen, lineImages in zip(lineLenList, lineList):
        lineLeft = rect[0]
        if align == textAlignRight:
            lineLeft += + rect[2] - lineLen - spaceWidth * (len(lineImages)-1)
        elif align == textAlignCenter:
            lineLeft += (rect[2] - lineLen - spaceWidth * (len(lineImages)-1)) // 2
        elif align == textAlignBlock and len(lineImages) > 1:
            spaceWidth = (rect[2] - lineLen) // (len(lineImages)-1)
        if lineBottom + fontHeight > rect[1] + rect[3]:
            break
        lastLine += 1
        for i, image in enumerate(lineImages):
            x, y = lineLeft + i*spaceWidth, lineBottom
            surface.blit(image, (round(x), y))
            lineLeft += image.get_width()
        lineBottom += fontHeight + lineSpacing

    if lastLine < len(lineList):
        drawWords = sum([len(lineList[i]) for i in range(lastLine)])
        remainingText = ""
        for text in listOfWords[drawWords:]: remainingText += text + " "
        return remainingText
    return ""

class InputBox():
    def __init__(self,max_len,x,y,width,height,text = ''):
        self.color = inactive_color
        self.len = max_len
        self.rect = pygame.Rect(x,y,width,height)
        self.text = text
        self.text_surf = font.render(text,True,self.color)
        self.active = False

    def event_handler(self,event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        self.color = active_color if self.active else inactive_color

        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode

    def draw(self,screen):
        pygame.draw.rect(screen, self.color, self.rect, 1)
        drawTextRect = self.rect.inflate(-5, -5)
        drawText(screen, self.text, self.color, drawTextRect, font, textAlignLeft, True)

    def update(self):
        pass

back_rect = pygame.Rect(30,30,45,45)

inputbox = InputBox(15,180,305,140,96)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        inputbox.event_handler(event)

    screen.fill(0)

    inputbox.update()
    inputbox.draw(screen)
    pygame.display.update()
    app_fps.tick(60)

Paragraph input in pygame


Expected Value of Naive Recommender System

Question: Let $k, n \in \mathbb{N}$, with $k \leq n$. Let $A = (a_1, a_2, ..., a_n)$ be an unordered finite sequence of real numbers. Let $(B_1, B_2, ..., B_k)$ be an unordered sequence of random variables such that each $B_i$ is sampled uniformly from $A$, without replacement. Let the random variable $X = max(B_1, B_2, ..., B_k)$.
What is the distribution $p(X)$? What is the expected value $\mathbb{E}[X]$. (The former would go a long way to compute the latter.)
This is very similar to Distribution of max of samples with replacement, except here the collection in question possibly has duplicate values and the sampling is without replacement.
In the context of recommendation systems, $a_i$ is the relevancy or score of some document or item $d_i$. A system may be allowed to recommend $k$ of the $n$ documents (an internet search engine may recommend 10 pages out of billions). $\mathbb{E}[X]$ is the expected relevancy or score of the naive recommendation system which chooses $k$ documents uniformly at random and without replacement.
This seems related to the Urn Problem, the Multivariate Hypergeometric Distribution, and this paper; but here, the balls have a number instead of a color and we are interested in value of the balls instead of counts.
(Any corrections to the concepts, terminology, or even notation/syntax are welcome.)
Answer: Here is a Python solution to compute the expected value, created by NabiNaga. By sorting the values in $A$, we can compute the cumulative distribution of $X$. The probability of $X$ is then the cumulative probability of a particular value from sorted $A$ minus the cumulative probability of the value that comes before it. The probability that $X$ assumes one of the $k-1$ smallest values is $0$, unless there are duplicates. The brute_force method verifies that this handles duplicate values in $A$.
from functools import reduce
from itertools import combinations
import operator as op

def ncr(n, r):
    # from https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python
    r = min(r, n - r)
    numer = reduce(op.mul, range(n, n - r, -1), 1)
    denom = reduce(op.mul, range(1, r + 1), 1)
    return numer / denom

def brute_force(A, k):
    total = 0
    count = 0
    for combination in combinations(A, k):
        total += max(combination)
        count += 1
    return total / count

def solve(A, k):
    assert k <= len(A)
    A = sorted(A)

    total = 0
    last_num_combs = 0
    for i in range(k, len(A) + 1):
        num_combs = ncr(i, k)
        X = A[i - 1]
        total += X * (num_combs - last_num_combs)
        last_num_combs = num_combs

    return total / last_num_combs

if __name__ == "__main__":
    A = [1, 3, 7, 10, 15, 20, 20, 100, 100, 112, 150]
    k = 5

    assert brute_force(A, k) == solve(A, k)
    print(solve(A, k))


Problemas com uma função de validação de datas em C

Question: Estou desenvolvendo um sistema para cadastros de pacientes. É um projeto da faculdade. Estou dividindo grupos de funções em arquivos diferentes. Acontece que criei uma função para validar o cadastro de data, a função funciona mas não registra o último valor digita que seria o correto.
Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "validacoes.h"

void validaData(int valor, int x, int y, char data[4]){
if(valor < x || valor > y){
        do{
            printf("%s não existente, digite um %s válido! \n", data, data);
            printf("%s: ", data);
            scanf("%d", &valor);
            printf("%d \n", valor);
        }while(valor < x || valor > y);
    };
}

Esse é o arquivo da função:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pacientes.h"
#include "validacoes.h"

typedef struct {
        int dia;
        int mes;
        int ano;
} data;
typedef struct {
        char rua[30];
        char bairro[30];
        char cidade[30];
        char estado[3];
        char cep[10];
} endereco;
typedef struct {
    int id;
    char nome[30];
    char email[30];
    char cpf[15];
    char telefone[15];
    //char comorbidade;
    data dataNascimento;
    endereco enderecoPaciente;
} cadastro;

cadastro paciente[100];
void registro(){

fflush(stdin);
        printf("Data de nascimento \n");
        printf("Dia: ");
        scanf("%d", &paciente[i].dataNascimento.dia);
        validaData(paciente[i].dataNascimento.dia, 1, 31, "Dia");
        printf("Mês: ");
        scanf("%d", &paciente[i].dataNascimento.mes);
        validaData(paciente[i].dataNascimento.mes, 1, 12, "Mes");
        printf("Ano: ");
        scanf("%d", &paciente[i].dataNascimento.ano);
        validaData(paciente[i].dataNascimento.ano, 1900, 2020, "Ano");
        system("Pause");
 }

A função registro é onde a função validaData deveria funcionar.
No entanto, quando estou fazendo o cadastro, a função validaData consegue pegar o valor caso digitado fora dos parâmetros passado na função. Mas quando ele termina de executar, com a digitação correta do valor, o que fica guardado na variável paciente[i].dataNascimento.dia é o primeiro valor digitado antes de passar pela validação.
Alguém saberia como resolver?
Answer: O parâmetro valor da função validaData é passado por valor. Assim sendo, quando você faz scanf("%d", &valor);, você vai mudar apenas o valor da variável local valor, mas isso não vai alterar o conteúdo de paciente[i].dataNascimento.dia, nem de paciente[i].dataNascimento.mes e nem de paciente[i].dataNascimento.ano. O certo seria a função validaData retornar o novo valor lido.
Um outro detalhe é que uma função chamada validaData deveria, dado o seu nome fazer apenas a validação. Mas ela não está fazendo isso, ela está fazendo a releitura caso a data esteja incorreta. Uma abordagem mais robusta seria fazer a função para ler a data e reler quantas vezes forem necessárias até que a data informada seja válida.
Há uma questão de validação também que o seu código aceita datas inválidas tais como 31/04/2020 ou 29/02/2021, pois nem todos os meses tem os dias 29, 30 e 31.
Além disso, há o caso de o usuário responder xyz quando for perguntado o dia, e isso vai confundir o scanf. Como isso é um projeto de faculdade, o melhor é ler o que o usuário digitar sem fazer nenhum tipo de presunção sobre o que ele digitar e então tentar construir uma data com isso.
Outra coisa é que o fflush(stdin) só funciona no windows. Veja essa e essa respostas explicando como resolver.
De fato, a função scanf é uma função arcana, arcaica e difícil de se utilizar corretamente e os seus maiores problemas se originam disso. Essa função não deveria mais ser usada. Veja aqui explicações sobre o porquê de não usá-la e o que usar em seu lugar.
Assim sendo, sugiro essa função para ler uma data:
// Autor: Victor Stafusa - https://pt.stackoverflow.com/users/132
#include <stdio.h>

typedef struct {
    int dia;
    int mes;
    int ano;
} data;

// Veja mais sobre isso nesses links:
// https://pt.stackoverflow.com/a/231882/132
// https://pt.stackoverflow.com/a/96012/132
#if defined(__MINGW32__) || defined(_MSC_VER)
#define limpar_input() fflush(stdin)
#else
#include <stdio_ext.h>
#define limpar_input() __fpurge(stdin)
#endif

// Monta um número de 2 dígitos a partir de 2 chars.
#define numero2(a, b) \
    ( (a - '0') * 10 \
    + (b - '0'))

// Monta um número de 4 dígitos a partir de 4 chars.
#define numero4(a, b, c, d) \
    ( (a - '0') * 1000 \
    + (b - '0') * 100 \
    + (c - '0') * 10 \
    + (d - '0'))

// Verifica se a string dada tem um formato NN/NN/NNNN.
// Mas não verifica nada após o 10o caractere.
int validarFormatoData(const char *digitado) {
    for (int i = 0; i < 10; i++) {
        char c = digitado[i];
        if ((i == 2 || i == 5) ? c != '/' : (c < '0' || c > '9')) return 0;
    }
    return 1;
}

// Descobre quantos dias há no mês de um determinado ano.
int diasNoMes(int mes, int ano) {
    // São bissextos os anos divisíveis por 4,
    // com exceção dos que terminam com 00 e não são divisíveis por 400.
    int bissexto = (ano % 4 == 0 && ano % 100 != 0) || ano % 400 == 0;

    // Tabela com os dias de cada mês.
    // Observe que fevereiro varia dependendo se o ano for ou não bissexto.
    // Observe que a posição zero não é usada porque não há mês zero.
    int dias[] = {0, 31, bissexto ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return dias[mes];
}

// Descobre se a data do meio de fato está entre a data mínima e a máxima.
int comparaData3(const data *min, const data *meio, const data *max) {
    // Monta um inteiro para cada data na forma AAAAMMDD.
    int a = min->ano * 10000 + min->mes * 100 + min->dia;
    int b = meio->ano * 10000 + meio->mes * 100 + meio->dia;
    int c = max->ano * 10000 + max->mes * 100 + max->dia;

    // Como as datas foram reduzidos a números inteiros,
    // fica fácil saber se estão na ordem correta.
    return a <= b && b <= c;
}

// Lê uma data do usuário no formato DD/MM/AAAA.
// Insiste até que uma data válida seja digitada.
// Inclui uma mensagem que pede para o usuário digitar alguma coisa.
// Inclui uma mensagem de erro para o caso de o usuário digitar algo inválido.
// Inclui as datas mínimas e máximas permitidas.
data lerData(const char *mensagem, const char *erro, const data *min, const data *max) {
    char digitado[12];
    int primeiraVez = 1;

    // Repete quantas vezes for necessário, a menos que o return seja alcançado.
    while (1) {
        // Se não for a primeira vez, então é porque a vez anterior deu errado e uma
        // mensagem de erro deve ser mostrada.
        if (primeiraVez) {
            primeiraVez = 0;
        } else {
            printf("%s\n", erro);
        }

        // Mostra a mensagem e lê o que o usuário digitar.
        printf("%s", mensagem);
        fgets(digitado, 12, stdin);
        limpar_input(); // Limpa o input se ficou sujeira nele.

        // Se os 10 primeiros caracteres não estiverem no formato NN/NN/NNNN,
        // então a data é inválida. E se houver algo depois desse NN/NN/NNNN, ela
        // também é.
        if (!validarFormatoData(digitado) || digitado[10] != '\n') continue;

        // Se chegou aqui, então a data tem um formato válido, o que ainda não
        // necessariamente significa que ela é válida. Nesse ponto já podemos
        // obter o número do dia, do mês e do ano ao montar inteiros a partir dos
        // caracteres digitados.
        int dia = numero2(digitado[0], digitado[1]);
        int mes = numero2(digitado[3], digitado[4]);
        int ano = numero4(digitado[6], digitado[7], digitado[8], digitado[9]);

        // Verifica se o dia e o mês são válidos.
        // Inclusive, graças a função diasNoMes, verifica se o mês tem 30 ou 31
        // dias ou sse for fevereiro, se o ano é bissexto ou não.
        if (mes < 1 || mes > 12 || dia < 1 || dia > diasNoMes(mes, ano)) continue;

        // A data é válida. Podemos construí-la.
        data d = {dia, mes, ano};

        // Verifica se que a data montada está entre a data mínima e a máxima.
        if (!comparaData3(min, &d, max)) continue;

        // Se chegou até aqui, a data está ok.
        return d;
    };
}

// Teste do código todo.
// Pede para digitar uma data, insistindo até que uma data válida seja digitada
// e então exibe essa data.
int main(void) {
    data min = {1, 1, 1900};
    data max = {31, 12, 2020};
    data d = lerData(
        "Digite a data de nascimento (DD/MM/AAAA): ",
        "Essa data não estava certa. Vamos tentar novamente.",
        &min,
        &max);
    printf("A data que você digitou foi %d/%d/%d.", d.dia, d.mes, d.ano);
    return 0;
}

Os comentários no código explicam o que ele está fazendo. Basicamente, ele te dará uma função lerData que vai pedir para o usuário digitar uma data e vai insistir até o usuário digitar uma data válida.
Veja aqui o código funcionando no repl.it.
Comment: @AnthonyAccioly Tem o [`struct tm`](http://zetcode.com/articles/cdatetime/) que seria o melhor tipo de dado já pré-fabricado para isso com várias funções de biblioteca já prontas que o manipulam. No entanto, utilizá-lo corretamente também traz seus desafios e complicações. Foi por causa de tanto conviver com esse tipo de situação utilizando tanta coisa de baixo nível em C e tendo que todo dia reinventar a roda quadrada, que acabei me especializando em Java e agora em Python.
Comment: Muito bom! 133 linhas de código, validação do tamanho do mês, anos bissextos, etc. Sempre que vejo essas soluções para problemas universitários minha apreciação por APIs modernas de *Date/Time* é renovada.
Comment: @VictorStafusa Mano, muito obrigado, me ajudou muito.


How to interpret sum of two random variables that cross domains?

Question: suppose we have two discrete random variables:
$X: \{$6 sided dice rolls$\}$ $\rightarrow \{1..6\}$ (following uniform distribution)
$Y: \{$coin flips$\}$ $\rightarrow \{0,1\}$ (following uniform distribution)
How can we add X+Y=Z, for Z a random variable? It makes no sense to me since X and Y have different sample space domains, but shouldn't there be a way to do this?
Comment: btw, does linearity of expectation still hold here? E(X)+E(Y)=E(Z)?
Comment: yes, linearity of expectation holds.
Comment: nice question that I also have this kind of question for a long time.
Answer: It's a good question, interpreted in the following way: the random variable $X$ determined by the coin experiment has a sample space of $\Omega_1=\{\text{Heads},\ \text{Tails}\}$ while the random variable $Y$ determined by the roll of a die has a sample space $\Omega_2$ consisting of the six possible stable orientations of the die on the table.  These obviously are not the same sample space, so what sense does it make to add them?
I will explain one approach to this problem in two ways: first using mathematical terminology and then again using a standard physical model (or metaphor) for probability spaces based on random sampling.
The mathematical account
Implicitly, we form the product space $\Omega=\Omega_1\times\Omega_2.$  Its elements consist of all the ordered pairs $(\omega_1,\omega_2)$ where $\omega_1\in\Omega_1$ and $\omega_2\in\Omega_2.$  The original random variables define new random variables on $\Omega:$ $X$ defines the random variable
$$(\omega_1, \omega_2) \to X(\omega_1)$$
while $Y$ defines the random variable
$$(\omega_1,\omega_2) \to Y(\omega_2).$$
It is a traditional abuse of notation to reuse the symbols $X$ and $Y$ for these new functions on this new space $\Omega.$  It is also understood, when $X$ or $Y$ have continuous distributions, that $\Omega$ is given a sufficiently rich set of events (its sigma algebra) to make these new functions into bona fide random variables: that is, they will be measurable.
Now it makes sense to write "$X+Y$" because it can be defined by pointwise addition (as usual) via

$$(X+Y)(\omega_1,\omega_2) = X(\omega_1,\omega_2) + Y(\omega_1,\omega_2)  = X(\omega_1) + Y(\omega_2)$$

where the last equality comes from the definitions of $X$ and $Y$ on $\Omega.$
If we continue to insist that the two original sample spaces were different, there is no way to model any dependency among them.  Each has its probability function $\mathbb{P}_1$ and $\mathbb{P}_2.$ One thing we can always do, though, is to give the events in $\Omega$ the probabilities $\mathbb P$ they must have according to the definition of independence.  In particular, when $E_1\subset \Omega_1$ and $E_2\subset\Omega_2$ are events, then $E_1\times E_2 = \{(\omega_1,\omega_2)\in\Omega\mid \omega_1\in E_1\text{ and } \omega_2\in E_2\}$ is an event and

$$\mathbb{P}(E_1\times E_2) = \mathbb{P}_1(E_1)\,\mathbb{P}_2(E_2).$$

This enables us to do probability calculations with random variables defined on $\Omega$ including, for example, $X+Y.$
In general, though, people usually assume this product construction has already been carried out, so that in effect $X$ and $Y$ were defined on a common sample space all along.  This permits us to model arbitrary dependencies among these variables, simply by defining any valid sigma algebra and probability function we like on $\Omega.$

A metaphorical (intuitive) account
In terms of the tickets in a box metaphor, $\Omega_1$ is a box with two tickets on it (one for each side of the coin) and $\Omega_2$ is a box with six tickets on it (one for each side of the die).  $X$ consists of writing $0$ on one of the coin tickets and $1$ on the other coin ticket.  $Y$ consists of writing the numbers $1,\ldots,6$ on the six die tickets, one number per ticket.  The "product box" $\Omega$ is created by tabulating all combinations a ticket from one box coupled with a ticket from the other box, as in this figure where elements of $\Omega_1$ index the columns and elements of $\Omega_2$ index the rows.
I have identified the six sides of the die by giving it a coordinate system in which the die is the cube bounded by the eight points with coordinates $\pm 1,$ so that unit vectors pointing out from its six faces determine those faces, and for brevity I write the vectors without parentheses or commas:
$$\array{& \text{Tails} & \text{Heads}  \\
\hline 100: & (\text{Tails}, 100) & (\text{Heads}, 100)\\
010: & (\text{Tails}, 010) & (\text{Heads}, 010) \\
001: & (\text{Tails}, 001) & (\text{Heads}, 001) \\
-001: & (\text{Tails}, -001) & (\text{Heads}, -001) \\
-010: & (\text{Tails}, -010) & (\text{Heads}, -010) \\
-100: & (\text{Tails}, -100) & (\text{Heads}, -100)
}$$
We cut out the $2\times 6 = 12$ cells of this table and put them into a new box: that's $\Omega.$  These tickets represent all possible combinations of a flip of the coin and a roll of the die.
(Clearly it doesn't matter whether you work with $\Omega_1\times \Omega_2$ or $\Omega_2\times\Omega_1;$ the difference--although a real one at a basic mathematical level as well as in the typographical formatting of the table--is just a matter of notation.)
One way to model the probability on the product space is to go through this process with the actual tickets in the boxes rather than the unique types of tickets as shown above.  For instance, if $\Omega_2$ has two tickets for "Tails" and one ticket for "Heads" (modeling a coin that favors Tails 2:1), then the table would have three columns: one for each ticket.  When $\Omega_1$ has $m$ tickets and $\Omega_2$ has $n$ tickets, this will create $mn$ new "product" tickets to put into $\Omega.$
If instead we put arbitrary numbers of each product ticket into $\Omega,$ we can change the probabilities of events and create dependencies among the random variables.  Thus, in a setting where we wish to add two random variables representing different kinds of outcomes, we usually assume this table has been created and the tickets consist of various cells from the table in various proportions.
Comment: +1 always enjoy reading your comprehensive answer.
Answer: Surely they can have different sample spaces (or supports) but you can add them and generate another RV.
If you assume independence between the two, the resulting mass function can be calculated by simply convolving the two. But, a more primitive solution is to list all possible scenarios:
$$\begin{align}&P(Z=1)=P(Y=0)P(X=1)=1/12\\&P(Z=2)=P(Y=0)P(X=2)+P(Y=1)P(X=1)=2/12\\&...\end{align}$$
which will make up the mass function of $Z$.
Comment: Support of $Z$ is $\{1,2,3,4,5,6,7\}$, i.e. all possible $Z$ that can occur with non-zero probability.
Comment: If you don't have independence, you need to *explicitly* define how they're dependent, otherwise you can't find the PMF of $Z$. For the domain, I refrain from going into measure theoretic details here, but the following question (third comment) pretty much summarises it if you're comfortable with measure theory. However, in a nutshell for your question, there is absolutely no reason that you cannot sum the two. https://math.stackexchange.com/questions/1617746/defining-a-sum-of-random-variables
Comment: so what is the domain of $Z$? Is it the cartesian product of $\{H,T\}$ and $\{$dice rolls: $1...6\}$? I thought Z and X+Y should be equal as functions...
Comment: Sure, that should be enough to define the random variable $Z$, but I was referring more formally to its domain as a function. e.g. $Z: S \rightarrow \mathbb{R}$. What is $S$? In a more general case, I don't have independence of $X$ and $Y$ so I wouldn't be able to use convolution.
Answer: Remember that X and Y will be the outcome of the roll of a dice/ flip of a coin. So if I understand your question correctly, you will ad the value you get from your first die roll (say 2) to the value of the coin toss (say 0). Resulting in a Z of 2 for example.
Answer: Any two sample space can be combined by the operation of direct sum. That's generally denoted by the symbol $\oplus$, although the simple addition symbol is sometimes used when it's considered obvious that the direct sum is intended.
However, in this case, it appears that regular addition is meant. The coin flips are being represented by the integers {0, 1}, so those numbers can be added to the die roll. While the sample space ranges, in the sense of the possible values, are different, in both cases the overall space is the set of integers, so addition is possible.


Executing a view programmatically with input filters

Question: I've created a View to search for suitable jobs. Along with View I want to give a "Subscribe" button for those who want matching jobs(if any) be delivered in their inbox daily. I want to save the input entered in the exposed filters and run the View at night in a batch for all those who have subscribed for jobs.
I will add a "Subscribe" button along with "Apply" in the Views form. So if any logged-in user selects the "Subscribe" button I want to: 1) Save the input of exposed filters; 2) Run this view every night and see if any new matches are found; 3) Email the user with new jobs found.
Is there any easy way to do it? Is there any module to help me?
I can use Views Saved Searches module to save current user selection of exposed filters.  This input could be fed when calling view programmatically.
Also two more useful links: Using Views Programmatically Drupalcamp & get the result view creates.
EDIT:
I need someone to provide me practical in-use implementation that can save my time.
Comment: a good solution will be to use search api and its contrib https://drupal.org/project/search_api_saved_searches
Comment: If [views_savedsearches](https://drupal.org/project/views_savedsearches) had support for [notifications](https://drupal.org/project/notifications) 7.x you would need just these 2 modules.
Comment: I've re-structured your question to reflect the fact that you're really asking 4 questions in one. The title of the original question _"Executing a view programmatically with input filters"_ you already answered with your second link. I think it would be easier to answer your question if it where broken into pieces, as there can be a wild variety of answer to each of the 3 remaining questions you're asking. At this point this isn't as much as a question - as much as a "tell me how to develop a full Drupal application". Hopefully somebody will eventually provide a nice answer ;)
Answer: I don't think that you need to execute the view programmatically. Because it's meaningless. Views just fetches data from the tables which you show and display it, it's all it does.
I think you need to alter Exposed Filter form and add your additional submit callback which on submission writes the searched strings into your custom table. And then you can query those table (from which table views fetch data.) with saved string as condition..
All of this logic must be run on cron job..
EDIT:
I don't know this can help you or not, but here is a very poor example. Not very performance friendly :). OPTIMIZE IT.
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
   if ($form['#id'] == 'MY_EX_FORM_ID') {
      if(user_is_logged_in()) {
         $form['actions'] = array(
            '#type' => 'actions',
         );

         $form['actions']['submit'] = $form['submit'];
         $form['actions']['subscribe'] = array(
            '#type' => 'submit',
            '#value' => 'Subscribe',
            '#submit' => array('my_ex_form_subscribe_submit'),
         );
         unset($form['submit']);
      }
   }
}

function my_ex_form_subscribe_submit($form, &$form_state) {
   global $user;
   $account = clone $user;

   $input_val = $form_state['values']['field_adv_price_first']['min']; //Find your input field value and change this..

   db_insert('MY_SUBSCRIBE_TABLE')
      ->fields(array(
         'uid' => $account->uid,
         'email' => $account->init,
         'input_val' => $input_val,
      ))
      ->execute();
}

function MY_MODULE_cron() {
   $subscribed_query = db_select('MY_SUBSCRIBE_TABLE', 'mst');
   $subscribed_query
      ->fields('mst', array('uid', 'email', 'input_val'))
      ->execute()
      ->fetchAllAssoc('id'/* id - is the primary key of MY_SUBSCRIBE_TABLE */);

   // Supposing that your view is querying for the node table to fetch jobs, by title field
   if(!empty($subscribed_query)) {
      foreach($subscribed_query as $key => $val) {
         $nids = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('title', '%' . db_like($subscribed_query[$key]['input_val']) . '%', 'LIKE')
            ->execute()
            ->fetchCol();

         if(!empty($nids)) {
            foreach($nids as $nid) {
               $node_url = url('node/' . $nid, array('absolute' => TRUE));
               $template = 'New job is found in our site and blablabla... BLABLABLA';

               // Suppose that you are using SwiftMail library.. You can use drupal's mail system as well. It's up to you
               $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
                  ->setUsername('MYGMAILUSERNAME')
                  ->setPassword('MYGMAILPASS');

               $mailer = Swift_Mailer::newInstance($transport);

               $message = Swift_Message::newInstance()
                  ->setFrom(array('no-reply@'.$_SERVER['SERVER_NAME'] => 'MY-SITE.com'))
                  ->setTo(array($subscribed_query[$key]['email']))
                  ->setBody($template, 'text/html');
               $mailer->send($message);
            }
         }
      }
   }
}

Comment: Indeed.  This is a job for a custom form that just saves the various inputs to be run by a View or other custom sql at some time later on.
Comment: @Jimajamma do you have any sample code which is used at any place?
Comment: @AgA no, sorry, I don't have a current real world use case for this, but it would be pretty straightforward.  create a form with the various filters as inputs.  display it on a page.  when a user submits it, save all the information in a table.  then via cron, execute views based upon the info in that table and mail the results to the respective user.
Comment: @Jimajamma plenty of people must be using this feature in this world. Secondly I don't want to run custom sql myself as you've mentioned in first comment. I'd rather execute the View so that it only generates sql automatically
Comment: @AgA I was just responding that I'm sorry, but no, I don't have any sample code at hand that accomplishes this exact task.
Comment: @AgA I added some sample code..
Answer: Is there any module to help me?
Much easier to answer if you break down your question logically.
1) Save the input of exposed filters;
The input of exposed filters is relative to the user entities "saving" those filters. In Drupal 7 users are entities, and some entities are fieldable (meaning you can add fields to them). Drupal 7 users are fieldable. This DA question contains all sorts of useful answers you can use to add fields to your user - where later on you can store the exposed filter data: How to add extra fields to user profile?.
2) Run this view every night and see if any new matches are found;
This separate questions gets into batch/cron jobs area. Look into hook_cron. You can define your own Drupal "job" that will run on any schedule you want. When the schedule runs depends if yo use standard system tools from managing cron (cron tab) - or if yo use a Drupal module such as elysia cron.
In your hook_cron() you could write a custom query that would search for all the users with a saved search. Since Drupal 7 users are entities, you can use EntityFieldQuery to get started.
If any users are found, then you could execute the View programatically (as you answered yourself), get the results, and email them. I don't think Views will provide you with the best e-mail friendly output out of the box. But you could easily write your own custom theming function that parses the output returned by the View. This should be relatively easy for a Drupal beginner to do. Drupal theming is a topic of it's own. So I'm going to spare readers of an answer to that and assume due diligence on behalf of those seeking an answer. Links: one, two.
3) Email the user with new jobs found.
Multiple questions already answered here on DA can help you with that. I'm only providing one, two, three as a sample, but you could keep searching DA to your heart's content. No reason to re-invent the wheel (or re-answer what's been already answered).
To conclude - there is no easy answer to your question that I could think of, and my answer would assume that you've got at least a decent handle on Drupal. But I hope it helps nevertheless.
Answer: In one of my projects I build something like this in custom way.Here are few pointers I can think of now.

Create custom form, custom database table to map filter values with uid,keep a flag_cron column and flag_updated in your custom table,flag_cron which will make sure that you are not picking up same filters to get data for and set flag_updated to 1 every time you get data for a set of filters and again if the user against a uid updates the filters set the flag_updated to 0,So while picking up the filters on cron run(you must be picking up the filters in chunks otherwise when users will grow system will fail to make request for),check for 0,0(flag_cron,flag_udpated) then give priority to 1,0(flag_cron,flag_updated).Key will be every time you get data update flag_cron and flag_udpated to 1.
This is what I did in my project, I feel custom forms give more flexibility over expose filters.
On cron run you might be calling API's , so with the fetched data if you are building nodes then views are good solution to create the display while this views is programmatically called with the filter values against the current logged in user or if not set any then you can keep default in place.(creating nodes should be good approch).
In case you are not making nodes and simply filling custom tables with data you get,you might make database query and may use different theme function to show the data.
Try to evaluate if better exposed filter form can take place for your custom form,otherwise underlying concept and custom filter table is supposed to be same.
In my projects I have to make several API calls at frequent intervals.Since API calls were large amount and they were fetching large data so I was looking for non blocking system, I used php command line tool exec.Code example
exec("/usr/bin/php path_to_php_file.php $param_0 $slot_0> /dev/null 2>&1 &");

and $patam $slot are diferent arguments you need on the stanalone php file, the benefit you get using non blocking call system is you can trigger different php process at same time thus making different API calls by passing different arguments in parallel, but its important to control the php process otherwise it may crash your server.Later on I found there is a drupal module which allows to make non blocking calls "backgroung_process"

For cron I used elysia cron and set crontab on server.

Elysia Cron extends Drupal standard cron, allowing a fine grain
  control over each task and several ways to add custom cron jobs to
  your site.


Who is the "winner" of each leg of a two-legged football match, or a match that goes to penalties?

Question: Match #1
Europa League, quarter-finals, 2nd leg: After 90 minutes Besiktas was up 2-1 against Lyon. Because of the aggregate score of 3-3 (Lyon won 2-1 in the 1st leg) they had to play extra time and then use penalty shootout to decide who got to go on in the to the semi-final. Lyon won on penalties.
Match #2
World Cup, round of 16: After 90 minutes the score was 1-1 between Spain and Russia. To get a winner they had to play extra time and do a penalty shootout. Russia won on penalties.
Questions

Which teams are considered the winner of the two single matches? (What I'm really wondering about is if that penalty shootout in a two-legged match is considered to be part of that single match or not.)
In a team form view of the team would you expect to see Lyon to have won or lost the last match? (Would you be able to say that Besiktas or Spain have not lost any of their X matches because of the full-time score?)
Comment: It might be helpful if you explained why this was important to you - I can see it is for betting purposes, but the answer is then "talk to your bookie". Other than that, it doesn't matter who won the two single Europa League matches, Lyon won the tie and went through; similarly for the World Cup, Russia went through, nothing else matters.
Comment: Statistical analysis is not usually part of the rules (US major sports being an absurd exception in some cases). FIFA certainly doesn't care about individual matches as part of a tie, only the end result according to max-total-goals/max-away-goals/KFTPM.
Comment: The question came up in regards of representing the team form graphically + having facts like "Team X has not lost in Y matches". But it also got more philosophically. There must some sort of rule/law/definition of this. I was unable to find anything about this in FIFA's rules.
Comment: Usually for an statistics porpuosse, the winner or loser of the match is the one that made it outside of the penalty shootout. Once a match reach that phase, is only a matter of who goes to the next round, but the result is the real one in full time
Answer: According to the Laws of the Game (2 Mb pdf-file):

Winning team
The team scoring the greater number of goals during a match is the
winner. If both teams score an equal number of goals, or if no goals
are scored, the match is drawn.
Competition rules
When competition rules require there to be a winning team after a match or home-and-away tie, the only permitted
procedures for determining the winning team are those approved by the
International F.A. Board, namely:

away goals rule
extra time
kicks from the penalty mark

Based on that penalty shootout is considered to be a part of a single play-off game. However, it is not clear whether penalty shootout can be considered as a part of the second match in a home-and-away tie.
So

The winner if every single match in 2-legs game is the team who scored the greater number of goals.

However, it is not defined who is the winner of the second leg in a home-and-away tie situation if it comes to penalty shootout. It's only defined who is the winner of the whole stage.
Comment: Take in mind, that the winner is not the one who has more goals.. in this case: A 2-1 B, and B 3-2 A, the winner is A on the away goals rule.


Is the assumption of risks proportionality required when we assessing the difference of two KM branches (curves)?

Question: There are two KM branches (curves) (for example, for male and female). Can I use a log-rank test if the assumption of risk proportionality is not satisfied?
P.S. I checked this with the code: plot(Y~sex, fun="cloglog")
Answer: Under the null hypothesis of no difference between the survival curves of, e.g., males and females, the hazard functions are proportional (actually they are equal). Therefore, the log-rank test has the nominal Type I error of 5% when you decide to reject at significance level of 5%.
Under the alternative hypothesis when there are differences between the survival curves of males and females, the log-rank test is most powerful (i.e., it has the highest chance of finding a statistical significant difference) when the hazard functions are proportional. If there are mild violations of the proportional hazards assumption, there are alternative tests that can be a bit more powerful, for example the Gehan-Wilcoxon test.
If you work in R and the survival package, both the log-rank and Gehan-Wilcoxon tests are available in the survdiff() function by suitably setting the rho argument.
Comment: Thank you Dimitris! (An example "male-female" is really bad.)


Wilcoxon signed-rank test can be a test for comparing means but not for comparing medians?

Question: Wikipedia says that we can rewrite the hypotheses of the one-sample Wilcoxon signed-rank test in terms of expected value (as "a test for the location of the mean") if the following assumptions are met (below we have random iid sample $(X_1,\ldots,X_n) \overset{\text{iid}}{\sim} F$):

$F$ has unique median $\mathrm{med}(X)$ such that $P(X = \mathrm{med}(X)) = 0$;
$F$ is symmetric about $\mathrm{med}(X)$;
Expectation $\mathrm{E}[X]$ exists.

So, if these assumptions are met then $\mathrm{med}(X) = \mathrm{E}[X]$ and the hypotheses of the one-sample Wilcoxon signed-rank test are the following (for the two-sided alternative):
$\quad\begin{aligned}H_0: ~\mathrm{med}(X) = 0 \\ H_1: ~\mathrm{med}(X) \neq 0 \end{aligned} \qquad \iff \qquad \begin{aligned}\widetilde{H_0}: ~\mathrm{E}[X] = 0 \\ \widetilde{H_1}: ~\mathrm{E}[X] \neq 0 \end{aligned}$
Next, I tried to use the fact that paired Wilcoxon signed-rank test is just a special case of its one sample version (if we have paired samples $(X_1,\ldots,X_n) \overset{\text{iid}}{\sim} F_1$ and $(Y_1, \ldots, Y_n) \overset{\text{iid}}{\sim} F_2$, we just need to replace $X$ by difference $X - Y$ in the aforementioned formulas), and got the following.
Assumptions for the paired Wilcoxon signed-rank test:

Distribution of $X - Y$ has unique median $\mathrm{med}(X-Y)$ such that $P(X - Y = \mathrm{med}(X-Y)) = 0$;
Distribution of $X - Y$ is symmetric about $\mathrm{med}(X-Y)$;
Expectation $\mathrm{E}[X-Y]$ exists.

If these assumptions are met then $\mathrm{med}(X-Y) = \mathrm{E}[X-Y]$ and the hypotheses of the paired Wilcoxon signed-rank test are the following (for the two-sided alternative):
$\quad\begin{aligned}H_0: ~\mathrm{med}(X-Y) = 0 \\ H_1: ~\mathrm{med}(X-Y) \neq 0 \end{aligned} \qquad \iff \qquad \begin{aligned}\widetilde{H_0}: ~\mathrm{E}[X-Y] = 0 \\ \widetilde{H_1}: ~\mathrm{E}[X-Y] \neq 0 \end{aligned}$
This all seems fine but one thing confuses me: expectation is a linear operator, so we can rewrite $\widetilde{H_0}$ and $\widetilde{H_1}$ as $\widetilde{H_0}: \mathrm{E}[X] = \mathrm{E}[Y]$ and $\widetilde{H_1}: \mathrm{E}[X] \neq \mathrm{E}[Y]$ respectively. But population median is not a linear operator, hence we can't rewrite $H_0$ and $H_1$ as $H_0: \mathrm{med}(X) = \mathrm{med}(Y)$ and $H_1: \mathrm{med}(X) \neq \mathrm{med}(Y)$ respectively.
In other words, paired Wilcoxon signed-rank test (if the aforementioned assumptions are met) is a test for comparing the means of the paired samples, but it is not a test for comparing the medians of the paired samples. Is this conclusion right or wrong?

P.S. There is a post on SSE on similar topic, it claims that paired Wilcoxon signed-rank test can be a test of median difference (or mean difference) only if two fairly strict assumptions are met:

The distribution of both groups must have the same shape.

The variance of both groups must be equal.

These assumptions seem strange for me because, as far as I know, paired Wilcoxon signed-rank test is just a special case of its one-sample version. And I didn't met these two assumptions in other sources (I saw these assumptions in requirements for the Mann–Whitney U test but not for the Wilcoxon signed-rank test).
Comment: In general it is not comparing medians but under the additional assumptions you made, it will be.
Comment: @Glen_b Does this mean that $\mathrm{med}(X-Y) = \mathrm{med}(X)-\mathrm{med}(Y)$ under these assumptions? If not, I still can't see how we can compare $\mathrm{med}(X)$ and $\mathrm{med}(Y)$ with each other.
Answer: The one-sample signed-rank test is, precisely, a test for the median pairwise mean. That is, we can define pairwise means $\Delta_{ij}=(X_i+X_j)/2$, and the test statistic has its minimum value when the median of $\Delta$ is zero. As sample size increases, the test will eventually reject for any distribution where $med[\Delta]\neq 0$.
If the distribution is symmetric and the mean of $X$ exists, the median of $\Delta$ and the mean of $X$ and the median of $X$ are all the same; they are all the centre of symmetry. In that special case, the test is also a test for the median of $X$ and for the mean of $X$, because they are all the same.   If the distribution is not symmetric, they are typically all different and the test is not a test for the mean of $X$ or the median of $X$.
Going on to paired tests, if $X_i=Y_i-Z_i$ then the test is still for the median pairwise difference fo $X_i$, and is for the mean or median of $X$ under the same assumptions as before. These are your second set of assumptions. Precisely because the median is not a linear functional, it takes additional assumptions for a test of the median to also be a test of the mean.
And finally, the situation for the Wilcoxon rank-sum test is very different.  There is no one-sample summary statistic analogous to $med(\Delta)$ that the Wilcoxon rank-sum test is a test for (without additional assumptions).  In fact, there is no ordering on all distributions that agrees with the Wilcoxon rank-sum test.  It's possible to have three variables $X$, $Y$, $Z$ such that the Wilcoxon test thinks $X$ is bigger than $Y$, $Y$ is bigger than $Z$, and $Z$ is bigger than $X$.
However, if you make additional assumptions, such as the two distributions being the same except for a shift in location, then  the Wilcoxon test is a test for means or for medians -- if two distributions are the same except for a shift in location then they can differ only if they have different means and only if they have different medians.
Comment: Thanks! But your statement "Precisely because the median is not a linear functional, it takes additional assumptions for a test of the median to also be a test of the mean." is slightly confusing - what is "the mean" here? Maybe you wanted to write "the medians (of $Y$ and $Z$)" instead?


Mercurial vs Git in IntelliJ IDEA

Question: Regarding IntelliJ IDEA 12 (or the new 13 Beta, but please specify which), which integration is better, the one with GIT or the one with Mercurial, and why?
Answer: JetBrains uses Git as their VCS. It is more likely to get the latest fixes since they are dogfooding. Mercurial support is good, but gets less attention.
Comment: Well those are nice, but they aren't really specific to the handling of Mercurial. The integration with is missing a lot of useful functionality, such as listing incoming and outgoing changesets, the history graph, rebase, graft, inline diff, etc... IntelliJ has many strengths, but version control is not one of them.
Comment: I wouldn't call mercurial support good. It is really miles behind the mercurial plugin for eclipse for instance. I'd say if you use IntelliJ you're pretty much going to have to use an external tool to handle your mercurial versioning.
Comment: I do use TortoiseHG as well. But I like the integration with IntelliJ tasks and the pre-checkin code inspections.

Mercurial vs Git in IntelliJ IDEA


Enviando arquivos no Nginx erro "413 Request Entity Too Large"

Question: Estou tentando enviar um arquivo de 2MB utilizando o Nginx, porem continuo recebendo o 413 arquivo muito grande.
Versão: Nginx/1.4.6
SO: Ubuntu 14.04 LTS
Answer: É necessário fazer alterações no arquivo php.ini
upload_max_filesize = <Tamanho Desejado>M

Em seguida alterar as configurações do servidor no Nginx. No arquivo  /etc/nginx/conf.d/default.conf ou no arquivo do seu servidor na pasta /etc/nginx/sites-available/
server {
    client_max_body_size <Tamanho Desejado>M;
    ...
}

E por final, reinicie o serviço.
# service nginx restart

Aqui esta funcionando corretamente.


Anscombe transform & Anderson-Darling test failure

Question: I created a synthetic constant image (all the pixel values are the same) on which I generated a Poisson distribution using a Poisson noise generator, with mean values set to input pixel values.
Then, I applied the Anscombe transform and checked if the output distribution fit the normal distribution by using the Anderson-Darling test with p=0.05.
Surprisingly, all the tests failed (I generated several Poisson distributions), do you have any explanation for this? Should we expect that the tests succeed (as the Anscombe transform is supposed to yield an APPROXIMATE normal distribution)?
Comment: I find the notion that a test is somehow "failing" when it correctly rejects non-normality to border on the perverse.
Answer: The Anderson-Darling test is a test of exact normality, your transformation is supposed to give approximate normality, so the null hypothesis for AD is false and the correct decision is to reject the null.
Also note that the AD (and other) tests are rule out tests, if they reject the null then that means your data is not consistent with the null hypothesis of exact normality.  If the test does not reject the null hypothesis that does not mean that the data is normal, it may be (probably is) that you do not have enough power to find the difference.
The real issue is how good is your approximation or is the data normal enough?  This is the much more interesting question, but the standard normality tests do not answer this question.  Plots can help you get a better feel for this, but the final decision is going to be subjective.
Answer: With large sample sizes, the Anderson-Darling test is prone to reject very large samples from otherwise acceptable distributions.
If you are dealing with thousands of data points, the  Ryan-Joiner or Shapiro-Wilk tests should be used.
Note: Changing the test should be something that, in the future, is done based on sample size information and not as a result of choosing hypothesis tests until you are successful.
Another word of caution: it is possible to change tests to something more robust for a larger sample size even though the data looks decent.  Using the data from this discussion on the topic of hypothesis tests, the large "normal" data still fails.  (I tested the data with a stabilized normal probability plot, and it becomes apparent that the seemingly normal data actually fails on multiple points, and not even in the tails.)
Comment: I cannot fathom the rationale for substituting a less powerful test for a more powerful one: that seems only like a way to hide what's going on.  If A-D says the data aren't normal, they likely aren't--so deal with it by understanding what that means, as discussed by Greg Snow in his answer.
Answer: Finally, I found out that if we have a large number of samples (cf. Wikipedia), AD test can fail. Hence, I tested this with  100 samples and the test succeeded.
Comment: Are you really comfortable with the practice of deciding that you have too much data because you don't get the answer you like, so you throw away data until you get the answer you want?  If this were good science then we could use this to prove that global warming (or other pet/hot topic) is real or nothing to worry about by just choosing the appropriate null hypothesis and throwing away data until we do not reject the null.
Comment: Why not just test with two samples, then, and be done with it?  That test will *always* succeed!  The motivation for using any normality test seems rather elusive at this point.  What is certain, though, is that if you are flexible enough to keep applying a test to smaller and smaller subsets of your sample until you get a satisfactory result, then your test isn't doing anything at all (at least nothing good...).
Comment: Indeed; why use consistent tests at all, if you dislike rejecting false nulls?


What do "breathy voice" and "full voice" mean?

Question: In vocal pedagogy some people talk about "breathy voice". What does this term refer to and how is it different from "full voice"?
I should add that breathy is also used for the speaking voice.
What I am referring to is not so much the breathy jazz singer (doing this on purpose) but the person who has a natural breathy voice (whatever that means).
Comment: Why the 'teaching' tag?
Answer: Just as we can talk in a whisper, normally, or shout, we can do the same while singing.
When whispering, there's a lot more air missing the vocal chords, but the words are still articulated by the shape of mouth, and tongue position. Without those, we'd just be blowing.
Full voice will incorporate more air pressure from lungs/diaphragm, which again will be tempered by lungs/diaphragm, from quiet singing to almost shouting. Go further, and it is shouting.
Comment: And Macy Gray for the opposite. Or Blossom Dearie.
Comment: I have a breathy speaking voice usually, full voice when singing. I have one friend whose normal conversational voice sounds like he's addressing the back row of the stalls. Makes Jean Luc Picard sound like he's under-performing. Some people are just like that ;))
Comment: @Tetsujin - yeah, often wondered what Brian Blessed sounds like 'normally'. I guess teachers develop that sort of voice out of necessity  - I know I did. And let's not forget Town Criers.
Comment: He whispers in ALL CAPS ;)) Actually, Brian Blessed, bless 'im, always sounded like he was 'proclaiming' rather than speaking.
Comment: @AndyBonner - Marilyn Monroe was probably up there (or down there) too.
Answer: It may help to think about the human voice as having two main components:

the sustained, pitched note
non-pitched sounds (everything else)

That second item includes the "breath" sound (essentially sustained noise), plosives ("P", "B"), other consonants--all the sounds that we naturally add to the sung pitch to form words. The volume relationship (or ratio) of the pitched note to everything else dramatically changes the quality and character of the voice.
This ratio exists on a continuum. On one end of the continuum, you have whispered speech. That's "everything else" and no pitched sound (say 0/100, which is 0% pitch and 100% non-pitched). At the other end of the continuum, you have the pitched note and little or no "everything else" (say 90/10).
Every singer falls somewhere on that continuum, and the main determinant is how much they support their vocal mechanism. This affects how much energy (sound) they create with the pitched note.
If a singer doesn't support their voice (intentionally or due to poor technique), they will be quieter overall and the sung pitch will be lower in volume relative to the other voice components. We might call that ratio 30/70. This will usually translate to more breath noise (to extreme: a "breathy" sound), or louder plosives and consonants (to extreme: a "spitty" or "clicky" sound).
At the other end of the continuum are trained singers who support their voice well and create a tremendous amount of volume with the pitched note. Think of the opera soprano projecting her voice to the back of a 5,000-seat hall without amplification.  We'll estimate her ratio at 90/10, which can create a problem with the "everything else". A very loud singer may form the vowels of the words properly but come up short on the diction. This makes them hard to understand. Good diction can help a singer increase the volume of those non-pitched components, but it's hard to do.
Let's circle back to your original question. A "breathy" voice is one that has less support and volume, making the non-pitched parts of the voice more prominent. Anyone can sing with less support to create a "breathy" sound. Reduce the support to its logical conclusion, and you'll be whispering the words of the song (back to 0/100).
A balanced  or "full" voice (50/50) is well-supported, with enough volume in the sung note to project and enough energy in the non-pitched elements to be clearly understood. That ratio is not necessarily optimum, though. A microphone will pick up everything, so a voice with less sustained note energy (say 30/70) is perfectly acceptable for amplified and recorded music. That voice won't cut it singing Wagner in front of an orchestra, however.
Comment: "A "breathy" voice is one that has less support and volume, making the non-pitched parts of the voice more prominent."  I have been told that we hear the breathy singing in the vowels (ie people singing breathy on pitch). Do you dissagree?
Comment: Vowel implies sustained, pitched sound and open mouth. So yes--it's only during a vowel that you'd hear the breath noise. You won't hear it during other non-pitched sounds, nor can you form a vowel while humming (another pitched "mode" of singing).
Answer: "Breathy" refers to a whisper-like vocal sound created by singing with partial vocal cord closure. Here's an example. At 0:32, the lyrics: "makes no difference who you are". Every word is very breathy, except it's non-breathy on the "ence" of difference and on the "who" and "you".
It's used stylistically to create different textures in the vocal sound. It's different from "full voice" as during "full voice" the vocal cords close completely.
Vocal cord closure is one of those components of phonation that you can adjust by itself. So you can sing a note, keep everything the same (pitch, register, volume, etc) and then freely add and remove vocal closure. Here's a resource on the physiology involved.


How get table total count in Sqlite3 in swift4?

Question: I am new in IOS and Sqlite3 DB.
What I want to achieve in sqlite3 DB and swift4 to get the total number count of table.
I Did the following steps.
func getTotalCount()->Int32{
    let queryStatementString = "SELECT COUNT(*) FROM Attendance"
    var stmt: OpaquePointer?

    print("select valid count \(queryStatementString) ")

    var totalCount: Int32 = 0
    var id: Int = 0

    if sqlite3_prepare_v2(db, queryStatementString, -1, &stmt, nil) == SQLITE_OK{
        if sqlite3_step(stmt) == SQLITE_ROW {
            id = Int(sqlite3_column_int(stmt, 0))
            print("id \(id)")
            totalCount = sqlite3_column_count(stmt!)
            print("db: validCount Result:")
            print("validCount \(totalCount)")

        }
    }

    if sqlite3_step(stmt) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(stmt)!)
        print("db: failure getting punchTime: \(errmsg)")

    }

    return totalCount
}

But is always return me 1 as a count.
I didn't get where I am missing.
Answer: I get an answer.
I am retrieving a wrong index value.
Refer below code.
func getTotalCount()->Int32{
    let queryStatementString = "SELECT COUNT(*) FROM Attendance"
    var stmt: OpaquePointer?
    var totalCount: Int32 = 0

    if sqlite3_prepare_v2(db, queryStatementString, -1, &stmt, nil) == SQLITE_OK{
        while sqlite3_step(stmt) == SQLITE_ROW {
            totalCount = sqlite3_column_int(stmt, 0)
            print("totalCount \(totalCount)")
        }
    }

    if sqlite3_step(stmt) != SQLITE_DONE {
        let errmsg = String(cString: sqlite3_errmsg(stmt)!)
        print("db: failure getting punchTime: \(errmsg)")
    }
    return totalCount
}