Simple measure for comparison of rainfall regularity

Question: In meteorology we have the concept of monthly rainfall, which is just the sum of daily rainfall over that month. Now, given this extreme example:
Situation 1:
First day of month: 210mm
All remaining days: 0mm

Monthly rainfall = 210 + 0 + ... + 0 = 210mm

Situation 2:
All days of month: 7mm
Monthly rainfall = 7 * 30 = 210mm

Which statistic can I use to show that Situation #2 has a more 'regular'
rainfall distribution? I'm not sure if standard deviation or entropy will give me a good result.
Answer: Here's a short paper* that summarizes various methods and favors a kind of scaled Shannon Entropy Index.
Personally, I prefer Simpson's Index because it avoids having to pick a small number to log when there is no rain. Lots of fields also use something very similar to measure competition or diversity, so it is easier to explain. The drawback is the potential maximum is less than 1, and it is dependent on the number of days with rainfall.

*Bronikowski, A., & Webb, C. (1996). Appendix: a critical examination of rainfall variability measures used in behavioral ecology studies. Behavioral Ecology and Sociobiology, 39(1), 27-30.
Comment: Is the Shannon entropy / Simpson's index valid for non count data ?  I also have rainfall data from multiple months and would like to do a rainfall distrubution analysis.


Is it possible to use an image style with a path rather than a URI?

Question: I want to be able to send an image included in a custom module to the image_style theme like:
  $render_image = [
    '#theme' => 'image_style',
    '#style_name' => $imagecache_template,
    '#uri' => '/modules/custom/MYMODULE/default.png',
    ...
  ];

But '#uri' is expecting something in the format public:// . Is it possible to marshall a relative path somehow?
Comment: It should be possible to create an image style derivative using an ImageStyle entity or the image.factory service, but I haven't tried it myself.
Answer: I'll expand a bit on what acrosman answered, only because I needed this exact same thing so hopefully this will help the next person who comes across this.
I'm working from preprocess_page and using a view to grab my images.
Like his answer make sure you add the ImageStyle:
use Drupal\image\Entity\ImageStyle;

Once I grabbed the view entity I was able to narrow down my image field and then work my way to the styled image.
$image = $entity->get('field_images')->getValue();
$image_entity = File::load($image[0]['target_id']);
$image_uri = $image_entity->get('uri')->value;
$style = ImageStyle::load('my_image_style');
$image_url = $style->buildUrl($image_uri);

So overall my whole function to grab the image from a View and apply a custom image style looked like.
function _mytheme_preprocess_page_front_projects(array &$variables) {
  $projects = array();
  $view = Views::getView('projects');

  if (is_object($view)) {
    $view->setDisplay('page_1');
    $view->preExecute();
    $view->execute();

    foreach ($view->result as $k => $v) {
      $entity = $v->_entity;

      // Grab image entity.
      $image = $entity->get('field_images')->getValue();

      // Load the first value for preview image.
      $image_entity = File::load($image[0]['target_id']);

      // Grab the uri of that first image.
      $image_uri = $image_entity->get('uri')->value;

      // Using ImageStyle you then load your style.
      $style = ImageStyle::load('my_image_style');

      // Use buildUrl to create the path to your styled image.
      $image_url = $style->buildUrl($image_uri);

      // Then I return the url as an image variable to grab in page template.
      $projects[$k]['image'] = $image_url;
    }

    return $projects;
  }
}

Comment: this works well, don't forget to include `use Drupal\file\Entity\File;` before `File::load`
Answer: I haven't tried it from a render array, but you can load the ImageStyle entity and have it build a URL from a path using buildUrl().
If you are doing this right in the .module file make sure to tell PHP you'll be using ImageStyle, in a plugin or controller you'll want to inject the class.
use Drupal\image\Entity\ImageStyle;

Then load you're style and build the URL (warning, I have not tested this):
$style = ImageStyle::load('img_style');
$image_path = $style->buildUrl('/modules/custom/MYMODULE/default.png');

From there you should be able to place that into whatever context you need to get the image rendered the way you'd like.


Difference between "Bar" and "Measure"

Question: I was taught musical theory in the UK where I grew up.  I was taught what a bar is.  In my experience, the terminology "measure" is not used in a musical sense in the UK.
Since living in the US, I have generally found that "measure" is a direct synonym for "bar".  However I hear some people here use both terms, which has confused me.
In the US, are the terms "bar" and "measure" exactly equivalent, or is there some subtle distinction between the two?
Comment: The terms are interchangeable. There is no distinction. However, the term "measure" was used in a similar sense as "bar" in older English. "Let us measure them a measure" in Shakespeare means "Let's dance for them for a few bars".
Comment: @WheatWilliams, I believe you are mistaken.  While we have measures in music, in the dance of Shakespeare's time, there were also measures -- it meant "figure", such that one measure of dance might take several (often four) measures of music -- *and* the word "measure" had come to mean, by synecdoche, "dance".  See "[The Old Measures](http://en.wikipedia.org/wiki/Old_measures)".  So "Let us measure them a measure", probably meant "dance them a dance", not "dance them a few bars."
Comment: @Codeswitcher: "translating" Shakespeare's word plays is likely to lose some meanings.  Here clearly *both* "a slow and stately dance, like the minuet" and "{To have hard measure}, to have harsh treatment meted out to one; to be harshly or oppressively dealt with" are implied.
Comment: There are standard, academically recognized definitions for these terms and all musical terms currently or formerly in use. The New Grove (ie. Grove's Dictionary of Music & Musicians) is the internationally recognized reference source for terminology. Wikipedia is pretty dependable too.
Answer: I've studied music in both the US and the UK (piano lessons in the UK at age 14, majored in piano in the US), and bar and measure are used interchangeably in both in my experience.  Jazz and blues musicians tend to say "bar" more often than "measure": 12-bar and 16-bar blues, for example.  Also, you'd never hear a jazz musician say "He stepped on four of my measures" if someone came in four bars early while he was improvising for an allotted number of bars.  Nevertheless, they mean the same thing, both in the US and the UK.
Answer: A "bar" is actually the graphical entity separating measures.  "Let's start at bar x" is probably what led to "bar" becoming a substitute for "measure" in some usage.  After all, "measure" has a lot of meanings already, and some of them in contexts close to music (a "at measured pace", the dance "measure", possibly also used for "phrase" generally).  I'd not be surprised if dancers called a basic dancing step (depending on the metre, one or two beats) a "measure": at least German dancers confuddled me a lot by what they choose to call a "Takt".
Comment: I thought the graphical entity separating measures was a "bar line" (or maybe that's a British English thing too).
Comment: Gardner Read's excellent book "Music Notation" contains a rant similar to the claim in your answer; in Standard American (English), the space between two *bars* is called a *measure*. But in Standard English English, it is not: *barlines* separare *bars*. So both you and he are simply wrong if you intend to address anything wider than US usage.
Answer: It is true that "measure" is used synonymously with "bar" in North America. Christopher Hasty, in Meter as Rhythm (1997) makes a compelling case for ceasing use of "measure" (in short, that he wishes to use the notion of "measure" more flexibly than the usage synonymous with bar, since in the process of making sense of rhythmic activity we use "measures" of a variety of lengths). While he advocates the use of "bar measure" as a surrogate, this hasn't caught on, to my knowledge; however, his case for reserving the term "measure" for the purposes he states is a compelling one for rhythmic theory. (On the topic of metric terminology, he also advocates the use of "meter signature" rather than "time signature," for obvious reasons. This is a practice followed by other careful thinkers on meter, including those who predate Hasty (e.g., George Houle, 1987), although many or most North Americans continue to use the term "time signature.")
Comment: I would love for you to expand this by clarifying exactly what 'the purpose he states' is; as it is now, your answer doesn't read easily.
Answer: Strictly speaking, a bar is the vertical line which defines a set of notes.  This set of notes constitutes the measure.  When we say "start at bar 10" we actually mean start at the bar at the beginning of measure 10.  You can also say "start at measure 10"
Comment: This is definitely a difference between British and American usage. In British usage these lines are usually "bar-lines".
Comment: When we say "start at bar 10" in the UK we mean "start at the beginning of bar 10". The bar lines are the separation between the bars, and the bars are (graphically) the stuff between them. It is, fundamentally, just a case of calling things different things - in much the same way that we say "semibreve" and Americans say "whole note".
Comment: I've never been taught "bar" meaning the drawn line, otherwise "we'll start halfway through bar 10" would be meaningless.
Comment: "bar line" is nicely unambiguous.  However, taking a look at 1913 Webster's (admittedly an American dictionary), "bar" has plentiful non-musical meanings and almost all of them stand for some sort of barrier or at least confined space, making it hard to assume a relation to "measure" without going through the separation line as "bar".  In fact, the musical definition is plainly "A vertical line across the staff. Bars divide the staff into spaces which represent measures, and are themselves called measures."
Comment: @BobBroadley: I call them bar-lines too, and I'm American.  Measure and bar I use interchangeably.
Comment: 'Bar' may sometimes mean 'bar-line' when we call 'bars' 'measures'.  But it isn't a strict definition.
Answer: I feel there are 4 beats to a "measure" or "Bar"....I used to think as the dividing line between "beats" as a bar....and a measure being the complete line...say of 4 beats....then to say there are 4 bars to a measure....even though I know that the terms bars and measure are used interchangeably, as well as, in Jazz and Blues they use the terms...12 bar and 16 bar phrases or lines...(Also as Bob Rodes above says 12 bar and 16 bar Blues...Joe Murphy (Drummer) S.W.FL. orig. J.C.NJ
Comment: Can you improve the grammar of this answer?  Right now it comes across as a stream of thought and is not very coherent - it sounds like you are saying there are 4 bars to a measure, which I think is definitely wrong in every musical context that I have been exposed to.  I can retract my downvote if you can make this clearer and/or more correct.
Answer: Bars and measures are the same thing but we (in the States) use them to talk about 2 different things when writing music. In 4/4 there are 4 beats per bar and 4 bars per measure. So this can change how many measures are in a song because one song has 4 bars per measure vs an 8/4 time song that has 8 beats per bar and 4 bars per measure or 6/5 time which has 6 beats per bar and 5 bars per measure. Now not every musician looks at it this way but I know plenty who do.
Comment: This is incorrect. No one (in the U.S. or elsewhere) disputes the meaning of the term "measure." It means the same thing as a bar. Maybe you're thinking of a [**hypermeasure**](https://en.wikipedia.org/wiki/Bar_(music)#Hypermeasure)?
Comment: What's more, even though some music may have the sense of hypermeasures of 3 bars (Ritmo di tre battute) or perhaps 5, nobody puts such a number in the bottom of a time signature; that number is always a power of 2, e.g. 2, 4, 8 or 16 but never 5.
Comment: I don't know any musicians who look at it this way. Doesn't mean that they don't exist, but to every music-reading musician I know, 8/4 means 8 beats per bar/measure and 4th note gets one beat. Then 6/5 time presupposes the existence of a "fifth note," which would get one beat. How to write six of those in one measure is problematical, and it doesn't make much sense to me to do it anyway, since AFAICS you could write the same rhythm and meter much more easily with 6/4 time signature.

Difference between "Bar" and "Measure"


Two negative beta's in a curvilinear regression when mean centered or using standardized values

Question: The problem I encounter is the following:
Imagine a (perfect) inverted U-shaped relation between an independent variable and a dependent variable. When you look at the curve estimation there is indeed a perfect inverted U-shaped relation.
If you conduct a regression analysis you have the normal independent variable and the squared term of the independent variable. In such a case, usually the normal independent variable gives a positive beta and the independent variable squared gives a negative beta. If these are both significant, this indicates that there is an inverted U-shaped relationship. However, it is well-known that in this way you have a very high VIF value (multicolliniearity), because there is an almost perfectly positive correlation between the normal independent variable and independent variable squared (because you square it of course).
The solution for reducing the multicolliniearity is to mean center the independent variable, and after then taking the squared term of the mean centered independent variable. If i perform a regression now (with both of the two predictors mean centered) I do not have problems anymore with multicollinearity, but I have two negative beta's. How is this possible? How can i have two negative beta's while i have a perfect inverted U shaped relationship according to the curve estimation and data? Is it still possible to prove the inverted U shaped relation with two negative beta's?
Comment: Is y =ax$^2$ with a>0 the onlt way to get a perfect inverted U?  I don't think so.  If the inverted U corresponds to a different function then there will not be an a that gives a perfect fit to y=ax$^2$.  Then it would be possible for some other model to fit better.
Comment: I suspect that you squared the mean-centered x instead of mean centering the squared x. If you mean center before you square, you get a u-shaped predictor.
Comment: http://orm.sagepub.com/content/15/3/339.abstract To all who come across this in the future, I recommend reading Dalal & Zickar (2012) -- The "solution" of using mean centering is not as straightforward as one would think.
Comment: I'm not sure there's a problem here, but if you can provide your data, people may be able to say more.
Comment: @Fojtasek I also tried to mean centering the squared X, then I have a positive beta for the normal independent variable and a negative beta for the squared one. That is exactly the case when there is an inverted U-shaped relation, but in that case there is a multicolliniearity problem because the VIF value is higher than 10.
Answer: Let's make up some data that has a nearly perfect inverted U:
x <- rnorm(100, 10, 2)
x2 <- x^2
centx <- x - mean(x)
centx2 <- centx^2
y <- (x-10)^2*-1 + rnorm(100)
plot(x,y)

Now, let's check the lm on the centered x and centered $x^2$
m1 <- lm(y~centx+centx2)
summary(m1)

And both have negative coefficients. So, why is there a problem?
The U shape is implied by the large coefficient on the quadratic term; its inverse shape by the negative sign.
Comment: When I ran @Peter's code several times I sometimes got a pos. coeff. for centx and sometimes a neg.  The fact that y ranged from about -25 to 5, whereas x was always pos., seems to help explain why the centx coeff. was sometimes neg.
Comment: @Peter Thank you very much for your answer. The confusing point was that in every academic article that I read they elaborated that there was an inverted U-shaped relation, because the normal predictor was positive and significant and the squared term was negative and significant.
Comment: That is weird, and reveals that people don't know elementary algebra.


ANOVA with 3 groups- does adding a group close to the mean reduce power?

Question: I have run a psychology experiment where participants received one of three sets of instructions (between-subjects). Either they were told to approach the experiment a certain way, told to approach it a different way or it was not specified how they should approach the task (it turned out that some in this group did it one way and some the other, about 60/40).
My ANOVA on performance in the experiment is nonsignificant, but my comparison between the 2 groups which received specified instructions were significant either as a planned comparison or in an independent t-test (the effect size between the two is pretty good, Cohen's d = ~0.45). I've been taught not to interpret ANOVA comparisons unless the overall effect is significant, but it seems to me that including this middle group (the means of which tend to be between the two groups) is underpowering the ANOVA. Is it "cheating" to just compare the two groups with a t-test? It certainly doesn't seem right to conclude there is no difference between groups when the ANOVA only breaks with inclusion of this middle group.
Comment: Note that a non-significant p-value doesn't justify a conclusion of "no difference between groups".
Comment: I think you were taught badly (although it's a common way of teaching). People rely on p-values too much and on effect sizes too little.
Comment: What's the 95% CI on the d, and what's the *p* of the *t*-test?
Comment: Yeah sorry about that Mark, and I agree Peter
Answer: The comments already raised many important issues and provided good general advice (don't overinterpret non-significant p-values, don't think that dichotomous significant/non-significant decisions is all there is to data analysis and focus on effect size). Previous questions on post-hoc tests (e.g. What do we call multiple testing?) might also shed some light on the advice you received about multiple comparisons.
However, your experiment seems a little unusual in that the third group is really a mixture of participants who self-assigned to one of the two other groups. Beyond the statistical issues related to multiple comparisons, double dipping and the like, ignoring the "no instruction" condition would seem defensible in this particular case but it begs the question of why you included it in the experimental design in the first place.
If you knew that participants were going to choose one of the two strategies, it was obvious that the variability among participants who did not receive any instruction was going to be higher and their mean score fall somewhere between the two other groups. What a test on these data could possibly reveal is not clear to me.
Since it seems you have a measure of the approach each participant took, another practical way to approach this problem would be to create a variable representing this strategy and compare the two groups defined by this variable. One drawback is that since the strategy is measured and not randomly manipulated, your data are not purely experimental and a causal interpretation of the effect would be much more questionable.


Factors given by DoE can experimentally not be reached

Question: We are running a DoE in a CCD manner at the moment.
One factor is quite difficult to reach and to reproduce: Humidity because it has to be set by chemical reactions.
To be more concise: The factor 56 % relative humidity can only be reached with 44 % relative humidity and some +/- % to reproduce it.
How to deal with that? My suggestion is to ignore that and kind of cheat the measurements by using the value 56 % for all the values which should be 56 %. I'd do this because in my understanding of the DoE it is less the value itself but more the factor that will be used. Sure, they are connected but in real experiments you will never be able to achieve all factors without any deviation.
Any advice?
The values are given here:

<code>A = H2 concentration
B = CO concentration
C = C2H2 concentration
D = Environment temperature
E = relative humidity
</code>
I can also ask for the actual DoE plan with all single measurement points? At the moment, I only receive the measured data on a dripping periodicity, so the first data points are not revealing the DoE. But I can ask for the plan.
Comment: Are we assuming that the experiments have already been performed? If not, why not just run at 44%? From the way it's phrased, it seems like an upper value. Another way is to use all your real values and depending on number of experiments,  perform a linear regression instead. Are any of the input factors correlated? That compromises the DOE
Comment: I genuinely cannot interpret why you can't use 44% as your upper limit? Also, with so many constraints, maybe make some compromised by widening your ranges on the other factors and setting alpha to zero? Some sort of optimal design is a good shout. Or, just have "low" and "high" humidity as categorical factors?
Comment: Can you tell us which design you are using? Factorial designs tend to lead to box experimental regions, and if some corners must be cut (seems to be your case?) the design is no longer. Such designs should be starting points, not straighjackets ... One possibility is to use optimal design software (search this site, also D-optimality) to find a good design which do not enforce a box.
Comment: Kind of both, I also adviced to aim at the 44 % instead. Just wanted to know if it is valid in terms of the theoretical framework of a DoE where you will get the exact values you've to use?
Linear regression is also planned. Btw, what models come into mind when performing DoE?
Comment: It's a CCD, how do I know whether the design is still valid? Thanks for the advices, will check it though I think for the moment it won't be applicable due to management decisions ;)
Comment: @Ben hard to tell without seeing the numbers.  Or maybe at least the coded values?
Comment: I added some values, is that helping?
Comment: Please add all the extra information in comments as an edit to the Q, not everybody reads comments!
Answer: You are finally analyzing the results of the experiment using some regression models. The situation seems to be that for the variable humidity, you cannot set the defined factor level exactly, but when set, you can measure it exactly?
If that is right, I can see no reason not to use it, in the analysis, as a numerical variable, using the measured value.
EDIT
Thinking a bit more about this, can there be some possible problems with this solution?  Write a stylized model as
$$ Y_i = \beta_0 + \beta_1 x_i + \epsilon_i $$  where $x_i$ is the chosen value in the design, which it in practice is difficult to reach. Then the realized model is
$$ Y_i = \beta_0 + \beta_1 (x_i+\delta_i) + \epsilon_i $$
Now, if the chemical processes in the lab which makes it difficult to realize $x_i$, and in its place leads to $x_i+\delta_i$, impurities or whatever, is related to the experimental error $\epsilon_i$ (like impurities influencing both), so $\epsilon_i$  and $\delta_i$ is correlated? Then there is problems --- but since $\delta_i$ is known, this can be investigated, maybe by plotting $\delta_i$ and model residuals.
Comment: The argument with centerpoints is that, if you see it geometrically, they lie simultaneously on **all** the lines. So, with even only one centerpoint, you can get the possibility to check for curvature in **all directions**.
Comment: **WHY** is it impossible to reach it? Maybe if you can explain that, something more can be said.  Even an approximate center point would be useful. As long as the actually reached valued can be measured precisely, I stand with my answer
Comment: Because it is hard or even impossible to reach these points in the lab due to chemical processes. Even if it can be reached it is almost impossible to reproduce the same value. I'm not doubting you or your opinion, I only would like to understand the theory. Given your statement I conclude the center points are quite arbitrary resp. they are not really backed by theory? Simply spoken it is "Add a measurement in between"? I'm fine with that.
Comment: does this mean, it doesn't matter whether I can reach e.g. rH = 56 % or not? What if all my measurements are like this rH={42 %, 44 %, 56 %, 62 %, 76%), which relevance does this center point than have?


(Strong) causality condition

Question: I'm studying the causality in Lorentz Manifold with the book "Semi-Riemann Geometry", B.O'Neill. I have the followig problem:
He says that, picked a subset A of a Lorentzian Manifold M, the causality condition hold on A if there aren't closed causal curve in A. After this he proves that if a set is compact it contains a closed causal curve. Then, if I understand, in a compact set the causality condition can't hold. But after this definition, the author proves a lemma in which he supposes that in a compact subset $K \subset M$ the causality condition holds. How can it be possible??
Comment: What he proves is not that a compact set has closed causal curves, but that a compact space-time has closed causal curves. Take Mikowski space-time and a compact subset, it will not have closed causal curves.
Comment: Interesting!! but the Definition of spacetime is just p.163 "connected time-oriented four-dimensional Lorentz manifold" and so why is a compact subset of the Minkowski space no a spacetime? (e.g. a 4 dimensional ball, in the associated euclidian metric)
Answer: No closed casual curves $\implies$ Causality condition holds
Is equivalent to
Causality condition does not hold $\implies$   a closed casual curve exists
Not equivalent to
Closed casual curve exist $\color{red}\implies$ Causality condition doesn't hold
In your problem
A is compact $\implies$ a closed casual curve exists
this last condition does not imply that "Causality condition doesn't hold"
Comment: I answered it only by logic, i am not expert in that topic
Comment: Thanks for your answer. I see the implication in another way:\\ Causality condition holds implies no closed causal curves. So closed causal curves implies causal condition doesn't hold...
Comment: So, in a compact, a closed causal curve esxists then the causality condition can't hold...It is wrong for you?
Comment: It is not necessarily that "Causality condition doesn't hold"
Comment: I mean that the existence of a closed casual curve is not enough to ensure that "Causality condition doesn't hold"
Comment: ok. thank you so much!!
Comment: The "if" in " If M contains no closed timelike curves, we say that the chronology condition holds on M" (same for causality) Semi-Riemannian geometry p.407, is a definition "if", not an implication. For me the question is still unanswered but the comment by MBN is exactly to the point
Comment: i.e. not just an implication but an equivalence
Answer: A compact subset and a compact manifold are different. There must be a point outside the compact subset with the causality condition, but a compact manifold has no this property and this is a key point in the proof of Lemma 14.10.

(Strong) causality condition


erro: "table vendas has 6 columns but 5 values were supplied"

Question: Criei a seguinte tabela em sql
CREATE TABLE vendas
    (
     ID INTEGER IDENTITY(1,1),
     Empresa VARCHAR (20),
     Modelo  TEXT,
     Preco REAL,
     Kilometragem REAL,
     Ano INTEGER,
     PRIMARY KEY(ID)
    );

Coloquei como chave primaria a coluna ID que esta com uma propriedade IDENTITY
Pelo o que eu pesquisei, ao inserir uma nova tupla na tabela eu posso omitir o campo ID porque ele eh auto-gerado, porem fiz a inserção.
INSERT INTO vendas VALUES ("Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017)

e retorna o erro
table vendas has 6 columns but 5 values were supplied: INSERT INTO vendas VALUES ("Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017)

Alguem pode me ajudar a solucionar esse problema, por gentileza?
Pessoal, fiz conforme o amigo guastallaigor me auxiliou, porem agora que eu fiz a inserções surgiu outro problema no campo id. Só esta indo NULL pra esse campo.
Comment: ID não é autoincrementado
Comment: qual é o banco ?
Answer: Ao executar a query sem informar o nome das colunas, o banco não tem como saber qual o valor deverá ser inserido em qual coluna. No código:
INSERT INTO vendas VALUES ("Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017)

Ele poderia tentar inserir "Movidas" na coluna ID por exemplo.
Você só consegue omitir o nome das colunas, se tiver um valor para cada na query.
Sendo assim, você precisa informar o nome das colunas:
Insert into vendas (Empresa,Modelo,Preco,Kilometragem,Ano) values ("Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017);

Observações:

No campo Modelo você está usando Text que é recomendado somente para textos muito grandes, pois é armazenado na área de blobs. O ideal seria Varchar. (Veja esta resposta)
No campo Ano você está usando Integer que pode armazenar um número muito grande (2.147.483.647) o que é totalmente desnecessário. Poderia ser apenas um NUMERIC(4,0), pelo menos até o ano 9999... depois disso deixa que outro programador resolva =]
Sobre os outros campos, não sei qual base você está usando, também não sei a especificação do REAL, então não vou entrar na questão.
Comment: Muito obrigado por suas dicas, vou aplicar elas.
Comment: Disponha, marque a questão que resolveu seu problema, e se desejar avalie-as. Faça o [Tour] para ver como funciona a comunidade
Answer: Tente algo assim se o ID estiver de forma incremental no banco:
INSERT INTO vendas (Empresa, Modelo, Preco, Kilometragem, Ano) VALUES ("Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017)

Caso contrário, tente no momento colocar um ID manualmente para ver se funciona:
INSERT INTO vendas VALUES (1, "Movidas","RENAULT SANDERO 1.6 EXPRESSION 8V FLEX 4P MANUAL", 36590.0,25.002,2017)

EDIT: No caso dos ID's ficarem nulos, provavelmente faltou o AUTOINCREMENT ao criar a tabela vendas em questão.
Supondo pela imagem que o banco é SQLite, não é possível realizar um ALTER TABLE. Desta forma, se puder o mais fácil é dropar toda a tabela (DROP TABLE vendas) e criá-la novamente, algo como:
CREATE TABLE vendas
(
 ID INTEGER IDENTITY(1,1) AUTOINCREMENT,
 Empresa VARCHAR (20),
 Modelo  TEXT,
 Preco REAL,
 Kilometragem REAL,
 Ano INTEGER,
 PRIMARY KEY(ID)
);

Caso contrário, deve-se criar uma nova tabela:
CREATE TABLE vendasaux
(
 ID INTEGER IDENTITY(1,1) AUTOINCREMENT,
 Empresa VARCHAR (20),
 Modelo  TEXT,
 Preco REAL,
 Kilometragem REAL,
 Ano INTEGER,
 PRIMARY KEY(ID)
);

Depois inserir todos os registros da tabela vendas na tabela vendasaux:
INSERT INTO vendasaux (Empresa, Modelo, Preco, Kilometragem, Ano) SELECT Empresa, Modelo, Preco, Kilometragem, Ano from vendas;

Em seguida, pode agora dropar a tabela vendas:
DROP TABLE vendas
E por fim, renomear a tabela vendasaux para vendas
ALTER TABLE vendasaux RENAME TO vendas

Obs: Não vou conseguir testá-los agora, mas creio que funcionará, qualquer problema envie nos comentários que auxilio posteriormente.
Comment: funcionou a primeira alternativa. Muito obrigado
Comment: Olá, por nada. Se funcionou aceite minha pergunta como a correta por gentileza para que auxilie outras pessoas com o mesmo problema. Obrigado.
Comment: surgiu outro problema, voce pode me ajudar?
Comment: Sim, no caso seu ID não está de forma auto incremental. Faltou adicionar o AUTOINCREMENT ao criar a tabela na coluna ID. Provavelmente isto não será possível ser alterado com o comando ALTER TABLE no caso do SQLite, é possível dropar a tabela e criá-la com a propriedade AUTOINCREMENT?
Comment: Editei a pergunta, veja se ajuda.


Rotate Point around pivot Point repeatedly

Question: For a while now I've been using the following function to rotate a series of Points around a pivot point in various programs of mine.
private Point RotatePoint(Point point, Point pivot, double radians)
{
    var cosTheta = Math.Cos(radians);
    var sinTheta = Math.Sin(radians);

    var x = (cosTheta * (point.X - pivot.X) - sinTheta * (point.Y - pivot.Y) + pivot.X);
    var y = (sinTheta * (point.X - pivot.X) + cosTheta * (point.Y - pivot.Y) + pivot.Y);

    return new Point((int)x, (int)y);
}

This has always worked great, until I tried to rotate a shape repeatedly by small amounts. For example, this is what I get from calling it for 45° on a rectangular polygon made up of 4 points:
foreach (var point in points)
    Rotate(point, center, Math.PI / 180f * 45);

But this is what I get by calling rotate 45 times for 1°:
for (var i = 0; i < 45; ++i)
    foreach (var point in points)
        Rotate(point, center, Math.PI / 180f * 1)

As long as I call it only once it's fine, and it also seems like it gets gradually worse the lower the rotation degree is. Is there some flaw in the function, or am I misunderstanding something fundamental about what this function does?
How could I rotate repeatedly by small amounts? I could save the base points and use them to update the current points whenever the rotation changes, but is that the only way?
Comment: Can you change to PointF?
Answer: Your Point position measure is off because of the integer rounding generated by the RotatePoint() method.
A simple correction in the method returned value, using float coordinates, will produce the correct measure:
To test it, create a Timer and register its Tick event as RotateTimerTick():
Added a rotation spin increment (see the rotationSpin Field) to emphasize the motion effect.
PointF pivotPoint = new PointF(100F, 100F);
PointF rotatingPoint = new PointF(50F, 100F);
double rotationSpin = 0D;

private PointF RotatePoint(PointF point, PointF pivot, double radians)
{
    var cosTheta = Math.Cos(radians);
    var sinTheta = Math.Sin(radians);

    var x = (cosTheta * (point.X - pivot.X) - sinTheta * (point.Y - pivot.Y) + pivot.X);
    var y = (sinTheta * (point.X - pivot.X) + cosTheta * (point.Y - pivot.Y) + pivot.Y);

    return new PointF((float)x, (float)y);
}

private void RotateTimerTick(object sender, EventArgs e)
{
    rotationSpin += .5;

    if (rotationSpin > 90) rotationSpin = 0;
    rotatingPoint = RotatePoint(rotatingPoint, pivotPoint, (Math.PI / 180f) * rotationSpin);
    Panel1.Invalidate(new Rectangle(new Point(50,50), new Size(110, 110)));
}

private void Panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.FillEllipse(Brushes.White, new RectangleF(100, 100, 8, 8));
    e.Graphics.FillEllipse(Brushes.Yellow, new RectangleF(rotatingPoint, new SizeF(8, 8)));
}

This is the result using float values:

And this is what happens using integer values:
Comment: Thank you for your answer, I realized this just now before checking for answers here. Such a silly little mistake.
Answer: If you want you can use the Media3D to only deal with matrix and simplify the coding. Something as simple as this will work.
public Point3D Rotate(Point3D point, Point3D rotationCenter, Vector3D rotation, double degree)
{
    // create empty matrix
    var matrix = new Matrix3D();

    // translate matrix to rotation point
    matrix.Translate(rotationCenter - new Point3D());

    // rotate it the way we need
    matrix.Rotate(new Quaternion(rotation, degree));

    // apply the matrix to our point
    point = matrix.Transform(point);

    return point;
}

Then you simply call the method and specify the rotation. Lets say you work with 2D (like in your example) and lets assume we work with XY plane so the rotation is in Z. You can do something like :
var rotationPoint = new Point3D(0, 0, 0);
var currentPoint = new Point3D(10, 0, 0);

// rotate the current point around the rotation point in Z by 45 degree
var newPoint = Rotate(currentPoint, rotation, new Vector3D(0, 0, 1), 45d);


There are 16 students in a class. Can they be paired over 12 time slots such that...

Question: I came across a scenario in class today that I think makes for an interesting math problem.
There were 16 students in class and each of us was asked to find a partner for a particular hour of the day. For example, I might pair with Janet at 12 p.m., with Armando at 1 p.m., with Kelly at 2 p.m., and so on. I found at the end of the activity that I had one slot left (at 3 p.m., say) but no one else had that slot free. As such, I was unable to complete the assignment. This got me wondering how this generalizes into a problem, which I've stated below.
Problem
There are 16 students in a class. Can they be paired (forming groups of 2 students) over 12 time slots such that they meet the following requirements?

Every student has a partner for each of the 12 time slots.
No student pairs with the same student twice.

To be clear, it is not necessary that every student pairs with every other student, only that no student pairs with another student more than once.
Proposed Solution
My suspicion is that as long as there is at least one more student then there are time slots (16 students for 12 time slots, for example), then I think that this should be possible. My reasoning is as follows:
There are 120 ways to form pairs from 16 distinct people ($C_{16,2}$). There are 192 total time slots $(16 \cdot 12 = 192)$. Each time a pair is made, two of these slots are filled. So, we essentially have 96 $(192 \div 2 = 96)$ time slots to fill with 120 potential pairs. So we should have pairings left over, which would mean that the problem should be solvable.
I'm ignoring cases with an odd number of students since that would guarantee that (at least) one person was left out for each time slot.
Questions
Is my reasoning sound? Is there a clearer way to think about this? And if this is solvable, why didn't I end up without a partner at 3 p.m.?
Answer: I wouldn't exactly say your reasoning is sound, but you are on the right track.  You say that as long as there are more student than there are time slots, it should be possible, but what you've really argued is the reverse; it is impossible if there are not more students than time slots.
A clearer way to think about it may be a round-robin tournament with $2n$ players and $2n-1$ rounds, each consisting of $n$ matches.  In a round-robin, each player plays each of the other competitors exactly once.  If you think of the players as students, the rounds as times slots, and the matches as pairing, you see that the problems are really exactly the same.
It has been known since the $19$th century that a round robin as described above can be scheduled for any even number of players.  See this scheduling algorithm.
As to your last question, just because a schedule is possible, it doesn't mean that every attempt will succeed.  Indeed, if that were true, there would be no need for an algorithm.
Comment: Well, you just got unlucky. Everyone you had not partnered with at some other time had already scheduled $3$ pm before you got around to scheduling that slot.  Let's say you pair with Janet at $12$ pm.  Meanwhile, the other $14$ students break up into $7$ pairs and schedule the $1$ pm time slot. Neither you nor Janet can schedule the $1$ pm slot, even though very little scheduling has been done at this point.
Comment: Can you explain how I've actually argued the opposite? I was trying to say that there are more pairings than slots (once we take into account that my pairing with Janet at 12 p.m. fills hers as well as mine), so we should be able to fill the slots without repeating the pairings.
Comment: And thank you for the note about the round robin tournament scheduling. That's exactly what I was looking for.
Comment: It's not enough to say, "We should be able to do it."  You have to show how to do it.  The reverse is true (and obvious) however; if there are more pairings than slots, it's impossible. There are a lot of these "combinatorial designs" where one can't reject the possibility simply with counting arguments, but constructing the design turns out to be impossible.
Comment: I see. I'm not actually trying to determine whether we can form every pairing in the given number of slots (which as you say, would be impossible), but rather that we can occupy every slot with the given pairings available (even if I never end up pairing with a Roger, Simone, or Elsie, for example).
Comment: The fact that I ended up without a pairing for that time slot had me wondering whether or not it was always possible, hence my question here.
Comment: That makes sense. Part of my hang up with this was differentiating between possible and guaranteed. Your answer and comments have done just that.


How to generate nD point process?

Question: Context:
Poisson point processes (PPP) are widely discussed in the literature.
In the following figure a framework to generate two-dimensional PPP is demonstrated. First the area being studied (part of space which can be in 1D, 2D, 3D, ..., in our example is a 2D shape i.e., square) is divided into cells (gridding). Second, for each cell a random number n is drawn from a Poisson distribution with density of $\lambda$. Then within each cell n points are uniformly distributed. The resulting point pattern is a homogeneous point process.
Questions:

Is the described method correct?
If we shuffle the numbers within area, then is it still a valid PPP?
Is it valid for further dimensions?

Please check whether the following steps are the same as I illustrated.

note
Please read the following invaluable answers and comments which are appreciable. I don't repeat them here. However I put a confusing point here hopefully to be solved by a gentle explanation.

The second point is if we do realization only once then why should we call it Poisson where it is simply a uniform-random-values?
Comment: @Developer It is a realization of Poisson point process - generate a Poisson number and then do a binomial point process (uniform). See this if you want to understand Poisson point process more rigorously: http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic-research/nichols/research/spatbayes/johnson_spatialpointproc.pdf
Answer: You don't need to grid.  You could just draw a Poisson count, $n$, for the total number of points and then simulate $n$ iid points uniform on the region.  For a square, you can draw $x_i$ and $y_i$ as independent uniforms.  (For a more complex region, the simplest thing would be to embed it in a square, simulate for the square, and then just keep the points in the target region.)
The same thing can be done in higher dimensions.  You draw the count from a Poisson with mean $\lambda V$ where $\lambda$ is the rate for the Poisson process and $V$ is the volume of the region, and then simulate that number of iid uniform points from the region.
And so 1: yes, 2: yes (if the grid regions are the same area), and 3: yes.
Comment: +1 I believe the point to gridding is to sample irregular regions with (slightly) higher computational efficiency, assuming an efficient data structure for locating grid cells within the region.  (The alternative is to sample the region's bounding box and reject samples outside the box.  That's usually ok in 2D but in higher dimensions tends to get bad.  E.g., a spherical region occupies an exponentially vanishing portion of the hypervolume of its bounding box as the dimension grows.)
Comment: @mp Thanks for the reminder.  I frequently forget to vote for a few minutes--sometimes inadvertently for a long time--but I do get around to it!  (I also make a point of upvoting good questions; with very rare exception, any question worth answering is a good one.)
Comment: @ Whuber I grabbed the idea from somewhere (let me try to find the source). The figure is my implementation. I believe gridding stage was a necessity to the method. It was not to do optimization in computing due to the source (book) was a pure statistics (as I remember).
Comment: Any comments on the `steps` that I added at the end of question. I grabbed it from an academic paper (ref. reserved). It is the source of my confusing, I think. Especially the step of sub-dividing region to sub-regions!
Comment: @Developer - It looks correct.
Answer: @Karl gave a good answer but it deserves an explanation.
A homogeneous Poisson point process (or "complete spatial randomness," CSR) is determined by two intuitive properties:

The probability that a point will be located within a small region $dA$ is directly proportional to $dA$ (up to second order in the hypervolume of $dA$).  Note that this immediately implies the expected number of points in any finite region of hypervolume $A$ is proportional to $A$.
The points are located independently of each other.

Assuming the points introduced within each cell are done so independently, using a Poisson distribution of counts in each cell assures overall independence.  To check (1), we lose no generality by assuming $dA$ is wholly located within a grid cell (because the probability that it straddles two cells is vanishingly small).  That reduces the check to verifying that points are generated with the same intensity within the cells.  Using a Poisson distribution of counts with expectation proportional to each cell's hypervolume assures this, as noted in (1).
This argument is independent of dimension.  In fact, it would apply to any finite dimensional manifold with a volume form (such as the surface of a sphere in 3D) in which a region has been partitioned into measurable "cells" of arbitrary shape.  The reason for using a grid, of course, is that grid cells can be addressed in $O(1)$ computational time and it's simple to generate random points within a rectangular region (merely by generating random coordinates within it).  If, as a preliminary matter, an irregular region is preprocessed to identify the cells it contains, this leads to a computationally efficient way to simulate a CSR process.  In higher dimensions the preprocessing for an arbitrary or complex region could be messy and time-consuming, but for simply defined manifolds and regions within them (such as spheres or their boundaries) there's no problem.
Comment: I found this explanation useful. However as I commented above (@Karl) I am still in doubt that gridding is arbitrary to be done.
Comment: @Developer The gridding is not statistically necessary.  In fact, a standard way to generate realizations of a homogeneous Poisson process within a GIS is to generate them within the bounding box and eliminate all points falling outside the region; no gridding whatsoever is involved.  We can only surmise that your stats text had an ulterior motive, either to clarify the exposition, to prepare for a later discussion of inhomogeneous processes, or because the author actually did have computational issues in mind.
Comment: I added `steps` at the end of question. Are they same as I've illustrated? There is a step to divide region to sub-regions! It is source of my confusing.
Comment: @Developer Those steps are exactly as you described.  In particular, for generating homogeneous processes in low-dimensional spaces, subdivision is unnecessary.
Comment: Well then why have they used sub-regions when they could just generate a number (random) n, then generate n uniform random coordinates (x,y)? According to your and Karl's comment generating regions is completely **unnecessary**. The second point is if we do realization only **once** then why should we call it `Poisson` where it is simply a `uniform-random-values`?
Comment: @Developer At this point we're repeating ourselves (the first two questions in your comment have already been answered) and you're moving into a different topic concerning what the Poisson distribution really is.  Further comments ought to take place in chat, or you might consider formulating a specific followup question to address the latter situation.
Comment: I don't think so. I'm not satisfied enough with the answers yet. The method that I've provided is an example that I knew. However the question **How to generate nD point process** is not answered yet! The suggested ideas are arguing the gridding stage proposed in the question which is a necessity step as the original text lists. I repeat my last point _if we do realization only once then why should we call it `Poisson` where it is simply a `uniform-random-values`?_ If we do many realizations Poisson could give us a series of numbers but for only one realization it has no meaning, I think!
Comment: @Developer Karl and I both gave explicit explanations of how to generate the ND point process. It is clear you do not understand what the Poisson process is nor how it is used here; your last two comments are changing the question altogether.   Prolonging this comment trail is not the way to clear up the confusion.
Comment: (**-10**) for an inappropriate language!
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1495/discussion-between-whuber-and-developer)

How to generate nD point process?


Two Dirichlet characters $\chi$, $\chi'$ are equal if $\chi(p) = \chi'(p)$ for almost all primes

Question: I want to prove the following: Let $\chi, \chi'$ be two primitive Dirichlet-characters of conductor $N$. Suppose that $\chi(p) = \chi'(p)$ for all but a finite number of primes $p$. Then $\chi = \chi'$.
My idea was to use the same trick as in Euclid's proof of the infinitude of primes. Let $p_1, ..., p_n$ be the (pairwise distinct) primes not dividing $N$ such that $\chi(p_i) \neq \chi'(p_i)$. Then $p_1 \cdots p_n + N$ is coprime to $N$ and no $p_i$ divides $p_1 \cdots p_n + N$. So $\chi(p_1 \cdots p_n + N) = \chi'(p_1 \cdots p_n + N)$. Now I thought we can use the fact that $p_1 \cdots p_n + N$ is a unit in $\mathbf{Z} / N\mathbf{Z}$, but I couldn't get my head around that.
Does anyone know how to do it?
Thanks!
Answer: You only need to check that $\chi(a)=\chi'(a)$ for every $a\in(\mathbb{Z}/N\mathbb{Z})^\times$. By Dirichlet's theorem, there exists a prime $p\equiv a\bmod N$ such that $\chi(p)=\chi'(p)$. Repeat this for every $a$ and you are done.
Comment: That's a nice answer! Using Dirichlet's theorem, this works out very fast. However, is there any more elementary proof of the claim?
Comment: @Steven I doubt it. For example, take $N=3$, then all the primes are $1\bmod 3$ or $-1\bmod 3$. If the hypothesis tells you that the equality occurs for almost all the primes of the second form, then you are happy: take one such prime to establish the equality for $a=-1$ and then two of these for $a=1$. However, if the hypothesis only tells you that the equality occurs for primes $1\bmod 3$, then you don't have any information about the case $a=-1$. This does not prove anything, but I would be rather surprised if that sort of proof you are asking existed.


In content type show same field twice with different widget

Question: I want to show one field (file type) twice in the same content type (without display suite as it breaks my other modules). After a user uploads a pdf and saves this content. I want one link to lead to pdf file for download(which it does) and the other link to show generic file (open a pdf in browser) and i dont know how to do that part (To change widget type). I have searched Drupal Answers and found some clues on how to do this in template.php
function bsthemel_preprocess_field(&$vars) {
 $node = $vars['node'];
     if($vars['element']['#field_name'] == 'field_document_pdf') {

        //code to copy and render this field with different widget (havent figured out how yet)
}

Now i am still new to drupal and can't seem to figure this out. Also what i have found is function hook_field_widget_form_alter but i think this has to be done after the new field is made. Or i might look at this completely wrong. Any help is appriciated
Answer: The "right" way to add additional elements to a view mode (without using a module like Display Suite or Panelizer to take over view modes) is to use hook_field_extra_fields():  This hook will make your added element visible on the core view mode configuration screen.
If you're new to Drupal it might be easier to go with the preprocess route. But instead of working at the level of template_preprocess_field() you should be working at the level of template_preprocess_node(). The node hook contains the field you want to duplicate. The field hook deals with only one field at a time.
Comment: This helped me a lot, Thank you for the explaination


Magento nav not displaying

Question: I am developing a new store in CE 18.104.22.168.
I have about 130 categories so far, all placed under a root category.
The root category is also defined in Ststem -> Magage Stores -> Our Store -> Root Category
If I access the Category pages directly, I can see all products and sub categories in breadcrumbs etc, so I know my structure is correct.  I know I am missing something simple.
I am using the the modern template for now until I get the site functional, so all the files are original.
EDIT I should also mention that the System -> Config -> Catalog -> Category Top Navigation -> Maximal Depth is set to 1
Any thoughts?
Comment: Have you cleared cached?
Comment: Cache is disabled -- all have been cleared and indexes run
Answer: OK --  After many hours of searching I finally figured it out.  If you export your products via any script (mine was custom built -- I exported from CE 220.127.116.11) and import them to a later version (126.96.36.199), even though the import goes smoothly, the values for certain things might not make the transition as smoothly.  Even though I had set my root category for my store view, my products were not applied to a store.  As a result they were there, but not there.
My solution:  Catalog -> Manage Products -> Select all -> Actions -> Update Attributes -> Submit ..  Once there check your Websites tab.  Make sure to "check" your main website button, and click save.  Run a full reindex and clear cache (I use SSH and sudo rm -R * inside /var/cache and /var/session directory).
I hope this helps others who have run into the same issue.
Thank you Moldovan Gheorghe Dani for your answer -- Your help is appreciated.
Answer: I just tried on my local environment with same version of magento and theme, and i have no problem at all.
I noticed that when you create a new category "Is Active" flag is set to No by default, so make sure that is set to Yes, and "Include in Navigation Menu" is also set to Yes for all categories. If still not work try to refresh cache even if is disabled, and indexes also. I hope that it will help you.
Comment: All categories are set to Is Active "yes" -- It was a category/product import and most are set to "yes" in the `include in Navigation Menu`  --  We have a few "experimental" categories that we don't want show, so those are set to "no"

Magento nav not displaying


Proving the convergence of Jacobi method

Question: Is there any elementary way of showing that the Jacobi method converges for the following system?
$$\begin{pmatrix}10 & -2 & -11\\-3 & 10 & 2\\-1 & 1& 10\end{pmatrix}X= \begin{pmatrix} 13\\9\\11 \end{pmatrix}$$
The problem I face is that the iteration matrix has two complex eigenvalues, so how could I show that this eigenvalues have an absolute value which is less than $1$?
Answer: Set $D=diag(2,1,1)$, then
$$
D^{-1}AD=
\begin{pmatrix}
10&-1&-5.5\\
-6&10&2\\
-2&1&10
\end{pmatrix}
$$
is diagonal-dominant. Which should be sufficient to show convergence of the Jacobi method.
Answer: I think, if the complex eigenvalues are $\lambda_1=re^{\theta}$ and $\lambda_2=re^{-\theta}$, then you just need to consider $r$, together with the real eigenvalue.
What happens is that, as the iteration matrix $D^{-1}R$ gets multiplied by itself itteratively, its corresponding eigenvalue matrix is taken to higher powers and if $r$ and the real eigenvalue are less than $1$, they would go to $0$, eventually.


Como carregar videos dentro de uma div com

Question: Olá !
Eu tenho uma select com os values e os títulos dos videos. Quero selecionar o video pelo value e carregar dentro de uma div.

               SELECIONE O VÍDEO...
               Vídeo-1
               Vídeo-2
               Vídeo-3

Como que ficaria uma jquery ?
Answer: Basicamente você pode fazer desta forma, inserindo uma tag video (HTML5) em uma div de acordo com a opção selecionada. O value das options você pode colocar a URL (origem) do respectivo vídeo.

Importante consultar nesta documentação as compatibilidades,
  opções e outros atributos da tag video.

Código:

$("#videos").change(function(){
   var src = $(this).val();
   var source = '<video width="400" controls><source src="'+src+'" type="video/mp4"></video>';
   $("#player").html(source);
});

<select id="videos">
   <option value="">Selecione um vídeo...</option>
   <option value="https://www.w3schools.com/html/mov_bbb.mp4">Vídeo-1</option>
   <option value="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4">Vídeo-2</option>
</select>

Comment: Funcionou perfeitamente. No meu caso carreguei os vídeos localmente. Depois é só mandar buscar no servidor. Muitíssimo obrigado.
Comment: @xavier, considere marcar a resposta como aceita, veja como em https://i.stack.imgur.com/evLUR.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079


como fazer controle de trafego nos app Android da Admob?

Question: Minha conta foi bloqueada por click inválidos, como identificar esse ip e fazer algo resolver problema.
Answer: Infelizmente a política do admob não fornece esse tipo de informação. Passei pela mesma situação, mandei email para o suporte e etc. Sugiro que crie uma outra conta em outro endereço para liberar novamente. Na aplicação nós temos que ter muito cuidado para colocarmos o espaço do admob em um lugar que não de muitos cliques inválidos, no caso bem longe de botões e etc (lugares que o usuário poderia acidentalmente clicar) foi essa informação que eles me passaram.


Use two different mail servers for a single domain

Question: sorry for my english, I have used Google Translate.
I have a Arsys host (an ISP host from Spain), which gives me 50 email accounts with 6GB of storage each.
I have about 6 accounts of those who need more than 6GB each, since they use much mail.
My problem is that I would like, that of the 50 accounts, who no longer need 6GB stay in Arsys, as the price goes into the budget for the storage they provide. But other accounts using more than 6GB use another mail server that offers apart eg. Amazon ... that even if you pay more you get up to 50GB of email
I've been watching Workmail Amazon, Google Apps for Bussiness, Microsoft Exchange, Office 365 ... and another that I do not remember because they offer mail service for businesses. It is quite out of my budget if I want to migrate all your mail accounts. So I just want some loose.
What I want to do is, if there is a DNS configuration to try a mail accounts (<6GB) to the mail server and the other Arsys (> 6GB) other payment server with more storage.
I do not know if I've explained.
Thank you.
Comment: You are much more likely to invest more money into troubleshooting problems caused by the configuration you suggest, than by simply investing a couple of Euros per month into a bigger email plan. My advice would be to get a bigger plan or move to another company with higher quotas.
Comment: This is not how SMTP works. MX records are configured on a domain-wide basis; there are no mechanisms for sub-dividing as you suggest.
Comment: @TomTom You have no way of knowing what the financial situation of this company is. Please refrain from making conjectures. Just answer the question and move on.
Answer: No, there is not. DNS wise. Normal approach is one server forwards specific accounts to another server. Via settings on the one authoritative server that gets all emails.


Customizing Entity Framework generated classes

Question: So I have a few model classes generated by entity framework and I want to customize at least one to fit my project needs. Here is the generated class:
    public partial class Token
    {
        public string token_admin { get; set; }
        public string username { get; set; }
        public string password { get; set; }
    }

And here is how I want to customize it:
    public partial class Token : IdentityUser
    {
        public string token_admin { get; set; }
        public string username { get; set; }
        [JsonIgnore]
        public string password { get; set; }
    }

Obviously each time the models are generated, the IdentityUser and decoration [JsonIgnore] disappear, making it hard to be consistent in my web api returns and impossible to find users using the http filter I setup... (the latter is actually a whole different problem on it's own)
I've been searching but can't find a clear answer to what is required to do here. Any suggestions?
FYI, this is part of a school lab so be lenient on the quality of what I do ;)
Comment: Possible duplicate of https://stackoverflow.com/questions/3782405/can-i-define-properties-in-partial-classes-then-mark-them-with-attributes-in-an
Comment: What templates are you using?
Comment: I didn't create the EF originally. It's an SQL binding as far as I know.
Answer: You should not have to modify the Entity models because you should not return Entity models from your WebApi.
Create a separate Token class in your WebApi project and map it with entity framework's model class.
Comment: sounds feasible but how to 'map' exactly?
Comment: I use AutoMapper(http://automapper.org/) to map models between different layers. This will be helpful https://github.com/AutoMapper/AutoMapper/wiki/Getting-started


Latent Profile Analysis and Statistical Methods in Psychology

Question: There has been a popular phenomenon that has several 'hallmark' components, and are uniquely associated with sexual abuse survivors. I would like to verify that the components can stand as a construct, and that these components are indeed a unique phenomenon among sexual abuse survivors, more than other typologies.
Previously, I have carried out Structural Equation Modelling (SEM) and regression investigating risk factors, correlates, etc. I would like to use a different approach on this phenomenon. I also have data on potential risk factors, correlates, etc.
a) What statistical approach do you guys recommend me to use? All variables are continuous, but categorization is also possible. Is Latent Profile Analysis (LPA) appropriate here, given we would like to assess typologies based on several latent continuous variables? I intend to use LPA to examine the determined typologies and assess whether the phenomenon (let's give it a name: construct A) is more pronounced in the group with SEXUAL violence than on the other groups.
Or are another statistical methods more appropriate (including SEM, Factor Analysis, etc)?
b) For Latent Profile Analysis, is it possible to use Mplus? Otherwise, what are application recommended for that?
Answer: Latent Profile Analysis (LPA) is a term typically used for a model which identifies latent sub-populations within a population based on a certain set of categorical variables. In your case, you have continuous variables, and the corresponding term used for this is Latent Class Analysis (LCA). Admitedly, there is some cross-over regarding the use of these terms.
So, if you want to identify latent subgroups, you can use LCA/LPA.
Yes, it is possible to fit both LCA and LPA models with Mplus
Comment: https://drive.google.com/file/d/1-sj8WIM-THBTXiKz4Lqs_CTmG8LulcIu/view?usp=drivesdk
Comment: attached above is the conceptual model we'd like to assess within subgroups (error terms, etc are not included. this just a prototype). Do you think it is possible to assess with LCA/LPA?
Comment: @robert-long when the distinction between LCA/LPA is maintained, isn't it the other way around? For instance [Spurk et al (2020) state](https://doi.org/10.1016/j.jvb.2020.103445) that distinction indicates the use of "the term latent class in cases where categorical indicators were analyzed, and latent profile where continuous indicators were analyzed"?
Answer: This question touches on both conceptual and statistical points, and I'd advise people in this situation to start with the conceptual part first.

There has been a popular phenomenon that has several 'hallmark' components, and are uniquely associated with sexual abuse survivors. I would like to verify that the components can stand as a construct, and that these components are indeed a unique phenomenon among sexual abuse survivors, more than other typologies.

I assume that the OP has a measure of some sort of symptom or trait that is unique to sexual abuse survivors. If you had omitted "unique", I would tend to guess it was something like post-traumatic stress disorder.
Whatever the case, in measuring psychological constructs like symptoms, we tend to reach for some sort of multiple-item scale. For example, the Patient Health Questionnaire-9 is a 0-27 point scale that measures depression. It has 9 questions. They cover affect (i.e. feelings, specifically sadness and inability to feel pleasure), cognitive (e.g. thinking you're a failure), and somatic (e.g. being fidgety, moving a lot more slowly than usual).
Most symptom scales undergo validation work. The developers will take some purposive approach to developing an item pool, i.e. a set of questions that get at the phenomenon they're trying to measure. The PHQ-9 developers were clinicians, and they just enumerated the symptoms of the DSM-III (the then-current version) - although the symptoms that get into the DSM to begin with get discussed in multiple rounds by psychiatrists relying on their practical experience, so it's not like they were generated at random. These authors had less of a knowledge base when they tried to develop a measure of quality of life for nursing home residents. (Disclosure: the first author was the wife of a late mentor.) They relied on intensive discussion with subject matter experts (policy makers and clinicians), plus resident interviews. Anyway, from there, you can select a set of items, maybe prune them or refine them using classical test theory or item response theory approaches.
When the OP says that they'd like to "verify that the components can stand as a construct," I would assume that they have not got a validated scale. It's unclear if the components they're referring to are a collection of individual questions, or (because they mentioned LPA, which typically refers to continuous indicators whose distribution is assumed to be Gaussian) if they have the sum scores of several separate tests, or if it's some collection of individual tests that produce continuous results (e.g. lab tests for hormones will return a continuous result), or something else.
How much do you know, theoretically?
I'll use "item" synonymously with a test question, e.g. one SAT question, one question on the PHQ-9. If there's already theoretical research that says that the construct in question is real, and there's already a validated scale, you can get by with doing no validation work. In fact, most randomized clinical trials do this. However, you can verify that the items in the scale hang together - that is, that they "can stand as a construct", by using confirmatory factor analysis.
You'd fit a structural equation model (SEM), positing that there's a unidimensional latent trait causing the item responses. (Assuming the scale was presented as a unidimensional construct.) If dealing with ordered categorical questions (like the PHQ-9 ones, where you're asking if someone was rarely bothered, sometimes bothered, often bothered, or almost always bothered by a symptom), you would want to use a weighted least squares estimator (as opposed to maximum likelihood) for technical reasons. You can then report a goodness of fit index, e.g. the Tucker Lewis Index, for which there are generally accepted cutoffs. Basically, it tells you how well the unidimensional model fits. If you're under the cutoff, that can indicate that your items are not hanging together well.
Alternatively, you could fit an item response theory (IRT) model, which is basically a generalized SEM model, and report the item discrimination/slope parameters. Items with low slopes (in education, I believe the preference is slopes > 1; I tend to repeat this in health services research but I have rarely seen slopes < 1) basically don't tell you much about the latent trait, and a lot of low slopes may implicate the construct or the measure of the construct. I don't believe there's a global test for good fit or not like the TLI, but I haven't done a lot of research in this.
If you were operating in a more exploratory mode, where you selected a bunch of items that you think may have something to do with one or more facets of the construct in question, you would probably want to do exploratory factor analysis (EFA). I believe that the 5-factor model of personality was developed using EFA; in that context, psychologists didn't have a great sense of what dimensions of personality even existed (apart from introversion/extraversion), so they had people rate themselves on a bunch of traits from the dictionary, then they ran EFA. They came out with, no surprise, 5 factors. In this context, you might not know what the facets or sub-factors of the overall construct are, so EFA could help.
I would consider the CFA or IRT approach to be testing for internal validity, specifically internal consistency. Note that Cronbach's Alpha is an older measure of internal consistency, but it has a number of downsides and I prefer not to use it. Normally, during test validation, researchers attempt to see how well their test correlates with or predicts a gold standard measure - for example, the PHQ-9 scores were validated against depression diagnoses made via clinical interviews. A gold standard may not be available - in the Kane et al paper, the person is ultimately the only reliable informant to their own quality of life, so there's no gold standard to validate against. I believe in psychometrics, this would be called showing criterion validity.
Discriminant validity
In psychometrics, discriminant validity means that the test you're interested in should not correlate with measures of different constructs. For example, a math test should not correlate too strongly with a verbal ability test. A depression symptom score should not correlate too strongly with, say, a measure of physical function. I realize this is not exactly what you are asking to do, but it is somewhat in the same vein.
In this case, you would probably need to define what other types of abuse might be related, and you would want to administer your test to samples of persons who have experienced sexual abuse and all the other comparison types. I assume the instrument in question produces a sum score that can be regarded as continuous. You could simply show the standardized mean differences on your instrument between the sexual abuse group and all the other groups. For example, Cohen's D is a pretty easy to calculate measure of the standardized mean difference - basically how many standard deviations do the means differ. 0.5 SD is usually regarded as a moderate difference, 0.2 as small.
What would latent class/profile analysis have told the OP?
I'll use LCA as a general synonym. Technically, I believe that LCA typically refers to binary, or at least to categorical items. LPA, as I mentioned, typically treats the items as continuous and distributed as Gaussian (but you can assume any distribution whose likelihood function you can write and that your software supports, e.g. you could simulate a mixture of Poisson distributions).
Depression can, practically, be treated as unidimensional. However, remember that I mentioned somatic items on the PHQ-9? One critique that some people make is that many older adults have a bunch of physical illnesses, and those might cause somatic symptoms and thus confound their responses to the PHQ-9. You might more generally wonder if there are some groups of patients with atypical responses to depression. You would not be the only one to wonder this; this is a systematic review of LCAs on depression scales. I haven't really dug into the findings. However, when you fit an LCA to symptom scales, you will almost surely find one high-symptom and one low-symptom group, plus maybe some intermediate groups. That's not very interesting. What's more interesting is the atypical groups. Some of the studies in that review found groups with high psychosomatic symptoms. A few found psychotic depression as their atyptical groups (but note that they may not have sampled from the general population and may have sampled from psychiatric treatment centers). Anyway, the atypical groups are the substantively interesting ones.
You may want to contrast LCA to exploratory factor analysis. What might have caused an atypical group of respondents? It could be that the construct is multidimensional, and one group of respondents has a higher level on one of the dimensions than the other. If the contention about older persons and somatic symptoms is correct, then if you ran an EFA on a sample, you might expect to be able to identify a group of somatic items. If you ran an LCA on that sample, you might expect an atypical group with a higher level of somatic symptoms. In this setup, EFA and LCA might provide similar information.
However, back to the question:

intend to use LPA to examine the determined typologies and assess whether the phenomenon (let's give it a name: construct A) is more pronounced in the group with SEXUAL violence than on the other groups.

LCA is not the best approach for the question explicitly identified in this statement. When I read the statement, I would tend to think more that construct A can be considered as unidimensional and continuous. So, you would just calculate and compare the means by group! Or if not unidimensional, you do that process for each identifiable dimension.
Under an LCA approach, you would be identifying qualitatively different typologies of construct A. You should treat them like an un-ordered categorical variable. You will probably find a group that's low in most symptoms, and a group that's high in most symptoms, so LCA can be used in this fashion. However, it is surprisingly not straightforward to regress these groups on an external independent variable (e.g. trauma type). An explanation is below this section.
If you object that you're not certain that your measure of construct A is really unidimensional (or close enough to unidimensional), then you would be better off trying to understand its dimensionality first, through methods like EFA.
LCA is hard!!
I would tend to recommend EFA over LCA to most applied statisticians. LCA has a lot of complex issues that can trip up applied analysts. For example, do you know how your statistical package handles estimates at the boundary of the parameter space? Specific to LPA with Gaussian indicators, do you know what your package's default treatment of the error terms' variance-covariance structure is, and what it implies? Do you know what might cause your model to fail to converge, and what are principled solutions to that? (Hint, many of them are related to the first issue.) Do you know that you should use numerous randomly selected start values, and why? Do you know that after an LCA, you don't have each observation's latent class? You really have a vector of latent class memberships. You thus can't directly take their latent class and do a multinomial regression on some other variable (which, by the way, is a little tricky to interpret to begin with). You could assign each observation to its most likely latent class, but this has measurement error that can bias your results. You can fit a latent class regression, which will simultaneously fit the LCA model and do the multinomial regression on the observed variables. Alternatively, there are approaches that correct for the measurement bias but are complex to explain. If you Google Jeroen Vermunt and his (and other authors') writings on three-step approaches, you will see what I mean. Stata definitely doesn't implement 3-step approaches, and I'm not aware of R packages that do; that would leave you with MPlus or Latent Gold, which are proprietary and quite rare softwares.


Double dispatch and factory pattern

Question: I've got the following code currently (not working):
#include <iostream>
#include <vector>

class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
};

class Creator {
public:
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    virtual bool equals(Shape& s) { return false; };
};

class Circle : public Shape {
private:
    Circle() : Shape() {};
public:
    class CircleCreator : public Creator {
    public:
        virtual Shape* create() { return new Circle(); };
        virtual bool equals(Shape& other_shape) { return false; };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {};
public:
    class RectangleCreator : public Creator {
    public:
        virtual Shape* create() { return new Rectangle(); };
        virtual bool equals(Shape& other_shape) { return false; };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

My goal is to use a factory pattern and avoid the creation of a new object if in a list I've got already that object. I tried to use a double dispatch pattern but it isn't easy to apply in this case. How can I do?
Edit: Since the code is used in a "critical" path, I want to avoid RTTI like dynamic_cast and so on.
Comment: Your equals-function returns false in all cases. Is that intended?
Comment: @nielsen no it's just an example becuase I don't know how to write these methods.
Comment: you don't want RTTI I can see. How about adding something else to distinguish the classes, e.g. a virtual function returning type information or a member variable? Is that also unacceptable?
Comment: It could be acceptable, can you provide a small example based on my code?
Comment: @nielsen: That's just implementing RTTI yourself, rather than leaving it up to the compiler.
Comment: @Hackl - sure but if that fulfills the needs, I guess it's ok. If you have a better solution, just post it.
Comment: possible duplicate of [C++ Double Dispatch for Equals()](http://stackoverflow.com/questions/7393458/c-double-dispatch-for-equals)
Answer: Maybe something like this could do it using member variables
#include <iostream>
#include <vector>

enum
{
CIRCLE,
RECTANGLE
};

class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    unsigned shapeType;
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
};

class Creator {
public:
unsigned shapeType;
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    bool equals(Shape& s) { return (this->shapeType == s.shapeType); };
};

class Circle : public Shape {
private:
    Circle() : Shape() {shapeType=CIRCLE;};
public:
    class CircleCreator : public Creator {
    public:
        CircleCreator() {shapeType=CIRCLE;};
        virtual Shape* create() { return new Circle(); };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {shapeType=RECTANGLE;};
public:
    class RectangleCreator : public Creator {
    public:
        RectangleCreator() {shapeType=RECTANGLE;};
        virtual Shape* create() { return new Rectangle(); };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

or this - using virtual function to return type
#include <iostream>
#include <vector>

enum
{
    CIRCLE,
RECTANGLE,
UNKNOWN
};
class Circle;
class Rectangle;

class Shape {
private:
    Shape() {};
public:
    virtual ~Shape() {};
    friend class Circle;
    friend class Rectangle;
    virtual unsigned iAmA(){return UNKNOWN;};
};

class Creator {
public:
    virtual ~Creator() {};
    virtual Shape* create() = 0;
    virtual bool equals(Shape& s) { return false; };
};

class Circle : public Shape {
private:
    Circle() : Shape() {};
    virtual unsigned iAmA(){return CIRCLE;};
public:
    class CircleCreator : public Creator {
    public:
        CircleCreator() {};
        virtual Shape* create() { return new Circle(); };
        virtual bool equals(Shape& other_shape) { return (CIRCLE == other_shape.iAmA()); };
    };
};

class Rectangle : public Shape {
private:
    Rectangle() : Shape() {};
    virtual unsigned iAmA(){return RECTANGLE;};
public:
    class RectangleCreator : public Creator {
    public:
        RectangleCreator() {};
        virtual Shape* create() { return new Rectangle(); };
        virtual bool equals(Shape& other_shape) { return (RECTANGLE == other_shape.iAmA()); };
    };
};

int main() {
    /* First step, build the list */
    std::vector<Shape*> shapeList;
    std::vector<Shape*>::iterator it;
    Rectangle::RectangleCreator rc;
    Circle::CircleCreator cc;
    Shape* s = cc.create();
    Shape* s1 = rc.create();
    shapeList.push_back(s);
    shapeList.push_back(s1);

    /* Second step: check if we've got a shape starting from a creator */
    for (it = shapeList.begin(); it != shapeList.end(); ++it) {
        if (rc.equals(**it)) {
            std::cout << "same shape" << std::endl;
        }
    }
    return 0;
}

Answer: I'm not sure what you're trying to do, but I guess this could point you some direction
enum class Shapes
{
    Rectangle,
    Circle,
    ...
};

class Shape
{
private:
    Shapes m_shape;

protected:
    Shape(Shapes shape)
    {
        m_shape = shape;
    }

public:
    Shapes GetShape() { return m_shape; } // this is used to check whether two shapes are equal

    virtual ~Shape() = default;
};

And now for factory pattern you'd do:
class ShapeFactory
{
public:
    static Shape* CreateShape(Shapes shape)
    {
        switch (shape)
        {
            case Shapes::Circle:
                return new Circle();
            // etc.
        }
    }
};

This feels very redundant and not very clever to me. Also, this can put alot of code into one place.
For the dispatch, you could do (I assume, I'm not really a fan of this concept as it can be made less verbose with a simple template use)
class ShapeCreator
{
public:
    virtual Shape* Create() = 0;
    virtual ~ShapeCreator() = default;
};

class Circle : public Shape
{
public:
    class Creator : ShapeCreator
    {
    public:
        Shape* Create() { return new Circle(); }
    };

    Circle() : Shape(Shapes::Circle)
    {}
};

bool SomethingWithCircle()
{
    Circle::Creator circleCreator;
    Shape* first = circleCreator.Create();
    Shape* second = circleCreator.Create();

    // notice memleak here
    return first->GetShape() == second->GetShape();
}

If using C++11, you can go even further and avoid the whole idea /which feels very java-like to me anyway/ using a proper template masturbation techniques. (Can still be applied to pre-C++11, you just won't be able specify the parameters.)
template<class T>
class ShapeCreator
{
public:
    template<class... TParams>
    static T* Create(TParams&&... parameters) { return new T(std::forward<TParams>(parameters)...); }
};

class Rectangle : public Shape
{
private:
    int m_width;
    int m_height;

public:
    Rectangle(int width, int height) : Shape(Shapes::Rectangle)
    {
        m_width = width;
        m_height = height;
    }
};

bool DoSomethingWithRectangles()
{
    Rectangle* first  = ShapeCreator<Rectangle>::Create(10, 15);
    Shape* second     = ShapeCreator<Rectangle>::Create(20, 25);

    // notice memleak here
    return first->GetShape() == second->GetShape();
}

TL;DR
You don't really need RTTI but you need to store the type info somewhere in the base type. I'm using the enum Shapes for this.
Both Factory and Dispatch may seem as a good idea, but you will still need dynamic casting somewhere when using them.
You can replace those two patterns using templates, but as soon as you'll get a vector of the base objects, you'll still have to dynamic_cast at some point.
I didn't measure this whatsoever, but I'm really interested in performance comparison of using virtual functions and dynamic cast as I imagine they'd be very similar...
End note:
Please notice, that I personally feel that using methods like equals or operator== on classes defining the basic interface is not very wise, since there are two possible outcomes:

The equals is virtual -> slow but acceptable
The equals is not virtual -> cannot be used in inherited types to actually do more advanced/relevant comparison, breaking the idea of Open to extension, closed for modification

Obviously, if you don't define the equals, you'd have to write comparison code every time. Or possibly use some templated Comparison class with possible specializations through traits yielding again the best performance with no code duplicity.
Generally speaking, you can get to point where you'd ask yourself "why isn't there base object and reflection like in java or c# in c++? It would allow me to use all these nice and clever patterns." The answer is templates. Why do it run-time, when you can do it compile time?

Double dispatch and factory pattern


POP3 / IMAP server for free mail-service

Question: The company I work for have a free email-service (like Hotmail/Gmail) with about 50.000 users.
The service is currently hosted by a partner, but would like to know what options we have for setting up our own servers and hosting a web-mail-interface etc.
There are no platform (windows, Ubuntu etc) preferences.
What servers would you recommend?
Comment: Own setup would be too much expensive... Its better to use "Google Apps for Business" ($50 per user per year only) or "Office 365"...
Comment: Are you serious ? $50 per user.. he says he has 50000 mailboxes, that's $2.5M per year.
Comment: @adaptr , i just signed in 2 seconds ago just to write exactly what you just did
Answer: If you lack experience in mail systems, the best advice I can give you is to consult an expert - or outsource it altogether.
Email is not a trivial subject, and takes many years to master.
That said, you will need hardware redundancy, centralized storage, a load-balanced web frontend, multiple MXes, and load-balanced POP/IMAP servers.
Good luck!
Comment: In that case, you're going to need to provide a LOT more information. SF is not a polling or "what-should-I-use" site; as noted in the FAQ, Q&A should be specific and practical.
Comment: We are not novices in hosting website/webapps, but are looking for a bit of guidance on IMAP/POP3 servers.
Answer: 50 000 users should be easy enough with Cyrus IMAPd. You can run it with Linux, *BSD or Solaris, at least. I've been administering a Cyrus installation with vast more than 50 000 users since 2003, no problems so far and the server is mostly idle. It supports POP3, IMAP, with both plain text logins and TLS/SSL and more exotic authentication mechanisms, too. With saslauthd you can make it work with stuff like OpenLDAP.
When it comes to Cyrus, one server with enough RAM should be more than enough for your workload. Cyrus loves RAM, but is not very CPU-intensive; in my case CPU usage is hovering under 10%. Get one or two servers more for fault-tolerance and setup for example Heartbeat v2 (or whatever it is called nowadays) for automatic failover with active-passive setup, should something go wrong. Have some kind of shared storage (like SAN) for your e-mails.
For webmail, one server should work just fine load-wise. Get SquirrelMail, RoundCube, Horde, or whatever you are familiar with. Get another server so you get fault-tolerance. Put a load-balancer in front of those.
For receiving e-mail and for authenticated SMTP, Postfix + amavisd-new + SpamAssassin/dspam should be a wonder combo. Use stuff like Postfix-policyd and policyd-weight if you see it necessary.


Tenenbaum and Pollard, Ordinary Differential Equations, Exercise 6, Problem 6

Question: After not doing serious math since I finished college I've decided to try to teach myself Differential Equations.  I'm using the Tenenbaum and Pollard text, but occasionally run into things I can't figure out.  Since it's been almost 20 years since my last math class, I can't always tell if the problem is my not understanding the new topic, or just a failure in doing calculus (or even algebra).
In this case, it's problem 6 in the exercises at the end of section 6, separable equations.
The problem asks to find a 1-parameter family of solutions, including intervals where it's valid, plus any particular solutions which are not members of the family of solutions.
The equation to solve is:
$$yx^2dy-y^3dx = 2x^2dy$$
My attempted solution is as follows:
Assuming $y\neq0$ and $x\neq0$, divide both sides by $y^3x^2$ to get:
$$\frac1 y dy-\frac1 {x^2} dx=\frac2 {y^3} dy$$
Rearrange to get:
$$x^{-2}dx=y^{-1}dy - 2y^{-3}dy$$
Integrating both sides, we get:
$$\int x^{-2}dx=\int y^{-1}dy - 2\int y^{-3}dy$$
$$-\frac1 x +C = \ln y + \frac1 {y^2}$$
Multiplying both sides by $y^2x$ and rearranging gets me to:
$$-y^2 + Cy^2x=y^2x\ln y +x$$
$$(Cx-1)y^2=(y^2\ln y+1)x, x\neq0, y\neq0$$
However, the solution in the books isn't the same.  Instead, they offer:
$$(cx+1)y^2=(y-1)x, x\neq0, y\neq0$$
For the life of me, I can't find either an error or how to get rid of the $\ln y$ term.
Additionally, the book lists $y=0$ as a particular solution not part of the family of solutions.  Why isn't $x=0$ also a particular solution?
Help much appreciated.
Comment: The first term in the equation after dividing by $y^3x^2$ should be $\dfrac{1}{y^2}\,dy$.
Answer:
Assuming $y\neq0$ and $x\neq0$, divide both sides by $y^3x^2$ to get
  $$\frac1 y dy-\frac1 {x^2} dx=\frac2 {y^3} dy$$

You made a mistake here. It should be
$$\frac1 {y^2} dy-\frac1 {x^2} dx=\frac2 {y^3} dy$$
Comment: Aha!  I was afraid it was something silly like that. Thanks!


Value of $1/e$ with the partial sum of $e$

Question: How to show $$1/e=1-1+\frac1{2!}-\frac1{3!}+\frac1{4!}+\dots$$
I have consider the product of the nth partial sums of the expansions for $e$ and $1/e$ but still can't prove there are equal to 1
with the definition $e=1+1+\frac1{2!}+\frac1{3!}+\dots$
Comment: How do you define $e$?
Comment: by using sum to infinity of 1+1+1/2!+1/3!+...
Comment: then you should include that in your post. Leaving it out results in answers such as Janitha357's, which use information about $e^x$ you have not.
Answer: I assume you know that
$$e = 1 + 1 + \frac{1}{2!} + \frac{1}{3!} + \ldots = \sum_{k=0}^{\infty} \frac{1}{k!}.$$
Now let
$$f = 1 - 1 + \frac{1}{2!} - \frac{1}{3!} + \ldots = \sum_{k=0}^{\infty} \frac{(-1)^k}{k!}.$$
By the Mertens theorem and the binomial formula
$$\begin{align*}
e \cdot f & = \left( \sum_{k=0}^{\infty} \frac{1}{k!} \right) \cdot \left( \sum_{k=0}^{\infty} \frac{(-1)^k}{k!} \right) = \sum_{n=0}^{\infty} \sum_{k=0}^n \frac{(-1)^{n-k}}{k! (n-k)!} \\[1ex]
& = \sum_{n=0}^{\infty} \frac{1}{n!} \sum_{k=0}^n \binom{n}{k} \cdot 1^k \cdot (-1)^{n-k} = \sum_{n=0}^{\infty} \frac{(1-1)^n}{n!} = \frac{1}{0!} = 1
\end{align*}$$
so $f = \frac{1}{e}$. In the end we used the fact that
$$0^n = \begin{cases} 1 & \text{ if } n = 0 \\ 0 & \text{ if } n > 0 \end{cases}$$
Comment: Is there any method without the Mertens Theorem?
Comment: @YenChuanOi Without proving that $$\sum_{n=0}^{\infty} \frac{x^n}{n!} = \lim_{n \to \infty} \left( 1+\frac{x}{n} \right)^n$$ at least for $x = 1$ and $x=-1$, I don't know of any.
Comment: You can think of it as Cauchy Product too.


Does YouTube Data API V3 work with YouTube Music?

Question: I would like to extract playlist data from Youtube Music, as well as metadata related to the songs in the said playlist. Is this possible with the Youtube Data V3 API, or YouTube Analytics API?
If so, where can I find documentation about calls and available metadata; I am not finding what I need on the YouTube Data API page. I am currently referencing PlaylistItems and Playlists in the reference Docs, but it seems that is geared to videos. Is that by design because you can toggle between video and audio in YT Music?
If possible is there an official Rust Crate?
Thank you in advance for the help.
Answer: Indeed, this feature is missing from YouTube Data API and quite a few other API users expressed the same need as yours.
The official Google staff account says the following:

This type of information is not available in the API. We have already raised a feature request for this but I can't guarantee that this feature will be implemented.

That is it: they may well implement this feature at some point, but, unfortunately, cannot tell when that'll happen.